Download as pdf or txt
Download as pdf or txt
You are on page 1of 154

What is

operator?

02

03
Thank You Miscellanous
Operator
04
Relational instanceof
Operator Operator

Logical I/D Bitwise


Operator Operator Operator
Arithmetic
Operator Conditional
Assignment
Operator
Operator
- /
*
Subtraction
Division

Addition Modulo Operation


Multiplication or
Remainder After Division
2-3 gives -1
15-7.2 gives 7.8
20-5 gives 15

Thank You
6/-2 gives -3
15/7.5 gives 2.0
20/3 gives 6
<= > >=
==
Greater
Less than Than
Or equals Not Equals
Greater Than
Less than
Or Equals
Equals
Thank You int a=10,b=5;
a>=10 gives true
a>=b gives true

int a=10,b=5;
a!=10 gives false
a!=b gives true
||

Logical AND Logical NOT


Logical OR
Example?
variable=condition?value1:value2;
|

~
OR Unsigned
Right Shift

XOR Left Shift

AND Right Shift

NOT
Bitwise int a=10;
Left Shift ? 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
a<<2;
Control Statements

Such statements which are used to control the flow of execution of other statements
in our program are called as control statements.

Control Statements

Conditional Selection
Looping
Branching Statement

Nested if If else switch for while Do while For each


if If else
else ladder
Conditional Branching

In conditional branching statements we create the branches of statements using the conditions. It is used to control
execution of statements according to the conditions. We have following conditional branching statements in java:

• if statement
• if else statement
• Nested if else statement
• if else if ladder
If (booleanexpression)
{
If block statements;
}

Note : When boolean expression is true then statements


of if block are executed,
if boolean expression yields false then statements of if
block are not executed.
We can avoid curly brackets when we control only a
single statement using if.
If require boolean
If (arithmeticexpression) expression
{
statements;
}

Note :if we use any expression


