Vous êtes sur la page 1sur 77

JAVA Code Structure:

common syntax:
class classname
{
public static void main(String[] args)
{
}
}
complete syntax:
package packagename;
import classe_name/library;
class classname
{
public static void main(String[] args)
{
}
}
-- after writing a program , save it as classname.java
-- to compile a program,
goto cmd.
goto the respective folder and set the path
to compile , javac classname.java
to run, java classname
the reason why do we give static in main function is , we can invoke
the main function automatically without creating an object
the reason why do we give String[] args is:
1. java will accept all the data as a string
2. when ever we want to pass the data through command line
class employee
{
public static void main(String[] args)
{
System.out.println("Hi!...Welcome");
System.out.println(args[1]);
System.out.println(args[0]);
}
}
// multiply two numbers
3
4
1.give name to the value
no1=3
no2=4

a=3
b=4
value1=3
value2=4
these names are called as variables
Variable is a name given to the value that to
be stored in the memory
-- variable should be given along with the type
integer data - int
character data - char
point data - float or double
boolean data(true/false ) - bool
String data - string
syntax:
datatype variable_name=value;
or
datatype variable_name;
class employee
{
public static void main(String[] args)
{
int a=4;
int b=3;
}
}
int a=4,b=3;
class employee
{
public static void main(String[] args)
{
//declare variable
int a,b,result;
//assign the value
a=4;
b=3;
//do the logic
result=a*b;
//print the output
System.out.println(result);
}
}
-- to print the name of the student and age
String name;
int age;
name="Sheik";
age=23;
System.out.println(name);
System.out.println(age);

-----String name="Sheik";
int age=21;
System.out.println(name+" "+age);
Programs:
-- Operations
can done using Operator
1. Arithmetic operators
+, -, *, / , %
% - remainder of the divison
/ - return the quotient
8/2 = 4
8%2 = 0
2.Relational Operators
< [Less than]
> [Greater than]
>= [Greater than or equal to]
<= [Less than or equal to]
== [Equal to]
!= [Not Equal to]
4>5 False
8<12 True
8<=8 true [8<8 or 8=8]
8<8 False
3. Logical Operators
&& - and
|| - OR
! - NOT
and(&&) - returns true only if all conditions are
true.
OR(||) - returns true if any one of the condition
is true
! - Complement operators
0->1
1->0
Note: Relational operators will execute the
condition given but returns ___value
ans: Boolean [True/false]
simple Program on operators:
class student
{
public static void main(String[] args)
{
int a=10,b=20;
boolean res;

res=a>b;
System.out.println(res);
}
}
Sequential programming - used to execute all
the lines in a program step by step.
Decision making programming - are used to take
decision in the programs.
Constructs are :
1. if..else
2. cascading if..else
3. switch case
if(condition)
{
//true statements
}
else
{
//false statements
}
//check the given no is positive or negative
condition : if number is greater than 0 it is +ve
else -ve
class student
{
public static void main(String[] args)
{
int a=10;
if(a>0)
{
System.out.println("Positive");
}
else
{
System.out.println("Negative");
}
}
}
Cascading if..else
- checking a series of conditions
Syntax:
if(condition1)
//statements
else if(condition 2)
//statements
else if(condition 3)
//statements
.
.
.
else
//statements

example:
class student
{
public static void main(String[] args)
{
int a=-12;
if(a==0)
System.out.println("The number is Zero.. cant be concluded");
else if(a>0)
System.out.println("Positive");
else
System.out.println("Negative");
}
}
-------------------------------------class student
{
public static void main(String[] args)
{
char grade='R';
switch(grade)
{
case 'A':
System.out.println("Excellent");
case 'B':
System.out.println("Good");
case 'C':
System.out.println("Fair");
case 'D':
System.out.println("Fail");
default:
System.out.println("Invalid grade");
}
}
}
--------------------------class student
{
public static void main(String[] args)
{
char grade='R';
if(grade=='A')
System.out.println("Excellent");
else if(grade=='B')
System.out.println("Good");
else if(grade=='C')
System.out.println("Fair");
else if(grade=='D')
System.out.println("Fail");
else
System.out.println("Invalid Grade");
}

}
-- switch case :
Note : in cascading if else all the lines will
be compiled , if none of the conditions met.
syntax:
switch(condition)
{
case value1:
//statements
break;
case value2:
//statements
break;
.
.
.
case value-n:
break;
default:
statements
}
----------------------------------class student
{
public static void main(String[] args)
{
char vowel='t';
switch(vowel)
{
case 'a':
System.out.println("Vowel");
break;
case 'e':
System.out.println("Vowel");
break;
case 'i':
System.out.println("Vowel");
break;
case 'o':
System.out.println("Vowel");
break;
case 'u':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");
}
}
}
--------------------------------

class student
{
public static void main(String[] args)
{
char vowel='A';
switch(vowel)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");
}
}
}
--------------------------------------class student
{
public static void main(String[] args)
{
int a=13;
int i=a%2;
switch(i)
{
case 0:
System.out.println("Even");
break;
default:
System.out.println("odd");
}
}
}
Loops :
class student
{
public static void main(String[] args)
{
//print multiples of table 5
int i=1;
System.out.println(i*5);
i=i+1;
System.out.println(i*5);
i=i+1;
System.out.println(i*5);

}
}
-- in the above program, the code lines
will increase as the logic becomes complicated.
to make these kind of process, easier, we have to use
loops.
Iterative constructs:
-- are used whenever we need to execute some set of
task again and again .. until the result is achieved.
Loops - are the iterative process to execute some
set of code again and again.
Every loop has three components ::
1. starting/initial condition.
2. Main Logic
3. Re-initial condition
Three types of loops:
1.while
2.do..while
3. for loop
class student
{
public static void main(String[] args)
{
//print multiples of table 5
int i=1;
while(i<=10)
{
System.out.println(i*5);
i=i+1;
}
}
}
++ add1
-- subtract 1
i++ or i=i+1
i-- or i=i-1
class student
{
public static void main(String[] args)
{
//print numbers from 1 to 10
int i=1;
while(i<11)
{
System.out.println(i);
i++;
}
}

}
------------------------class student
{
public static void main(String[] args)
{
//print even numbers between 1 to 10
int i=2;
while(i<11)
{
System.out.println(i);
i=i+2;
}
}
}
-----------------------------class student
{
public static void main(String[] args)
{
//print even numbers between 1 to 10
int i=1;
while(i<11)
{
if(i%2==0)
System.out.println(i);
i++;
}
}
}
While - first check the condition, if the
condition is correct, then body of the loop will be
executed.
this is called as top - tested loop.
do.. while ::
first execute the body atleast once and then
check the condition.
this is called as bottom tested loop/exit controlled
loop.
class student
{
public static void main(String[] args)
{
//print even numbers between 1 to 10
int i=10;
do
{
if(i%2==0)
System.out.println(i);
i++;
}
while(i<11);
}
}
----------------------------------------

for loop - used to execute the code iteratively.


-- more compact to use
--helps in complex logics.
for(initial;main-condition;re-initial)
{
//body
}
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
//print even numbers between 1 to 10
for(int i=10;i>=2;i=i-2)
{
System.out.println(i);
}
Method - are small modules or functions in program
that breaks complexity of the code
int
int
int
int
int

a=10,b=12;
sum=a+b;
pro=a*b;
diff=a-b;
quo=a/b;

public void add()


{
res=a+b;
}
public void mul()
{
res=a*b;
}
public void difference()
{
res=a-b;
}
access-specifier return-type methodname(parameters)
{
}
How do create objects in java?
classname object =new classname();
new - allocate memory for the class specified.
by using the object only, the methods inside
the class can be accessed.
How to access the methods inside the class?
objname.methodname();

class faculty
{
public void subject()
{
System.out.println("Oliver Teaches JAVA");
}
}
class student
{
public static void main(String[] args)
{
faculty c=new faculty();
c.subject();
}
}
-----------------create a class that stores all the grocery items.
create 3 methods to display current quantity,
add quantity and delete quantity.
class Products
{
String prodname="Milk";
int quantity=12;
public void displayproduct()
{
System.out.println("Productname="+prodname);
System.out.println("Quantity="+quantity);
}
public void addquantity()
{
quantity=quantity+10;
System.out.println("Quantity after add="+quantity);
}
public void subtractquantity()
{
quantity=quantity-5;
System.out.println("Quantity after remove="+quantity);
}
}
class items
{
public static void main(String[] args)
{
Products p=new Products();
p.displayproduct();
p.addquantity();
p.subtractquantity();
}
}
1.how do we pass parameters to a method?
Example 01 : to pass parameters to a method.

