You are on page 1of 57

JAVA:

=====
Keywords:(Reserved words)
========
Note:Keywords should be in lowercase.

Reserved words=53 words

1)Reserved Keywords(50)-they are associated with some functionalities


a)Used(48)-if,else,for,,,,,
b)Unused(2)- goto, const

2)Reserved Literls(3)-they represents values


true and false are the values For boolean datatypes
null- default value For Object type.

Used Keywords(48):
-------------------
Keywords For datatype(8):
------------------------
byte,short,int,long,float,double,char,boolean

keywords For flow control:


---------------------------
if,else,do,while,for,break,continue,return,switch,case,default

keywords For exception handling:


---------------------------------
try,catch,finally,throw,throws,assert

Class level keywords:


---------------------
class,extends,interface,implements,import,package

Object level keywords:


----------------------
new,this,super,instanceof

Keywords For access modifiers:


-------------------------------
public,protected,private,abstract,synchronized,static,strictfp,transient,
final,volatile,native,<default>

enum keyword:
-------------
enum keyword is used to represent a group of constants.

Ex:
---
enum Weekdays
{
sunday,monday,.......,saturday;
}

Weekdays w1= sunday;//ok


Weekdays w2= monday;//ok
Weekdays w3= someotherday;//error

void keywords:
--------------
ex:
m1()//error
{
}

void m1()//ok
{
}
Unused keywords(2):
------------------
goto: It increases the complexity of the program,i.e its harder to debug
the programs.

const: final keywords replaces const keyword in java.

Datatypes:(8)
==========
1)Numerical-byte,short,int,long,float,double
2)Non-numerical-char,boolean

Note:
-----
1 Terra byte=1024 Gigabytes
1 giga byte=1024 Megabytes
1 mega byte=1024 kilo byte
1 kilo byte=1024 bytes
1 Byte=8 bits
1 bit=0 (OR) 1

00000001=1
00000010=2
00000100=4
00001000=8
00010000=16
00100000=32
01000000=64
10000000=128

97=64+32+1=01100001===97
111=64+32+8+4+2+1=01101111===111

1 Byte:(max)=11111111=255
(min)=00000000=0
0.........255

byte:
-----
size=1 Byte
range=-128 to 127

byte b=10;//ok
byte b=-128;//ok
byte b=-130;//error
byte b=128;//error

short:
-------
size=2 Bytes
range= -32768....0.....32767

short s=32000;//ok
short s=33000;//error

int:
-----
size=4 Bytes
range= -210cr....0.....210cr

long:
-----
size=8 Bytes

float:
-------
size=4 Bytes
range= -210.00cr....0.....210.00cr

double:
-------
size=8 Bytes

char:
------
size=2 Bytes

Range:0....255(ascii)........65535

ASCII:(American std code For information interchage)


characters : '/0'...' '...'#'...'0','1'....'A','B'....'a','b'.....

ASCII values: 0....32....35.....48,49.....65,66.......97,98......255

ex:char ch='a';//97==01100001

boolean:
--------
No size.
it just represents either true or false.

ex: boolean b=true;


boolean b=false;

TypeCasting:
============
1)Implicit Typecasting
------------------------
Its also known as Upcasting or Widening.
Its supported by compiler and programers need not worry about it.

Ex:
-128...0....10....127
int a=10;//ok
int a=(int)10;//compiler code

short s=126;//ok
short s=(short)126;//cc
-32000...0....32000
double d=1000;//ok
double d=(double)1000;//cc
Sopln(d);//1000.00

int x='a';//ok
int x=(int)'a';//cc
Sopln(x);//97

2)Explicit Type casting


------------------------
Its also known as Downcasting or Narrowing.Its not supported by compiler,i.e
programers have to specify it explicitly.

byte b=125;//ok
byte b=130;//error
byte b=(byte)130;//ok ET
Sopln(b);//-126

-128,-127,-126,-125......-2,-1,0,1,2,3......127,-128,-127,-126(130)....0....127,-
128.....

byte b=10.50;//error
byte b=(byte)11.990;//ok ET
Sopln(b);//11

Literals:
---------
EX:int x=10;
-----------
int=primitive datatype
x=identifier/variable
10=constant(or)literal

Integral literals:
-----------------
int x;
Sopln(x);//0
int x=10;//ok
short s=20;//ok
float f=350;//ok
long l=100L;//ok
long l=34444l;//ok
int i=10L;//error
double d=2344.98;

floating point literals:


------------------------
Every floating point literals in java is of double type by default.

float f;
Sopln(f);//0.0
float f=10.50;//error
float f=10.50F;//ok
float f=33.00f;//ok
double d=22.33F;//ok
double d=10.49;//ok

Character literals:
-------------------
char c;
Sopln(c);//blank
char c='a';//ok
char c=a;//error
char c="a";//error
char c=97;//ok
char c=(char)97;//cc
Sopln(c);//a
char c='ab';//error
char c='\n';//ok

Boolean literals:
----------------
The default value For boolean is false.
Ex:
boolean b;
Sopln(b);//false

boolean b=true;//ok
boolean b=false;//ok
boolean b=True;//error
boolean b=0;//error
boolean b="true";//error

String literals:
================
Default value For String(Object) is null.
String s;
Sopln(s);//null

String s=100;//error
String s=tree;//error
String s="tree";//ok
String s='a';//error
String s="a";//ok
String s="100";//ok

Important Notes:
================
Object class:
=============
Object class is the topmost class in java.
Every class in java is the child class of Object class either directly
or indirectly(User defined and pre defined classes).

JDK,JRE and JVM:


=================
JDK(Java development kit):JDK is used to develop and run java applications.

JRE(Java runtime environment):JRE is used to run java application.

JVM(Java virtual machine):JVM provides the environment to interpret(read)


the bytecodes line by line and provides the output in human understandable
form.

Classses and Objects:


----------------------
Class is a user defined datatype.
Object is an instance(variable) of a class.

For:
----
class Account
{
};

int x;//x is a variable of interger datatype