that yields a number,
inside the paranthesis of if,
then it is a compilation error in
java.
Program to check number is odd or even ?
class OddOrEven
{ public static void main(String args[])
{ java.util.Scanner sc=new java.util.Scanner(System.in);
//We can use full qualified path of a class, instead of importing it.
int n;
System.out.println("Enter a number ");
n=sc.nextInt();
if(n%2==0)
System.out.println(n+" is a even number ");
if(n%2!=0)
System.out.println(n+" is a odd number ");
}
}
If (booleanexpression)
{
If block statements;
}
else
else
{
block statements;
}
Note : When boolean expression is true then statements of if block are executed.
if boolean expression yields false then statements of else block are executed.
We can avoid curly brackets when we control only a single statement using if else.
If you put a semicolon (;) after the parenthesis of if block in a if statement then the if is
considered as body less.
Eg :
if(booleanexpression);
{
_______________;
_______________;
_______________;

Note : The statement of block after if will be executed whether the boolean expression is true or false.
If you put a semicolon (;) after the parenthesis of if in if else statement then it is a compilation error.
Eg :
if(booleanexpression);
{
_______________;
_______________;
_______________;

}
else
{
_______________;
_______________;
_______________;
_______________;

}
We can not give condition with else keyword, if we do so then it is a compilation error.

Eg :
if(booleanexpression)
{
_______________;
_______________;
_______________;

}
else(booleanexpression)
{
Error
_______________;
_______________;
_______________;
_______________;

}
When we use an if else inside another if else then it is called as nested if else. It is used when we want to execute
statements after checking multiple conditions.
The inside if else is considered as a single statement for the outer if else.
So a if statement contains a if else statement inside it then we can omit the {} of outer if .
Syntax :
If(booleanexpression)
{ if(booleanexpression)
{ ____________;
}
else
{ ____________;
}
}
else
{ if(booleanexpression)
{ ____________;
}
else
{ ____________;
}
}
In if else ladder we use several if else one after another. Its syntax looks like a ladder.
If(condition1)
{ _______________;
}
else
if(condition2)
{_______________;
}
else
if(condition3)
{_______________;
}
else
{_______________;
}
In Ladder if condition1 is true then its related statements are executed, condition2 and condition3 will not be evaluated.
Condition2 is checked only when condition1 is false, similarly condition3 is checked only when condition1 and condition2 both
are false. In short a condition is checked only when its previous condition is false. The last else part is executed only when all the
conditions are false. Last else is not compulsory it is used when required.

Trainings 7742817777
It is also called as selection statement. It is used to execute statement according to the value of a variable. It is also called as M-
way branching. It works with Integers , Characters and String in java.

Syntax:
switch(var)
{ case value1:
statement;
break;
case value2:
statement;
break;
case value3:
statement;
break;
default:
statement;
break;
}

Trainings 7742817777
1.The break causes exit from the switch after executing statements of a case. If we omit to use break after every
case statement then all the cases including default are executed , from the case whose value is matched with switch
expression.
2. Case values must be constant and unique. No two case can have same values.
3.Default is optional. Generally it is used as last case. If we use default as last case then break is not compulsory after statements
of default, but if we use it in middle or beginning of switch then it should be followed by a break.
4. In java switch statement can be used with integers , strings , character and wrapper classes.

Trainings 7742817777
Looping is the ability of programming which provides the facility to repeat the statements again and again until a
given condition is false.
Looping is also called as iteration or repetition.
We have following four loops in java
1. for loop
2. while loop
3. do while loop
4. for each loop

Trainings 7742817777
Syntax:
for(initialization;booleanexpression;inc/dec)
{
______________________;
______________________; Body of loop
______________________; Enclosed in { }

Note: The initialization is performed only once. If boolean expression is true then statements of body are executed, after
executing body inc/dec is performed. After inc/dec boolean expression is tested again.
The above process is repeated again and again until the condition is false.

Trainings 7742817777
Syntax:
Initialization;
while(booleanexpression)
{ _________________;
_________________;
Body of loop
_________________;
Enclosed in { }
_________________;
inc/dec;

1. The initialization is executed first and once only.


2. After initialization condition of loop is evaluated. If the condition is true then body of loop is executed.
3. After execution of loop body inc/dec is performed.
Note: Step 2 and 3 are repeated until the condition of loop is false.

Trainings 7742817777
Syntax:
Initialization;
do
{ _________________;
_________________;
Body of loop
_________________;
Enclosed in { }
_________________;
inc/dec;
} while(booleanexpression);

1. The initialization is executed first and once only.


2. After initialization body of loop is executed.
3. After execution of body inc/dec is performed.
4. After inc/dec the condition is tested, If the condition is true then body of loop is executed, otherwise loop is terminated.
Note: while and for loops are top checker loops, it means they test condition before executing the body. Unlike them, do while
loop is down checker loop, it test condition after executing the body. So do while loop executes its statements at least once.

Trainings 7742817777
When we use a loop inside another loop, then it is called as nested loop.
Generally, nested loop is used to print patterns etc.
We can use for inside for, for inside while, for inside do while. It means we can use any loop inside the other loop.
Generally we use for loop inside for loop to print patterns.

Syntax:
for(init;condition;i/d)
{ for(init;condition;i/d)
{
______;
______;
______;
}
}

Trainings 7742817777
What is an array?
Array is a collection of multiple value of same datatype. Actually array allows us to store multiple values under a same name.
To create an array we use following syntax in java:
datatype []arr=new datatype[size];
E.g. int []arr=new int[5];
In the above example the arr is called as array reference variable and memory is provided to arr using the new operator,
here we are creating array of 5 integers and storing it into the arr. By default array elements are initialized with 0.
Initializing an Array
Java provides the means of declaring , constructing , and explicitly initializing an array in one declaration statement :
datatype []arrayname={arrayinitializationlist};
E.g. int []arr={10,20,30,40,50};
The array arr is declared as an array of integers.
It is constructed to hold 5 element.
The expression in the arrayinitializationlist are evaluated from left to right.
We can put a , at the end in initialization list.

Trainings 7742817777
In java all the array supports length property which gives size of the array, size means how many elements can be stored
in the array.
Individual elements of array are accessed using the index numbers.
Index number starts with 0. Index number of nth element is n-1.
The following example demonstrates how to create an array and print all the elements of the array.

int a[]={10,20,30,40,50};
for(int i=0;i<a.length;i++)
System.out.print(a[i);

Points to remember
What is difference in both statements:
1. int a[],x;
2. int []a,x;
In the first declaration a is a reference to array while x is an int variable.
In the second declaration a and x both are reference to array.

Trainings 7742817777
Points to remember
• The array object is referenced by the array name, but individual array elements are accessed by specifying an index with
the [] operator.
• Each element is treated as a simple variable of the element type.
• The value of index is automatically checked at runtime to ensure that it is within the array index bounds.
If the index value is less than 0 , or greater than or equal to array length , an ArrayIndexOutOfBoundsException is generated.
• If you try to create an array with negative size then NegativeArraySizeException is generated.
For eg:
1. int a[]=new int[3];
2. a[3]=30;
Line number 2 will generate an ArrayIndexOutOfBoundsException at runtime.
3. int a[]=new int[-2];
Line number 3 will generate NegativeArraySizeException at runtime.

Trainings 7742817777
An array of arrays is also called as Multidimensional array. We use following syntax to create array of array.
Elementtype [][]…[]arrayname;
Or
Elementtype arrayname[][]…[];
The following declarations are equal :
• int mArr[][];//2-dimensional array
• int [][]mArr;//2-dimensional array
• int []mArr[];//2-dimensional array
We can combine declaration with construction like following :
int mArr[][]=new int[3][3];//2-dimensional array of 3X3

The mArr is shown in diagram on next slide :

Trainings 7742817777
mArr

0 1 2

Trainings 7742817777
To create methods in java we use following syntax :
Returntype methodName(<arguementList>)
{ ___________________;
___________________;
___________________;
___________________;
<return value;>
}
Note : 1. In java all the methods are member of a class or interface. A static
member methods can call other static member of the class only.
2. In java variables are always passed by value but array and objects are passed
by reference.
A class denotes a category of objects, and acts as a blueprint for creating such objects.
A class models an abstraction by defining the properties and behaviors for the objects
representing the abstraction.
An object exhibits the properties and behaviors defined by its class. The properties of
an objects of a class are also called attributes, and are defined by fields in Java.
A field in a class is a variable which can store a value that represents a particular
property of an object.
The behaviors of an object of a class are also known as operations, and are defined
using methods in Java. Fields and methods in a class declaration are collectively called
members.

An important distinction is made between the contract and the implementation that a
class provides for its objects.
The contract defines what services, and the implementation defines how these
services are provided by the class.
Clients (i.e., other objects) only need to know the contract of an objects, and not its
implementation, in order to avail themselves of the object’s services.
Example on next slide shows the
declaration of the class Student depicted in
Student class diagram 1.
A class declaration consists of a series of
name member declarations. In the case of the
Fields age
class Student, It has following three fields
rollNumber
• name is a String object to hold name of
getName()
the student.
getAge() • age is a integer variable to hold age of
Methods student.
getRoll()
printDetails() • rollNumber is a integer variable to hold
roll number of the student.
The class Student have four methods
getName(),getAge(),getRoll(), and
Class Diagram 1 printDetails().
class Student//class name
{ //class declarations
//Fields
private String name;
private int age,rollNumber;

//Constructor
public Student(int a,int r,String n)
{name=n; age=a; rollNumber=r;}

//Methods
public int getAge(){ return age; }
public int getRollNumber(){ return rollNumber; }
public String getName(){ return name; }
public void printDetails()
{ System.out.println(“Name \t : \t”+name);
System.out.println(“Roll number \t : \t”+rollNumber);
System.out.println(“Age \t : \t”+age);
}

}
Class instantiation, Reference Values, and References
The process of creating objects from a class is called instantiation. An object is an
instance of a class.
The object is constructed using the class as a blueprint and is a concrete instance of
the abstraction that the class represents.
An object must be created before it is used in the program.

A reference value is returned when an object is created.


A reference value denotes a particular object.
An object reference (or simply reference) is a variable that can store a reference value.
A reference thus provides a handle to an object, as it can indirectly denote an object
whose reference value it holds.
In java, an object can only be manipulated via the reference value, or equivalently by a
reference that holds its reference value.

The process of creating objects usually involves the following steps :


1. Declaration of a variable to store the reference value of an object.
This involves declaring a reference variable of the appropriate class to store the
reference value of the object.
//Declaration of two reference variables that will refer to two distinct objects
Student s1,s2;

2. Creating an object
This involves using the new operator in conjunction with a call to a constructor , to
create an instance of the class.

//create two distinct Students


s1=new Student(33,12345,”Tarun Verma”);
s2=new Student(29,21456,”Nitin Khatri”);

The new operator creates an instance of Student class and returns the reference value
of this instance.
The reference value can be assigned to a reference variable of the appropriate class.
The reference variable can then be used to manipulate the object whose reference
value is stored in the reference variable.
Each object has its own copy of fields declared in the class declaration.
The two students, referenced by s1 and s2, will have their own name, age, and
rollNumber fields.

The purpose of the constructor call on the right side of the new operator is to initialize
the newly created object.
In this particular case, for each new student instance created using the new operator,
we pass arguments.
The constructor initializes all the fields.

The declaration of a reference and the instantiation of the class can also be combined,
as in the following declaration statement:
Student s1=new Student(26,12345,”Tarun Verma”);

Object Aliases
An object can be referred by several references, meaning that they store the reference
value of same object.
Such references are called as aliases.
The object can be manipulated by any one of its aliases, as each one refers to the same
object.
In the following example a single student object, is referenced by both s1 and s2
references, so they are alias of each other.
They will have same name, age, and rollNumber fields because they are pointing to
same object in the memory.

Student s1=new Student(40,45784,“Arun”);


Student s2=s1;

The following diagram explains this:

name:Arun
s1 roll:45784
age:40

s2
Instance members
Each object created will have its own copies of fields defined in its class.
The fields of an object are called as instance variables.
The value of instance variables in an object comprise its state. Two distinct objects can
have the same state, if their instance variables have same values.
The methods of an object define its behavior.
These methods are called as instance methods. Instance variables and instance
methods, which belongs to an object are called as instance members.
Invoking methods
Objects communicate by message passing.
This means that an object can be made to exhibit a particular behavior by sending the
appropriate message to the object.
In java, this is done by calling a method on the object using the binary infix dot(.)
operator.
A method call spells out the complete message: the object that is the receiver of the
message, the method to be invoked, and the arguments to the method, if any. The
method invoked on the receiver can also send information back to the sender, via a
single return value.
The method called must be one that is defined for the object, otherwise compiler
reports an error.
Student s1=new Student(26,12345,”Tarun Verma”);//Create a student
int a= s1.getAge();//getAge() is called and age of s1 will be returned and stored into a
s1.printDetails();//details of s1 will be printed
s1.setData();//Compile time error: no such method in Student
Lifetime of variables
We distinguish between lifetime of variables in following three context:
• Instance variable : are member of a class and created for every object of the class.
In other words, every object of class will have its own copies of these variables,
which are local to the object. The values of these variables at any given time
constitute the state of the object. Instance variables exist as long as the object they
belong to is in use at runtime.
• Static variable : are also members of a class, but not created for any specific object
of the class and, therefore, belong only to the class. They are created when the class
is loaded at runtime, and exist as long as class is available at runtime.
• Local variable : (also called as method automatic variables)are declared in methods,
constructors, blocks; and created for each execution of method, constructor, or
block. After the execution of the method local variables are no longer available.
As we can create an array reference for primitive types, similarly we can also create an
array of references for objects. To declare array of references we use following steps:

1. Declaring array variable

Classname arraname[];

2. Constructing an array

arrayname=new Classname[size];

3. Initializing elements

for(int i=0;i<arrayname.length;i++)
{
arrayname[i]=new Classname();
}
Each method has a signature, which comprises the name of the method, and types
and order of the parameters in the formal parameter list.
Several method implementations may have the same name, as long as the method
signature differs.
This is called as method overloading. Since overloaded methods have the same name,
their parameter lists must be different.
Rather than inventing new method names, method overloading can be used when the
same logical operation requires multiple implementations.
The java standard library makes heavy use of method overloading. For example, the
class java.lang.Math contains an overloaded method min(), which returns the
minimum of two numeric values.
In the following examples, three implementations of the method show() are shown:
• public static void show(int a)
• public static void show(int b,int c)
• public static void show(double a,double b)
The corresponding signatures of three methods are as follows :
show(int )//number of parameters
show(int,int) //number of parameters 1,2
show(double,double) //type of parameters 2,3

Consider the following two declarations:


void bake(Cake large);
void bake(Cake small);

The above two methods are not overloaded and they are ambiguous because
changing only the parameter name does not work in overloading.

Also consider the following two declaration :


int halfIt(int x);
double halfIt(int y);

The above two methods are not overloaded and they are ambiguous because
changing the return type does not work in overloading.
The main purpose of constructor is to set the initial state of an object, when the
object is created using new operator.

A constructor has the following general syntax :


accessibility_modifier classname (formal_parameter_list)
{ //constructor body
}

Constructor declarations are very much like method declarations. However, the
following restrictions on constructors should be noted:
• Modifiers other than accessibility modifiers are not permitted in the constructor
header.
• Constructors cannot return a value and, therefore, do not specify a return data type,
not even void, in the constructor header. But their declaration can use the return
statement that does not return a value in constructor body. If we explicit specify a
return type for constructor then it is treated as a member function in java , instead of
constructor.
• The constructor name must be the same as the class name.
The default constructor
A default constructor is a constructor without any parameters, i.e. it is a no parameter
constructor. It has the following signature:

classname()

If a class does not specify any constructor ,then an implicit default constructor is
generated for the class by the compiler. The implicit constructor is equivalent to the
following implementations :
classname()
{
super();
}

The only action taken by the implicit default constructor is to call the super-class
default constructor. This ensures that the inherited state of the object is initialized
properly. In addition, all instance variables in the object are set to the default value of
their type.
In the following code, the class Light does not specify any constructors.
class Light
{
//Fields
int noOfWatts;
boolean indicator;
String location;
}
class GreenHouse
{ public static void main(String args[]){
Light oneLight=new Light();}
}
In the code above, the following implicit default constructor, will initialize the fields of
the object to their default initial values. noOfWatts will store 0, indicator will store
false and location will store null.

A class can choose to provide an implementation of the default constructor. In the


following example, the class Light provides an explicit default constructor. Note that it
has the same name as class, and does not specify any parameter.
class Light
{
//Fields
int noOfWatts;
boolean indicator;
String location;
Light()
{
noOfWatts=20;
indicator=true;
location=“XYZ”;
}
}
class GreenHouse
{ public static void main(String args[]){
Light oneLight=new Light();}
}
In the previous example, the explicit default constructor ensures that any object
created with the object creation expression new Light(), will have it fields noOfWatts,
indicator, and location initialized to 20, true, XYZ, respectively.

If a class provides any explicit constructors, it can no longer rely on the implicit default
constructor to set the state of its objects. If such a class requires a default constructor ,
its implementation must be provided.

Parameterized constructor
In the next example we will define a parameterized constructor for the class Light. A
parameterized constructor simply takes arguments. As the class only have
parameterized constructor any attempt to call the default constructor will be flagged
as an error by the compiler.
class Light
{
//Fields
int noOfWatts;
boolean indicator;
String location;
Light(int noOfWatts,boolean indicator, String location)
{//this keyword is used to differentiate between instance and local variables
this.noOfWatts = noOfWatts ;
this.indicator = indicator ;
this.location = location;
}
}
class GreenHouse
{ public static void main(String args[]){
Light oneLight=new Light(1500,true,”Bikaner”);//OK
Light twoLight=new Light();//Compilation Error}
}
Constructor Overloading
Like methods, constructors can also be overloaded. Since the constructors in
a class all have the same name as the class, their signatures are differentiated by their
parameter lists. In the following example we are overloading the constructor of Light
class :
class Light
{ //Fields
int noOfWatts;
boolean indicator;
String location;
Light()
{ noOfWatts=0 ; indicator=false; location=“N.A.”; }
Light(int noOfWatts,boolean indicator, String location)
{ this.noOfWatts=noOfWatts ;this.indicator=indicator;this.location=location;
}
}
class GreenHouse
{ public static void main(String args[]){
Light oneLight=new Light(1500,true,”Bikaner”);
//Calls parameterized constructor
Light otheroneLight=new Light();
//Calls default constructor}
}
A fixed arity method must be called with the same number of actual parameters (also
called arguments) as the number of formal parameter specified in its declaration.
If the method declaration specifies two formal parameters, every call of method must
specify exactly two arguments. We say that the arity of this method is 2.
In other words arity of such a method is fixed, and it is equal to the number of formal
parameters specified in the method declaration.

Java also allows declaration of variable arity methods; meaning that the number of
arguments in its call can be varied.
Invocation of such a method may contain more actual parameters than formal
parameters.

The variable arity parameter in method declaration is represented by the …(ellipsis).


It have following syntax:
<return-type> <methodname>(<type>…<parameter-name>)
{
}
The ellipsis(…) is specified between type and the formal parameter name.
The type can be a primitive data-type , a reference type.
Whitespaces can be specified on both sides of ellipsis.
Such a parameter is called a varargs parameter.
Apart from the vararg parameter , a variable arity method is identical to a fixed arity
method.

The method show() below is a variable arity method:

public void show(int … x)


{ for(int y:x)
{ System.out.println(y);
}
}

The vararg parameter in a variable arity method is always interpreted as array. So in


method show() x is treated as a simple array of integers.
Only one vararg parameter is permitted in the formal parameter list, and it is always
the last parameter in the formal parameter list.
Given that the method declaration have n formal parameters, and the method call has
k actual parameters, k must be equal to or greater than n-1.
The last k-n+1 actual parameter are evaluated and stored in an array whose reference
value is passed as the value of actual parameter.

Calling a varargs method

show(10,20);
show();
show(10,20,30,40,50);
The java command executes a method called main() in the class specified on the
command line. Any class can have a main() method, but only the main() method of the
class specified in the java command is executed to start a java application.

The main method must have public accessibility so that the interpreter can call this
method. It is a static method belonging to the class, so that no object of the class is
required to start the execution. It does not return a value, that is, it is declared void. It
always has an array of String objects as its only formal parameter. This array contains
any arguments passed to the program on the command line. The following method
header declarations fit the bill, and any one of them can be used for the main()
method:
public static void main(String []args)
public static void main(String …args)
public static void main(String args[])

The main method can be overloaded like any other method. The JVM ensures that the
main() method having the above method header is the starting point of program
execution.
Any arguments passed to the program on the command line can be accessed in the main() method of the class
specified on the command line.

These arguments are called as Program Arguments or Command Line Arguments.

>java MyProg Tarun Arun Aman Ajay

Note that the command name, java, and the class name MyProg are not passed to main() method.

Since the formal parameter of main() method is an array of String objects, individual String elements in the array can
be accessed by using [] operator.

When no arguments are specified on the command line, an array of zero String element is created and passed on
the main() method. This means that the reference value of the formal parameter is never null.

For online training contact us at +917742817777


A package in java is an encapsulation mechanism that can be used to group related
classes, interfaces, enums, and subpackages.
The below diagram shows a package hierarchy, comprising a package called java that
contains two other packages; io and awt. The package io has a class InputStream that
implements the interfaces Closeable and AutoCloseable, also found in the same
package. The package awt has two classes Color and Frame.
java

io awt
Closeable AutoCloseable Color

Frame
InputStream
The dot (.) notation is used to uniquely identify package members in the package
hierarchy. The class java.io.InputStream is different from the class java.awt.Color. The
Frame class can be easily identified by java.awt.Frame. This is called the fully qualified
name of the type.

Java programming environment usually map the fully qualified name of packages to
the underlying file system. For example, on a window system, the class Frame.class
corresponding to the fully qualified name java.awt.Frame would be found under the
folder java/awt.

Defining packages
A package hierarchy represents an organization of the java classes and interfaces. It
does not represent the source code organization of the classes and interfaces. The
source code is of no consequence in this regard. Each java source file (also called
compilation unit) can contain zero or more type declarations, but the compiler
produces a separate .class file containing the java byte code for each of them. A type
declaration can indicate that its java byte code be placed in a particular package , using
a package declaration.
The package statement has following syntax :
package <fully qualified package name>;

At most one package declaration can appear in a source file, and it must be the first
statement in the source file. The package name is saved in the java byte code for the
types contained in the package.

Note that this scheme has two consequences. First, all the classes and interfaces in a
source file are placed in the same package. Second, several source files can be used to
specify the contents of the package.

If a package declaration is omitted in a compilation unit, the java byte code for
declarations in the compilation unit will belong to an unnamed package (also called
the default package) , which is typically synonymous with the current working
directory on the local host system.

The next slide have an example to add units into a package:


package MyPackage;

public class MyMaths


{
public int sum(int ... x)
{
int s=0;

for(int n:x)
s+=n;
return s;
}
}
Using packages:
The import facility in java makes it easier to use the contents of packages. The
accessibility of types in a package determines their access from other packages. Given
a reference type that is accessible from outside a package, the reference type can be
accessed in two ways. One way is to use the fully qualified name of the type. However,
writing long names become tedious. The second way is to use the import declaration
that provide a shorthand notation for specifying the name of the type, often called
type import.

The import declaration must be the first statement after any package declaration in a
source file. The simple form of the import declaration has the following syntax:
import <fully qualified type name>;
This is called single-type-import. As the name implies, such an import provide a
shorthand notation for a single type. The name of the type can now be used to access
this particular type. Given the following import declaration:
import MyPackage.MyMath;
The simple name MyMath can be used in the source file to refer to this class.
Alternatively, the following form of import declaration can be used:
import <fully-qualified-package-name>.*;
This is called type-import-on-demand. It allows any type from the specified package to
be accessed by its simple name.
An import declaration does not recursively import sub packages. The declaration also
does not result in inclusion of source code of the types. The declaration only imports
type names.
All compilation units implicitly import the java.lang package. This is the reason why we
can refer to the class String by its simple name, and need not use its fully qualified
name java.lang.String all the time.
Static members belong to the class in which they are declared and are not part of any instance of the class.
The declaration of static members is prefixed by the keyword static to distinguish them from instance
members.
Depending on the accessibility modifiers of static members in a class, clients can access these by using the
class name or through object references of the class.
The class need not be instantiated to access its static members.

Static variables (also called class variables) exist in the class they are defined in only.
They are not instantiated when an instance of the class is created.
In other words, the values of these variables are not a part of the state of any object.
When the class is loaded, static variables are initialized to their default values if no explicit initialization
expression is specified.

Static methods are also known as class methods.


A static method in a class can directly access other static members in the class.
It cannot access instance (non-static) members of the class, as there is no object associated with a static
method.
The following example demonstrates static members:
class Light
{ //Fields
private int noOfWatts; //wattage
private boolean indicator; // on or off
private String location; //placement
//static variables
private static int counter; //No. of lights created
//parameterized constructor
Light(int noOfWatts,boolean indicator,String location)
{ this.noOfWatts=noOfWatts;
this.indicator=indicator;
this.location=location;
++counter;//increment counter
}
public static void writeCount()
{ System.out.println("Total number of lights "+counter);
//System.out.println("Watt "+noOfWatts); error , Field noOfWatts is not accessible
}
public void printDetails()
{ System.out.println("Location : "+location+"\nWatt "+noOfWatts
+"\nIs on : "+indicator);
}
}
public class WareHouse
{ public static void main(String[] args)
{ Light.writeCount();//invoking using class name
Light light1=new Light(200,false,"Basement");//Create an object
light1.printDetails();
Light.writeCount();//invoking using class name
Light light2=new Light(100,true,"Kitchen");//Create another object
light2.printDetails();
light2.writeCount();//invoking using reference
}
}
• A block that is created using the static keyword is called static block. The static block is used to initialize the static
members of the class. Static block is not member of the class, and it cannot have return statement.
• The static block can use only other static members of the class, it cannot access instance members of the class.
• Static block is executed only once before the execution of the main method and before constructor of the class.
• A class can have any number of static blocks and they are executed in the order, in which they are defined.
• this keyword and super keyword cannot be used in the static block.
• In java 1.6 and earlier the static block was executed even if class did not have main method, but after java 1.6 the
static block is executed only if our class has the main method. The following example demonstrates the static
block.

public class DemoStaticBlock


{ static
{ System.out.println("This is the static block1");//Will be executed first
}
public static void main(String[]args)
{ System.out.println("Inside the main function");//will be executed at last
}
}
For online training contact us at +917742817777
• As static initializer block can be used to initialize static fields in a named class, java provides ability to initialize the
instance variables during object creation using instance initializer block.
• Primarily, instance initializer block serve the same purpose as constructor during the object creation.
• Instance initializer block is executed before the execution of the constructor. An instance initializer block is
executed exactly once for every object created.
• A class can have any number of instance initializer blocks and they are executed in the order, in which they are
defined.
• this keyword and super keyword can be used in the instance initializer block.
• Instance initializer block can be used for common initialization code that will be executed regardless of which
constructor is executed for object creation.

public class DemoInitializerBlock


{ { System.out.println("This is the initializer block1");//Will be executed first for every object created
}
public DemoInitializerBlock(){System.out.println("Object Created");}
public static void main(String[]args)
{ DemoInitializerBlock d1=new DemoInitializerBlock ();
DemoInitializerBlock d2=new DemoInitializerBlock ();
}
}
For online training contact us at +917742817777
Inheritance is one of the fundamental mechanisms for code reuse in OOP. It allows
new classes to be derived from an existing class. The new class (also called subclass,
subtype, derived class, child class) can inherit members from the old class ( also called
super class, super type, base class , parent class). The subclass can add new behavior
and properties and, under certain circumstances, modify its inherited behavior.

In java, implementation inheritance is achieved by extending classes and modifying


inherited members. Inheritance of members is closely tied to their declared
accessibility. If a super-class member is accessible by its simple name in the subclass,
that member is considered inherited. This means that private, overridden , and hidden
members of the super-class are not inherited. Inheritance should not be confused
with the existence of such members in the state of a subclass object.

The super-class is specified using the extends clause in the header of the sub-class
declaration. The subclass only specifies the additional new and modified members in
its class body. The rest of its declaration is made up of its inherited members in its
class body. If no extends clause is specified in the header of a class declaration, the
class implicitly inherits from the java.lang.Object class.
Private members of super-class are not inherited by the sub-class and can only be
indirectly accessed. Using appropriate accessibility modifiers, the super-class can limit
which members can be accessed directly and, thereby, inherited by its sub-class.
The friendly access members of a super class are not inherited by subclasses in other
packages but can be inherited by subclasses in same package.

The constructors and initializer blocks are not inherited by the class.
Instance method overriding
A subclass may override instance methods that it inherit from a superclass. Overriding such a
method allows the subclass to provide its own implementation of the method. When the
method is invoked on an object of the subclass, it is the method implementation in the sub class
that is executed. The overridden method in the superclass is not inherited by the subclass, and
the new method in the subclass must abide bt the following rules of method overriding :
• The new method definition must have the same method signature , the method name, and
types and the number of parameters, including their order, are the same in the overridden
method.
• The return type of the overriding method can be a subtype of the return type of the
overridden method(called covariant return ).
• The new method definition can not narrow the accessibility of the method, but it can widen it.
• The new method definition can only throw all or none, or a subset of the checked exceptions
that are specified in the throws clause of the overridden method in the superclass.
Overriding vs Overloading
Comparison Criteria Overriding Overloading
Method name Must be the same. Must be the same.
Argument List Must be the same. Must be the different.
Return type Can be the same type or a covariant Can be same or different.
type.
throws clause Must not throw new checked Can be same or different.
exceptions. Can narrow exceptions
thrown.
Accessibility Can make it less restrictive but not Can be same or different.
more restrictive.
Declaration context A method can only be overridden in A method can be overloaded
a subclass. in same class or a subclass.
Method call resolution The runtime type of the reference, At compile time, the declared
i.e. the type of the object referenced type of the reference is used
at runtime, determines which to determine which method
method is selected for execution. will be executed at runtime.
Hiding Members
Hiding Field
A subclass cannot overrides fields of the super-class, but it can hide them. The subclass can
define fields with the same name as in the super-class. If this is the case, the fields in the super-
class cannot be accessed in the subclass by their simple names; therefore, they are not inherited
by the subclass. Code in the subclass can use the keyword super to access such members,
including hidden fields. Of course, if the hidden field Is static, it can also be accessed by the
super-class name.

Static method hiding


A static method cannot override an inherited instance method, but it can hide a static method if
the exact requirements for overriding instance methods are fulfilled. A hidden super-class
method is not inherited. The compiler will flag an error if the signature are same, but the other
requirements regarding return type, throws clause, and accessibility are not met. If the
signature are different, then method is overloaded, not hidden.
Constructor in inheritance
In Java, constructor of base class with no argument gets automatically called in derived class
constructor. For example, output of following program is:

Base Class Constructor Called


Derived Class Constructor Called
class Base
{
Base()
{
System.out.println("Base Class Constructor Called ");
}
}

class Derived extends Base


{
Derived()
{
System.out.println("Derived Class Constructor Called ");
}
}
public class Main
{
public static void main(String[] args)
{
Derived d = new Derived();
}
}

But, if we want to call parameterized contructor of base class, then we can call it using super().
The point to note is base class constructor call must be the first line in derived class
constructor. For example, in the following program, super(x) is first line derived class
constructor.

class Base
{
int x;
Base(int x)
{
this.x = x;
}
}
class Derived extends Base
{
int y;
Derived(int x, int y)
{ super(x);
this.y = y;
}
void Display()
{ System.out.println("x = "+x+", y = "+y);
}
}

public class Main


{
public static void main(String[] args)
{ Derived d = new Derived(10, 20);
d.Display();
}
}
Abstract class
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).

Abstraction is a process of hiding the implementation details and showing only functionality to
the user. Another way, it shows only important things to the user and hides the internal details
for example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.Abstraction lets you focus on what the object
does instead of how it does it.

Ways to achieve Abstaction


There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)

A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Example abstract class
abstract class A{}
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.

Example abstract method


abstract void printStatus();//no body and abstract

In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
abstract class Bike
{
abstract void run();
}

class Honda extends Bike


{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
//Bike obj=new Bike();Compilation error
Bike obj = new Honda();
obj.run();
}
}

Note: An abstract class can have data member, abstract method, method body, constructor and
even main() method.
final keyword
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. Class

1. The final keyword can be applied with the variables, a final variable that have no value is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only. If
you make any variable as final, you cannot change the value of final variable(It will be constant).

In following example there is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value can never be
changed.

class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400; //Compile time error
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}

2. final method
If you make any method as final, you cannot override it. Consider the following example :

class Bike
{ final void run()//final method cannot be overridden
{ System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda= new Honda();
honda.run();
}
}

3. final class
If you make any class as final, you cannot extend it. Consider the following example :
final class Bike//Bike is final class, can not be inherited.
{
}

class Honda extends Bike//Compilation error


{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda= new Honda();
honda.run();
}
}
Note : 1. final method is inherited but you cannot override it.
2. We can initialize blank final variable only in constructor.
3. Static final variable are also called as CONSTANTS.
4. A method/class can not have both abstract and final.
5. Constructor cannot be abstract or final.

Eg:
class A
{
final A() //Error, final not allowed here
{}
}
class A
{ abstract A();//Error, abstract not allowed here
}
abstract final class A//Error illegal combination of modifier
{
}
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve full abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve full abstraction and
multiple inheritance in Java. Java Interface also represents IS-A relationship. It cannot be
instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.
1. It is used to achieve full abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.

Note: The java compiler adds public and abstract keywords before the interface methods. The
java compiler adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and
abstract.
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.

Class Interface Interface

Extends Implements Extends

Class Class Interface


Following code demonstrates a simple interface :
interface printable
{
void print();
}

class A4 implements printable


{
public void print()
{
System.out.println("Hello");
}

public static void main(String args[])


{
A4 obj = new A4();
obj.print();
}
}
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
interface Printable
{
void print();
}

interface Showable
{
void show();
}

class A4 implements Printable,Showable


{

public void print()


{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A4 obj = new A4();
obj.print();
obj.show();
}
}

Interface inheritance
A class implements interface but one interface extends another interface . Consider the
following example :
interface Printable
{ void print(); }
interface Showable extends Printable
{ void show(); }
class Test implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
Test obj = new Test();
obj.print();
obj.show();
}
}
Difference between abstract class and interface
Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can have static methods, Interface can't have static methods, main
main method and constructor. method or constructor.
5) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape public interface Drawable
{ public abstract void draw(); } { void draw(); }
The following code demonstrates uses of both interfaces and abstract classes :