class calculator
{
public void mul(int a,int b)
{
int res=a*b;
System.out.println(res);
}
}
class demo3
{
public static void main(String[] args)
{
int x=4,y=12;
calculator c=new calculator();
c.mul(x,y);
}
}
Explanation:: In the above example, mul method is called and value of x and y
is passed to a and b.
x and y are actual parameters - called function
a and b are formal parameters - calling function
Example 02 : another example for passing parameters.
//create a class manufacture, which gets the productname
and qty. this class should have a main function
create another class product, which contains a method called
check - to confirm whether the product name is books and quantity is 4.
class product
{
void check(String n,int q)
{
if((n.equals("Books")) && q==4)
System.out.println("Order Accepted");
else
System.out.println("Order Rejected");
}
}
class manufacture
{
public static void main(String[] args)
{
String Pname="Pens";
int qty=4;
product p=new product();
p.check(Pname,qty);
}
}
---------------------------------------- returning values from the program
class product
{
String check(String uname,String pass)
{

if((uname.equals("student")) && pass.equals("niit"))


return "success";
else
return "failure";
}
}
class manufacture
{
public static void main(String[] args)
{
String uname="student";
String pass="niit";
product p=new product();
String res = p.check(uname,pass);
System.out.println(res);
}
}
--------------------------------------case i: [Pass by Value]
x and y is a variable - yes
int y=12;
int x=y;
case ii:[Pass by Reference]
x and y are object
Employee x=new Employee();
Employee y=x;
Example of passing parameters as object:
class calculator
{
int x;
void compute(calculator c2)
{
System.out.println(c2);
}
}
class manufacture
{
public static void main(String[] args)
{
calculator c=new calculator();
c.x=45;
calculator c1=c;//both objects will share memory
c1.compute(c);
}
}
void add(int a,int b)
{
int res=a+b;
System.out.println(res);

}
-- Analyze
1. value is intialized in the method
2. logic is done inside in the method
initializing the data
doing the logic
class calculator
{
int x,y;
void assign(int a,int b)
{
x=a;
y=b;
}
void add()
{
int res=x+y;
System.out.println(res);
}
}
class demo5
{
public static void main(String[] args)
{
calculator c=new calculator();
c.assign(4,2);
c.add();
}
}
-- any thing new in this program?
no
-- why we should add a separate method to intialize
the data and why it has to be separately called?
We have to include some method in the program
which will automatically initialize the data when ever
we execute the program
Constructor - is a special method used to
intialize all the variables in a program
class calculator
{
int x,y;
calculator(int a,int b)
{
x=a;
y=b;
}
void add()
{
int res=x+y;
System.out.println(res);
}
}
class demo5

{
public static void main(String[] args)
{
calculator c=new calculator(10,2);
c.add();
}
}
class calculator
{
int x,y;
void print()
{
System.out.println("X="+x);
System.out.println("Y="+y);
}
}
class demo5
{
public static void main(String[] args)
{
calculator c=new calculator();
c.print();
}
}
-- in theabove program , the value of x and y
is not assigned.
so when we try to print we may think
1. it will print garbage value
2. empty value
3. default value
4. it will throw error
but ans: X=0,Y=0
because of the line
calculator c=new calculator();
-- calls a default constructor and ensures all
the variables used in a program is assigned
a default value.
in the memory::
caculator()
{
x=0;
y=0;
}
Whether it is possible to add our own constructor?
-- if we want to give user-defined value then
we can create user-defined constructor.
-- Example of user-defined Constructor
class calculator
{
int x,y;
calculator()
{
x=10;

y=12;
}
void print()
{
System.out.println("X="+x);
System.out.println("Y="+y);
}
}
class demo5
{
public static void main(String[] args)
{
calculator c=new calculator();
c.print();
}
}
Constructors are also methods, but they dont
take any return type?
-- constructors are used for initializing purpose
not for any logic.
class calculator
{
int x,y;
calculator()
{
x=10;
y=12;
}
calculator(int a,int b)
{
x=a;
y=b;
}
void print()
{
System.out.println("X="+x);
System.out.println("Y="+y);
}
}
class demo5
{
public static void main(String[] args)
{
calculator c=new calculator(10,2);
c.print();
}
}
-------------------------------class calculator
{
int x,y;
calculator()
{
x=10;
y=12;
}

calculator(int a,int b)
{
x=a;
y=b;
}
void print()
{
System.out.println("X="+x);
System.out.println("Y="+y);
}
}
class demo5
{
public static void main(String[] args)
{
System.out.println("FirstObject");
calculator c1=new calculator();
c1.print();
System.out.println("SecondObject:");
calculator c2=new calculator(10,4);
c2.print();
}
}
--Note: Constructor is the first to be executed
in the program before the main method logic.
modified version of the above program :
class calculator
{
int x,y;
calculator()
{
System.out.println("FirstObject");
x=10;
y=12;
}
calculator(int a,int b)
{
System.out.println("SecondObject:");
x=a;
y=b;
}
void print()
{
System.out.println("X="+x);
System.out.println("Y="+y);
}
}
class demo5
{
public static void main(String[] args)
{
calculator c1=new calculator();
calculator c2=new calculator(10,4);
System.out.println("Firstobj");
c1.print();

c2.print();
}
}
Summarize - Charactersitics of Constructors:
1. used to initialize data, not for any other logic
2. it has same name as class name
3. we can more than one constructor in a program
but it should be differentiable.
calculator(int a,int b)
{
}
calculator(int x,int y)
{
}
calculator c2=new calculator(10,3);
//it is an ambiguity.
4. no return types
calculator(int a,int b)
{
}
calculator(int x,int y,int z)
{
}
calculator c2=new calculator(10,3);//work. it will
call first constructor
-----------------------------------------To find
avg of three given no - 3 variables
10 nos - 10 varibles
formula
n variables - n values.
if all the data are of similar type, then we can
put them together as in one memory block - Array
Arrays - is the concept of storing homegenous data
[Similar] under one common name.
Advanced for loop [Foreach loop]
for(datatype destination : source){
}
//to find average of ten given numbers
class demo5
{
public static void main(String[] args)
{

int[] a={10,45,21,78,90};
int[] b=new int[3];//store only 3 elements
//System.out.println(a[4]);
for(int num:a)
System.out.println(num);
String[] fruits={"Apple","Grapes","Orange","Pineapple"};
for(String y:fruits)
System.out.println(y);
for(int i=0;i<5;i++)
System.out.println(a[i]);
}
}
class demo5
{
public static void main(String[] args)
{
String s="Welcome";
System.out.println(s.length());
System.out.println(s.toUpperCase());
System.out.println(s.substring(0,4));
System.out.println(s.toLowerCase());
System.out.println(s.concat("to java batch"));
}}
java.util.Date d=new java.util.Date();
System.out.println(d);
Java.util - is a library package that provides
various builtin classes used by programmer on certain
logics.
import - keyword is used to include packages/ library
classes that be used in the program.
import java.util.Date;
-- above line will use only the date class of utility.
import java.util.*;
-- we can use any classes inside the utility package.
Example 01:
import java.util.Date;
class demo6
{
public static void main(String[] args)
{
Date d=new Date();
System.out.println(d);
}
}

Note:
Utility is a package. Package is a collection of classes
--- Once we invoke object, memory gets allocated
and values are intialized using constructor.
Once after the program reaches end of line
{
Employee e=new Employee();
} - after the end of the line
memory gets destroyed or released.
this process is called as Garbage Collections.
this is done automatically by a destructor.
Module2:
1. Simple java code structure with main method
2. Variables, datatypes & Operators
3. Constructs - if..else, cascading if..else
switch case
4. Loop - for , while , do..while
5. Creating objects
6. Methods - how to create methods, pass parameter,
return values, pass by value and reference
7. Arrays and enhanced for loop
8. Constructors and garbage collection
9. Import statements
10.String Operations
Module 3:
Encapsulation and subclassing :
-----------------------------Encapsulation ::
---------------ID,Name and Salary
Which is constant? - ID and name [Private]
which will vary? - Salary
private and Public
Programmer can fix :
1. which information can be visible to everyone?
2. Which information should be hidden?
1.which information can be modified by others?
2.Which information cannot be modified by others?
Encapsulation is the process of enclosing the
ir-relevant data to the user. ie. hiding of the data
from the user.
This is also called as information hiding or
data hiding
Capsule - tablet

Encapsulation is achieved using access -specifiers.


Private and Public are examples of such access specifiers.
Abstraction - is the process showing the relevant
data.
-----Analyze the program below :
class employee
{
int id;
String name;
int salary;
employee(int i,String n,int s)
{
id=i;
name=n;
salary=s;
}
public void print()
{
System.out.println("EmployeeID:"+id);
System.out.println("EmployeeName:"+name);
System.out.println("EmployeeSalary:"+salary);
}
}
class Manager
{
int id;String name;int salary;String dept;
Manager(int i,String n,int s,String d)
{
id=i;name=n;salary=s;dept=d;
}
void print()
{
System.out.println("ManagerID:"+id);
System.out.println("ManagerName:"+name);
System.out.println("ManagerSalary:"+salary);
System.out.println("ManagerDept:"+dept);
}
}
class demo6
{
public static void main(String[] args)
{
employee e=new employee(1001,"Amit",6700);
e.print();
Manager m=new Manager(1001,"Amit",6700,"IT");
m.print();
}
}
The analysis are :
1.lengthy and complexity increases
2.wastage of memory as same set of variables
are used. ie. repetition of data.