x=10;

Account a;//a is an instance(variable) of Account class


a=new Account();

Account a=new Account();//a is an object of Account type

Java.lang package:
------------------
This is the default package which will get imported by the compiler
internally For every java program.

Arrays:
=======
Array is a set of similar datatypes.

1D Array:
---------
Ex:
int x[10];//error
int x[];
x=new int[4];
or
int x[]=new int[4];
x[0]=10;
x[1]=10.40;//error
x[1]=20;
x[2]=30;
x[3]=33;
x[4]=44;//error

int x[]={10,20,30,40};

String s[]={"tree","hi",.....};

char c[]=new Char[2];


c[0]='a';
c[1]='3';

1D array can be declared in 3 ways:

int x[];
int []x;
int[] x;

2D Array(Arrays of Array)
---------------------------
EX:1)
int x[][]=new int[2][2];
x[0][0]=10;
x[0][1]=20;

x[1][0]=30;
x[1][1]=40;

Ex:2)
int[] x[]=new int [2][];
x[0]=new int[3];
x[0][0]=10;
x[0][1]=20;
x[0][2]=30;

x[1]=new int[1];
x[1][0]=40;

2D Arrays can be decl. in 6 ways:

int x[][];
int [][]x;
int []x[];
int[][] x;
int[] []x;
int[] x[];

String Class:
------------
String s=new String("hello");
or
String s="hello";

length variable v/s length() method:


====================================
length is a variable used to identify the length of an array.

Ex:
int x[]={11,22,33,44,55};

int i;
for (i=0;i<x.length;i++)
{
System.out.println(x[i]);//11,22,33,44,55
}

length() method is used to find the length of a String.

String s="hello";
System.out.printl(s.length());//5

For-each Loop:
==============
Ex:1)
String s[]={"hello","tree","hiii"};
int i;
for (i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
Ex:2)
String s[]={"hello","tree","hiii"};
for(String x : s)
{
System.out.println(x);
}
Note: "For each String variable x in the array s"

Ex:3)
int s[]={22,33,44444444};
for(int pavan : s)
{
System.out.println(pavan);
}

Types Of Variables:
===================
Based on the value represented by the variables they are divided into 2 types:
1)primitive variables:
----------------------
int x=10;
float y=33.33;
here x and y are primitive variables.

2)Reference variables:
----------------------
String s1=new String();
here s1 is reference variable pointing to an Object of String Type.

Based on the behaviour and declaration the variables are divided into 3 types:
1)instance variables
2)static variables
3)local variables

1)instance variables:
----------------------
*They are declared outside the method,blocks and constructors.
*They are stored in heap area of the memory.
*They are varied from object to object.i.e if any objects makes any changes to an
instance
variable that will not get reflected to the other objects.
*JVM assigns default value for instance variables.
*Instance variables and methods cannot be accessible directly from static
area but can be accesible directly from instance area.But by using the objects
we can access instace variables and methods from static area.
*The access modifiers which are applicable for instance variables are
public,private,
protected,<default> and final.

EX:1)
class Test
{
int x=10;
void m1()
{
System.out.println("instance method");
}
public static void main(String args[])
{
System.out.println(x);//error
m1();//error
Test t1=new Test();
System.out.println(t1.x);//10
t1.m1();//instance method
t1.m2();//10...instance method
}
void m2()
{
System.out.println(x);//10
m1();//instance method
}
}
EX:2)
class Test
{
int x=10;

public static void main(String args[])


{
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
System.out.println(t1.x);//10
System.out.println(t2.x);//10
System.out.println(t3.x);//10

t2.x=20;

System.out.println(t1.x);//10
System.out.println(t2.x);//20
System.out.println(t3.x);//10
}
}
Ex:3)
class Test
{
int x;
float y;
String z;

public static void main(String args[])


{
Test t1=new Test();
System.out.println(t1.x);//0
System.out.println(t1.y);//0.0
System.out.println(t1.z);//null

}
2)Static variables:
--------------------
*They are declared outside the method,blocks and constructors.
*They are stored in method area of the memory.
*JVM assigns default value for static variables.
*They are not varied from object to object,i.e when we declare any static variable
a single class level copy will get created which will be reference from every
object
of that class.So by using any object if we make any changes to that static
variables
that will get reflected to other objects also.
*static variables and methods can be accessible directly from both instance as well
as
static areas.
*The access modifiers which are applicable for static variables are public,private,
protected,<default> and final.

Ex:1)
class Test
{
static int x=10;
static void m1()
{
System.out.println("static method");
}
public static void main(String args[])
{
//3 ways of calling static members
System.out.println(x);//10
m1();//static method
System.out.println(Test.x);//10
Test.m1();//static method
Test t1=new Test();
System.out.println(t1.x);//10
t1.m1();//static method
}
void m2()
{
System.out.println(x);//10
m1();//static method
}
}
Ex:2)
class Test
{
static int x;
static float y;
static String z;

public static void main(String args[])


{
Test t1=new Test();
System.out.println(t1.x);//0
System.out.println(t1.y);//0.0
System.out.println(t1.z);//null

}
Ex:3)
class Test
{
static int x=10;

public static void main(String args[])


{
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
System.out.println(t1.x);//10
System.out.println(t2.x);//10
System.out.println(t3.x);//10

t2.x=20;

System.out.println(t1.x);//20
System.out.println(t2.x);//20
System.out.println(t3.x);//20
}
}

Local variables:
----------------
*They are declared inside the methods,blocks and constructors.
*They are stored in stack area of the memory.
*JVM doesnot assigns any default values for local variables.
*Ther are not accessible outside the method,block and constructors where they are
declared.
*The only modifier which is applicable for local variables is final.

EX:1)
class Test
{

public static void main(String args[])


{
int x=10;//local variable
System.out.println(x);//10

}
}

