Professional Documents
Culture Documents
Javacomplete
Javacomplete
operator?
02
03
Thank You Miscellanous
Operator
04
Relational instanceof
Operator Operator
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
||
~
OR Unsigned
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
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 : 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;
Trainings 7742817777
Syntax:
Initialization;
do
{ _________________;
_________________;
Body of loop
_________________;
Enclosed in { }
_________________;
inc/dec;
} while(booleanexpression);
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
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.
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.
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.
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:
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
The above two methods are not overloaded and they are ambiguous because
changing only the parameter name does not work in overloading.
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.
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.
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.
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.
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.
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.
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.
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.
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);
}
}
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.
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.
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();
}
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");
}
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.
{
}
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.
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.
interface Showable
{
void 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 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
Exception Handling is a mechanism to handle runtime errors and prevent our program from
abnormal termination.
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
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...");
}
}
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.
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.
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.
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 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.
Method Description
1) public void write(int)throws IOException: is used to write a byte to 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.
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.
Constructor Description
Method Description
3) public void write(byte[] b) throws writes byte array into this stream.
IOException
}
}
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.
Constructor Description
Method Description
Constructor Description
Method Description
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:
Class constructors
Constructor Description
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:
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:
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.