//Creating interface that has 4 methods


interface A
{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}

//Creating abstract class B,that provides the implementation of one method of A interface
//B class must be abstract because it does not provide implementation of all the methods of A
abstract class B implements A
{
public void c()
{
System.out.println("I am C");
}
}
/*Creating subclass of abstract class, now we need to provide the implementation of rest of the
methods */
class M extends B
{ public void a()//accesibilty modifier must be public, otherwise error
{ System.out.println("I am a"); }
public void b()
{ System.out.println("I am b"); }
public void d()
{ System.out.println("I am d"); }
}
//Creating a test class that calls the methods of A interface
class Test
{ public static void main(String args[])
{ A a=new M();
a.a();
a.b();
a.c();
a.d();
}
}
What is exception

Dictionary Meaning: Exception is an abnormal condition. In java, exception is an event that


disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is exception handling

Exception Handling is a mechanism to handle runtime errors and prevent our program from
abnormal termination.

The next slide shows the exception classes hierarchy in java :


Types of Exception
There are mainly two types of exceptions: checked and unchecked, where error is considered as
unchecked exception.

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.


Common scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException

3) Scenario where NumberFormatException occurs


The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string
variable that have characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

5) Scenario where NegativeArraySizeException occurs


If you are creating an array of negative size then NegativeArraySizeException is generated:
int a[]=new int[-5]; //NegativeArraySizeException

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method. Java try block must be followed by either catch or finally block.
Syntax of java try-catch
try
{
//code that may throw exception
}
catch(Exception_class_Name ref)
{}

