0% found this document useful (0 votes)
31 views

ilovepdf_merged

Uploaded by

202310943
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

ilovepdf_merged

Uploaded by

202310943
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Module 1 Study Guide

History
Java language, originally called the ‘Oak’, was developed by James Gosling
at Sun Microsystems, which is now a subsidiary of Oracle Corporation, and
released in 1995 as a core component of Sun Microsystems' Java platform.
It has derived much of its syntax from C and C++ but has a simpler object
model and fewer low-level facilities.

Java is a general-purpose, concurrent, class-based, object-oriented


language that is specifically designed to have as few implementation
dependencies as possible.
The Java source code files (files with .java extension) are compiled into a
format called bytecode (files with .class extension), which can be executed by a
Java interpreter.

It was intended for use in Sun’s project research to work on a programming


software to control electronic devices.
It was modified to take advantage of the World Wide Web. The
WebRunner, later named as HotJava, was the very first web browser created in
Java.
In 1995, the Netscape Navigator internet browser was also developed to
support Java.

Features of Java:
1. Simple, Object-oriented, and Familiar
Java can be programmed without extensive programmer
training while being attuned to current software practices.
The needs of distributed, client-server based systems coincide
with the encapsulated, message-passing paradigms of object-
based software.
It looks like C++ as far as possible results in it being a familiar
language, while removing the unnecessary complexities of C++.
2. Robust and Secure
It provides extensive compile-time checking, followed by a
second level of run-time checking
Java technology is designed to operate in distributed
environments, which means that security is of paramount
importance
3. Architecture Neutral and Portable
Java technology is designed to support applications that will be
deployed into heterogeneous network environments.
To accommodate the diversity of operating environments, the
Java compiler product generates bytecode – an architecture
neutral intermediate format designed to transport code
efficiently to multiple hardware and software platforms. The
interpreted nature of Java technology solves both the binary
distribution problem and the version problem; the same Java
programming bytecodes will run on any platform.
4. High Perforrnance
The automatic garbage collector runs as a low priority
background thread, ensuring a high probability that memory is
available when required, leading to better performance.
5. Interpreted, Threaded, and Dynamic
The Java interpreter can execute the bytecodes directly on any
machine to which the interpreter and run-time system have
been ported.
Java technology’s multi-threading capability provides the
means to build applications with many concurrent threads of
activity. Multi-threading thus results in a high degree of
interactivity with end users.
While Java compiler is strict in its compile-time static checking,
the language and run-time system are dynamic in their linking
stages.

Java Editions:
J2SE: Java 2 Standard Edition
J2EE: Java 2 Enterprise Edition
J2ME: Java 2 Micro Edition

The Java Virtual Machine (JVM)


Java is a portable language that could run on any platform. The language
was able to do this by generating intermediate code for a hypothetical
computer called a virtual machine.

The Java source code (.java file) is normally compiled to produce the
bytecode file (.class file) which is normally interpreted by the Java virtual
machine (JVM).

The J2SDK (JDK)


Java 2 Software Development Kit contains
• java – the loader for Java applications
• javac – the compiler
• javadoc – the documentation generator
• other tools

Steps in Creating a Java Application


1. Create the source code.
2. Compile the source code.
3. Run the program.

Steps 1 : Creating the source code


Create the source code using any text editor.
Save the file with a “.java” extension.
Example: HelloJava.java

Steps 2 : Compiling the source code


Compile the source code to create the byte code using javac tool from the
J2SDK.
Open an MS-DOS console, browse for the directory where you saved the
source code.
Type the command javac HelloJava.java and press ENTER.
Verify that the HelloJava.class has been created.

Steps 3 : Running the Program


To execute the program, type the command: java HelloJava and press
ENTER.
Exploring Netbeans IDE
• An Integrated Development Environment is a computer software to help
computer programmers develop software.
• The Leaders:
- NetBeans
- Microsoft Visual Studio
- Eclipse
• What does an IDE consist of:
- Source code Editor.
- Compiler and/or interpreter.
- Build- automation tools.
• Optional Tools:
- Debugger.
- Version control system.
- Various tools to simplify the construction of a GUI.
• Tools For Object Oriented Design:
- Object inspector.
- Class Browser.
- Class hierarchy diagram.

• IDE abstracts the configuration necessary to piece together various utilities


in one unit, which could ease the learning of a language, and increases
developer productivity.
• Most IDEs today have GUI modeling utilities that simplify the development
of UIs, which is critical for commercial software today.

• The History Of NetBeans