We can overcome this,


as per the drawing drawn on document camera
1. we can use a common class , which contains
all the common data
2. this set of data can be re-used by other classes
with help of inheritance
Inheritance - process in which child class make use
of the parent classes.
Parent - child
Tomorrow we have a class 11-1
class employee
{
int id;
String name;
int salary;
employee(int i,String n,int s)
{
id=i;
name=n;
salary=s;
}
public void print1()
{
System.out.println("EmployeeID:"+id);
System.out.println("EmployeeName:"+name);
System.out.println("EmployeeSalary:"+salary);
}
}
class Manager extends employee
{
String dept;
Manager(int i,String n,int s,String d)
{
super(i,n,s);
dept=d;
}
void print2()
{
System.out.println("ManagerDept:"+dept);
}
}
class demo6
{
public static void main(String[] args)
{
Manager m=new Manager(1001,"Amit",6700,"IT");
m.print1();
m.print2();
}
}
--26/08/2015

features or characteristics of the parent class


is used by the child classes.
- inheritance - achieved using extends keyword
class class1
{
int x=12;
}
class class2 extends class1
{
public void print()
{
int res=x*5;
System.out.println(res);
}
}
class demo7
{
public static void main(String[] args)
{
class2 c=new class2();
c.print();
}
}
-- actor - versatile for all characters
Kamal hasan
Aamir khan
-- single object - existing in many forms
Polymorphism - single object existing in many
forms
Poly - many / morphism - many forms.
class class1
{
public void add(int a,int b)
{
System.out.println(a+b);
}
public void add(int a,int b,int c)
{
System.out.println(a+b+c);
}
public void add(float a,int b)
{
System.out.println(a+b);
}
}
class demo7
{
public static void main(String[] args)
{
class1 c=new class1();
c.add(1,45,2);
}

}
-- order/sequence of parameter
void add(float a,int b)
void add(int a,float b)
--no.of parameter
void add(float a,float b)
void add(float a,float b,float c)
-- datatype of parameter
void add(int a,int b)
void add(float a,float b)
Overloading - process in which we use same name
to multiple functions with unique signatures.
-- is achieved using mechanism of polymorphism
-- datatype of the parameters
class class1
{
public void add(int a,int b)
{
System.out.println(a+b);
}
public void add(float x,int y)
{
System.out.println(x+y);
}
}
class demo7
{
public static void main(String[] args)
{
class1 c=new class1();
c.add(10,20);
}
}
---variable length arguments
-- how to pass multiple value as parameters.
class class1
{
void compute(int[] b)
{
for(int res:b)
System.out.println(res);
}
}
class demo7
{
public static void main(String[] args)
{
int[] a={10,4,21,56,78,21,87};
class1 c=new class1();
c.compute(a);

}
}
(int... b) - variable length arguments
dots represent that 'n' no of data can be accepted
by this variable
class class1
{
void compute(int... b)
{
for(int res:b)
System.out.println(res);
}
}
class demo7
{
public static void main(String[] args)
{
//int[] a={10,4,21,56,78,21,87};
class1 c=new class1();
c.compute(1,2,3,4,5,6,7);
}
}
-- Logic to find average
void compute(int... b)
{
int sum=0;
for(int res:b)
sum=sum+res;
System.out.println(sum/7);
}
Module3 summary:
1. Encapsulation - datahiding
2. Access specifiers - public and private
3. Inheritance - using super keyword
4. Making classes immutable - using constructors
with parameters
5. Polymorphism - overloading
6. Variable length arguments
7. Single inheritance
-- one parent used by one child classes.
class A - base class
class B extends A
Class C extends A
class D extends A
-- one parent used by mutiple child
Inheritance - parent /child relationship
Polymorphism - when to use same object/method
in many forms

Module4:
1.Access Specifier :
Various access specfiers in java
public ,private, default, protected
class class1
{
int x=12;
}
class demo7
{
public static void main(String[] args)
{
class1 c=new class1();
System.out.println(c.x);
}
}
-- in the above program , x variable is accessed
from main function of another class, because
x has "default" access specifier.
when we use default access specifier , data can
accessed by multiple classes within the same
package.
class1.java
package test;
public class class1
{
public int x=12;
}
demo7.java
import test.class1;
class demo7
{
public static void main(String[] args)
{
class1 c=new class1();
System.out.println(c.x);
}
}
--field shadowing
class class2 extends class1
{
int x=5;
void print()
{
System.out.println(x+10);
}
}

-- Field Shadowing
-- when we same variable names in parent as well in child classes
class A
{
int x=10;
}
class B extends A
{
int x=7;
public void print()
{
System.out.println(super.x*8);
}
}
class demo8
{
public static void main(String[] args)
{
B b=new B();
b.print();
}
}
---------------------------class B
{
int x;
B(int x)
{
this.x=x;
}
public void print()
{
System.out.println(x*x);
}
}
class demo8
{
public static void main(String[] args)
{
B b=new B(5);
b.print();
}
}
- this keyword
-- to represent the current object data
-- is used to avoid confusion in specifying the same
names for variables and parameters.
class employee
{
int eid;
string ename;
employee(int eid,string ename)
{
this.eid=eid;
this.ename=ename;
}
}

Super -keyword is used to access the parent/base class data - variable or a meth
od.
this - to make difference between the actual data and parametrized data.
-- program to understand "this" keyword
class employee
{
int eid;
String ename;
employee(int eid,String ename)
{
this.eid=eid;
this.ename=ename;
}
public void print()
{
System.out.println(eid+" "+ename);
}
}
class demo8
{
public static void main(String[] args)
{
employee e1=new employee(1001,"Arun");
e1.print();
}
}
-Overloading - process in which one or more methods have same name but different
definitions
-- polymorphism
Overriding case 1:
Manager m=new Manager();
m.print2();
-- output : welcome to child class
case 2:
employee e=new employee();
e.print1();
Manager m=new Manager();
m.print2();
--output : welcome to parent class
welcome to child class
case 3:
-- invoking parent class methods using super keywords
directly from child class.
class employee
{
void print1()
{

System.out.println("Welcome to parent class");


}
}
class Manager extends employee
{
void print2()
{
super.print1();
System.out.println("Welcome to child class");
}
}
class demo8
{
public static void main(String[] args)
{
Manager m=new Manager();
m.print2();
}
}
case 4:
Override - rewrite,take over replacing the data with another data.
replacing oldlogic with new logic.
Overiding - the process in which the definitions of the parent class is overridd
en(modified)
by the child classes.
class Bank
{
int interest(){
return 100;}
}
class SBI extends Bank
{
int interest() {return 200;}
}
class ICICI extends Bank
{
int interest() {return 300;}
}
class demo8
{
public static void main(String[] args)
{
SBI s=new SBI();
System.out.println(s.interest());
ICICI i=new ICICI();
System.out.println(i.interest());
}
}
case (i):
SBI s=new SBI();
ICICI i=new ICICI();

case (ii): Polymorphism[Runtime Polymorphism]


Bank b=new SBI();
b=new ICICI();
class Bank
{
int interest(){
return 100;}
}
class SBI extends Bank
{
int interest() {return 200;}
}
class ICICI extends Bank
{
int interest() {return 300;}
}
class HDFC extends Bank
{
int interest()
{
return super.interest();
}
}
class demo8
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("SBI ACC="+b.interest());
b=new ICICI();
System.out.println("ICICI Acc="+b.interest());
b=new HDFC();
System.out.println("HDFC ACC="+b.interest());
}
}
---------------------------------------Another example of over-riding :
class subject
{
int score() {return 100;}
}
class java extends subject
{
int score() {return 80;}
}
class android extends subject
{

int score(){
return super.score();}
}
class demo8
{
public static void main(String[] args)
{
subject s=new android();
System.out.println(s.score());
}
}
---------------------------------Inheritance - extend other class
by default every class extends ________class?
ans: Object
Object class contains various methods like
clone(), finalize()
hashcode(), equals(), tostring() methods
-- we can override these methods.
--toString() method example
class employee
{
}
class demo8
{
public static void main(String[] args)
{
employee e1=new employee();
employee e2=new employee();
if(e1.equals(e2))
System.out.println("True");
else
System.out.println("True");
}
}

class employee
{
int eid;
String ename;
employee(int eid,String ename)
{
this.eid=eid;
this.ename=ename;
}
public String toString()
{

return(eid+ " "+ename);


}
}
class demo8
{
public static void main(String[] args)
{
employee e1=new employee(1001,"Oliver");
System.out.println(e1);//calls toString()
}
}
e1.equals(e2)
-- whether both objects belongs to same class ??
what we want to check?
whether both the objects are referring to
same address?
employee e1=new employee();
employee e2=new employee();
//e2=e1;//pass by reference
System.out.println("E1 Object="+e1.hashCode());
System.out.println("E2 Object="+e2.hashCode());
if(e1.equals(e2))
System.out.println("True");
else
System.out.println("False");
whether both objects belongs to same class ??
using instanceof operator
instanceof -operator is used to check whether
object belongs to class or not.
equals - compare objects and check whether objects
refer to same memory locations
Module 5:
--------Generalization
-- extract common things
- general statement
-- to go public
--general rules
Rule - is a statement which has to be followed.
-- to login on time
-- mobile phones - dont use during session
--maintain 80% attendance