Ex:2)
class Test
{

public static void main(String args[])


{
int x;
System.out.println(x);//error

}
}
Ex:3)
class Test
{
static void m1()
{
int y=10;
}
public static void main(String args[])
{

System.out.println(y);//error
}
}
Ex:4)
class Test
{
public static void main(String args[])
{
public int x=10;//error
private int y=20;//error
final int z=30;//ok

}
}

Main method:
===========
public static void main(String[] arguments)
{
}

public: Its public because the JVM should be able to call this method from
anywhere.
------
static: Its static because the JVM should call this method before the creation of
objects.
-------
void : Its doesnot return anything.
-----
main: method name
----
String: predefined class
-------

Command line arguments: These are used to change the behaviour of main method.
=======================
Ex:1)
class Test
{
public static void main(String args[])
{
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);

}
}
Output:
-------
input: java first second third
output: first second third

Ex:2)
class Test
{
public static void main(String args[])
{
int x=Integer.parseInt(args[0]);
System.out.println("The square of "+x+" is "+(x*x));
}
}
//int x=Integer.parseInt("10");//10
//double d=Double.parseDouble("10.50");//10.50

String Concatination( + operator):


----------------------------------
class Test
{
public static void main(String args[])
{
int a=10;
int b=20;
int c=30;
String name="Harish";
String name2="Naveen";
System.out.println(a+b+c);//60
System.out.println(a+b+c+name);//60harish
System.out.println(a+b+name+c);//30harish30
System.out.println(a+name+b+c);//10harish2030
System.out.println(name+a+b+c);//harish102030
System.out.println(name+name2);//harishnaveen

}
}

var-arg methods:(Variable arguments meythods):


==============================================
Ex:
void add(int...x)
{

}
without var-arg method:
---------------------
class Test
{
static void add(int x,int y)
{
System.out.println(x+y);
}
static void add(int x,int y,int z)
{
System.out.println(x+y+z);
}
static void add(int w,int x,int y,int z )
{
System.out.println(w+x+y+z);
}
public static void main(String args[])
{
add(10,20);
Test.add(10,20,30);
add(10,20,30,40);

}
}
with var-arg method:
--------------------
class Test
{
static void add(int...x)//int x[]
{
int sum=0;
for(int value:x)
{
sum=sum+value;
}
System.out.println(sum);
}
public static void main(String args[])
{
add(10,222);//x[0]=10,x[1]=222
Test.add(10,20,333);//x[0]=10,x[1]=20,x[2]=333
add(11111,20,30,40);//x[0]=11111,x[1]=20,x[2]=30,x[3]=40

}
}

Java Coding Standards:(Industry Standards)


==========================================
variables:
----------
int sun=10;//okkkkkkkkkkkk
int Sun=10;
int SUN=10;

int sunmoonmars=20;
int SunMoonMars=20;
int SUNMOONMARS=20;
int sunMoonMars=20;//okkkkkkkkkkkkk
int Sunmoonmars=20;

methods:
----------
void sun(){}//okkkkkkkkkkkk
void Sun(){}
void SUN(){}

void sunmoonmars(){}
void SunMoonMars(){}
void SUNMOONMARS(){}
void sunMoonMars(){}//okkkkkkkkkkkkkk
void Sunmoonmars(){}

class:
------
class sun
class Sun//okkkkkkkkkk
class SUN

class sunmoonmars
{
};
class SunMoonMars//okkkkkkkkkk
{
};
class SUNMOONMARS
{
};
class sunMoonMars
{
};
class Sunmoonmars
{
};

Scanner Class and BufferedReader Class:


=======================================
Output:
-------
Enter Your name:Harish

Enter any two numbers for addtion:10 20

Welcome Harish
The addtion od 10 and 20 is 30

Scanner:
---------
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
String name;
int a,b,sum;
System.out.print("Enter your name :");
//name=scan.next();//scans a single word
name=scan.nextLine();//scans a whole line

System.out.print("Enter any 2 nos for addition :");


a=scan.nextInt();
b=scan.nextInt();
sum=a+b;

System.out.println("Welcome "+name);
System.out.println("The addition of "+a+" and "+b+" is "+sum);

}
}
BufferedReader:
---------------
import java.util.Scanner;
import java.io.*;
class Test
{
public static void main(String args[])throws Exception
{
//InputStreamReader isr=new InputStreamReader(System.in);
//BufferedReader br=new BufferedReader(isr);
//[OR]
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String name;
int a,b,sum;
System.out.print("Enter your name :");
name=br.readLine();//reads the whole line

System.out.print("Enter any 2 nos for addition :");


a=Integer.parseInt(br.readLine());//"10"==>10
b=Integer.parseInt(br.readLine());
sum=a+b;

System.out.println("Welcome "+name);
System.out.println("The addition of "+a+" and "+b+" is "+sum);

}
}

OOP Concepts(Object Oriented programming):


==========================================
Data Hiding:
============
Hiding the data from an outside world.
"private" access modifier is used to achieve Data Hiding.

Ex:1)
class Test
{
private int x=10;

public static void main(String args[])


{
Test t=new Test();
System.out.println(t.x);//10

}
}
Ex:2)
class Hello
{
private int x=10;
};
class Test
{
public static void main(String args[])
{
Hello h=new Hello();
System.out.println(h.x);//error

}
}
Abstraction:
============
Showing only the outer functionalities to the users meanwhile hiding the internal
complex details.
Ex:ATM machine.

Encapsulation:
==============
Binding variables and methods into a single unit called class is known as
Encapsulation.
Ex:
class Test
{ //members
int x=10;//variable OR member variables
void m1()//method OR member functions
{
Sopln("Good Morning");
}
};

Inheritance:(IS-A Relationship)
===============================
Inheritence is nothing but inheriting one's class properties in another class.
The main objective of inheritence is code reusabilty.
Inheritence can be achieved by using extends keyword in java.

EX:
class A
{
m1()
{
Sopln("good morning");
}
m2()
{
Sopln("good evening");
}
};
class B extends A//inheriting A's class properties in B class
{//3 methods
m3()
{
Sopln("good night");
}
};