Syntax of try-finally block


try
{
//code that may throw exception
}
finally
{}
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.

Problem without exception handling


Let's try to understand the problem if we don't use try-catch block.
public class Testtrycatch1
{
public static void main(String args[])
{
int data=50/0;//will throw exception
System.out.println("rest of the code...");
}
}
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).There can be 100 lines of code after exception. So all the code
after exception will not be executed.
Solution by exception handling
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2
{
public static void main(String args[])
{
try
{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
Internal working of java try-catch block
Using multiple catch blocks with a single try
If a try block can generate different exceptions then we can use multiple catch blocks to handle
all of them:
Let's see a simple example :
public class TestMultipleCatchBlock
{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println(“Arithmetic exception:/ by zero");}
catch(ArrayIndexOutOfBoundsException e){System.out.println(“array index does not exist");}
catch(Exception e){System.out.println(“other than AruthmeticExcpetion and ArrayIndex
exception");}

System.out.println("rest of the code...");


}
}
Note: 1. At a time only one Exception is thrown and only one catch block is executed.
2. All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .

Following code will generate compilation error


class TestMultipleCatchBlock1
{
public static void main(String args[])
{ try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Java Nested try block
The try block within a try block is known as nested try block in java.
Let's see a simple example of java nested try block.
class Excep6
{
public static void main(String args[])
{
try
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc. Java finally block is always executed whether exception is handled or not. Java finally
block must be followed by try or catch block.
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock
{
public static void main(String args[])
{ try
{ int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{ System.out.println(e);
}
finally
{ System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1
{
public static void main(String args[])
{ try
{ int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{ System.out.println(e);
}
finally
{ System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2
{
public static void main(String args[])
{ try
{ int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{ System.out.println(e);
}
finally
{ System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Note: 1. For each try block there can be zero or more catch blocks, but only one finally block.
2. The finally block will not be executed if program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).
Java throw keyword

The Java throw keyword is used to explicitly throw an exception. We can throw either checked
or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw
custom exception. We will see custom exceptions later. The syntax of java throw keyword is
given below.
throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error);

In the following example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained. Exception Handling is mainly
used to handle the checked exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not performing check up before the code
being used.
import java.io.IOException;
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

Note:If you are calling a method that declares an exception, you must either caught or declare
the exception.

There are two cases:


Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception, In case you handle the exception, the code will be executed
fine whether exception occurs during the program or not.
import java.io.*;
class M
{
void method()throws IOException
{ throw new IOException("device error");
}
}
public class Testthrows2
{ public static void main(String args[])
{ try
{ M m=new M();
m.method();
}
catch(Exception e)
{ System.out.println("exception handled");
}

System.out.println("normal flow...");
}
}
Case2: You declare the exception
A)In case you declare the exception, if exception does not occur, the code will be executed fine.
B)In case you declare the exception if exception occurs, an exception will be thrown at runtime
because throws does not handle the exception.

Program if exception does not occur


import java.io.*;
class M
{
void method()throws IOException
{
System.out.println("device operation performed");
}
}
class Testthrows3
{
public static void main(String args[])throws IOException
{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}

Program if exception occurs


import java.io.*;
class M
{
void method()throws IOException
{ throw new IOException("device error");
}
}
class Testthrows4
{ public static void main(String args[])throws IOException
{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Difference between throw and throws in Java
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:

throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
Checked exception cannot be propagated Checked exception can be propagated with
using throw only. throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
Stream

A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream
because it's like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.

1) System.out: standard output stream


2) System.in: standard input stream
3) System.err: standard error stream

Let's see the code to print output and error message to the console.
System.out.println("simple message");
System.err.println("error message");

Let's see the code to get input from console.


int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
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.

Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class
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.

Commonly used methods of OutputStream class

Method Description

1) public void write(int)throws IOException: is used to write a byte to the current output
stream.

2) public void write(byte[])throws is used to write an array of byte to the


IOException: current output stream.

3) public void flush()throws IOException: flushes the current output stream.

4) public void close()throws IOException: is used to close the current output stream.
The following diagram shows the class hierarchy of Output Stream classes
InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an input
stream of bytes.
Commonly used methods of InputStream class

Method Description
1) public abstract int read()throws reads the next byte of data from the input
IOException: stream.It returns -1 when no data is
available.

2) public int available()throws returns an estimate of the number of bytes


IOException: that can be read from the current input
stream.

3) public void close()throws IOException: is used to close the current input stream.
The following diagram shows the class hierarchy of Input Stream classes
FileInputStream and FileOutputStream (File Handling)
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file.
In another words, they are used for file handling in java.
Java FileOutputStream class
Java FileOutputStream is an output stream for writing data to a file.
Example:
import java.io.*;
class Test
{
public static void main(String args[])
{
try
{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println(“Data written on the file...");
}catch(Exception e){system.out.println(e);}
}
}
Java FileInputStream class
Java FileInputStream class obtains input bytes from a file.
Example:
import java.io.*;
class SimpleRead
{ public static void main(String args[])
{ try
{ FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1)
{ System.out.println((char)i);
}
fin.close();
}
catch(Exception e)
{ System.out.println(e);
}
}
}
Java ByteArrayOutputStream class
Java ByteArrayOutputStream class is used to write data into multiple files. In this stream, the
data is written into a byte array that can be written to other stream.The
ByteArrayOutputStream holds a copy of data and forwards it to another streams.The buffer of
ByteArrayOutputStream automatically grows according to data.

Constructors of ByteArrayOutputStream class

Constructor Description

ByteArrayOutputStream() creates a new byte array output stream with


the initial capacity of 32 bytes, though its
size increases if necessary.

ByteArrayOutputStream(int size) creates a new byte array output stream,


with a buffer capacity of the specified size,
in bytes.
Methods of ByteArrayOutputStream class

Method Description

1) public synchronized void writes the complete contents of this byte


writeTo(OutputStream out) throws array output stream to the specified output
IOException stream.

2) public void write(byte b) throws writes byte into this stream.


IOException

3) public void write(byte[] b) throws writes byte array into this stream.
IOException

4) public void flush() flushes this stream.

5) public void close() Closes the opened stream.


Java ByteArrayOutputStream Example
Let's see a simple example of java ByteArrayOutputStream class to write data into 2 files.
import java.io.*;
class S
{
public static void main(String args[])throws Exception
{
FileOutputStream fout1=new FileOutputStream("f1.txt");
FileOutputStream fout2=new FileOutputStream("f2.txt");
ByteArrayOutputStream bout=new ByteArrayOutputStream();
bout.write(139);
bout.writeTo(fout1);
bout.writeTo(fout2);
bout.flush();
bout.close();
System.out.println("success...");

}
}
Java BufferedOutputStream class
Java BufferedOutputStream class uses an internal buffer to store data. It adds more efficiency
than to write data directly into a stream. So, it makes the performance fast.
Example:
import java.io.*;
class Test
{
public static void main(String args[])throws Exception
{
FileOutputStream fout=new FileOutputStream("f1.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Sachin is my favourite player";
byte b[]=s.getBytes();
bout.write(b);

bout.flush();
bout.close();
fout.close();
System.out.println(“data written successfullysuccess");
}
}
Java BufferedInputStream class
Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.

import java.io.*;
class SimpleRead
{ public static void main(String args[])
{ try
{ FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1)
{ System.out.println((char)i);
}
bin.close();
fin.close();
}
catch(Exception e)
{ System.out.println(e);}
}
}
Java FileWriter and FileReader
Java FileWriter and FileReader classes are used to write and read data from text files. These
are character-oriented classes, used for file handling in java.

Java FileWriter class


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

Constructors of FileWriter class

Constructor Description

FileWriter(String file) creates a new file. It gets file name in


string.

FileWriter(File file) creates a new file. It gets file name in


File object.
Methods of FileWriter class

Method Description

1) public void write(String text) writes the string into FileWriter.

2) public void write(char c) writes the char into FileWriter.

3) public void write(char[] c) writes char array into FileWriter.

4) public void flush() flushes the data of FileWriter.

5) public void close() closes FileWriter.


In this example, we are writing the data in the file abc.txt.
import java.io.*;
class Simple
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("success");
}
}
Java FileReader class
Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class.

Constructors of FileReader class

Constructor Description

FileReader(String file) It gets filename in string. It opens the


given file in read mode. If file doesn't
exist, it throws FileNotFoundException.

FileReader(File file) It gets filename in file instance. It opens


the given file in read mode. If file doesn't
exist, it throws FileNotFoundException.
Important methods of FileReader

Method Description

1) public int read() returns a character in ASCII form. It