• It all started as a student project called Xelfi
• The Goal was to write a Delphi- like Java IDE in Java for the first time.
• The original plan was to develop network-enabled JavaBeans components,
hens the name. but coming out of the spec for enterprise changed the
plans.
• Sun decided it needs a more powerful Java development tool, and the rest
is history.
• A fast fully-featured Integrated Development Environment (IDE) with
support for Java.
• Compliant applications for accelerating development across all major OS
platforms.
• Provides an open source, high performance, modular, extensible, multi-
platform Java IDE for GUI, mobile tools, Web, and Desktop applications.
• Written in java and therefore runs on every operating system that supports
Java VM.

NetBeans Features
• Environment: easily configured user interface and a modular architecture
extensible with additional plugins.
• Project System: support for multiple source roots, easy management of
libraries, easily ported to other environments, all based on Apache Ant.
• Web Development: Web Application project type, Supports the J2EE 1.3
and 1.4 standards with web application build support based on Apache Ant.
• Enterprise Java Beans (EJB) Development: easy to create and deploy and
import java beans.
• Web Services Development: wizards for creating web services and web
services clients, providing the basic (java/wsdl) code needed, and easy to
use testing tools of existing web services.
• Java 2 Platform, Micro Edition (J2ME) MIDP development: visual design
editor with end-to-end support for enterprise applications.
• Code Editor: Syntax highlighting for Java, XML, HTML, CSS, JSP and IDL, full
support of new JDK 1.5 features, live parsing/error marking, popup javadoc,
code completion, and fast class importing.
• Refactoring: renaming, changing and moving of various objects, field
encapsulation and usage finding.
• Award Winning Debugger: Language independent debugger core, variable
modification and watches, various breakpoints and “Fix and Continue”
mechanism.
• GUI Builder: fully WYSIWYG designer with "Test Form" feature, extensible
Component Palette pre-installed Swing and AWT components, showing a
components tree and properties, automatic code generation and full
JavaBeans support.
• Version control Support: supports command lined vcs, supplying merging
and diff tools and containing a built- in CVS client.
• XML: XML, DTD and CSS Text Editor and XML Productivity Tools Wizards to
help user generate codes.

NetBeans Extras
• NetBeans Profiler: provides information about the runtime behavior of
applications. Allows developers to monitor the thread state, CPU
performance, and memory usage of their applications. makes it easy to
track down performance problems and memory leaks.
• NetBeans Platform: provides the services common to almost all large
desktop applications such as: window, menu, settings management and
storage, file access and more.
• NetBeans Mobility Pack: used to write, test, and debug applications for the
Java Micro Edition platform (J2ME) technology-enabled mobile devices. It
integrates support for the Mobile Information Device Profile (MIDP) 2.0,
the Connected, Limited Device Configuration (CLDC) 1.1.
• The mobility pack allows for the unique “On-Phone” debugging mode.

NetBeans Matisse
• The Goal: to take the best features from OSX and VS designers and allow
the same possibilities for Java Programmers.
• In order to reach that goal there was a need to develop a new layout
manager to support all the needed functionalities.
• Matisse provides a simple and intuitive layout of GUIs without having to
understand the complexities of Swing layout managers.
• As you drag and drop components into a form, the IDE automatically
suggests alignment, spacing, and resizing constraints.
• By simply right clicking a UI Object you can add an event handler with a
method waiting to be implemented without knowing too much about the
surrounding of this object. (watch example clip in the site)

NetBeans Matisse - Advantages


• For the first time, there’s an intelligent way to build GUI for Java (unlike
eclipse), that can actually compete with the Visual Studio Gui builder.
• Supports internationalization, and industrial look-and-feel rules, which is
very important for large scale application meant to be spread world wide.
• Builds also GUI web applications, HTML, JSP, etc
• No built-in support for Drag-n-Drop or double-click events.
• Matisse’s code is protected so customizing is not very easy and not always
possible.
• Not all applications are easily built. For instance, an MDI Project is not that
trivial to build

Installation
• Installing JDK: in order to install NetBeans you need to first install JDK. You
can easily find an installation in Sun’s web site.
• NetBeans installation: you can find the installations kits for all the versions
in the NetBeans home page.
• Installation steps: you can watch a movie describing the installation step by
step in the.

• Quick Start Guide


• Starting up a project
• Creating and editing java source code
• Compiling and running a project
• Testing and debugging a project

Starting Up A Project
• When creating a new project, NetBeans already includes all the needed
packages for compiling and testing. It also outlines the sources by the right
logical directories and creates the files that are mandatory. For instance, if
you create a new java application you must implement a main class and so
it’s automatically created.