EX:1)
class A
{ void m1()
{ System.out.println("Good Morning"); }
void m2()
{ System.out.println("Good Afternoon"); }
};
class B extends A
{ void m3()
{ System.out.println("Good Evening"); }
};
class Tester
{
public static void main(String[] args){
A a1=new A();
a1.m1();//GM
a1.m2();//GA
a1.m3();//error

B b1=new B();
b1.m1();//GM
b1.m2();//GA
b1.m3();//GE

A a2=new B();//parent reference can be used to hold child class object


a2.m1();//GM
a2.m2();//GA
a2.m3();//error

B b2=new A();//error
}};
Note:
-----
Parent reference variable can be used to hold child class object, but in case of
inheritance
by using that parent reference we cant call child specific methods because the
method resolution
(method execution) is always taken care by compiler based on reference type.

HAS-A Relationship:
===================
The main objective of Has-A relationship is code reusabilty.
There is no specific keyword to implement Has-A relationship but usually we do it
through
using "new" keyword.
Has-A relationship is also known as Composition & Aggregation.
-------------------------

Composition:
------------
Without existing container object there is no chance of existing contained object
then both
of them are said to be strongly associated.This phenomenon is known as Composition.

Ex:Inner class
--------------
class University
{
class Deparments
{
};
};

Aggregation:
-----------
Without existing container object there is a chance of existing contained object
then both
of them are said to be weakly associated.This phenomenon is known as Aggregation.

Ex:Car HAS-A Engine


-------------------
class Engine
{
void m1()
{
Sopln("US engine");
}
void m2()
{
Sopln("Uk engine");
}
.......
.......
void m100()
{
Sopln("Australia engine");
}
};
class Car
{
Engine e1=new Engine();
e1.m2();//UK engine
};

Polymorphism:
=============
Polymorphism is a phenomenon in which the same entity can exist in two or more
forms.
The main objective of Has-A relationship is code reusabilty.

Ex: method Overloading and method Overriding.


----------------------------------------------

Method Signature in Java:


------------------------
In C language:
-------------
void add(int x,int y);
----------------------
void-return type
add-function name
int x,int y-arguments lists
These 3 are part of method signatures

In Java:
--------
void add(int x,int y);
----------------------
void-return type
add-function name
int x,int y-arguments lists
In case of Java return type is not part of method signature

Ex: add(int x,int y);


----------------

Method Overloading:
-------------------
In java,if any 2 methods are said to be overloaded if and only if both methods
having the same
name and different argument lists atleast in their order.

Ex:
1)
void m1(int x);
void m1(float x);
//ok
2)
void m1(int x,float y);
void m1(float x,int y);
void m1();
//ok
3)
void m1()
void m1(int x)
//ok
4)
void m1(int x,float y);
void m1(int y,float x);
//error
Ex:
---
class A
{
static void m1(int x)
{
System.out.println("Int argument "+x);
}
static void m1(float y)
{
System.out.println("Float argument "+y);
}
};
public class Test{
public static void main (String[] args)
{
A.m1(10);//int-argument 10
A.m1('L');//int-arg 76
A.m1(10.50f);//float-arg 10.50
//A.m1(10.30);//error
A.m1(22L);//float-arg 22.00
//A.m1("100");//error
//A.m1();//error

}
}

Method Overriding:
------------------
In Java,if any 2 methods are said to be overrided if anf only if both overriding
and overidden
methods are having the same method signatures with different implementations.
Method Overriding is a phenomenon in which parent class method will be
reimplemented in the
child class.

Ex:
class Parent
{
void property()
{
Sopln("Gold+Cash+Land");
}
void car()//overriden method
{
Sopln("Maruthi-800");
}
};
class Child extends Parent
{
void car()//overriding method
{
Sopln("Benz");
}
};
EX:
class Parent
{ void m1(){System.out.println("Good Morning");}
void m2(){System.out.println("Good Afternoon");}
};
class Child extends Parent
{ void m2(){System.out.println("Good Evening");}
void m3(){System.out.println("Good Night");}
};
class Test
{ public static void main(String [] hhh)
{
Parent p1=new Parent();
p1.m1();//GM
p1.m2();//GA
//p1.m3();//Error
Child c1=new Child();
c1.m1();//GM
c1.m2();//GE
c1.m3();//GN
Parent p2=new Child();
p2.m1();//GM
p2.m2();//GE
//p2.m3();//error
//Child c2=new parent();//error
}
};
Note:
-----
Parent reference variable can be used to hold child class object, but in case of
overriding
by using that parent reference if we call overriden method then child specific
method will be
called because the method resolution (method execution) is always taken care by JVM

based on runtime object.

Static Blocks:
--------------
These are the blocks which will get executed only once at the time of class
loading,i.e
before the execution of main method.
Static blocks are used for initialization purposes.
Ex:
static
{
Sopln("this is a static block");
}
Ex:
class Test
{
static
{
System.out.println("Static block 1");
}
public static void main(String [] hhh)
{
System.out.println("Inside the main method");
}
static
{
System.out.println("Static block 2");
}
};
Instance Blocks:
----------------
Instance blocks will get executed for each and every object creation before the
execution of
constructors.
Instance blocks are used for initialization purposes.
Ex:
{
Sopln("This is an instance block");
}
Ex:

class Test
{
Test()
{
System.out.println("This is a constructor");
}
public static void main(String [] hhh)
{
System.out.println("Inside the main method");
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();

}
{
System.out.println("Instance block 1");
}
{
System.out.println("Instance block 2");
}
};
Constructors:
-------------
Constructors are used to initialize the objects which are just created.
Constructors will be having the same name as class name and it doesnot have any
return type
not even void.
Suppose if we are not specifying any constructors in our program then compiler
itself by
default creates one No argument constructor with empty implementation and calls
that
no argument constructor internally whenever we create the objects,i.e constructors
will get executed for each and every object creation.

Ex:
class Test
{
Test()
{
Sopln("This is a constuctor");
}
};

Ex:

class Test
{
Test()
{
System.out.println("This is a constructor");
}
public static void main(String [] hhh)
{

Test t1=new Test();


Test t2=new Test();
Test t3=new Test();

};

Ex:
//with out using constructors
class Student
{
int rollno;
String name;

public static void main(String [] hhh)


{
Student s1=new Student();
s1.rollno=100;
s1.name="raju";
Student s2=new Student();
s2.rollno=101;
s2.name="suman";
////////
////////
Student s100=new Student();
s100.rollno=200;
s100.name="harish";
System.out.println(s1.rollno+"..."+s1.name);
System.out.println(s2.rollno+"..."+s2.name);
System.out.println(s100.rollno+"..."+s100.name);

};

Ex:
//Using constructors
class Student
{
int rollno;
String name;
Student(int rn,String nm)
{
this.rollno=rn;
this.name=nm;
}
public static void main(String [] hhh)
{
//Student s=new Student();//error
Student s1=new Student(100,"Raju");
Student s2=new Student(101,"Suman");
////////
////////
Student s100=new Student(200,"harish");
System.out.println(s1.rollno+"..."+s1.name);
System.out.println(s2.rollno+"..."+s2.name);
System.out.println(s100.rollno+"..."+s100.name);

};

this() and super() in constructors:


-----------------------------------
this() is used to refer current class constructor.
super() is used to refer parent class constructor.

Note:this() and super() must be the first statement in the constructor. We cant use
both
this() and super() in a single constructor.

Ex:
---
class Test
{ Test()
{
this(10);
System.out.println("No argument constructor");
}
Test(int i)
{
this(10.50);
System.out.println("int argument constructor");
}
Test(double d)
{
System.out.println("double argument constructor");
}

public static void main(String[] args)throws Exception


{
Test t=new Test();//double-int-no
Test t2=new Test(100);//double-int
Test t3=new Test(20.40);//double
}
};
Ex:
class A
{
A()
{
System.out.println("A class constructor");
}
};
class Test extends A
{
Test()
{
//super();
this(10);
System.out.println("Test class No arg constructor");
}
Test(int i)
{
//super();
System.out.println("Test class int arg constructor:");
}

public static void main(String[] args)throws Exception


{
Test t=new Test();//A class--test no arg con
Test t2=new Test(100);//A class--test int arg con

}
};

Inner Classes: A class inside a class.


==============
Ex:
class Outer
{
class Inner
{
void m1()
{
System.out.println("Inner class method");
}
};
};
class Test
{ public static void main(String [] hhh)
{
Outer o = new Outer();
Outer.Inner i=o.new Inner();
i.m1();//ICM
//[or]
Outer.Inner i1=new Outer().new Inner();
i1.m1();//ICM
//[or]
new Outer().new Inner().m1();//ICM
}
};

Declarations & Source file Structure:


=====================================
Source file Structure:
------------------------
In a single Java program we can have any number of classes.Suppose,If all the
classes within that
program are having default access modifier then we can save and compile that
program with
any name.
Ex: India.java,Hcl.java

After compiling,we will get .class files as many as classes in that program.We cant
run
that java program with the saved name, but we run by using class names.

Ex:
class A
{

};
class B
{
public static void main(String [] hhh)
{
System.out.println("B Class");
}
};
class C
{

};
class D
{
public static void main(String [] hhh)
{
System.out.println("D Class");
}

};

In a single Java program,we can hava any number of classes.But we can have atmost
one public
class. If any class is public,then save that program with that public class name
otherwise
we will get compile time error.i.e we cant have 2 public classes in a single
program.

Ex:
class A
{

};
public class B
{
public static void main(String [] hhh)
{
System.out.println("B Class");
}
};
class C
{

};
class D
{
public static void main(String [] hhh)
{
System.out.println("D Class");
}

};

Import statement & Packages in Java:


====================================
Import Statement:
-----------------
1)Explicit import
-----------------
Ex:
import java.util.ArrayList;
import java.util.Vector;
class Test
{
public static void main(String [] hhh)
{
ArrayList al=new ArrayList();
Vector v=new Vector();
}
};
2)Implicit import:
------------------
EX:

import java.util.*;
class Test
{
public static void main(String [] hhh)
{
ArrayList al=new ArrayList();
Vector v=new Vector();
}
};

Package:
--------
Package is a group of related .class files with similar functionalities.
Ex:
java.io--->consits of classes related to input and output operations
java.util---->consists of classes related to utility operations
java.lang---->consists of classes related to basic java language

Note: We can define our own packages also


-----
Ex:
package com.icici.loan.carloan.shortterm;

class Account
{
static double balance=10000.00;
public static void main(String [] hhh)
{
System.out.println("Account balance= "+balance);
}
};
Output:
--------
For creating package under CWD: javac -d . Account.java
For creating package under D drive : java -d d: Account.java

Access Modifiers:
=================
class level modifiers:
----------------------
Outer class: public,abstract,final,strictfp,<default>
Inner class: public,abstract,final,strictfp,<default>,private,static,protected

final:
=======
variables:
----------
Ex:
final int x=10;
x=20;//error

final int x;//error


final int x=10;//ok

methods:
--------
Ex:
class A
{
void m1()
{
Sopln("GM");
}
final void m2()
{
Sopln("GE");
}

};
class B extends A
{
void m1()
{
Sopln("GA");
}
final void m2()//error
{
Sopln("GN");
}

};

classes:
---------
final class A
{
};
class B extends A//error
{
};

public:
=======
classes & methods:
------------------
public classes and methods can be accessible from anywhere.
package pack1;
public class A
{
public void m1()
{
System.out.println("public method m1()");
}
};

package pack2;
import pack1.A;
class B
{
public static void main(String[] args)
{
A a1=new A();//ok
a1.m1();//ok
}

};

<default>:
==========
classes and methods:
--------------------
<default> classes and methods can be accessible only within the package but not
outside the package.
Ex:1)
package pack1;
public class A
{
void m1()
{
System.out.println("public method m1()");
}
};