returns -1 at the end of file.

2) public void close() closes FileReader.


In this example, we are reading the data from the file abc.txt file.
import java.io.*;
class Simple
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);

fr.close();
}
}
java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The PrintStream class
automatically flushes the data so there is no need to call flush() method. Moreover, its methods
don't throw IOException.

There are many methods in PrintStream class. Let's see commonly used methods of PrintStream
class:

public void print(boolean b): it prints the specified boolean value.


public void print(char c): it prints the specified char value.
public void print(char[] c): it prints the specified character array values.
public void print(int i): it prints the specified int value.
public void print(long l): it prints the specified long value.
public void print(float f): it prints the specified float value.
public void print(double d): it prints the specified double value.
public void print(String s): it prints the specified string value.
public void print(Object obj): it prints the specified object value.
public void println(boolean b): it prints the specified boolean value and terminates the line.
public void println(char c): it prints the specified char value and terminates the line.
public void println(char[] c): it prints the specified character array values and terminates the
line.
public void println(int i): it prints the specified int value and terminates the line.
public void println(long l): it prints the specified long value and terminates the line.
public void println(float f): it prints the specified float value and terminates the line.
public void println(double d): it prints the specified double value and terminates the line.
public void println(String s): it prints the specified string value and terminates the line./li>
public void println(Object obj): it prints the specified object value and terminates the line.
public void println(): it terminates the line only.
public void printf(Object format, Object... args): it writes the formatted string to the current
stream.
public void printf(Locale l, Object format, Object... args): it writes the formatted string to the
current stream.
public void format(Object format, Object... args): it writes the formatted string to the current
stream using specified format.
public void format(Locale l, Object format, Object... args): it writes the formatted string to the
current stream using specified format.
DataInputStream class
The Java.io.DataInputStream class lets an application read primitive Java data types from an
underlying input stream in a machine-independent way.Following are the important points
about DataInputStream:
1. An application uses a data output stream to write data that can later be read by a data input
stream.
2. DataInputStream is not necessarily safe for multithreaded access. Thread safety is optional
and is the responsibility of users of methods in this class.

