Java Code
Java Code
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);
}
}
----------------------------------------
a=10,b=12;
sum=a+b;
pro=a*b;
diff=a-b;
quo=a/b;
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)
{
}
-- 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
}
-- 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()
{
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()
{
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 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};
class
class
class
class
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)
{
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.
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
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
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);
{
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
----------------------------------------------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:
-----------------------------
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
{
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
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);
}
}