package pack2;
import pack1.A;
class B
{
public static void main(String[] args)
{
A a1=new A();//ok
a1.m1();//error
}

};
Ex:2)
package pack1;
class A
{
public void m1()
{
System.out.println("public method m1()");
}
};

package pack2;
import pack1.A;
class B
{
public static void main(String[] args)
{
A a1=new A();//error

};

protected:
==========
protected methods can be accessible within the class,within the package and child
classes of
outside packages only by using child class objects but not using parent class
objects.

Ex:
package pack1;
public class A
{
protected void m1()
{
System.out.println("public method m1()");
}
};

package pack2;
import pack1.A;
class B extends A
{
public static void main(String[] args)
{
A a1=new A();
a1.m1();//error
B b1=new B();
b1.m1();//ok
}
};

private:
========
private variables and methods can be accessible only within the class.

Ex:1)
class A
{
private int x=10;
private void m1();
{
Sopln("Good morning");
}
public static void main(String[] args)
{
A a1=new A();
Sopln(a1.x);//10
a1.m1();//GM
}

};
Ex:2)class A
{
private int x=10;
private void m1();
{
Sopln("Good morning");
}
};
class Test
{
public static void main(String[] args)
{
A a1=new A();
Sopln(a1.x);//error
a1.m1();//error
}
};

Setter & Getter methods:


------------------------
These are the methods used to set and get the private members(variables) of a
class.

Ex:
class Student
{
private int rollno;
private String name;

public void setRollno(int rn)


{
rollno=rn;
}
public void setName(String nm);
{
name=nm;
}
public int getRollno()
{
return rollno;
}
public String getName()
{
return name;
}
};
class Test
{
public static void main(String[] args)
{
Student s=new Student();
s.setRollno(101);
s.setName("raju");
System.out.println(s.getRollno());//101
System.out.println(s.getName());//raju

}
};

Abstract:
=========
abstract Classes and methods:
-----------------------------
abstract is a keyword which is applicable for classes and methods.If we declare any
classes
with abstract keyword then we cannnot create objects For that class.If we declare
any method with
abstract keyword then we should declare that class with abstract keyword,otherwise
we will
get compile time error.

abstract methods should be overriden in child classes,otherwise the child class


will also become
abstract class.

abstract classes can have any number of abstract methods including Zero number
also.

If we are having full requirement specification and knowing only partial


implementation
then we should go For abstract classes.

Ex:
abstract class A
{
void m1()
{
Sopln("Good morning");
}
abstract void m2();
};

Ex:1)
abstract class Account
{
static double balance=10000.00;
public void withdraw()
{
///////
//////
Sopln("Amount has been withdrawn");
}
public abstract void deposit();
};
class Test extends Account
{
public void deposit()
{
///////
/////
System.out.println("Amount has been deposited");
}
public static void main(String[] ggg)
{
Account a1=new Account();//error
Test t1=new Test()'
t1.withdraw();//ok
t1.deposit();//ok

}
};

Interfaces:
===========
It is 100% pure abstract class.
[or]
Its a contract between client and service provider.
[or]
If we are having full requirement specification but not knowing about
implementation then we
should go For interfaces.
Ex:
interface A
{
public abstract void m1();
public abstract void m2();
}
Ex:
interface DigitalBilling
{
public abstract void sportsBill();
public abstract void CollegeFees();
public abstract void foodBill();
//////////////////////////////
}
Note:
-----
In interface every variable is by default public,static and final internally.
Ex:
interface A
{
int x=10;//public static final int x=10;
public int y=20;//static final int y=20;
}
In interface every method is by default public and abstract.
EX:
interface A
{
void m1();//public abstract void m1();
public void m2();//publc abstract void m2()
}

Examples:1)
-----------
interface DigitalBilling
{
void sportsBill();
void collegeFees();
}
abstract class CollegeProject implements DigitalBilling
{
Public void sportsBill()
{
System.out.println("Sports bill implementation");
}
};
class Test extends CollegeProject
{
public void collegeFees()
{
System.out.println("College fees implementation");
}
public static void main(String[] hh)
{
DigitalBilling db=new DigitalBilling();//error
CollegeProject cp=new CollegeProject();//error
Test t=new Test();
t.sportsBill();//ok
t.collegeFees();//ok
}

};

Note:
-----
class A interface M
{ {
}; }
class B interface N
{ {
}; }
class C interface O
{ {
}; }
interfaces:
------------
1)interface P extends M,N,O
{
}
2)interface P implements M//error
{
}
3)interface P extends/implements A//error
{
}

classes:
--------
1)class D extends A//ok
{
};
2)class D extends A,B//error
{
};
3)class D implements M,N,O//ok
{
};
4)class D extends B implements M,N,O//ok
{
};
5)class D extends M//error
{
};

Ex:1)
interface A
{
public abstract void m1();
}
interface B
{
public abstract void m1();
}
class Test implements A,B
{
public void m1()
{
System.out.println("Good Morning");
}
public static void main(String[] args)
{
Test t=new Test();
t.m1();//GM
}
};

Ex:2)
interface A
{
public abstract void m1(int x);
}
interface B
{
public abstract void m1();
}
class Test implements A,B
{
public void m1(int x)
{
System.out.println("Good Morning");
}
public void m1()
{
System.out.println("Good Evening");
}
public static void main(String[] args)
{
Test t=new Test();
t.m1(10);//GM
t.m1();//GE
}
};
Ex:3)
Note:
-----
If any 2 interfaces are having methods with same method signature(method name +
arguments)
but different return type,then it is imposible to implement both interfaces
simultaneously.

interface A
{
public abstract void m1();
}
interface B
{
public abstract int m1();
}
class Test implements A,B
{
public void m1()
{
System.out.println("Good Morning");
}
public int m1()
{
System.out.println("Good Evening");
return 100;
}
public static void main(String[] args)
{
Test t=new Test();
t.m1();//error

}
};