Class constructors

Constructor Description

DataInputStream(InputStream in) This creates a DataInputStream that


uses the specified underlying
InputStream.
Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum
constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.

Points to remember for Java Enum


enum improves type safety
enum can be easily used in switch
enum can be traversed
enum can have fields, constructors and methods
enum may implement many interfaces but cannot extend any class because it internally extends
Enum class

class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args) {
for (Season s : Season.values())
System.out.println(s);
}}
Enumeration example
enum Car
{ lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;
Car(int p)
{ price = p; }
int getPrice()
{ return price;
}
}
public class Main
{
public static void main(String args[])
{ System.out.println("All car prices:");
for (Car c : Car.values())
System.out.println(c + " costs " + c.getPrice() + " thousand dollars.");
}
}
It would be nice if we could write a single sort method that could sort the elements in an Integer
array, a String array or an array of any type that supports ordering.
Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods or, with a single class declaration, a set of related types,
respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types
at compile time.
Using Java Generic concept, we might write a generic method for sorting an array of objects,
then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to
sort the array elements.

Generic Methods:
You can write a single generic method declaration that can be called with arguments of different
types. Based on the types of the arguments passed to the generic method, the compiler handles
each method call appropriately. Following are the rules to define Generic Methods:

All generic method declarations have a type parameter section delimited by angle brackets (<
and >) that precedes the method's return type ( < E > in the next example).
Each type parameter section contains one or more type parameters separated by commas. A
type parameter, also known as a type variable, is an identifier that specifies a generic type
name.