Generalization - is creating a standard in


programmming, to implement a rule which has
to be followed by classes.
Generalization [ Super-subtype relation]
In a parent class, we create a rule
All child classes has to follow
NIIT - parent class
SLT students should have ID
class java - they have to follow
class dotnet - they have to follow
Abstract - overview, things are not in detail.
-- small idea of what to be implemented
abstract method
-- represent a standard method which can be
used by the child classes.
-- these methods do not have a body.
-- these methods can be used only inside
the abstract classes.
Abstract classes :
-- represent the parent classes
-- contains abstract methods.
-- we cannot create objects for the abstract classes
abstract class Animal
{
abstract void eat();
}
class Herbivorus extends Animal
{
void eat()
{
System.out.println("Herbivorus eats plants");
}
}
class Carnivorus extends Animal
{
void eat()
{
System.out.println("Carni eats flesh");
}
}
class demo9
{
public static void main(String[] args)
{
Animal a=new Carnivorus();
a.eat();
}
}

Note:
1. Abstract class can have abstract methods,
non abstract methods and any variables
2. All the abstract methods has to be used
by child classes.
abstract class Vehicle
{
abstract void wheels();
abstract void seats();
void driver()
{
System.out.println("every vehicle requires driver");
}
}
class car extends Vehicle
{
void wheels()
{
System.out.println("4 wheels in a car");
}
void seats()
{
System.out.println("more than 4 depend on cartype");
}
}
class demo9
{
public static void main(String[] args)
{
car c=new car();
c.wheels();
c.seats();
}
}
Note:
Abstract comes under concept of single
inheritance
abstract class NIITScore
{
abstract void score(int pmr,int CT,int MT);
public void books()
{
System.out.println("Every course has books");
}
}
class JAVA extends NIITScore
{
void score(int pmr,int CT,int MT)
{
super.books();
System.out.println(pmr+CT+MT);
}
}

class Html extends NIITScore


{
void score(int pmr,int CT,int MT)
{
System.out.println(CT+MT);
}
}
class demo9
{
public static void main(String[] args)
{
JAVA j=new JAVA();
j.score(25,20,45);
Html h=new Html();
h.score(0,22,70);
}
}
-------------------------------Static variables and static methods :
class employee
{
int empcount=0;
void print()
{
empcount++;
System.out.println(empcount);
}
}
class demo9
{
public static void main(String[] args)
{
System.out.println("First Object");
employee e1=new employee();
e1.print();
System.out.println("Second object");
employee e2=new employee();
e2.print();
}
}
-- in the above program, the output prints
as 1 , 1 instead of 1 2
because the empcount is a local variable
which will not retain the data from one object
to another object.
-- to retain the data for multiple objects
we have to use static variables.
Static variable - will have only one instance
of class in memory.. only one copy of data in
memory.

class employee
{
static int empcount=0;
void print()
{
empcount++;
System.out.println(empcount);
}
}
class demo9
{
public static void main(String[] args)
{
System.out.println("First Object");
employee e1=new employee();
e1.print();
System.out.println("Second object");
employee e2=new employee();
e2.print();
}
}
Static methods:
-- can have only static variables
--- can be called directly using the class name
classname.methodname();
-- using objects to call static methods
is not a good programming practice.
static int empcount=0;
int a=5;
static void print()
{
a++;//error. normal variables cannot be used in
//static methods.
empcount++;
System.out.println(empcount);
}
-- Final variables and Final Methods:
------------------------------------When we delcare a variable as final, it cannot
be modified.. it act as a "CONSTANT" Value.
class employee
{
final int a=10;
}
class manager extends employee
{
void compute()
{
a=45;

System.out.println(a*5);
}
}
class demo9
{
public static void main(String[] args)
{
manager m=new manager();
m.compute();
}
}
-- in the above program
the variable "a" is in employee class
-- it is a final variable
-- in the manager class we try to give a new
value for the variable "a"
Error: final variable cannot be modified.
-- if you dont want a method in the parent class
to be over-ridden by the child classes,
then we can use __________methods
ans: final
class employee
{
final void compute()
{
System.out.println("welcome");
}
}
class manager extends employee
{
void compute()
{
System.out.println("hi");
}
}
class demo9
{
public static void main(String[] args)
{
manager m=new manager();
m.compute();
}
}
-- in the above program, we have a method compute
in parent class, which is declared as final
-- when child class overrides the same method,
it results in error.
class employee
{
final void compute()

{
System.out.println("welcome");
}
}
class manager extends employee
{
void compute()
{
System.out.println("hi");
}
}
class demo9
{
public static void main(String[] args)
{
manager m=new manager();
m.compute();
}
}
static imports:
import static java.lang.Math.random;
int a=random();
Difference between static and final variables
Static variable - used to retain the data
in a program for multiple objects.
Final variable - used to declare constants values
in the program
import static java.util.Date;
double d=Date();
Date d=new Date();
Module 5 continued..
why do we prefer final keyword?
to set a constant value for a variable
we give final keyword to a method, if we
dont want the method to be overridden.
What are the other ways to give constant in java?
Enumeration - is a technique which stores a set
of data with constant/fixed values.
The keyword used to declare enumeration is
enum
syntax:
enum enumeration_name { data1,data2,data3... datan}
some examples:
enum colors { Red,Green,Blue};
enum months {jan,feb,Mar,Apr,May};

enum days {Mon,tue,Wed,thu,Fri,sat,sun};


enum directions {North,south,east,west};
example 01:
enum months {jan,feb,Mar,Apr,May};
class demo10
{
public static void main(String[] args)
{
System.out.println(months.Mar);
}
}
-- output: Mar
the above programs and print the enum data, not
the value of the enum
example 02:

enum months {jan(31),feb(28),


Mar(31),Apr(30),May(31) ;
public int data;
private months(int d)
{
data=d;
}
}
class demo10
{
public static void main(String[] args)
{
months m=months.Mar;
System.out.println(m.data);
}
}
-- to print more than one data
months m=months.Mar;
System.out.println(m.data);
m=months.May;
System.out.println(m.data);
-- if want to print all data of a enum
enum months {jan(31),feb(28),
Mar(31),Apr(30),May(31) ;
public int data;
private months(int d)
{
data=d;
}
}
class demo10
{

public static void main(String[] args)


{
for(months m : months.values())
System.out.println(m+" "+m.data);
}
}
-- Implementing Design patterns
Design patterns are the standards available
in programming which promotes the concept
of reusability.
-- These are patterns that are created which
increases the efficiency of the program
Common Design patterns are :
1. single ton pattern
2. Nested classes
3. Annonymous inner classes.
Singleton pattern:
case(i):
emp e1=new emp();
emp e2=new emp();
-- both occupies different block of memory
-- if we want to make both objects to point to
same instance
case (ii);
emp e1=new emp();
emp e2=e1;
instead of assigning the objects separately,
we can create one object, whose instance can be
accessed by all objects - single ton.
class emp
{
static final emp e=new emp();
public static emp getInstance(){
return e;
}
}
class demo10
{
public static void main(String[] args)
{
emp e1=emp.getInstance();
emp e2=emp.getInstance();
if(e1.equals(e2))
System.out.println("Both points to same reference");
}
}
-- we are creating one object as static/final

when ever we create access data of the same class


using other objects eg:
emp e1=new emp1();
instead of this ,we can access using
emp e1=emp.getInstance();
--- getInstance method will return the object
reference.
--2. Nested classes:
-- one class with another classes.
structure:
class outer
{
class inner
{
}
}
example :
class niit
{
String course;
class SLT
{
public void mode()
{
course="java";
System.out.println("IT is a online class:"+course);
}
}
public void print()
{
SLT s=new SLT();
s.mode();
}
}
class demo10
{
public static void main(String[] args)
{
niit n=new niit();
n.print();
}
}
Note:
1. outer
by inner
2. inner
by outer

class
class
class
class

variables can be accessed


variables
methods can be accessed
objects

syntax:
outerclassobject.new innerclass().methodname();

Design patterns:
1. Singleton
2. nested classes
3. Anonymous inner class.
Anonymous inner class:
-- it is a class which has no name.
class Object
{
public String toString(){
return "welcome";
}
}
class demo11
{
public static void main(String[] args)
{
Object o=new Object();
System.out.println(o);
}
}
-- in the above program, we declare a separate
class object which has toString() method.
instead of delcaring a separate class, we can
call the class object directly in the progam
using anonymous inner classes.
class demo11
{
static Object o=new Object(){
public String toString(){
return "Welcome";
}
};
public static void main(String[] args)
{
System.out.println(o);
}
}
Module 5 - completed
Summary :
1. Generalization - Abstract classes and methods.
2. Final methods and variables
3. Static variables and methods
4. Enumeration
5. Design patterns.
Today we will have revision session
on Chapter 3 and 4
Timings:: 2 - 4 PM
-- Tomorrow CR [11-1 PM] - 2/09/2015
PMR2 - 05/09/2015 - 11-1 PM