Exception Handling:
===================
An unwanted,unexpected event that disturbs the normal flow of execution of a
program is known
as Exception.
The main objective of Exception handling is to terminate the program gracefully.
i.e to provide
an alternative way to continue the rest of the program normally.

Diagram:???????
========
Differnce B/N Exception & Error:
--------------------------------
Exception: Exceptions usually caused by the programmers. i.e if programmmers makes
any mistake
in codes.

EX: ArithmeticException

Error: They are usually caused by the lack of system resources.

Ex: OutOfMemoryError

RuntimeException:
-----------------
1)ArithmeticException:
Ex:
class Test
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println(10/0);//RuntimeException:Arithmetic Exception-divide
by Zero
System.out.println("good morning");
}
};

2)NullPointerException:

Ex:
class Test
{
static String s;
public static void main(String[] args)
{

System.out.println(s.length());//NPE

}
};
3)NumberFormatException:

Ex:
class Test
{

public static void main(String[] args)


{
String s="ten";
int x=Integer.parseInt(s);//NFE

System.out.println(x);

}
};

Differnce B/N Unchecked exceptions and Checked exceptions:


----------------------------------------------------------
Unchecked exceptions: These are the exceptions which are not checked by the
compiler for the
smoother execution of the program.
Ex:All RuntimeException and Error

Checked exceptions: These are the exceptions which are checked by the compiler for
the
smoother execution of the program.
EX:All Exception expect RuntimeException and Error.

throw keyword:
--------------
throw keyword is used for customized exception handling.
throw keyword is used to handover the exception object to the JVM which is created
by the
programmer explicitly.
Ex:
class Test
{
public static void main(String[] args)
{
System.out.println("hello");
ArithmeticException ae=new ArithmeticException("Divide by zero
Explicity");
throw ae;
//[or]
//throw new ArithmeticException("Divide by zero Explicity");

}
};
Ex:
class Test extends RuntimeException
{
Test(String message)
{
System.out.println(message);
}
public static void main(String[] args)
{
System.out.println("hello");
throw new Test("test class object thrown");

}
};
Ex:
class InsufficientFundException extends RuntimeException
{
InsufficientFundException(String message)
{
System.out.println(message);
}
};
class Account
{
private int balance=1000;
public void withdraw(int amount)
{
if(amount>balance)
{
throw new InsufficientFundException("Your balance is lesser than
amount entered");
}
System.out.println("Plz take your money:::"+amount);
}
public static void main(String[] args)
{
Account a=new Account();
int amount=Integer.parseInt(args[0]);
a.withdraw(amount);

}
}
Note:
=====
In our program,if there is a chance of raising checked exceptions then we should
handle that
exception either by using "try" and "catch" or throws keyword. Otherwise we will
get
compiler time error.

throws keyword:
--------------
throws keyword is used to deligate the responsibilty of exception handling to the
caller(JVM
or a method),then the caller is responsible to handle that exception.

throws keyword is used to handle only checked exceptions.

Ex:FileNotFoundException:
-------------------------
import java.io.*;
class Test
{
public static void main(String[] args)throws
FileNotFoundException,IOException
{

PrintWriter pw=new PrintWriter("abc.txt");


pw.println("Hello r u coming to bangalore?");
pw.println(100);
pw.println(100.45);
pw.println('d');
pw.println(true);
pw.println("thank you !!!!!!!!!!!!!!!!!!!!!!!1");
pw.flush();
pw.close();
}
}

try-catch-finally:
------------------
try-block: It is used to specify the Risky code.

catch-block: It is used to specify the handling.

finally: It is used to specify the clean-up code.

Ex:1)
class Test
{
public static void main(String[] args)throws Exception
{
try
{
System.out.println("hello");
System.out.println(10/2);
System.out.println("Hii");
}
catch(ArithmeticException e)
{
System.out.println(e);
System.out.println(10/5);
}
finally
{
System.out.println("Some clean-up codes");
}
}
}
Ex:2)
class Test
{
public static void main(String[] args)throws Exception
{
try
{
System.out.println("hello");
System.out.println(10/0);
System.out.println("Hii");
}
catch(ArithmeticException e)
{
System.out.println(e);
System.out.println(10/5);
}
finally
{
System.out.println("Some clean-up codes");
}
}
}
EX:3)
class Test
{
public static void main(String[] args)throws Exception
{
System.out.println("hello");
try
{
System.out.println(10/0);
}

catch(ArithmeticException e)
{
System.out.println(e);
System.out.println(10/5);
}
finally
{
System.out.println("Some clean-up codes");
}
System.out.println("Hii");
}
}
Ex:4)
class Test
{
public static void main(String[] args)throws Exception
{
try
{
System.out.println("hello");
System.out.println(10/0);
System.out.println("Hii");
}
catch(Exception e)
{
System.out.println(e);
System.out.println(10/5);
}

}
}
Ex:5)
import java.io.*;
class Test
{ public static void main(String[] args)
{ try
{
PrintWriter pw=new PrintWriter("abc.txt");
pw.println("Hello r u coming to bangalore?");
pw.println(100);
pw.println(100.45);
pw.println('d');
pw.println(true);
pw.println("thank you !!!!!!!!!!!!!!!!!!!!!!!1");
pw.flush();
}
catch(FileNotFoundException e)
{
System.out.println(e);
System.out.println("refer some other folders");
}
finally
{
pw.close();
System.out.println("clean-up code");
}

}
}
Ex:6)
import java.io.*;
class Test
{ public static void main(String[] args)
{ try
{
PrintWriter pw=new PrintWriter("abc.txt");
pw.println("Hello r u coming to bangalore?");
System.out.println(10/0);
pw.println(true);
pw.println("thank you !!!!!!!!!!!!!!!!!!!!!!!1");
pw.flush();
pw.close();
}
catch(FileNotFoundException e)
{ System.out.println(e);
System.out.println("refer some other folders");
}
catch(ArithmeticException e)
{ System.out.println(e);
System.out.println(10/2);
}
finally
{
System.out.println("clean-up code");
}

}
}

