Java Notes
Java Notes
====================
Keywords(32)
-----------
Keywords are the words which are associated with some functionalities.
EX: short,int,long,float,double,char,if,for,while,do,break,continue,switch,case,
default,return,void,.....
if and else:
=============
//C program to add 2 numbers
#include<stdio.h>//preprosessor directive-std input/output header file
void main()
{
int firstno=200;
int secondno=20;
if(firstno >20)
{
printf("good morning");
}
else
{
printf("good evening");
}
for Loop:
=========
//C program to add 2 numbers
#include<stdio.h>//preprosessor directive-std input/output header file
void main()
{
int x=10;
int y=20;
printf("x=%d,y=%d\n",x,y);//x=10,y=20
x=y;
printf("x=%d,y=%d\n",x,y);//x=20 ,y=20
y=x;
printf("x=%d,y=%d\n",x,y);//x=20 ,y=20
x=8;
x=y;
printf("x=%d,y=%d\n",x,y);//x=20 ,y=20
x++;//x+1
y--;//y-1
printf("x=%d,y=%d\n",x,y);//x=21 ,y=19
x=y++;
printf("x=%d,y=%d\n",x,y);//x=19 ,y=20
y=++x;
printf("x=%d,y=%d\n",x,y);//x=20 ,y=20
}
EX:
==
#include<stdio.h>
void main()
{
int x;
printf("before for loop");
for(x=1;x<=100;x++)
{
printf("%d\n",x);
}
printf("after for loop");
}
}
Ex:
#include<stdio.h>
int main()
{
int i,j,sum=0;
for(i=1;i<4;i++)
{
for(j=1;j<4;j++)
{
sum=i+j;
printf("The sum of %d and %d is %d\n",i,j,sum);
}
printf("The control goes out of the inner for loop\n");
}
printf("The control goes out of the outer for loop\n");
}
while loop:
===========
#include<stdio.h>
void main()
{
int x=1;
printf("before while loop");
while(x<=100)
{
printf("%d\n",x);
x++;
}
printf("after while loop");
break: break keyword is used to get the control out of the recent loop.
======
#include<stdio.h>
int main()
{ int i=2;
int num;
printf("enter any no to find prime or not\n");
scanf("%d",&num);//5
while(i<=num-1)
{ if(num%i==0)
{
printf("Not a prime");
break;
}
i++;
}
if(i==num)
printf("Prime number");
}
Function:
=========
Function is a block consits of set of statements to perform particular tasks.
function signature:
-------------------
EX:1)int add(int x,int y);
EX:2)void sub();
Ex:1)
#include<stdio.h>
void message();//func decl
void main()
{
printf("Beginning of main method\n");
message();//func call
printf("End of main method\n");
}
void message()//func def
{
printf("Hi welcome to HCL\n");
printf("Techbee scholars\n");
}
Ex:2)
#include<stdio.h>
void m1();//func decl
void m2();//func decl
void m3();//func decl
void main()
{
printf("Beginning of main method\n");
m1();//func call
printf("End of main method\n");
}
void m1()//func def
{
printf("beginning of m1\n");
m2();//func call
printf("end of m1\n");
}
void m2()//func def
{
printf("beginning of m2\n");
m3();//func call
printf("end of m2\n");
}
void m3()//func def
{
printf("beginning of m3\n");
printf("end of m3\n");
}
Return Types:(void,int,float,double,char...)
=============
void(Empty)
------------
#include<stdio.h>
void add(int x,int y);//FDecl
int main()
{
int a=10,b=20;
add(a,b); //a,b actual arguments//Fcall
}
void add(int m,int n)//m,n formal arguments//Fdef
{
int z;
z=m+n;//30
printf("The addition is %d",z);// 30
}
int(10,-3455)
-------------
#include<stdio.h>
int add(int x,int y);//fun dcl
void main()
{
int a=10,b=20,c;
c=add(a,b); //a,b actual arguments//Fcall
printf("The addition is %d",c);//30
}
int add(int m,int n)//m,n formal arguments//Fdef
{
int z;
z=m+n;
return z;
Arrays:
-------
Array is a set of similar datatypes.
1-Dimensional array:
-------------------
int x[];//error
int x[3];//ok
x[0]=10;
x[1]=20.50;//error
x[1]="hi";//error
x[1]='f';//error
x[1]=77;
x[2]=30;
x[3]=40;//error
int x[3]={10,20,30};//ok
int x[]={10,20,30,40};//ok
2-D array(Matrix):
-------------------
int x[row][column];
int x[3][2];
x[0][0]=10;
x[0][1]=20;
x[1][0]=30;
x[1][1]=40;
x[2][0]=50;
x[2][1]=60;
int x[3][2]={{10,20},{30,40},{50,60}};
char name[10]={'h','a','r','i','s','h'};
Pyramid Example:
=================
(39)*\n
(38)* * *\n
(37)* * * * *\n
(36)* * * * * * *\n
(35)* * * * * * * * *\n
Ex:
#include<stdio.h>
int main(){
printf("Enter number of rows");
int rows;
int i,j,k,center=40;
scanf("%d",&rows);//5
for(i=1;i<=rows;i++)//traversing rows
{
for(j=1;j<=center-i;j++)//printing spaces
{
printf(" ");
}
for(k=1;k<=2*i-1;k++)//printing *stars
{
printf("*");
}
printf("\n");
}
JAVA:
=====
Keywords:(Reserved words)
========
Note:Keywords should be in lowercase.
Used Keywords(48):
-------------------
Keywords For datatype(8):
------------------------
byte,short,int,long,float,double,char,boolean
Ex:
---
enum Weekdays
{
sunday,monday,.......,saturday;
}
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.
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
ex:char ch='a';//97==01100001
boolean:
--------
No size.
it jsut represents either true or false.
=====
Keywords:(Reserved words)
========
a)Used(48)-if,else,for,,,,,
-------------------
------------------------
---------------------------
if,else,do,while,for,break,continue,return,switch,case,default keywords For
exception handling:
---------------------------------
---------------------
----------------------
-------------------------------
public,protected,private,abstract,synchronized,static,strictfp,transient,
final,volatile,native,<default> enum keyword:
-------------
---
enum Weekdays
sunday,monday,.......,saturday;
--------------
ex:
m1()//error
} void m1()//ok
Unused keywords(2):
------------------
==========
1)Numerical-byte,short,int,long,float,double
2)Non-numerical-char,boolean Note:
-----
1 Byte=8 bits
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
byte b=-128;//ok
byte b=-130;//error
byte b=128;//error short:
-------
size=2 Bytes
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:
------
--------
No size.
boolean b=false; TypeCasting:
============
1)Implicit Typecasting
------------------------
Its supported by compiler and programers need not worry about it. Ex:
-128...0....10....127
int a=10;//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
------------------------
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
------------------------
Sopln(f);//0.0
float f=10.50;//error
float f=10.50F;//ok
float f=33.00f;//ok
double d=22.33F;//ok
-------------------
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
----------------
Ex:
boolean b;
Sopln(b);//false boolean b=true;//ok
boolean b=false;//ok
boolean b=True;//error
boolean b=0;//error
================
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
================
Object class:
=============
Every class in java is the child class of Object class either directly
the bytecodes line by line and provides the output in human understandable
----------------------
----
class Account
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",.....};
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;
int x[][];
int [][]x;
int []x[];
int[][] x;
int[] []x;
int[] x[];
String Class:
------------
String s=new String("hello");
or
String s="hello";
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
}
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);
}
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",.....};
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;
int x[][];
int [][]x;
int []x[];
int[][] x;
int[] []x;
int[] x[];
String Class:
------------
String s=new String("hello");
or
String s="hello";
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
}
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;
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;
}
}
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[])
{
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;
}
}
Ex:3)
class Test
{
static int 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
{
}
}
Ex:2)
class Test
{
}
}
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
}
}
}
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
}
}
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
{
};
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.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.println("Welcome "+name);
System.out.println("The addition of "+a+" and "+b+" is "+sum);
}
}
Ex:1)
class Test
{
private int 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 Test
{
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
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:
===================
}
}
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.
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.
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
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
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)
{
};
Ex:
//with out using constructors
class Student
{
int rollno;
String 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);
};