Java Notes (II - Unit) Final
Java Notes (II - Unit) Final
Java Notes (II - Unit) Final
4. The if…else ladder: It is used perform operations of multiple conditions. When conditions are
more we may use if…else ladder. The conditions are evaluated for the top to bottom. When any
condition is found true the statements associated with it are executed and the control skips the rest of
the conditions, when all the conditions are false it executes the statements under else (default
statements) will be executed.
Syntax: Entry
If (Condition 1)
True
Block -1 statements; Condition 1 Block-1 statements
else if (Condition 2)
Block-2 statements; False
else if (Condition 3)
Condition 2 True Block-2 statements
Block-3 statements;
False
else if (Condition n)
Block-n statements; True
Condition 3 Block-3 statements
else
default-statemensts; False
Ex: If (ave>=70)
Condition n True
Grade=’A’; Block-n statements
else if (ave>=60)
False
Grade = ‘B’;
else if (ave>=50) Default-statements
}
The enhanced for loop: This is also called “for each loop”. It is used to retrieve the elements form a
collection instead of incrementing a value.
Syntax:
For (Type Identifier: Expression)
{
Body of the loop;
}
Here Type represents the data type or object used. Identifier refers to the name of the variable; the
expression is an instance of the java.
Program to demonstrate enhanced for loop:
class forloop
{
public static void main(String args[])
{
String states[]={"Andhra Pradesh", "Orissa" , "Tamilnadu" , "Karnataka" ,"Kerala",};
for (String i:states)
System.out.println(i);
}
}
Jumps in Loops: Some times we have to jump the control from the loop to required place. For this
purpose java provides some statements like break and continue.
break: it is used to exit from the loop and moves to the next line after the loop, when loops are
nested, the break will exit form the loop containing it.
continue: it is used to terminate the loop and continued from the starting. When it is faced by the
control, the control skips the remaining lines in the loop and control moves to the starting iteration
point (test condition.)
Unit II 6
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
while (test condition) do for (initialization; test condition; increment)
{ { {
:::::::::::::::::: ::::::::::::::::: :::::::::::::::::
If (condition) if (condition) if (condition)
break; break; break;
:::::::::::::::::: :::::::::::::::: :::::::::::::::::
} }while(condition) }
Here continue statement restarts the inner for loop, continue cdc; restarts the outer for loop. The
break statement jumps inner loop, break wgl; statement jumps out for loop.
EX: The below given program has to print 20 stars(“*”) in twenty lines but before the we used break
and continue to break the inner loop and continue cdc to restart labeled loop cdc:
class labelloop
{
public static void main(String args[]) When we delete break and
{ continue statements it will
cdc : for(int i=1;i<=20;i++) display 20 stars for 20 lines
{ Output; like below.
System.out.println(" "); * *******************
if(i>10) break; ** *******************
for(int j=1;j<=20;j++) *** *******************
{ * * * * *******************
System.out.print("* "); * * * * * *******************
if(i==j) * * * * * * *******************
continue cdc; * * * * * * * *******************
} ******** *******************
} ********* *******************
} ********** *******************
} *******************
Unit II 7
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Classes, Objects and methods
Java is a true object-oriented programming language, so anything we wish to represent in a
program must be encapsulated in a class. A class defines the state and behavior of the program
components known as objects. Classes create objects and objects use methods to communicate
between them. Methods are just like functions.
Defining a Class: A class is a user-defined data type serves to define properties. Once a class is
defined we can create variables of that type using declarations. In java these variables are called
“instances of classes”. These are the actual objects. The class is defined as below:
class <class name> extends < super class name>
{
fields declaration;
methods declaration;
}
Here we are defining a class using the keyword “class’”. The keyword extends indicates that the
properties of super class are extended to the defined class, that is an option.
Fields declaration: Data is encapsulated in a class by placing data fields in the class. These
variables are called “instance variables”. These are declared just as local variables;
class triangle The class triangle has two integer type instance variables.
{ We may declare the variables in a single line also.
int length; These variables are also called member variables.
int width;
}
Methods Declaration: A class with only data fields has no life. Such classes cannot respond to any
messages. We must add methods that are useful for manipulating the data of the class. Methods
are declared in the body of the class immediately after declaration of instance variables.
Syntax: type methodname (parameter list)
{
body of the method;
}
The method has four basic parts: they are
1. The name of the method (method name) (It is any valid identifier)
2. The type of the value the method return (type) (it is any valid data type, it is void when it does
not return any value.)
3. A list of parameters (parameter list) ( This list contains variable names and types of all the
values we want to send as input, when no input data are required, we must use empty
parentheses)
4. The body of the method: It describes the operations to be performed on the data.
Creating Objects: An object is a block of memory that contains space to store all the instance
variables. Java has an operator new to create objects. Creating an object is also referred to as
instantiating an object.
Ex: triangle tri1; ( declaring the object)
Tri1 = new triangle (instantiating the object)
The above two statements are combined into a single statement as
Triangle tri1 = new triangle();
We may create any number of objects of triangle.
Ex. Triangle tri1 = new triangle( );
Triangle tri2 = new triangle( );
Accessing class Members: every object contains its own set of variables. We should assign
values to these variables in order to use them in our program. When we are outside the class we
cannot access the instance variables and methods directly. For this we use dot operator.
Sy: objectname.varaiblename = value;
objectname.methodname(parameter list);
Ex: tri1.length = 15;
tri2.length = 20;
tri1.getData( 20,30)
Unit II 8
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Ex: A java program to demonstrate application of classes, objects and methods.
class triangle
{
int length, width; Instance variables declared in a single line
void getData(int x, int y) getData is a method, it does not return any
{ value so its type is void, we are passing two
length = x; integer values and they are assigned to
width = y; length and width
}
int triarea( ) triarea is another method, it returns a
{ value of data type int. We are not
int area = (length * width)/2 ; passing values, so the parameter list
return (area); is empty
}
}
class triarea class with main method
{
public static void main (String args[ ])
{
int area1, area2;
triangle tri1 = new triangle(); Creating objects
triangle tri2 = new triangle();
tri1.length = 20; Accessing variables
tri1.width = 30;
area1 =( tri1.length * tri1.width)/2;
tri2.getData( 10, 15); Accessing Methods
area2 = tri2.triarea();
System.out.println( "area1 = " + area1);
System.out.println( "area2 = " + area2);
}
}
Constructors: Constructor is a method that have same name as the class, it enables an object to
initialize itself when it is created. Constructors do not specify a return type, not even void also.
Constructors are two types they are parameterized constructors and default constructors.
A parameterized constructor is explicitly invoked by passing certain arguments, at the time of
object initialization where as default constructor is used to initialize the object variables with some
default values at the time of object initialization, so it does not take any parametric values.
Ex: triangle tri1 = new triangle(15,20) parameterized constructor
triangle tri1 = new triangle( ) default constructor
A program to demonstrate Parameterized and default constructors.
Methods overloading: Java allows the user to create methods with same name in a class, but with
different parameter lists. This is called “method overloading”. It is used when we want to perform
similar tasks using different parameters. When we call that method based on the number and type of
the parameters it decides the method to execute. This feature is also called “polymorphism”. For this
we have to create several methods with same name and with different number of or type of
parameters in a class. Here the methods return type does not play any role.
Ex A program to demonstrate methods overloading.
Static Members: A class declares variables and methods. These are called instance variables and
methods. These are associated with objects, when we instantiated a class a new copy of each of
them is created. If we want a member that is common to all objects and accessed without using a
particular object, we have to use Static Members. These are declared using a keyword “static”.
Ex: static int total;
static int max( int x, int y)
Static variables are called with out using objects. They are also used by other classes.
Suppose float x= Math.sqrt(25.0); here sqrt is a static method of Math class. Static methods are
called using class names. They have some restrictions:
1. They can only call other static methods.
2. They can only access static data.
3. They cannot refer to this or super in any way.
Ex:Program tt demonistrate Static Members.
class methods
{
static int add( int x, int y)
{
return x+y;
}
static int substract(int x, int y)
{
return x-y;
}
}
class staticmethods
{
public static void main(String args[ ])
{
int a = methods.add(20,30);
int b = methods.substract(a,25);
System.out.println("b = "+b);
}
}
Unit II 10
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Nesting of Methods: A method of a class can be called by an object of that class, in case of static
methods by class itself using dot operator. A method can be called by using only its name by another
method of the same class, this is known as nesting of methods.
Ex: A program to demonstrate nesting of methods.
class nesting
{
int a, b;
nesting( int x, int y)
{
a=x;
b=y;
}
int largest()
{
return((a>b)?a:b);
}
void display()
{
int large = largest() ;
System.out.println( "Largest value = " + large);
}
}
class nestmethod
{
public static void main(String args[])
{
nesting nest = new nesting(20,30);
nest.displ ay();
}
}
Inheritance: Reusability is an important aspect of the Object Oriented Programming. This is nothing
but reusing already existing concepts instead of creating again. Java supports this feature. We can
reuse a class by creating new classes. The mechanism of deriving a new class form already existing
class is called “inheritance”. The old class is known as super class or parent class, the new one is
known as derived, child or child class. The inheritance allows the subclasses to inherit all the
variables and methods of parent class. It has different forms; A
A A A B
B
B B C D
C
C
Single Inheritance Hierarchical Inheritance Multiple Inheritance
(Only one super (One super class, many Multilevel Inheritance (Derived
(Several Super classes)
class) subclasses from Derived classes)
Overriding Methods: A method of super class is inherited by subclass and used by the objects
created by subclass. Java allows the user to create a method in sub class with same name as in the
super class with same arguments and same return type. This is called Methods overriding. This is
useful to perform different behaviors when it is called. When it is called with the object of the
subclass the method in the subclass will be invoked, when we call it with object of super class the
method of the super class is invoked.
Ex: Program to demonstrate overriding methods.
class super1 this.s2=y;
{ }
int s1; void display()
super1( int x) {
{ System.out.println(" super s1 ="+s1);
this.s1=x; System.out.println(" sub s2 ="+s2);
} }
void display() }
{ class subtest
System.out.println(" super s1 ="+s1); {
} public static void main(String args[ ])
} {
class sub1 extends super1 sub1 su1=new sub1(10,20);
{ super1 sup1=new super1(100);
int s2; su1.display();
sub1( int x, int y) sup1.display();
{ }
super(x); }
Final variables, methods and classes: All the methods and variables of super class are overridden
in subclasses. If we want to prevent the subclasses from overriding the members of super class we
can declare them as final using the keyword “final”. The final methods and variables are not allowed
to define in subclasses.
Ex: final int TOTAL = 100; (Final variable)
final void abc() (Final method)
We may prevent a class being further subclasses for some reasons. A class that cannot be
sub classed is called final class. This is possible by using the keyword “final”.
Ex: final class abc extends xyz
The class abc is not used as super class for any other class.
Unit II 12
Chaitanya Degree College B.Sc.III Year V Sem (Java Notes)
Abstract Methods and Classes: The keyword final prevents the methods and classes to overridden
in sub classes. Java supports a method exactly opposite to this, that is to make it must to redefine in
a subclass that means making overriding compulsory. This is possible by using the keyword
“abstract” in method definition.
Ex: abstract class cdc
{
::::::::::::::::::::::
abstract void teaching();
:::::::::::::::::::::
}
When any class contains abstract method or methods it must be declared as abstract; there are
some restrictions for abstract classes;
1. We cannot use abstract classes to instantiate objects directly.
2. The abstract method of an abstract class must be defined in its subclass.
3. We cannot declare abstract constructors and abstract static methods.
Visibility Control: We may inherit all the members of a class by subclass using keyword “extends”.
Some times we need to access members of a class everywhere in the program, in some other cases
we have to restrict certain members to access form out side of the class. All these things are
possible using “visibility modifiers” or “access modifiers”. Java provides three types of visibility
modifiers like “public, private and protected”.
Public Access: Public access is used to visible or access any variable or method to visible or
access everywhere in the program. It is possible by using key word “public” before the variable or
method while defining:
Ex: public int x;
public int sum(int x, int y)
Friendly Access: This is the default access modifier. When we do not use any access modifier then
by default it takes friendly access. This modifier is used to access the variable or method everywhere
it the package in which it is defined.
Protected Access: Protected access is used to access the variables or methods visible everywhere
in the same package in which it is defined and also in the subclasses of other packages. Non
subclasses of other packages cannot access protected members.
Ex: protected int x;
Private Access: Private access is used to access the variable or methods to access in their own
class. We can not inherit by subclasses, so we cannot use in subclasses. We can not over ride
private members.
Ex: private int x:
Private protected access: We may declare a member as “private protected”. This is used to
access the member in all subclasses in all packages. This is accessed in its own class and all the
subclasses of all the packages. But it is not accessed in other classes in the same package and non
sub classes in the other packages.
Ex: private protected int x;
Unit II 13