Java.lang.String class:
=======================
Difference B/N String and StringBuffer class:
----------------------------------------------
String class:
-------------
Once you create a String Object, we cannot perform any changes to the existing
object.
If we are trying to make any changes with those changes a new object will be
created.
This non-changable behaviour is known as Immutabilty of String.

Ex:1)
String s1=new String("Hindusthan");
s1.contact("computers limited");
System.out.println(s1);//Hindusthan

Ex:2)
String s1=new String("Hindusthan");
String s2=s1.contact("computers limited");
System.out.println(s1);//Hindusthan
System.out.println(s2);//Hindusthan computer limited

StringBuffer:
-------------
Once you create a StringBuffer Object, we can perform any changes to the existing
object.
This changable behaviour is known as Mutabilty of StringBuffer.

Ex:
StringBuffer sb1=new StringBuffer("Hindusthan");
sb1.append("computers limited");
System.out.println(sb1);//Hindusthan computers limited

String class methods:


---------------------
1)charAt(int index):
--------------------------
String s=new String("Systems");
System.out.println(s.charAt(3));//t

2)concat(String s):
----------------------
String s1=new String("Hindusthan");
String s2=s1.contact("computers limited");
System.out.println(s1);//Hindusthan
System.out.println(s2);//Hindusthan computer limited

3)equals(String s):
--------------------
String s1="JAVA";
String s2="java";
System.out.println(s1.equals(s2));//false

4)equalsIgnoreCase(String s):
-------------------------------
String s1="JAVA";
String s2="java";
System.out.println(s1.equalsIgnorecase(s2));//true

5)length():
-----------
String s="hello";
Sopln(s.length());//5

6)replace(char old,char new):


-----------------------------
String s="ababa";
Sopln(s.replace('a','b'));//bbbbb

7)substring(int begin):
--------------------------
String s="Systems:";
Sopln(s.substring(3));//tems

8)substring(int begin,int end):


---------------------------------
String s="Systems:";
Sopln(s.substring(2,6));//stem(end-1=6-1=5)

9)indexOf(char ch):
--------------------
String s="systems";
Sopln(s.indexOf('s'));//0

10)lastIndexOf(char ch):
--------------------
String s="systems";
Sopln(s.lastIndexOf('s'));//6

11)toUpperCase():
-------------------
String s="hello";
Sopln(s.toUpperCase());//HELLO

12)toLowerCase():
-----------------
String s="Hello";
Sopln(s.toLowerCase());//hello

13)trim():
------------
String s=" hello hii ";
Sopln(s);// hello hiii
Sopln(s.trim());//hello hii

14)split(String expression):
----------------------------
class Test
{ public static void main(String[] args)
{
String s=new String("Hindusthan computers limited");
String[] words=s.split(" ");
for(String xyz:words)
{
System.out.println(xyz);
}

}
}

Annotation:
===========
A data about metadata.

Ex:@Override,@FunctionalInterface,@SupressWarnings,........

//without Using(@Override) Annotations


//---------------------------------------
class A
{
void something()
{
System.out.println("Good Morning");
}
};
class B extends A
{
void samething()
{
System.out.println("Good evening");
}
};

class Test
{ public static void main(String[] args)throws Exception
{
B b1=new B();
b1.something();//Good Morning
}
}

//with Using(@Override) Annotations


//---------------------------------------
class A
{
void something()
{
System.out.println("Good Morning");
}
};
class B extends A
{
@Override
void something()
{
System.out.println("Good evening");
}
};

class Test
{ public static void main(String[] args)throws Exception
{
B b1=new B();
b1.something();//Good Evening
}
}

Object Typecasting:
===================
??????????????
Collections:
============
Difference between Arrays and Collections:
-------------------------------------------
Arrays:
-------
1)Arrays are non-growable in nature. i.e we cant increase or decrease the size of
an array.
2)In Arrays we can store only homogeneous datatypes.

Collections:
------------
1)Collections are growable in nature(no concept of increasing & decreasing size).
2)In Collections we can store homogeneous and heterogeneous datatypes.

Collection(I):
-------------
If you want to represent a group of individual objects as a single entity then we
should
go for Collection(I).

methods:
--------
1)boolean add(Object o)
2)boolean remove(Object o)
3)void clear()
4)boolean isEmpty()
5)int size()
6)boolean contains(Object o)
7)Iterator iterator()

List(I):
--------
If you want to represent a group of individual objects as a single entity where
duplicates are
allowed and insertion order must be preserved.

methods:
--------
1)void add(int index,Object o)
2)Object get(int index)
3)Object remove(int index)
4)Object set(int index,Object o)
5)int indexOf(Object o)
6)ListIterator listIterator()
ArrayList(C);
-------------
Ex:
import java.util.ArrayList;
class Test
{
public static void main(String[] args)throws Exception
{
Test t1=new Test();
ArrayList al=new ArrayList();
System.out.println(al.isEmpty());//true
System.out.println(al.add(10));//true
al.add(20);
al.add(20);
al.add("green");
al.add(10.99);
al.add(null);
al.add(false);
al.add('D');
al.add(t1);

System.out.println(al);//[10,20,20,green,10.99,null,false,D,Test@a12b345]
System.out.println(al.isEmpty());//false
System.out.println(al.size());//9
System.out.println(al.contains(10.99));//true
System.out.println(al.remove(10.99));//true
System.out.println(al.contains(10.99));//false
System.out.println(al);//[10,20,20,green,null,false,D,Test@a12b345]
al.add(0,"hello");
System.out.println(al.get(0));//hello

System.out.println(al);//[hello,10,20,20,green,null,false,D,Test@a12b345]
System.out.println(al.remove(1));//10
System.out.println(al);//[hello,20,20,green,null,false,D,Test@a12b345]
System.out.println(al.set(2,'d'));//20(old value)
System.out.println(al);//[hello,20,d,green,null,false,D,Test@a12b345]
System.out.println(al.indexOf("green"));//3
al.clear();
System.out.println(al);//[]
}
};

You might also like