Editing and Refactoring


• When editing a code you can see the difference between the old version
and the new version when using the Code Completion tool.
• You can use “Find Usage” tool when working on a project to predict the
changes you will need to make.
• You can use refactoring to easily change places of things without going
through all the code to change it.

Building and Running


• No makefile or manual creation of an Ant file needed (by default). A simple
instruction saying which class to run and what to build will suffice.
Netbeans will create the Ant file automatically.
• While Building you can also generate the javadoc very easily.

Testing
• JUnit Tests: you simply choose the class you want to test and in the tools
menu choose “create JUnit Test”. After filling the arguments NetBeans
automatically creates a test class inheriting from TestCase with the default
methods to implement and puts everything under the Test package.

Debugging
• NetBeans has two modes, run mode and debug mode.
• The debug mode is very easy to use.
• You can use the local variables window and watch window to follow the
progress of the program.

Compiling and Running the Program


Because of the IDE's Compile on Save feature, you do not have to manually
compile your project in order to run it in the IDE.
When you save a Java source file, the IDE automatically compiles it.
The Compile on Save feature can be turned off in the Project Properties
window.
Right-click your project, select Properties. In the Properties window, choose
the Compiling tab.
The Compile on Save checkbox is right at the top.
Note that in the Project Properties window you can configure numerous
settings for your project: project libraries, packaging, building, running, etc.
To run the program:
Choose Run > Run Project.
Press F6/Shift+F6.
Click the run button from toolbar.
Click the play button from output window.
The next figure shows what you should now see.
Module 2 Study Guide

Basic Structure of a Java Program


class HelloWorld{
public static void main(String args[ ]){
System.out.println(“Hello World”);
}
}
class HelloWorld – defines a class, a template for an object of derived type HelloWorld
public – access specifier/modifier, the main method is declared public so that it is accessible as
part of the public interface of the program.
static – state of the method, it is static because it must be called before the class that hosts the
method is instantiated
void – It returns void because the Java interpreter does not expect to receive or process any
output from the class.
System.out.println( ) – The println method is one of dozens of methods in the System class. The
System class is a part of the core Java language package of the Application Programming
Interface (API)

Java Language Fundamentals


Identifiers are names that are given by the programmer as name of variables, methods or
functions, classes etc. The name used as an identifier must follow the following rules in Java™
technology:
Each character is either a digit, letter, underscore or currency symbol.
First character cannot be a digit.
The identifier name must not be a reserved word.
Java Comments are of three (3) types:
1. A single-line comment starting with //
2. A multi-line comment enclosed within /* */
3. A documentation or javadoc comment is enclosed between /** and */.
These comments can be used to generate HTML documents using the
javadoc utility, which is part of Java language comment.
JAVA DATA TYPES
Primitive Data Types
Type Width (in bytes) Min Value Max Value

byte 1 -128 127

short 2 -32768 32767

int 4 -2147483648 21474833647

long 8 Long.MIN_VALUE Long.MAX_VALUE


float 4 Float.MIN_VALUE Float.MAX_VALUE

double 8 Double.MIN_VALUE Double.MAX_VALUE

boolean (1 bit) true false

char 2 (unsigned) ‘\u0000’ ‘\uFFFF’

Derived Data Types


String
Date
Integer
Double
Long
Float

VARIABLES
Variable Declaration
Syntax: <datatype> <varName>; [= value;]
Example: String name;
int age;
double price = 55.66;
Assigning a value
Syntax: <varName> = value;
Example: name = “Maria Blanco”;
age = 22;
price = 200.50;
WRAPPER CLASSES
Java Wrapper Classes are used in converting one data type (such as a String) into another data
type (such as int or double). It is also used in wrapping a primitive value into an object.
Wrapper Class Primitive Type

Integer int

Float float

Double double

Long long

Byte byte
Short short

Character char

Boolean boolean

Basic Input and Output


In Java, you can simply use

System.out.println(); or
System.out.print(); or
System.out.printf();
System is a class
out is a public static field: it accepts output data.

class AssignmentOperator {
public static void main(String[] args) {
System.out.println("Java programming is interesting.");
}
}
Output:
Java programming is interesting.

Difference between println(), print() and printf()


print() - It prints string inside the quotes.
println() - It prints string inside the quotes similar like print() method. Then the cursor moves to
the beginning of the next line.
printf() - Tt provides string formatting (similar to printf in C/C++ programming).

Java User Input (Scanner)


The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read Strings:
import java.util.Scanner; // Import the Scanner class
public class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username: ");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
Output:
Enter username: MyUsername
Username is: MyUserName