Module 6: Interfaces:
--------------------abstract class Bank
{
abstract void interest();
}
Notes:
1. it is not possible to create object
for the abstract class - True
2. Abstract methods must be give inside
the abstract class only - True
3. Abstract classes are used to achieve
single inheritance - True
Inheritance -we had a single parent class
and many child classes.
[one parent - one child =>single inheritance]
class employee{}
class manager extends employee{
}
class clerk extends employee{
}
more than one parent has to be accessed by a child.
class niit{ - parent
}
class slt{ - parent
}
class student extends niit,slt{ //error.
}
multiple inheritance
-- the above line will throw an error ..
that a class cannot extend more than one class..
so, to achieve the concept of multiple inheritance
we use the concept of interfaces.
Interface - mediator , medium,
point of interconnection,boundary etc
Interface - is a standard , represent a set of
methods which has to be followed by all the
child classes, where child classes implement
the functionality.
interface interfacename
{
//method declarations;
}
interface calculator
{
void add();
void sub();

}
Note : just declare the method.
void add(); declare
void add(){ define
//code
}
Abstract classes and methods:
1. can have any variables of any type
2. can have abstract method as well non abstract
methods.
3. it is used to achieve single inheritance
4. the methods can be private, protected etc
5. used by similar classes
6. extends keyword
abstract class Bank{abstract void interest();}
class SBI extends Bank{}
class ICICI extends Bank{}
Interface
1. can have only static final variables
2. can have only method declaration
3. used to achieve multiple inheritance
4. by default all methods are public only.
5. can be used by dis-similar classes.
6. implements keyword
void fly();
class Birds
class Airplane
class Ballon
class Kite
void fuel();
class vehicle
class rocket
class generator
example 01:
Simple example - using one interface
interface ATM
{
void withdraw();
void checkbalance();
}
class bank implements ATM{
public void withdraw(){
System.out.println("withdraw money");
}
public void checkbalance(){
System.out.println("check balance of your acc");
}
}
class demo11
{

public static void main(String[] args)


{
bank b=new bank();
b.withdraw();
b.checkbalance();
}
}
example 02: uses more than one interface
-- multiple inheritance
interface Addition{
void add();
}
interface Subtraction{
void sub();
}
class calculator implements Addition,Subtraction
{
int a=10,b=5;
public void add(){
System.out.println(a+b);
}
public void sub(){
System.out.println(a-b);
}
}
class demo11
{
public static void main(String[] args)
{
calculator c=new calculator();
c.add();c.sub();
}
}
example 03:
using abstract classes and interface :
interface Addition{
void add();
}
interface Subtraction{
void sub();
}
abstract class multiplication{
abstract void mul();
}
class calculator extends multiplication
implements Addition,Subtraction
{
int a=10,b=5;
public void add(){
System.out.println(a+b);
}

public void sub(){


System.out.println(a-b);
}
public void mul(){
System.out.println(a*b);
}
}
class demo11
{
public static void main(String[] args)
{
calculator c=new calculator();
c.add();c.sub();c.mul();
}
}
example 04:
-- we can use interface methods as well as user
defined methods inside the child class
interface Addition{
void add();
}
class calculator implements Addition
{
int a=10,b=5,res;
public void add(){
res=a+b;
}
public void print(){
System.out.println(res);
}
}
class demo11
{
public static void main(String[] args)
{
calculator c=new calculator();
c.add();c.print();
}
}
example 05:
Addition a=new calculator();
a.add();//works.. interface contains add method
a.print()//throw error.
in the above example,
we are creating object of the interface
and then assigning a child class to it.
there fore when we call a.add()
it will first call the interface and check
whether the method is available in the interface or
not.

if it is available, control will go to child


class and then method will be called.
if it is not available, then will throw an error
message.
example 06:
one interface uses another interface
interface Addition{
void add();
}
interface subtraction extends Addition
{
void sub();
}
class calculator implements Subtraction
{
}
Module6 Continued..
Interfaces:
-- is a standard to be followed by child classes
child class will implement the functionality.
Recap example 01:
interface Shape
{
void draw();
}
class circle implements Shape
{
public void draw(){
System.out.println("Draw circle");
}
}
class Triangle implements Shape
{
public void draw(){
System.out.println("Triangle");
}
}
class demo12
{
public static void main(String[] args)
{
circle c=new circle(); c.draw();
Triangle t=new Triangle(); t.draw();
}
}
example 02:[using interface objects]

Parent obj=new child();


child obj=new parent();//error
class demo12
{
public static void main(String[] args)
{
Shape s=new circle();
s.draw();
s=new Triangle();
s.draw();
}
}
example 03:[more than one interface]
interface Shape
{
void draw();
}
interface geometry
{
void angle();
}
class Triangle implements Shape,geometry
{
public void draw(){
System.out.println("Right angle triangle");
}
public void angle(){
System.out.println("angle must be 90degree");
}
}
class demo12
{
public static void main(String[] args)
{
Triangle t=new Triangle();
t.draw(); t.angle();
}
}
example 04:one interface implements another interface
interface Shape
{
void draw();
}
interface geometry extends Shape
{
void angle();
}
class Triangle implements geometry
{
public void draw(){
System.out.println("Right angle triangle");
}

public void angle(){


System.out.println("angle must be 90degree");
}
}
class demo12
{
public static void main(String[] args)
{
Triangle t=new Triangle();
t.draw(); t.angle();
}
}
example 05: checking the instance of interface
class demo12
{
public static void main(String[] args)
{
Triangle t=new Triangle();
if(t instanceof Shape)
t.draw();
}
}
example 06 : marker interface
public class demo implements Runnable
{
public void run(){
}
}
Note: marker interfaces are those which is available
pre-defined in the java libraries, which can be
directly used by the child classes .
example 07: using abstract and interface :
interface Shape
{
void draw();
}
abstract class Geometry
{
abstract void angle();
}
class Triangle extends Geometry implements Shape
{
public void draw(){
System.out.println("Right angle triangle");
}
public void angle(){
System.out.println("angle must be 90degree");
}
}
class demo12

{
public static void main(String[] args)
{
Triangle t=new Triangle();
if(t instanceof Shape)
t.draw();
}
}
interface A
{
}
interface B
{
}
interface C
{
}
DAO Patterns and Code Reusability:
DAO Patterns ::
-- NOTE : REFER TO THE excel sheet.
Module 7:
--------Generics and Collections:
-------------------------class emp
{
void add(double a){
System.out.println(a);
}
}
class demo13
{
public static void main(String[] args)
{
emp e=new emp();
//e.add(4);
//e.add("welcome");
e.add(4.5);
}
}
-- note:
in the add method , we try to pass data of
different datatypes.. which leads to modifying
the method every time
so we need to create some mechanism, to define
a method which accepts the data of any type.
This can be achieved by using concept of
Generics.
Generics is the concept of defining a template
in the code, so that template accepts the data

of any type.
Syntax:
class classname<T>
{
void methodname(T){
}
}
example of Generics 01:
class emp<T>
{
void add(T a){
System.out.println(a);
}
}
class demo13
{
public static void main(String[] args)
{
emp e=new emp();
e.add(4);
e.add("welcome");
e.add(4.5);
}
}
example 02:
class Student<T>
{
void print(T id,T marks)
{
System.out.println(id + " "+marks);
}
}
class demo13
{
public static void main(String[] args)
{
Student s=new Student();
s.print(1001,45)
s.print(1002,78.3000);
s.print(1003,89.3F);
}
}
-- Collections:
---------------- group of items - we have to give a size
Arrays
Advantages of arrays:
1. store a group of data together
2. optimize memory space
Drawbacks of arrays:
1. only similar data can be stored
2. insertion and deletion of data is complex.

3. Since the size is fixed, there is a


possibility in wastage of memory space.
if array size is 40, if only 30 elements are
present, then remaining 10 space will go waste.
-- so the above drawbacks has to be addressed.
solution : instant memory.
if items comes, allocate memory and store it.
if items removed, then deallocate memory.
This can be achieved using the concept of
collections.
Collections are dynamic data type, which allocates
memory when items added, deallocates when item
gets removed.
Examples of collections classes are:
1. ArrayList
2. Sets
3. HashMap
4. Deque
-- Linkedlist,Stack,queue,Trees,Graphs
Hashtable,dynamic arrays
-- to implement collections, whether any
package is required?
yes
java.util.*
ArrayList ::
-- class used to store 'n' no of items of different
types or a generic type
Syntax:
ArrayList obj =new ArrayList();//items of anytype
ArrayList<Type> obj=new ArrayList<Type>();
Type indicates the datatype in which the value
has to be stored.
example 01:
import java.util.*;
class demo13
{
public static void main(String[] args)
{
ArrayList a=new ArrayList();
a.add("Arun");
a.add(45);
a.add("welcome");
a.add(89.3);
System.out.println(a);
}
}
output:
[Arun, 45, welcome, 89.3]