The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.

A generic method's body is declared like that of any other method. Note that type parameters
can represent only reference types, not primitive types (like int, double and char).

Following example illustrates how we can print array of different type using a single Generic
method:

public class GenericMethodTest


{ // generic method
public static < E > void printArray( E[] inputArray )
{ // Display array elements
for ( E element : inputArray )
{ System.out.printf( "%s ", element ); }
System.out.println();
}
public static void main( String args[] )
{ // Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println( "Array integerArray contains:" );
printArray( intArray ); // pass an Integer array
System.out.println( "\nArray doubleArray contains:" );
printArray( doubleArray ); // pass a Double array
System.out.println( "\nArray characterArray contains:" );
printArray( charArray ); // pass a Character array
}
}
Bounded Type Parameters:
There may be times when you'll want to restrict the kinds of types that are allowed to be passed
to a type parameter. For example, a method that operates on numbers might only want to
accept instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends
keyword, followed by its upper bound.
Example:
Following example illustrates how extends is used in a general sense to mean either "extends"
(as in classes) or "implements" (as in interfaces). This example is Generic method to return the
largest of three Comparable objects:

public class MaximumTest


{ // determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{ T max = x; // assume x is initially the largest
if ( y.compareTo( max ) > 0 )
{ max = y; // y is the largest so far }
if ( z.compareTo( max ) > 0 )
{ max = z; // z is the largest now }
return max; // returns the largest object
}
public static void main( String args[] )
{
System.out.printf( "Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3,
4, 5 ) );

System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7,


maximum( 6.6, 8.8, 7.7 ) );

System.out.printf( "Max of %s, %s and %s is %s\n","pear", "apple", "orange",


maximum( "pear", "apple", "orange" ) );

Generic Classes:
A generic class declaration looks like a non-generic class declaration, except that the class name
is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more
type parameters separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.
Following example illustrates how we can define a generic class:

public class Box<T>


{
private T t;
public void add(T t)
{ this.t = t;
}
public T get()
{ return t;
}
public static void main(String[] args)
{
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}
A collections framework is a unified architecture for representing and manipulating collections.
All collections frameworks contain the following:

Interfaces: These are abstract data types that represent collections. Interfaces allow collections
to be manipulated independently of the details of their representation. In object-oriented
languages, interfaces generally form a hierarchy.

Implementations, i.e., Classes: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.

Algorithms: These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of the
appropriate collection interface.

In addition to collections, the framework defines several map interfaces and classes. Maps store
key/value pairs. Although maps are not collections in the proper use of the term, but they are
fully integrated with collections.
A collections framework is a unified architecture for representing and manipulating collections.
All collections frameworks contain the following:

Interfaces: These are abstract data types that represent collections. Interfaces allow collections
to be manipulated independently of the details of their representation. In object-oriented
languages, interfaces generally form a hierarchy.

Implementations, i.e., Classes: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.

Algorithms: These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of the
appropriate collection interface.

In addition to collections, the framework defines several map interfaces and classes. Maps store
key/value pairs. Although maps are not collections in the proper use of the term, but they are
fully integrated with collections.

You might also like