Scanner Input Types


Module 3 Study Guide

Operators
JAVA OPERATORS
1. Unary Arithmetic Operators
2. Binary Arithmetic Operators
3. Bitwise Operators
4. Shift Operators
5. Relational and Logical Operators
6. Cast Operator
7. Assignment Operator
8. Ternary Operator

Unary Arithmetic Operators


+ Sign Operators
-

++ Increment
-- Decrement

Increment and decrement operators have two formats: postfix and prefix.

Binary Arithmetic Operators


+ Addition
Precedence Level
- Subtraction
*/%
* Multiplication
+-
/ Division
% Modulo Division

Arithmetic Operators
There are some general guidelines to consider when creating arithmetic expressions:
Use parentheses to alter precedence.
Consider the size of resulting values and possible loss of precision.
Apply arithmetic operators’ precedence level.
Arithmetic Operators
When using negative numbers with modulus calculation, drop the negative signs
from either operand and calculate the result. The sign of the left operand is the
sign of the result.

The (+) operator can be used to add numbers and String objects.
Dividing integer by zero results in the throwing of ArithmeticException
Bitwise Operators
works on integer values, by manipulating its bit-pattern equivalent.
Operator Use Operation

~ ~Op Bitwise inversion (unary)

| Op1 | Op2 Bitwise OR

& Op1 & Op2 Bitwise AND

^ Op1 ^ Op2 Bitwise EX-OR

OR logic table AND logic table

Shift Operators
performs bit manipulation on data by shifting the bits of its first operand right or
left. This table summarizes the shift operators available in the Java
programming language.

Operator Use Operation

>> op1 >> op2 shift bits of op1 right by distance op2

<< op1 << op2 shift bits of op1 left by distance op2

>>> op1 >>> op2 shift bits of op1 right by distance op2 (unsigned)

Relational Operators
compares two values and determines the
relationship between them.
Relational Operators
compares two values and determines the
relationship between them.
Logical Operators
often used with relational operators to construct more complex decision-making
expressions.
Operator Use Operation

&& Op1 && Op2 Short circuit AND


|| Op1 || Op2 Short circuit OR
& Op1 & Op2 AND
| Op1 | Op2 OR

Cast Operators
used in converting (casting) one type into another type or an object into
another object.
Syntax:
(Cast type) Value;
Example:
double dbl = 55.66;
int number = (int)dbl;
Assignment Operators
Used to assign values to a variable
Shorthand operator if combined with other operators
Example:
int a=10;
a+=10; // a = a+ 10
a-=10; // a = a- 10
a*=10; // a = a* 10
a/=10; // a = a/ 10

Ternary Operator
an operator that deals with three operands.
Syntax:
variable = condition ? value : value;
Example:
int x = 20, y = 30;
int biggerNumber = 0;
biggerNumber = x>y ? x : y;
// What do u think will be the value of the biggerNumber??
Module 4 Study Guide
Control Structures
if, else statement
switch, case statement
while loop
do, while loop
for loop

The if statement enables your program to selectively execute other statements, based on some
criteria.
The else statement performs a different set of statements if the expression is false.
Syntax:
if(condition/boolean expression) {
//codes to execute if the condition is true
}
else {
//codes to execute if the condition is false
}
The switch statement is used to conditionally perform statements based on an integer
expression.
Syntax:
switch(varName)
{
case const1: codes here; break;
case const2: codes here; break;
default: codes here; break;
}
The break statement causes the program flow to exit from the body of the switch construct.
Each case label takes only a single argument, but when execution jumps to one of these labels,
it continues downward until it reaches a break statement.

The default keyword is comparable to the else part of the if statement.


The statements associated with this keyword is executed if the value of the switch variable does
not match any of the case constants.

The while loop executes a given statement or block of statements repeatedly as long as the
value of the expression is true.
Syntax:
while(condition/expression) {
//codes to execute if condition is true
}

The do-while loop facilitates evaluation of condition or expression at the end of the loop to
ensure that the statements are executed at least once .
Syntax:
do{
//codes to execute if condition is true
} while(condition/expression);

The for loop executes a given statement or a block of statements for a definite number of
times.
Syntax:
for (initialization; condition; altering list) {
//codes to execute if condition is true
}

The foreach loop is for traversing items in a collection. foreach is usually used in place of a
standard for statement. It usually maintain no explicit counter: they essentially say "do this to
everything in this set", rather than "do this x times".
Syntax:
for(initialization : [collection/array]) {
//codes to execute if condition is true
}
Arrays