example 02:
if we want to restrict the data only to a particular
type.
ArrayList<Integer> a=new ArrayList<Integer>();
a.add(45);
a.add(89);
a.add(12);
a.add(4);
System.out.println(a);
Note: List obj=new ArrayList();
(2)SETS:
-- used to store dynamic collection of data as
arraylist
note: it will not allow duplicate values.
import java.util.*;
class demo13
{
public static void main(String[] args)
{
//Set s=new TreeSet();
Set<Integer> s=new TreeSet<Integer>();
s.add(12);
s.add(45);
s.add(12);
System.out.println(s);
}
}
output:
[12,45]
(3) HASHMAP
------------ to store the data dynamically
-- will store the data as key-value pairs.
import java.util.*;
class demo13
{
public static void main(String[] args)
{
HashMap<String,String> h=new
HashMap<String,String>();
h.put("Name1","Ramesh");
h.put("Name2","Oliver");
h.put("Name3","Arun");
h.put("Name3","Vinayak");
System.out.println(h);
}

}
output:
{Name3=Vinayak, Name2=Oliver, Name1=Ramesh}
(4)DEQUE:
-- applies the concept of Queue and Stack
Queue - FirstInFirstOut [FIFO]
Stack - LastInFirstOut[LIFO] or
FirstInLastOut[FILO]
import java.util.*;
class demo13
{
public static void main(String[] args)
{
//queue implementation
Deque d=new ArrayDeque();
d.add(12);
d.add("Oliver");
System.out.println(d);
//stack implementation
Deque d1=new ArrayDeque();
d1.push(12);
d1.push("Oliver");
System.out.println(d1);
d.remove();
System.out.println(d);
d1.pop();
System.out.println(d1);
}
}
Module 7 Contd..
Collections:
------------- example of dynamic datatype
-- memory gets allocated when item added,
memory gets destroyed when item gets removed
ArrayList, Set, HashMap and Deque
ArrayList a=new ArrayList();
a.add("Rakesh");
a.add(23);
a.add(34.5)
--above code is a normal code that accepts
data of alltypes
-- example 02:
ArrayList<String> a=new ArrayList<String>();
a.add("Rakesh");
a.add("23");
a.add("Arun");
System.out.println(a);
the above code is a generalized code that stores

only string data