An array is a structure that holds multiple values of the same type.


The length of an array is established when the array is created (at runtime).
After creation, an array is a fixed-length structure.

First index
0 1 2 3 4 5 6 7 8 9

Array length is 10

Element at index 8
Array Declaration
Syntax:
type arrayName[ ] = new type[length];
Example:
String names[ ] = new String[5];
int [ ]grades = new int[15];
double[ ] grades;
grades = new double[2];

Array Initialization
Syntax:
type arrayName[ ] = {value,value,…};
Example:
String names[ ] ={“maria”,”blanco”,”forever”};

Storing Values in an Array


Syntax:
arrayName[index] = value;
Example:
names[0] = “John Doe”;
names[1] = “Jane Doe”;
Multi-dimesional Array
Syntax:
type[ ][ ] = new type[row][column];
Example:
int[ ][ ] = new int[5][4];
Module 5 Study Guide
Programming Model:
Procedural Programming
is a technique of solving a problem and breaking it down into smaller parts and solving
each of the smaller problems.
Procedural Programming
This model of software development is process-centric or procedural since it concentrates on
the procedures in a system.
Object-Oriented Programming

It describes the task to be performed on objects. These objects that have to be created
and stored in the computer memory, contain data and instructions to perform tasks specific to
that object.
Procedural vs. OOP
The focus of procedural programming is to break down a programming task into a
collection of variables, data structures, and subroutines
Whereas in object-oriented programming, it is to break down a programming task into
objects that expose behavior (methods) and data (members or attributes) using
interfaces.
The most important distinction is that while procedural programming uses procedures
to operate on data structures, object-oriented programming bundles the two
together, so an "object", which is an instance of a class, operates on its "own" data
structure.

Object-Oriented Programming
It uses a collection of objects interacting with each other.
One of the principal advantages of using OOP technique is that it enables programmers to
create modules that need not be changed when a new type of object is added.
Benefits of OOP:
Reduced software complexities and realistic modelling through the use of various
techniques:

Abstraction – the process of picking out the common features of objects and
procedures. This process focuses on the essential characteristics of an object.
Reduced software complexities and realistic modelling through the use of various
techniques:
Encapsulation – the process of hiding the implementation details of an object.

Software reusability by implementing inheritance. Programs are built that can be used
by several other applications.

Inheritance – allows an object to extend its characteristics to another object.

Resilience to change with the use of polymorphism.


Polymorphism – ability to process objects differently depending on their data type or class.

A class is a template or blueprint that defines an object’s attributes and operations


and that is created at design time
An object is a running instance of a class that consumes memory and has a finite
lifespan
Object Relationships:
Association – exists when an object contains a reference to another object. Referred to as the
“has a” relationship

superclass (base class) – the parent class from which properties are inherited by
another class
subclass (derived class) – a new class with properties taken from a parent class
abstract class – a well-encapsulated conceptual class. The objects of this class do not
exist in real world

Unified Modeling Language (UML)


UML is a general-purpose notational language used for specifying and visualizing
complex software, usually large object-oriented project. It uses several types of diagrams such
as the case diagram, class diagram, and state chart diagram.

Class Diagram
A class diagram is used to describe the attributes and behaviours of objects in the
system.

Attributes and Operations:


Attributes are the data contained in a class
Operations are the actions performed on that data
Accessibility: Public (+), Private (-), Protected (#)
UML Access Modifier Symbols
+ - public
- - private
# - protected
~ - package
““ - no symbol indicates default access
italics - represents abstract class method
underline – represents static method or attribute
Declaring Classes
A class definition is consist of several constructs for defining and declaring the following:
1. Attributes – declared either at the start or end of a class definition. These variables
identify the data stored in the object.
2. Constructor – a method that is automatically executed when an object is created. This
method is used to initialize the attributes.
3. Standard Methods – used to change or access the private data in an object.
• Mutator (Setter) – a method that is used to change the data.
• Accessor (Getter) – a method that is used to access or retrieve data.
4. Custom Methods – implement the business rules for which the application is being
developed.

Class Name

Attributes attributes declaration

Operations or constructor definition


Methods
standard methods definition
custom methods definition

Steps in Declaring Classes:


1. Define the class name
2. Declare the attributes
3. Create constructor
4. Create standard methods
5. Create custom methods
Classification of Variables:
1. Instance Variables (non-static fields) –variables stored in each object of a class,
usually referred to as the non-static member fields of a class.

2. Class Variables (static fields) –variables stored in the class and are available to all
objects of a class or objects of other classes if access is permitted, usually referred to as the
static members of the class.

3. Local Variables (method variables or local data) – data used in a method. This data is
temporary and does not exist once the method has completed execution.
Module 6 Study Guide
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from
users. To achieve this, you must:
• declare class variables/attributes as private (only accessible within the same class)
• provide public setter and getter methods to access and update the value of
a private variable
Get and Set
Private variables can only be accessed within the same class (an outside class has no
access to it)
However, it is possible to access them if we provide public getter (accessor)
and setter (mutator) methods.
The get method returns the variable value, and the set method sets the value.
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from outside this
class.

Why Encapsulation?
Better control of class attributes and methods
Class variables can be made read-only (if you omit the set method), or write-only (if you
omit the get method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data

Inheritance
The technique of deriving new class definitions from an existing class definition.
The following are the benefits of using class inheritance in OOP:
Re-use of predefined and well-tested classes
Standardization of behaviors across a group of classes
Ability to use members of a family of classes interchangeably in methods

Superclasses and Subclasses


Superclass is the class from which another class inherits properties. This is a class that is
on top of a hierarchy.
Subclass is a class that inherits all the non-private attributes and methods, except
constructors from a superclass. This class has the ability to override methods of
the superclass.
Types of Inheritance:

Take Note:

Java does not support multiple inheritance, however, Java provides same effects and
benefits of multiple inheritance through the use of interface.

The this and the super Keywords:

this – contains a reference to the current object being constructed. It represents an


instance of the class in which it appears. It can be used to access class variables and
methods.
Module 7 Study Guide
Polymorphism and Abstraction

Polymorphism is the ability of objects belonging to different types to respond to


methods of the same name, each one according to the right type-specific behavior.
It is the ability to redefine methods for derived classes.
Implementing Polymorphism
1. Method Overloading
Using one method identifier to refer to multiple functions in the same class, In the Java
programming language, methods can be overloaded but not variables or operators.
Method Overloading
Constructor Overloading
- creating more than one constructor in a class
Method Overloading
- creating multiple methods having same name in one class.

2. Method Overriding
Providing a different implementation of a method in a subclass of the class that originally
defined a method.
Overloading Overriding
Overloaded functions supplement each other. Overriding function replaces the function it
overrides.

Overloaded functions can exist, in any number, Each function in a base class can be overridden
in the same class. at most once in any one derived class.

Overloaded functions must have different Overriding functions must have argument lists
argument lists. of identical type and order.

The return type of an overloaded function may The return type of an overriding method must
be chosen freely. be identical to the function it overrides.

This ability of our reference to change behavior according to what object it is holding is called
polymorphism. Polymorphism allows multiple objects of different subclasses to be treated as
objects of a single superclass, while automatically selecting the proper methods to apply to a
particular object based on the subclass it belongs to.
Abstraction
The Abstract Class and Interface:

Abstract Class – contains one or more abstract methods and, therefore, can never be
instantiated. It is defined so that other classes can extend them and make them
concrete by implementing the abstract methods.

Syntax for Declaring Abstract Class:

Take Note:

All abstract classes are public by default and cannot be instantiated. Constructors and
public methods cannot be declared as abstract.

An abstract class is a class that cannot be instantiated. It often appears at the top of an object-
oriented programming class hierarchy, defining the broad types of actions possible with objects
of all subclasses of the class.
Those methods in the abstract classes that do not have implementation are called
abstract methods.

Coding Guidelines:
Use abstract classes to define broad types of behaviors at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of the
abstract class.
Interfaces
An interface is a special kind of block containing method signatures (and possibly constants)
only. Interfaces define the signatures of a set of methods without the body.
Interfaces define a standard and public way of specifying the behavior of classes. They allow
classes, regardless of their location in the class hierarchy, to implement common behaviors.
Note that interfaces exhibit polymorphism as well, since program may call an interface method
and the proper version of that method will be executed depending on the type of object passed
to the interface method call.

Interface – an abstract class that represents a collection of method definitions and constant
values. It can later be implemented by classes that define the interface using the implements
keyword.
Why do we use Interfaces?
We need to use interfaces if we want unrelated classes to implement similar methods.
Thru interfaces, we can actually capture similarities among unrelated classes without artificially
forcing a class relationship.
Another reason for using an object's programming interface is to reveal an object‘s
programming interface without revealing its class.
As we can see later on the section Interface vs. Classes, we can actually use an interface as data
type.
Finally, we need to use interfaces to model multiple inheritance which allows a class to have
more than one superclass.
Multiple inheritance is not present in Java, but present in other object-oriented languages like
C++.

Interface vs. Abstract Class


The following are the main differences between an interface and an abstract class:
interface methods have no body,
an interface can only define constants and
an interface have no direct inherited relationship with any particular class, they are defined
independently.

Interface vs. Class


One common characteristic of an interface and class is that they are both types. This means
that an interface can be used in places where a class can be used.
For example, given a class Person and an interface PersonInterface, the following declarations
are
valid:
PersonInterface pi = new Person();
Person pc = new Person();
However, you cannot create an instance from an interface. An example of this is:
PersonInterface pi = new PersonInterface(); //COMPILE
//ERROR!!!

Another common characteristic is that both interface and class can define methods.
However, an interface does not have an implementation code while the class have one.

When your class tries to implement an interface, always make sure that you implement all the
methods of that interface, or else, you would encounter this error,
Coding Guidelines:
Use interfaces to create the same standard method definitions in may different classes.
Once a set of standard method definition is created, you can write a single method to
manipulate all of the classes that implement the interface.

Relationship of an Interface to a Class

As we have seen in the previous section, a class can implement an interface as long as it
provides the implementation code for all the methods defined in the interface.
Another thing to note about the relationship of interfaces to classes is that, a class can only
EXTEND ONE super class, but it can IMPLEMENT MANY interfaces.

Interfaces are not part of the class hierarchy.


However, interfaces can have inheritance relationship among themselves.
Module 8 Study Guide

EXCEPTION
Exception denotes an abnormal event that occurs during the execution of the program
and disrupts its normal flow.
CONCEPTS OF EXCEPTION
1. When an error occurs within a method, the method creates an object called exception
object and hands it off to the runtime system.
2. Exception object contains information about the error, including its type and the state of
the program when the error occurred.
3. Creating an exception object and handing it to the runtime system is called throwing an
exception.
4. After a method throws an exception, the runtime system attempts to find a list of
methods, called the call stack to handle it.
5. The runtime system searches the call stack for a method that contains a block of code
that can handle the exception called exception handler.
6. When an appropriate handler is found, the runtime system passes the exception to the
handler. An exception handler is considered appropriate if the type of the exception
object thrown matches the type that can be handled by the handler.
7. The exception handler chosen is said to catch the exception. If the runtime system
exhaustively searches all the methods on the call stack without finding an appropriate
exception handler, as shown in the next figure, the runtime system (and, consequently,
the program) terminates.

Exception-Handling Keywords

try
catch
throw
throws
finally
Exception-Handling Techniques

Declare the exception


The programmer can declare that he is aware of the exception by including the clause
throws <name-of-exception>. This is the specific requirement of the Java language.
Exception-Handling Techniques

Handle the exception


This is the catch requirement of the Java language. Handle the exception by enclosing
the code in a try-catch block.
Exception-Handling Techniques

Re-throw the exception and declare this in the method signature


Use the try-catch block to catch the exception and re-throw the exception to another
subclass of the exception. In this event, the programmer is passing the exception up the call
stock.
The try / catch and finally Blocks

try{
//codes that may throw exception
}
catch(ExceptionType e1){
//codes that handle exception e1
}
catch(ExceptionType e2){
//codes that handle exception e2
}
finally{
/*codes to execute whether or not errors are
encountered*/
}

Exceptions thrown during execution of the try block can be caught and handled in a
catch block.
The code in the finally block is always executed.

The following are the key aspects about the syntax of the try-catch-finally construct:
• The block notation is mandatory.
• For each try block, there can be one or more catch blocks, but only one finally block.
• The catch blocks and finally blocks must always appear in conjunction with the try
block, and in the correct order.

• A try block must be followed by at least one catch block OR one finally block, or both.
• Each catch block defines an exception handle. The header of the catch block takes
exactly one argument, which is the exception its block is willing to handle. The
exception must be of the Throwable class or one of its subclasses.

The throw and throws Statements


public void methodName throws ExceptionList
{
//statements
throw ThrowableInstance;
}

where:
ExceptionList – list of exception types separated by comma
ThrowableInstance – an instance (object) of an exception

Common Predefined Exceptions


ArithmeticException – is thrown when an exceptional arithmetic condition occurred
such as dividing integers by zero.

NullPointerException – is thrown when an application attempts to use a null object


that has not been initialized or instantiated.
ArrayIndexOutOfBoundsException – is thrown when an attempt is made to access an
element in the array that is beyond the index of the array.
User-defined Exceptions
Steps on how to create and use customized exceptions:
1. Create a class that extends from Exception.
2. In a method of another class, throw a new instance of the Exception.
3. Use the method that throws exception in a try-catch block.

Assertions
An assertion is a statement in Java that enables you to test your assumptions about
your program.
Each assertion contains a boolean expression that you believe will be true when the
assertion executes.
By verifying that the boolean expression is indeed true, the assertion confirms your
assumptions about the behavior of your program, increasing your confidence that the
program is free of errors.
Types of Assertion:
Pre-condition – an assertion which invokes when a method is invoked.
Post-condition – an assertion which invokes after a method finishes.
The assertion statement has two forms:
The first is:
assert Expression1;
where: Expression1 = boolean expression.
When the system runs the assertion,
it evaluates Expression1 and if it is false throws an AssertionError with no details.

Enabling assertions onNetBeans


To enable runtime assertion checking in NetBeans IDE, simply follow these steps:
1. Look for the project name in the Projects panel on the left. Right click on the
project name or icon.
2. Select Properties. This is the last option of the drop-down menu.
3. Click on Run from the Categories panel on the left.
4. Enter -ea for VM Options text field.
5. Click on OK button.
6. Compile and run the program as usual.

Complex Assertion Form


Use the second version of the assert statement to provide a detailed message for the
AssertionError.
The system passes the value of Expression2 to the appropriate AssertionError
constructor, which uses the string error message.

Complex Assertion Form


The purpose of the message is to communicate the reason for the assertion failure
Don’t use assertions to flag user errors.
When an Assertion Fails
Assertion failures are labeled in stack trace with the file and line number from which
they were thrown.
Second form of the assertion statement should be used in preference to the first when
the program has some additional information that might help diagnose the failure
When To Use Assertions
Internal Invariants
Many programmers use comments to indicate programming assumptions.
if (i % 3 == 0) { ... }
else if (i % 3 == 1) { ... }
else { // We know (i % 3 == 2)
... }
When To Use Assertions
Now we can use assertions to guarantee the behavior.
if (i % 3 == 0) { ... }
else if (i % 3 == 1) { ... }
else { assert i % 3 == 2 : i; ... }

To run the example:


Compile the example with:
javac AssertionExample.java

Run the example with:


java -ea AssertionExample

To enable assertions at runtime,


-ea command-line option is used
Module 9 Study Guide

Collections
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet).

Collection
What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
It provides readymade architecture.
It represents a set of classes and interfaces.
It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:
Interfaces and its implementations, i.e., classes
Algorithm
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for the Collection
framework.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.
It contains only one abstract method. i.e.,

Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean
addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of
Collection interface.

List Interface
List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have duplicate
values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.

ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion
order and is non-synchronized. The elements stored in the ArrayList class can be
randomly accessed.

LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements. It maintains the insertion
order and is not synchronized. In LinkedList, the manipulation is fast because no
shifting is required.
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of
Collection framework.
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure,
i.e., Stack. The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o), which defines
its properties.
Queue Interface

PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue.
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables
us to perform the operations at both the ends.
Deque can be instantiated as:
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
Unlike queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store the
duplicate items. We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet.
Hashset
HashSet class implements Set Interface. It represents the collection that uses a hash
table for storage. Hashing is used to store the elements in the HashSet. It contains
unique items.
Linked Hashset
LinkedHashSet class represents the LinkedList implementation of Set Interface. It
extends the HashSet class and implements Set interface. Like HashSet, It also contains
unique elements. It maintains the insertion order and permits null elements.
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its
elements. The elements of the SortedSet are arranged in the increasing (ascending)
order. The SortedSet provides the additional methods that inhibit the natural ordering
of the elements.
The SortedSet can be instantiated as:
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements. However, the access and retrieval
time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
Module 10 Study Guide
InputStream and OutputStream

Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
OutputStream
Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.

OutputStream Class
Java OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts output bytes
and sends them to some sink.

InputStream class is an abstract class. It is the superclass of all classes representing an


input stream of bytes.
Useful methods of InputStream

Java FileOutputStream is an output stream used for writing data to a file.


If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream class.
But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
FileOutputStream class declaration for Java.io.FileOutputStream class:

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can also
read character-stream data. But, for reading streams of characters, it is recommended
to use FileReader class.
FileInputStream class declaration for Java.io.FileInputStream class:

FileWriter and FileReader

Java FileWriter class is used to write character-oriented data to a file. It is character-


oriented class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array because
it provides method to write string directly.
Java.io.FileWriter

Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class.
It is character-oriented class which is used for file handling in java.
Java.io.FileReader

You might also like