output:
[Rakesh, 23, Arun]
-- example 03: using for loop to print the data
ArrayList<String> a=new ArrayList<String>();
a.add("Rakesh");
a.add("23");
a.add("Arun");
for(String b:a)
System.out.println(b);
output:
Rakesh
23
Arun
-- example 04: using hashmap
HashMap<String,Integer> h=new
HashMap<String,Integer>();
h.put("k1",1001);
System.out.println(h);
example 05:
ArrayList a=new ArrayList();
a.add("Oliver");
a.add("Dhiraj");
a.add("Arun");
Iterator i=a.iterator();
while(i.hasNext())
System.out.println(i.next());
--example 06:
class product
{
int pid;String pname;
public product(int i,String n){
pid=i;
pname=n;
}
}
class demo14
{
public static void main(String[] args)
{
product p1=new product(1001,"Books");
product p2=new product(1002,"Flowers");
ArrayList a=new ArrayList();
a.add(p1);a.add(p2);
Iterator i=a.iterator();

while(i.hasNext()){
product p=(product)i.next();
System.out.println(p.pid+" "+p.pname);
}}
-- Arranging the object data.
Comparable and Comparator
Comparable interface - used to arrange the
data based on one value.
example 01: comparable
import java.util.*;
class product implements Comparable<product>
{
int pid;String pname;
public product(int i,String n){
pid=i;
pname=n;
}
public int compareTo(product p){
if(p.pid==pid) {return 0;}
else if(p.pid<pid) {return 1;}
else {return -1;}
}
}
class demo14
{
public static void main(String[] args)
{
product p1=new product(1001,"Books");
product p2=new product(1002,"Flowers");
ArrayList a=new ArrayList();
a.add(p1);a.add(p2);
Collections.sort(a);
Iterator i=a.iterator();
while(i.hasNext()){
product p=(product)i.next();
System.out.println(p.pid+ " "+p.pname);;
}}
}
-- if we want to arrange data by different
properties - use comparator concept
import java.util.*;
class product
{
int pid;String pname;
public product(int i,String n){
pid=i;

pname=n;
}
}
class Idsort implements Comparator<product>{
public int compare(product p1,product p2){
if(p1.pid==p2.pid){return 0;}
else if(p1.pid>p2.pid){return 1;}
else {return -1;}
}
}
class namesort implements Comparator<product>{
public int compare(product a,product b){
return b.pname.compareTo(a.pname);
}
}
class demo14
{
public static void main(String[] args)
{
product p1=new product(12,"Books");
product p2=new product(8,"Flowers");
product p3=new product(10,"Pens");
ArrayList a=new ArrayList();
a.add(p1);a.add(p2);a.add(p3);
Collections.sort(a,new Idsort());
System.out.println("Sorting by ID..");
Iterator i=a.iterator();
while(i.hasNext()){
product p=(product)i.next();
System.out.println(p.pid+ " "+p.pname);;}
Collections.sort(a,new namesort());
System.out.println("Sorting by Name..");
Iterator i1=a.iterator();
while(i1.hasNext()){
product p=(product)i1.next();
System.out.println(p.pid+ " "+p.pname);;
}}
}
Module 8 ::
String processing ::
-------------------1. pass the string data as a command
line arguments
class demo15
{
public static void main(String[] args)
{
System.out.println(args[0]);
System.out.println(args[1]);
}
}
-- when we compile the above program,
we pass the data as
javac demo15.java

java demo15 Oliver IT


-- Oliver and IT are the two data passed to a program
these data are stored in the string array
and value is fetched using the index
-- if we are going to pass more number of data
using cmd line .. then it is better to declare
a for loop to get all the value.
This can be done using Length Property.
String[] a={"apple","orange","banana"};
System.out.println(a.length);
output: 3
class demo15
{
public static void main(String[] args)
{
for(int i=0;i<args.length;i++){
System.out.println(args[i]);
}
}
}
2. using properties.
we can create a file -> employee.properties
Empname=Arun
EmpCode=14321
Department =IT
-- if we have a file which contains the data,
these files can be accessed from any where with
the help of properties.
class demo15
{
public static void main(String[] args)
{
String name=System.getProperty("n");
System.out.println(name);
}
}
-- in the above program , we are accessing the
property value. this property value can be accessed
from the file or directly through the command prompt.
from the commmand prompt, if we want to pass the
property value, syntax is
java -Dpropertyname=value classname
eg:
java -Dn=Nishanth demo15
3. other methods used to print data.
PrintWriter
-- to write data to a file
-- used in netbeans to exactly know the data where

the line gets processed.


import java.io.*;
class demo15
{
public static void main(String[] args)
{
PrintWriter p=new PrintWriter(System.out,true);
p.println("welcome");
}
}
another code to format data using printwriter:
import java.io.*;
class demo15
{
public static void main(String[] args)
{
int a=4,b=6,res;
res=a+b;
PrintWriter p=new PrintWriter(System.out,true);
//p.println("welcome");
p.printf("The sum of %d and %d is %d",a,b,res);
String name="Oliver";
p.printf("%s is the name of the faculty",name);
}
}
4. String Operations::
String Builder and String Buffer
equals(), contains(),
replace(), substring()
class demo15
{
public static void main(String[] args)
{
StringBuilder sb=new StringBuilder(50);
sb.append("java batch");
sb.insert(5,"PGP12 ");
System.out.println(sb);
}
}
-- some operations in string

class demo15
{
public static void main(String[] args)
{
String t1="Welcome";
String t2="Hello";
if(t1.equals(t2))
System.out.println("Match!");

else
System.out.println("Not match");
if(t1.contains("co"))
System.out.println("Found");
String s=t1.replace("W","h");
System.out.println(s);
System.out.println(t2.substring(1,4));
}
}
-------------------------5. using split methods in strings
class demo15
{
public static void main(String[] args)
{
String fruits="Apple,Grapes,Orange,Pineapple";
String[] res=fruits.split(",");
for(String r:res)
System.out.println(r);
}
}
--we can also print data using
StringTokenizer classes
import java.util.*;
class demo15
{
public static void main(String[] args)
{
String fruits="Apple,Grapes,Orange,Pineapple";
StringTokenizer s=new StringTokenizer(fruits,",");
while(s.hasMoreTokens())
System.out.println(s.nextToken());
}
}
---------------------------------------------Scanner class:
--------------- used to get the input value from the user
dynamically.
import java.util.*;
class demo15
{
public static void main(String[] args)
{
int a,b,res;
Scanner s=new Scanner(System.in);

System.out.println("Enter first number");


a=Integer.parseInt(s.nextLine());
System.out.println("Enter Second number");
b=Integer.parseInt(s.nextLine());
res=a+b;
System.out.println(res);
}
}
another way:
int a,b,res;
Scanner s=new Scanner(System.in);
System.out.println("Enter first number");
a=s.nextInt();
System.out.println("Enter Second number");
b=s.nextInt();
res=a+b;
System.out.println(res);
-- Class schedule:
08/09/2015 - CR :: 11.30-1 PM
09/09/2015[Wednesday] - CR :: 10 - 1 PM
10/09/2015[Thursday] - CR :: 10-1 PM
11/09/2015 - MR
--- do a program
to get the student name, and marks
from the user and to print the details
import java.util.*;
class demo15
{
public static void main(String[] args)
{
String name;
int marks;
char grade;
Scanner s=new Scanner(System.in);
System.out.println("Enter your name");
name=s.next();
System.out.println("Enter marks");
marks=s.nextInt();
System.out.println("Enter grade");
grade=s.next().charAt(0);
System.out.println("The name is"+name);
System.out.println("Mark is"+marks);
System.out.println("Grade is"+grade);
}
}
Module8 contd..
import java.util.*;
class demo16
{
public static void main(String[] args)

{
String dept;
Scanner s=new Scanner(System.in);
System.out.println("Enter your dept");
dept=s.next();
if(dept.equals("IT"))
System.out.println("InformationTechnology");
else if(dept.equals("CSE"))
System.out.println("ComputerScienceEngg");
else if(dept.equals("Mech"))
System.out.println("MechanicalEngg");
else
System.out.println("Not in choice");
}
}
---------------------------------------Regular Expressions:
-------------------What is regular expression?
- are the formats used to represent a set of
data in the correct pattern
EmployeeID used be starting with E followed
by 4 digits.
formula : E\d{4} [Regular expression]
E1001 - correct
E108 - wrong [ not matching with pattern]
Code - number[8digits]
1. what is the regular expression for mail ID?
2. regular expression for mobile number?
3. regular expression for a password?
Regular Expressions:
Pattern and Matcher
Pattern - format of the regular expression
Matcher - whether the format is matching with the
input provided.
import java.util.regex.*;
class demo16
{
public static void main(String[] args)
{
String str="Welcome to PGP12 batch";
Pattern p=Pattern.compile("java"); //format
Matcher m=p.matcher(str);
if(m.find())
System.out.println("Data matched!");
else
System.out.println("Data not match!");

}
}
//Problem : check whether the given string
//contains "to" word. After to print all the
//remaining words.
Pattern : to.*
case(i):
Pattern p=Pattern.compile("to.*");
output: to PGP12 Batch
case(ii): fetch integers/digits
Pattern p=Pattern.compile("\\d\\d");
output: 12
case(iii):
Pattern p=Pattern.compile("\\sto\\s");
output : to
case(iv):
Pattern p=Pattern.compile("to.*batch");
output: to PGP12 Batch
case(v);
String str="Welcome to the java batch to do java program";
Pattern p=Pattern.compile("Welcome.*java");
output:
Welcome to the java batch to do java
String str="Welcome to the java batch to do java program";
Pattern p=Pattern.compile("Welcome.*?java");
Output:
Welcome to the java
Matching and groups:
--------------------- we need to find exactly whether the user
data is matching with the format or not.
import java.util.regex.*;
class demo16
{
public static void main(String[] args)
{
String myid="george.johngmail.com";
Pattern p=Pattern.compile("^(.+)@(.+)$");
Matcher m=p.matcher(myid);
if(m.find())

System.out.println("matched");
}
}
ReplaceAll method:
-----------------import java.util.regex.*;
class demo16
{
public static void main(String[] args)
{
String text="Welcome to C# batch to do C# programs";
Pattern p=Pattern.compile("C#");
Matcher m=p.matcher(text);
if(m.find())
text=m.replaceAll("java");
System.out.println(text);
}
}
Volume II:
----------Chapter 9:
What are the errors we can get in program?
1. Syntax error
missing a semicolon
case sensitive "String" - capital 'S'
not closing the brackets
These errors are clearly specified by the compiler
and hence can be corrected.
2. Logical error.
expected result is not equal to actual result.
divide the numbers ,return the remainder.
int a=4,b=2;
int res=a/b;
the above code is not having any syntax error.
but logic
Logic should be a%b.
Whether these logical errors can be corrected?
ans: yes
3. Runtime errors:
-- which the compiler will face when the user passes

the value at the run time


or program in the run time.
Exception handling is the process of solving
the unexpected errors in the program
Expection -unexpected event or cause.
How to handle these kind of errors in the
program?
try
catch
-- These are the keywords used for exception
handling
Syntax:
try{
//code
}
catch(Exception e){
//handle the errors
}
-- Exception - class used to handle runtime errors
in program
Note: Try block must be always associated with
catch block
without exception:
class demo17
{
public static void main(String[] args)
{
int a=4,b=0;
System.out.println(a/b);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at demo17.main(demo17.java:8)
The above error is a runtime error, which can
be solved using Try and catch blocks as below
class demo17
{
public static void main(String[] args)
{
int a=4,b=0;
try{
System.out.println(a/b);
}
catch(Exception e){
System.out.println("Error!");
}
}
}

----------------------------------------------import java.util.*;
class demo17
{
public static void main(String[] args)
{
int no;
Scanner s=new Scanner(System.in);
System.out.println("Enter the number");
try{
no=s.nextInt();
System.out.println(no);
}
catch(Exception e){
System.out.println("Give proper input");
}
}
}
Inside the catch block, we give Exception - common
name which will handle all exceptions.
--Note:
if we know the exact exception name, we can use
them directly in the program as below
catch(InputMismatchException e){
System.out.println("Give proper input");
}
--is it possible to have multiple catch blocks.
import java.io.*;
import java.util.*;
class demo17
{
public static void main(String[] args)
{
int no;
Scanner s=new Scanner(System.in);
System.out.println("Enter the number");
try{
no=s.nextInt();
System.out.println(no);
}
catch(InputMismatchException e){
System.out.println("Give proper input");
}
catch(FileNotFoundException e){
System.out.println("file is not found");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Please check array value");
}
}

}
--- out of the three catch blocks, based on the
error from the try block, corresponding catch
block gets executed.
we can also handle error using catch | symbol
catch(InputMismatchException | ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
Note: if you feel difficult to mention different
exception names, then use
catch(Exception obj){}
finally - used to execute whether the exception
is thrown or not.
This block will always execute regardless of
exception thrown or not.

import java.io.*;
import java.util.*;
class demo17
{
public static void main(String[] args)
{
int no;
Scanner s=new Scanner(System.in);
System.out.println("Enter the number");
try{
no=s.nextInt();
System.out.println(no);
}
catch(InputMismatchException | ArrayIndexOutOfBoundsException e){
System.out.println("Give proper input");
}
finally{
System.out.println("Transaction ends..");
}
}
}
Note: every method, can have one try , mutiple
catch and one finally.
every try block must have a catch block.
finally block is optional.
add(), sub()
add() - one try, multiple catch and one finally
sub() - one try, multiple catch and one finally
(or)
try-with resources statement:
-----------------------------

--- use the try with resources used in the program


either the transaction is completed or an error
is thrown, close method will be automatically
called and ensure that resources are closed whenever
not needed.
class employee implements AutoCloseable
{
public void display()
{
System.out.println("display details");
}
public void close(){
System.out.println("Resources closed");
}
}
class demo17
{
public static void main(String[] args)
{
try(employee e=new employee()){
e.display();}
catch(Exception obj){
System.out.println(obj.getMessage());
}
}
}
-------------------------------throws and throw keywords in exceptions:
Throws keyword - used when any class or a method
may thrown an exception once it is invoked
syntax:
return-type methodname throws exceptionname{}
return-type methodname throws exception1,exception2
{}
Program:
import java.util.*;
class employee
{
public void display() throws InputMismatchException
{
int no;
Scanner s=new Scanner(System.in);
System.out.println("Enter number");
no=s.nextInt();
System.out.println(no);
}
}
class demo17
{

public static void main(String[] args)


{
employee e=new employee();
try{ e.display(); }
catch(Exception e1){
System.out.println("Error!Give valid input");
}
}
}
throw:
-- it is like a statement ,incorporated any where
in the program to call the exceptions
Syntax:
throw new exceptioname(message);
Program:
class demo17
{
void test(int score)
{
if(score<0)
throw new ArithmeticException("Not a valid mark");
else
System.out.println("passed");
}
public static void main(String[] args)
{
demo17 d=new demo17();
d.test(-5);
}
}
Throw keyword - plays an important role in custom
exceptions.
Custom - user defined exceptions.
we can also create user defined exceptions by extending the inbuilt
exception classes.
syntax:
class userdefinedname extends Exception{
//add a constructor
}
class ScoreException extends Exception{
ScoreException(String msg){
System.out.println(msg);
}
}
class demo17
{
void test(int score)
{
if(score<0)
throw new ScoreException("Not a valid mark");

else
System.out.println("passed");
}
public static void main(String[] args)
{
demo17 d=new demo17();
d.test(-5);
}
}
format eg:
class MyException extends Exception{
MyException(String msg){
}
}
void display() throws MyException
{
if(score<0)
throw new MyException("not valid");
}
Assertions:
-- a declaration made when no supporting
evidence is necessary.
--fact
examples of facts:
human body consist of 206 bones.
vote to age is above or equal to 18 years.
Leap year comes once in 4 years
Assertions in Programs:
Assertions are the declarations used in the program
to check the conditions.
Syntax:
assert condition : message
Run the assertion program
java -ea filename
import java.util.*;
class demo18
{
public static void main(String[] args)
{
int age;
Scanner s=new Scanner(System.in);
System.out.println("Enter your age..");
age=s.nextInt();
assert age>=18:"Not valid age to Vote!";
System.out.println("entered age:"+age);
}
}
Exceptions - Checked Exceptions or unchecked
Exceptions

Checked - exceptions which can be handled or declared.


unchecked - exceptions are not typically handled
or delcared.
eg: java.lang.RuntimeExceptions
ArrayIndexOutofBounds, Arithmetic,NullPointerException
Wrapper Exceptions:
------------------embedding one exception with another
class InvalidAgeException extends Exception{}
catch(SQLException e){
throw new InvalidAgeException("Error!");
}
suppressed exception:
catch(Exception e){
for(e.getSuppressed()){
S.o.p(e.getMessage());
}
----------------------------------------------Module 9 :
1. different types of errors
2. exception handling
3. using try and catch block
4. finally block
5. try with resources statement
6. throw and throws
7. userdefined exceptions
8. assertions.
Module 10:
---------JAVA I/O Fundamentals:
---------------------IO
Where do we store the input in a program?
Variables
the data in variables are permanent or
temporary?
ans: temporary
reason: value in the variable is alive only during
the execution of the program
Program:
employee details: Empname and empdepartment
Store these details permanenlty.
files, databases
Files - are the collection of data stored permanently
which can be accessed when ever required.
eg:image, audio, video, text, etc
collections of files is a package or folder.

Files are categorized into :


Character files - file which is easily readable
and in text format.
Byte files - file which contains byte code
[image,audio,video,objects]
Package - java.io.*
Classes :
Character Files :
FileReader - reading data from a file
FileWriter - writing the data to a file
Byte file:
FileInputStream - reading data from a file
FileOutputStream - writing the data to a file.
Stream - is the passage of the data between
source to the destination.
Input Stream - reading the data from the source
Output Stream - writing the data to the
destination(sink)
Syntax of read method:
read(char)
read(char,from)
read(char,from,to)
Example 01: Reading the Character data from the
existing file:
import java.io.*;
class demo18
{
public static void main(String[] args) throws IOException
{
//1.decide the class [Textfile]
char[] data=new char[100];
FileReader f=new FileReader("E:\\PGP12_JAVA\\product.txt");
f.read(data);
System.out.println("Contents of the file:");
for(char res:data)
System.out.print(res);
}
}
Note:
f.read(data,0,11); - reads 11 characters from the
file
Example 02: Writing the data to a file:
import java.io.*;
class demo18

{
public static void main(String[] args) throws IOException
{
FileWriter f=new FileWriter("E:\\PGP12_JAVA\\arun.txt");
f.write("StudentDetails");
f.close();
System.out.println("data written to the file..");
}
}
Example 03: to get user data and store them to a file
import java.util.*;
import java.io.*;
class demo18
{
public static void main(String[] args) throws IOException
{
String sname,dept;
Scanner s=new Scanner(System.in);
System.out.println("Enter name and dept");
sname=s.next();
dept=s.next();
FileWriter f=new FileWriter("E:\\PGP12_JAVA\\arun.txt");
f.write(sname+ " " +dept);
f.close();
System.out.println("data written to the file..");
}
}
--- In the above program, the data entered by
the user is saved to file, but the data is not appended
previous data will be erased and new data is
overwritten.
Example 04: using BufferedWriter to append data
to a file.
import java.util.*;
import java.io.*;
class demo18
{
public static void main(String[] args) throws IOException
{
String sname,dept;
Scanner s=new Scanner(System.in);
System.out.println("Enter name and dept");
sname=s.next();
dept=s.next();
FileWriter f=new FileWriter
("E:\\PGP12_JAVA\\arun.txt",true);
BufferedWriter bw=new BufferedWriter(f);
bw.write(sname+ " " +dept);
bw.close();
System.out.println("data written to the file..");
}

}
Example 05: using both read and write
operations in the same program
import java.util.*;
import java.io.*;
class demo18
{
public static void main(String[] args) throws IOException
{
char[] data=new char[100];
FileReader f1=new FileReader("E:\\PGP12_JAVA\\arun.txt");
FileWriter f2=new FileWriter("E:\\PGP12_JAVA\\arun1.txt");
while((f1.read(data))!=-1)
f2.write(data);
f2.close();
System.out.println("Data copied successfully");
}
}
Byte data:
A-65,B-66...
a-97,b-98...
--Reading and writing data to byte file.
import java.util.*;
import java.io.*;
class demo18
{
public static void main(String[] args) throws IOException
{
byte[] data=new byte[100];
FileInputStream f=new FileInputStream("E:\\PGP12_JAVA\\product.txt");
f.read(data);
System.out.println("Contents of the file:");
for(byte res:data)
System.out.print(res);
FileOutputStream f1=new FileOutputStream("E:\\PGP12_JAVA\\vignesh.txt");
f1.write(103);
f1.close();
}
}
------------------------------------Chained Streams: - using series of file classes
to get the output.
FileWriter f=new FileWriter
("E:\\PGP12_JAVA\\arun.txt",true);
BufferedWriter bw=new BufferedWriter(f);
Module 10 Continued
Recap of Module10
1.concept of files

2.Character file - FileReader and FileWriter


3.Byte file - FileInputStream and fileOutputStream
4.Chaining of streams.
JAVA I/O
1. files
2. Console I/O
Console - Command Prompt
CUI - Character User Interface.
The application which uses command prompt to accept
input and produce output, are called as Console Application
Scanner - class used for getting input.
Console - belongs to java packages.. which is used
to accept input/display output.
System.in - standard input
System.out - standard output.
System.err - to handle standard errors
Example Program :
import java.io.*;
class demo19
{
public static void main(String[] args)
{
Console c=System.console();
String name,pass;
name=c.readLine("%s","Username");
pass=c.readLine("%s","Password");
if((name.equals("oliver")) && (pass.equals("niit")))
System.out.println("Valid user");
else
System.out.println("incorrect details");
}
}
-------------------------------------------Using Channels in files:
welcome
a1.txt -> a2.txt
char[] a=new char[100];
FileReader f;
f.read(a);
Note: In the above example, we transfer the data
from a1.txt file to a2.txt file,
the contents of one file are copied to another as
character by character.
if the data is large,then the time gets wasted.

To overcome this, instead of char, we can pass


the data as a block. this is done using Channel classes.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
class demo19
{
public static void main(String[] args)
{
try(FileChannel fci=new
FileInputStream("E:\\PGP12_JAVA\\emp11.txt").getChannel();
FileChannel fco=new
FileOutputStream("E:\\PGP12_JAVA\\emp12.txt").getChannel()){
ByteBuffer buf=ByteBuffer.allocate((int)fci.size());
fci.read(buf); //data from file is stored to the buffer
buf.position(0);
fco.write(buf); //write the buffer data to the output file.
System.out.println("Data written..");
}
catch(IOException e) {}
catch(Exception e){}
}
}
Serialization and Persistence:
Persistence :
Permanent storage
-- concept of files, databases, xml files etc.
In java, data comes in the form of _________
ans: Objects
Student s=new Student();
System.out.println(s); //address of object - hashcode
System.out.println(s.id+" "+s.name);
Serialization - process of converting the object data
into a byte code.
Deserialization - process of converting the byte
code into the original format.
-- Note:
1. the variable or field which is specified
as transient will not serialized
eg: transient int fees;
2. static fields also not be serialized.

import java.io.*;
class student implements Serializable
{
String name,dept,fees;
public student(String n,String d,int f){
name=n;
dept=d;
fees=f;
}
}
class demo19
{
public static void main(String[] args) throws Exception
{
student s=new student("Vasanth","IT");
//FileOutputStream f=
//new FileOutputStream("E:\\PGP12_JAVA\\stud.txt");
//ObjectOutputStream o=new ObjectOutputStream(f);
//o.writeObject(s);
FileInputStream f=new
FileInputStream("E:\\PGP12_JAVA\\stud.txt");
ObjectInputStream o=new ObjectInputStream(f);
student s1=(student)o.readObject();
System.out.println(s1.name+ " "+s1.dept);
}
}

Vous aimerez peut-être aussi