Java 4 U
Java 4 U
Java KeyWords
Some identifiers are reserved in Java which has saparate functionality and meaning
such type of reserved indentifiers are called reserved words.
53 reserved words are there in java
50 are keywords-----------48 used keywords,2 unused keywords(goto,const)
3 reserved literals----------true,false,null
Keywords for premitive datatypes:
*byte *short *int *long
*float *double *char *boolean
Keywords for flow control:
*if *else *switch *case *default *for
*do *while *break *continue *return
Keywords for Exception Handling:
*try *catch *finally *throw *throws *assert
Keywords for modifiers:
*public *private *protected *static *abstract *strictfp
*final *transient *native *volitle *synchronised
Class related key words:
*class *interface *package
*extends *implements *import
Object related key words:
*new *instanceOf *super *this
Other:
Void
Unused keywords:
*const *goto
Example:
class KeyEx1
{
int goto=10; ←---------------here we will get identifier expected error
}
Reserved literals:
*true *flase *null
New key words in j2SE 1.5:
*enum
All the key words contains only lower case alphabate symbols
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
short Datatype:
size------------16 bits or 2 bytes
range--------- -2 pow 15 to + 2 pow 15-1 i.e -32768 to 32767
this data type is very rarely used type in java.but best suitable for 16 bit
process(these 16 bit processer are completely out dated and hence also the short
data type is out dated now a days)
Long datatype:
Size----------64 bits or 8bytes
Range------- -2 pow 63 to 2 pow 63 -1
If int is not enough to hold big values like the amount of distence trvelled by light in
1000 days,we shoud go for long datatype only.
Float datatype:
Size--------------32bits or 4 bytes
Range---------- -3.4e38 to + 3.4e38
For 6 to 7 decimal places of accuracy , we should for float data type.so this is less
accuracy.
Double datatype:
Size--------------64bits or 8 bytes
Range---------- -1.7e308 to + 1.7e308
For 14 to 15 decimal places of accuracy , we should for double data type.so this is
more accurency.
Boolean datatype:
The size of boolean is not applicable.(it is purely depend on the underlying
jvm).range not applicable.
But allowed values are true or flase. TRUE or FALSE are not allowed.
Char datatype:
Size--------------16 bits or 2 bytes.
Range----------- 0 to 65535.
This is to providing unicodes for all the worldwide charater sets.
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
boolean Literal:
boolean valid literals are true or flase
boolean b=10; (not valid error PLP found:int reqired :boolean)
char literals:
A char literal can be specified as a single charter in single codes.
Ex: char ch=’@’; (valid)
char ch=a; (not valid)
char ch=’ad’; (not valid) error unclosed character literal.
An integral literal which represents the Unicode value of the character.
Ex: char ch=97; output: a
The valid integral literals must be from 0 to 65535.
for the Unicode values which are not sported by the system,we get ‘?’ as output.
char ch=0x(face) (valid)
char ch=ox61; output:1
The Unicode may be in octal /hexa decimal form.
char ch=97 ;
char ch= ‘a’;
char ch= 0x61;
char ch=’\uXXXX’; --------------------->Unicode representation
Ex: char ch=’\u0061’; output=a;
Unicode representation in nothing but \u followed by 4 digit hexadecimal number .
(only small u,capital u is not allowed).
char ch=’\uface’; valid output: ?
char ch=’\ubeef’; valid
char ch=\ubeef; invalid ‘ ‘ missed.
char ch=’\ibeef’; invalid u missed.
Escape charater
Ex: char ch=’\b’; valid
char ch=’\t’; valid
char ch=’\n’; valid
char ch=’\f’; valid
char ch=’\k’; not valid
Escape sequences:
unicode value charater
\u0008 backspace
\u0009 horizental tab
\u000a new line
\u000d carriage return
\u000c form feed
\u0027 single quote
\u0022 double quote
\u005c back space
String literal:
Instead of \n and /r we are not allowed to the corresponding unicode charater
\u000a and \u000d
Validation leads to compile time error ever in the comments also.
String s=” laxman scjp”; (valid)
String s=”laxman \n scjp”; (valid)
String s=”laxman \t scjp”; (valid)
String s= “laxman \u0009 scjp”; (valid)
String s= “laxman \u000a scjp”; (not valid) gives error illegal escape character
String s=”laxman \u000d scjp”; (not valid) gives error illegal eacape chracter
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Depends on the content hold by the variables are divided into two categories.
1.reference variable
2.primitive variable
reference variable can be used to hold object references.
Ex: String s=”Laxman”;
Here s is a String object
Primitive variable can be used to hold primitive values.
Example: int i=10;
int[][] a={{1,2},{3,4,5},{6,7,8,9},{}};
for(int i=0;i <= a ;i++)
System.out.println(a[i].length);
}
output: 2,3 ,4,0
Depends on the position at which it is declared all the variables divided into 3
categories.
1.instance variables/attributes/member variables
2.static variables
3.local variables
Example:
class Student {
String name;
int rollno;
public static void main(String arg[]) {
Student s=new Student();
}
}
Instance variables:
If the values of the variables are varied from instance to instance3, such type of
variables are called instance variables.We can declare instance variables with in class
,but outside of any method or block.These are also known as attributes
/properties/member variables.The instance variable will create when ever an object
is created and destroyed ,whenever garbage collection destroys this object.Instance
variable will get default variable no need to perform ,explicit initialization.
Static variables:
A single copy of the static variable will maintain and shared by all instances .the
value of the static variable is the same for the instances.The static variable will
create whenever the class loaded into the memory and destroy whenever the class is
unloaded from the memory.These variables are also known as fields.
Example:
class Student {
String name;
int rollno;
static String collname;
Public static void main(String arg[]) {
Student s1=new Student();
System.out.println(s1.name); // null
System.out.println(collname); // null
}
}
With out s1 and static Compile time error
Static variables will get default values .No need to perform explicit initialization.
System.out.println(Student.collname);
System.out.println(s1.collname);
Static variables we can access by using either class name (highly recommended) or
by using object reference.
Local variables:
The variables which are declared inside a method or block or constructor or as
method argument are called local variables.Also known as temporary variables /stack
variable/automatic variables.The local variables will create as the part of the method
execution and will destroy when ever the method terminates.The local variables
never get default values and must be initialized before using that local
variable.Violation leads to CTE saying variable I might not have been initialized.
Example:
case1:
class Sample{
public static void main(String arg[]){
int i;
System.out.println(”hello”); // hello
}}
Case2: class Sample{
public static void main(String arg[]) {
int i;
System.out.println(i); // CTE variable I might not have been initialized.
}}
Case3: class Sample {
public static void main(String arg[]) {
int i=10;
System.out.println(i); // 10
}}
Case4: class Sample {
public static void main(String arg[]) {
int i;
if(arg.length>0) {
i=20;
}
System.out.println(i); // error
}}
It is not recommended to initialized local variable with in the logical blocks .(But
legal)
Case 5:class Sample {
public static void main(String arg[]) {
int i;
if(arg.length>0) {
i=20;
}
else{
i=40;
}
System.out.println(i); // valid
}}
Case6: class Sample{
int[] a;
public static void main(String arg[]) {
Sample s=new Sample();
System.otu.println(s.a); // null
System.out.println(a) // error
System.out.println(s.a[0]); //RTE ---> null pointer exception
System.out.println(a.length); // RTE ---> null pointer exception
}}
case 7: If we declare as static int [] a;
System.out.println(a) // null
System.out.println(a[0]); //RTE ---> null pointer exception
System.out.println(a.length); // RTE ---> null pointer exception
Case8: static int [] a =new int[6];
public static void main(String arg[]) {
Sample s=new Sample();
System.out.println(a) // [I@add234]
System.out.println(a[0]); //0
System.out.println(a.length); //6
}
case9: class Sample {
public static void main(String arg[]) {
int [] a;
System.out.println(a); // error
System.otu.println(a[0]);
System.out.println(a.length);
}}
case10: class Sample {
public static void main(String arg[]) {
int [] a=new int[6];
System.out.println(a); // [I@add34]
System.out.println(a[0]); // 0
System.out.println(a.length); // 6
}}
Once an array object is created its elements will always get default values.
summarization:
Instance array:
int [] a;
System.out.println(objref.a) //null
System.out.println(objref.a[0]); // null pointer exception
System.out.println(objref.a.length); //null pointer Exception
int [] a=new int[6];
System.out.println(objref.a) //[I@add234]
System.out.println(objref.a[0]); // 0 default value for int
System.out.println(objref.a.length); //6
Static array:
static int [] a;
System.out.println(objref.a); //null
System.out.println(objref.a[0]); // null pointer exception
System.out.println(objref.a.length); //null pointer Exception
static int [] a=new int[6];
System.out.println(objref.a) //[I@add234]
System.out.println(objref.a[0]); // 0 default value for int
System.out.println(objref.a.length); //6
Local array:
int [] a;
System.out.println(objref.a) //CTE
System.out.println(objref.a[0]); // CTE
System.out.println(objref.a.length); //CTE
int [] a=new int[6];
System.out.println(objref.a) //[I@add234]
System.out.println(objref.a[0]); // 0 default value for int
System.out.println(objref.a.length); / /6
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Coding Standards
5.Constants:
java constants are created by marking variables as and final.
They should be named using upper case letter with unscore (_) is the saperator.
Ex: MIN_HIGHT,MAX_HIGHT
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Example:
int []a[]; ------>2 di
int []a[];-------->2di
int []a[],b[]; ------->a is 2 di,b is 2 di
int []a[],[]b[]; --------> //not valid
Construction of arrays:
At the time of construction we should specify the size ,other wise compail time error
occures.
i.e int a =new int [6]; (not valid)
int [] a=new int []; (not valid)
int s[]=new int[0]; (valid)
It is legal to have an array with size zero.
If we want to specify the size of the array by using some variable ,the allowed
data type for that variable are byte,short,char,int(i.e any data type which can
be implicitly promoted to the int type).
The maximum allowed size for java array is 2147483647.
Once an array is created ,all the elements will assign with default values
(depends on data types)
Example:
int [] a=new int [6];
000000
Then a -------------------->For int default 0,for string it is null
int [][] a= new int [3][2];
Then a-----------------------> In java the 2 dimensional array is not implemented as
the matrix.it is simply an array of arrays.
int [][] a= new int [3][];
a[0] =new int[2];
a[1]=new int[3];
a[2]=new int[4];
so,no need to specify the second dimension in 2d,3d arrays.
Array Examples:
int [][] a=new int[3][2]; (valid)
int [][] a=new int[3][]; (valid)
int [][] a=new int[][2]; (not valid)
int [][] a=new int[][]; (not valid)
Base size should be specified mandatory.
Example:
int[] a=new int [6];
System.out.println(a[0]); -----------> output: 0
boolean[] b=new booleab[3];
System.out.println(b[0]); -------------> output: false
String s=new String [6];
System.out.println(s[0]); -------------->output: null
Example:
int [][] a=new int [2][3];
System.out.println(a[0]); -----------> output: Garbage value[I@add234]
System.out.println(a[0][0]); -----------> output: 0
int [][] a=new int [2];
System.out.println(a[0]); -----------> output: null
System.out.println(a[0][0]); -----------> output: Null Pointer Exception
Initializing an array:
int [] a=new int[3];
a[0]=20;
a[1]=30;
a[2]=40;
a[3]=50 ------> Leads to array index out of bound Exception
If you are accessing an array with invalid index or some -ve index we will get a RTE
saying array out of bound exception.
a[4.0]; ---------> leads to compail time error
Deceleration ,construction and initialization in single line:
int [] a;
a=new int [3];
Example:
char[] ch={‘l’,’a’,’x’,’m’,’a’,’n’};
String [] s= {“laxman”,”scjp”};
int [] a;
a ={10,20,30}; ----------------> Leads to compail time error illegal start expression
so Declaration,contraction,initialization must in a single Line.
length Vs length():
length:This is a variable.applicable for only for array objects represents the number
of elements or the size of the array.
Ex1:
int a=new int[6];
System.out.println(a.length); ------------------> output: 6
Can’t apply to String
Ex2:
String s=”Laxman”;
System.out.println(s.length);
Given CTE because length variable applicable only for array objects.
length(): It is a final method applicable for string objects.
It represents the number of characters present in the String Object.
Ex:
String s=”Laxman”;
System.out.println(s.length()); ---------> 4
System.out.println(s.length); ---------->error
Anonymous Arrays:
There are name less arrays.
Purpose of these anonymous arrays is just for instant use.
Example:
class Sample {
public static void main(String arg[]) {
System.out.println(sum(new int[]{10,20,30}));
}}
output: 60
While constructing anonymous arrays we are not allowed to specify the size
.violation leads to compile time error.
If we want ,we can assign anonymous array for any reference variable.
i.e int [] a=new int[] {10,20,30,40}; ----------> valid
Java operators
Operators&Assignments:
• increment/decrement
• shift
• arithmetic
• equality(==,!=)
• relational
• bit-wise
• short-circuit
• instanceof
• cast
• conditional(?)
• new
•[]
Increment& decrement operators:
• Post Increment ------> y=x++;
• Pre Increment ------> y=++x;
• Post Decrement ------> y=x--;
• Pre Decrement ------> y=--x;
Increment or decrement operators, we can apply Only for variables not for
constant expressions. Violation leads to Compile time error saying
unexpecompile time errord type Required: variable but found=value.
byte + short=int
char + char=int
int + char=int
int + long=long
doubles + byte=double
Arithmetic OPERATORS:-( + , - , * , / , % )
byte a=10
byte b=20
byte c=a+b; //compile time error plp req:byte
If we can perform arithmetic operators b/w any two operands a and b , the
result type is, max(int, type a, type b)
For representing infinity, there are no constant ; define in the integer class.
Hence 0/0 results is sum time exception saying arithmetic exception
But in the float and double classes for representing infinity constants are
defined.
Ex:System.out.println(0.0 / 0) → NaN
System.out.println(Math.sqrt(4)); → 2.0
System.out.println(Math. Sqrt(-4)); → NaN.
System.out.println(10/0)→ Arithmatic exception
System.out.println(10.0 / 0)→ infinity
System.out.println(-10.0 /0→ - infinitz
System.out.println(0/0) → Arithematic Exception.
System.out.println(0.0/0 → NaN
System.out.println(-10/0) → arithmatic exception
System.out.println(-10.0/0)→ -infinity,
System.out.println(-0.0/0)→ NaN.
Float. POSITIVE_INFINITY = = Float. POSITIVE_INFINITY; // true
Float . POSITIVE_INFINITY = =Double. POSITIVE_INFINITY. // true
Float . NaN = =Float. NaN.
Float. NaN >double. NaN }false
Float. NaN !=Float. NaN →true.
if one are comparing NaN with any other , including NaN itself, the result is
always false, except for not equal(!=)operator.
Arithmetic exception:
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Access modifiers
class Modifiers:
Once we are writing a class the access modifier describes the properties of that
class .(creation of child class is allowed or not ,creation of object is allowed or not
,we can access this class from outside the package or not and so on).
Access specifiers or Access modifiers are same in case of java.java compiler shows
the error related to public,static,.......so on , it use the word modifier not Specifier.
The allowed modifiers for the Top level classes are :
1.public 2.default 3. final 4.abstract 5. strictfp
If we are using other then these modifiers ,compile time error saying modifier some
not allowed here.
For the inner classes the following are allowed modifiers:
1.public 2. private 3.protected 4.default 5.final 6.abstract 7.static 8.strictfp
public class:
A public class can be accessed from any where with in the package /outside the
package.
package pack1;
public class B
{
System.out.println(“hai”);
}
package pack2
{
import pack1.B;
class A
{
public static void main(String arg[])
{
B b=new B(); // we can access
}
class:
If a class declared as the default ,we are allowed to access that class only with in the
current package.If you are trying to access from outside package compilation fails.
package pack1;
class B
{
System.out.println(“hai”);
}
package pack2
{
import pack1.B;
class A
{
public static void main(String arg[])
{
B b=new B(); //we can't access
}
Here class B is is default ,but not public in pack1.So this class can’t be accessed from
outside package.
final class:
If a class declared as the final then we are not allowed to create the child class.
Advantage:
We can implement security .
Limitation:As we are not allowed to create the child class,we are missing the key
benefits of object oriented programming ,re usability and flexibility.Its not a good
programming practice to use final classes in the real time unless security is required.
final method:
If a method declared as the final ,it indicates that this implementation is final
implementation.
i.e we are not allowed to override this implementation the child class.
Observations:
If a class declared as the abstract ,we should create the child class to provide
implementation for abstract methods.
If a class declared as the final ,you are not allowed to create the child
class.Hence final and abstract combination is illegal for classes.
Example:
class Sample
{
void m1(); //error: missing method body or declaration missing.
public static void main(String arg[])
{
System.out.println(“hai”);
}
}
final is the keyword which can be applied for classes ,methods and variables.
This keyword we can apply for classes and methods .i.e we can’t apply strictfp
for the variables.
If a method declared as the strictfp all the floating point calculations inside
that method has to follow “IEEE 754” standards so that we will get platform
independent result.
If a class declared as the strictfp ,all concrete methods in that class has to
follow IEE 754 standard for floating point calculations .
Abstract and strictfp combination is not-valid for methods .But it is valid
combination for the classes.
Not-valid combinations:
abstract and final .
abstract and strictfp
abstract and synchronized
abstract and static
abstract and native
abstract and private.
If class A is declared as public ,then the class B compiles fine and prints “Hai”.
default member:
If a member declared as the default ,that member is visible with in the current
package only.
package pack1;
public class A
{
void m1()
{
System.out.println(“hai”):
}
}
package pack2;
import pack1.A;
class B
{
public static void main(String arg[])
{
A a=new A();
a.m1(); //error
}
}
error:m1() is not public in pack1.A.
If a member declared as the private we can access with in that class only.i.e
from outside the class,you are not allowed to access.
It is highly recommended to declare data members as private to achieve
security.
Example:
package pack1;
public class A
{
protected void m1()
{
System.out.println(“hai”);
}
}
case 1:
class B
{
public static void main(String arg[])
{
A a=new A();
a.m1(); // hai
}
}
Case 2:
class B extends A
{
public static void main(String arg[])
{
B b=new B();
b.m1(); // hai
}
}
case 3:
A a1=new B();
a1.m1(); //hai
case 4:
B a=new A();
a.m1(); // error
Example:
package pack2;
import pack1.A;
class B extends A
{
public static void main(String arg[])
{
A a=new A();
a.m1();
}
case 2:
B b=new B();
b.m1(); // valid
case 3:
a a1=new B();
a1.m1(); // in-valid
conclusions:
The protected members can be accessed with in the current package any
where either by using parent class reference or by using child class reference.
But from outside package we can access protected member only by using
child class reference .
If we are using parent class reference to access protected member from
outside package we will get a compile time error.
Example:
case 1:
class Sample
{
public static void main(String arg[])
{
Object o=new Object();
o.finalize(); // error
System.out.println(“hai”);
}
}
error :finalize has protected access.
Case 2:
public static void main(String arg[])throws Throwable
{
Sample s=new Sample();
o.finalize(); // valid
System.out.println(“hai”);
}
case 3:
Object o=new Sample();
o.finalize(); //in valid
final variables:
final is the keyword which can be applied for methods classes and variables.
Instance and static variables will get default values always .There is no need
to perform explicit initialization.
But the local variables never get any default values .Before accessing a local
variable ,we should perform initialization other wise compile time error.
final instance variables :
For the final instance variables ,we should perform initialization other wise compile
time error.
The final instance variable must be initialization before constructor compiles.i.e at
the time of declaration or inside instance initialization block or inside constructor.
Example:
final int i;
public static void main(String arg[])
{
Sample s=new Sample()
System.out.println(s.i); // invalid
}
final-static variables:-
Final static variables must be initialized before class loaded into memory. otherwise
compile time error. i.e we can perform initialization for the final static variables at
one of the following places.
1. at the time of declaration
2. inside the static initialization block
final static int I;
static
{
int i=30;
}
final-local variables:-
Local variables even though we can declared as the final must be initialized before
using.
class Sample
{
Public static void main(String args[])
{
final int I;
System.out.println(“hai”);
} // hai
Example:
class test
{
public static void main(String arg[])
{
final int a; //instead of final we cant write int modifier
System.out.println(“hi”);
}
}
The variables which are declared as the method arguments are simply acts as local
variables of that method .hence the only applicable modifier for the logical variables
is final. If any formal parameter declared as the final we are not allowed change its
value with in the method.
Example:
class test
{
public static void main(String arg[])
{
m1(100,200);
}
}
public static void m1(final int i, final int j)
{
i=200; //error
i=300; //error
}
}
Static Modifier:
For every object a separate copy of instance variables will be created but in
the case of static variables a single copy will be created at the class level and
shared by all the objects of that class.
Example:
class test
{
int i=10;
static int j=20;
public static void main(string arg[])
{
Test t1=new Test();
t1.i=100;
t1.j=200;
System.out.println(t1.i+’…”+t1.j); //100,200
Test t2=new Test();
System.out.println(t2.i+’…”+t2.j); // 10,200
t2.j=2000;
System.out.println(t1.i+’…”+t1.j); //100,2000
}
}
Most of the cases the keyword static associated with final modifier for defining class
level constants.
Non static variables can not be returning form static modifier/ content:
class test
{
int i=10;
public static void main(String arg[])
{
System.out.println(i);
}
}
error: Non static variable I cant be returning static content
example:
1) int i=10;
2) static int i=10;
3)public void m1()
{
System.out.println(i);
}
4) public static void m1()
{
System.out.println(i);
}
Which of the following are not allowed simultaneously in the same class
1) & 3) instance variable can't be accessed from instance area,either instance block,
constructors or instance access block
1) & 2) compile time error.. non static variables are instance variables can not be
referenced from static constant
2) & 3) , 2) & 4)… static variables can be accessed from any where either from
instance area or static area
3)Usually static methods are utility methods and we should provide complete
implementation but for abstract methods we are not allowed to provide
implementation . Hence abstrace and static combination is illegal for the methods.
Synchronized is the keyword which can be apply for method and blocks. i.e
we can not apply synchronized keyword for classes and variables.
If a method declared as synchronized at a time only one thread is allowed to
execute that method on the given object.
Advantages:
1) We can provide thread safety
2) We can avoid data inconsistency problems
Disadvantages:
1)synchronized keyword increases waiting time of threads and hence performance of
the system goes down.hence unless and until there is no specific requirement do not
use synchronized keyword in the coding.
Note:Synchronized is the keyword which is always talks about implementation but
abstract never talks about implementation.Hence synchronized and abstract
combination is illegal for the methods.
Native Modifier:
Native is the keyword which can be apply only for methods. i.e we can not apply
native keyword for classes and variables.
1) A native method means. The method which is implemented in non-java like c,c+
+;
2) Native methods are also known as foreign methods.
Advantages of Native method:
1) As the performance of java is low for improving the performance we can depends
on c or c++. This stage methods can be helped by native keywords
2) We can communicate legacy systems by using native keyword
Demo:
class NativeEx
{
static
{
System.loadLibraries(“path of native methods library”);
}
native void m1();
}
class Client
{
public static void main(String arg[])
{
Native n=new NativeEx();
n.m1();
}
}
Transient Keyword:
Transient is the keyword which can be applicable only for variables i.e., we are not
allowed to use transient keyword for methods and classes.
Serialization:
The process of saving an object to a file is called serialization Strictly serialization
means “The process of converting java supported format object to network
supported format object (or) file supported format object is called serialization.
1)If a variable declared as a transient, at the time of serialization JVM ignores the
values of that the transient variable. Instead of original values JVM saves default
value.
2) Hence transient means not to serialize.
Example:- While saving account information permanently to a file we are not
allowed to save passwords for security reasons such type of variables we have to
declare by transient keyword
3)We can serialize only serializable objects violation leads to runtime exception
saying not serializable exception
4)An object is said to be serializable if an only if the corresponding class implements
serializable interface
Transient Example:
import java.io.*;
class Transient Demo implements Serializable
{
int i=10;
int j-20;
public static void main(string args[])throws exception
{
Transient demo t1=new transient demo();
System.out.println(t1.i+”----“+t1.j);
file output stream fos=new file output stream(“abc.txt”);
object output stream oos=new object output stream(fos);
oos.writeobject(t1);
//t1.i=1000
//t1.j=2000
FileInputStream fis=new FileInputStream(“abc.txt”);
ObjectInputStream fis=new ObjectInputStream(fis);
Transient Demo t2=( Transient Demo)ois.writeObject(t1);
System.out.println(“t2.i+”…”+t2.j);
1).If we are not declaring implements serializable we will get a runtime exception not
serializable exception
2)if we are not keeping throws exception compile time error saying unreported
exception must be called or declared to be thrown
Note:- static variables never part of object state hence we are not participating in
the serialization process during a static variables as the transient is useless and
there is no impact.
Volatile Keyword:
Volatile is the keyword which can be applicable only for variables i.e we can not use
for classes and methods . If the value of the variable is changing frequently such tpe
of variables we have to declare with the keyword volatile.
1) For the volatile variables JVM will create a separate private copy for every
thread.After completing entire transaction but that thread the final value will be
updated in the master copy. So that the value of the volatile variable is always stable
2) At variable level we can achieve synchronization by using volatile keyword
3) For every thread maintaining a separate copy is always difficult .hence
performance of the system goes down
4) Volatile means the value keep on changing but final means the value is not
allowed to change. Hence volatile and final combination is always illegal. We are not
declaring a final variable as volatile.
class,object
class:
Programming languages that support classes all subtly differ in their support for
various class-related features. Most support various forms of class inheritance. Many
languages also support features providing encapsulation, such as access specifiers.
class Example:
Class java
properties(variables);
Actions(methods);
object:
Any language present objects and this should not be confounded with the most
powerful concept of object-orientation.
In procedural programming, an object may contain data or instructions, but not
both. (Instructions may take the form of a procedure or function.) In object oriented
programming, an object may be associated with both the data and the instructions
that operate on that data.
int i=10;
void mone()
System.out.println("java");
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Abstraction
Encapsulation
Encapsulation Advantages:
Security
Easy to enhance
Maintainability
Modularity
Example:
class Sample
{
public int i=10;
public int getId()
{
return i;
}
public void setId(int x)
{
this.i=x;
}
}
The major limitations od encapsulation is,it increases the code (because we have to
getter and setter methods for the data variables )and hence slows down the
execution.
• If the parent class is not tightly encapsulated no child class is tightly encapsulated.
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Java Inheritance
IS-A relation:
• Also known as Inheritance
• By using extends keyword we can implement IS-A relationship.
• Re usability is the benefit of IS-A relationship
Inheritance is accepted up to certain level but after reaching problems. Because for
every child class object, internally all the parent objects will be created in the
inheritance tree.
In the real time it is recommended to have inheritance up to 8 to 10 levels only.
Beyond that it is not suggestible.
is a relation Example:
class Superclass
{
void display()
{
System.out.println("Hi");
}
}
class InheritanceExample extends Superclass
{
public static void main(String arg[])
{
InheritanceExample ie=new InheritanceExample();
ie.display();
}
}
HAS-A relation:
• Also known as composition or Aggregation.
• By using new operator we can implement HAS-A relationship.
• Reusability (CBM->Component Based Model) is the benefit of HAS–A relationship.
• The limitation of HAS-A relationship is, we are increasing the dependency between
the classes. As a result, the maintenance of the code becomes complex or costly.
has a relation Example:
class Car
{
Engine e= new Engine();
. …….
.......
}
class Engine
{
m1(){}
m2(){}
}
Car class has Engine reference. Hence Car allowed using all the features of engine.
But without Engine object we can’t create Car object.
Method Signature
Method Signature :
Example:
public void m1(int a, int b)
{
m1(int, int); -----> signature of method m1
}
Example:
public void m1(int a, float b)
{
m1(int , float); //valid
m1(float , int);//invalid
}
• In java the method signature is compiled with method name and argument list (the
order of arguments also important).
• Return type is not part of the signature.
• Compiler uses the method signature to resolve method calls.
• With in a class two methods having same the signature is not allowed, violation
needs to CTE saying method is already defined in class.
Example:
class Test
{
public int m1(int i){}//invalid, CTE: m1(int) is already defined in test
public void m1(int i){}
}
Method Overloading
Method Overloading:
Two methods having the same name are not allowed in the case of C-language, for
every data type even though the functionality in the same; we should maintain
different method names. It increases the complexity of the programming. But in
java, two methods having the same name is allowed irrespective of parameters. We
can maintain the same method name for similar type of functionality. It simplifies
the programming. Such types of methods are called Overloaded methods.
• Two methods are said to be overloaded if and only of they have the same method
name, but different parameter list(at least order).
• The signatures of the two overloaded methods must be different.
Example:
public void m1(){}
private int m1(int i){}
• Here m1() & m1(int i) are overloaded. We never consider return type, access
modifier and throws class in overloading.
Example:
class Sample
{
public void m1()
{
System.out.println(“no arg”);
}
public void m1(int i)
{
System.out.println(“ int arg”);
}
public void m1(double d)
{
System.out.println(“ double arg”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1();
s.m1(10);
s.m1(10.5);
}
}
s.m1(10L);//double arg
s.m1(‘a’);//int arg
}
}
In the case of overloading the method resolution performed by the compiler is based
on the reference type.
Method Overriding
If you don’t want parent class implementation for any method we can override in the
child class based on our child class requirement. This concept is called Overriding.
While overriding we have to fallow rules:
1. In the overriding, the method names and arg’s must be same.
Ie. In the case of the overriding the signatures of the methods must be same
Until 1.4 version, the return types must be same. But from 1.5 version onwards
covariant return types are also allowed.
Example:
class p { public Number getNumber(){} }
class c extends P{ public Number getNumber(){} }
(or)
class C extends P
{
public Byte/Short/Integer getNumber(){}
}
Example:
import java.io.*;
class P
{
public object m1(){ return new object; }
}
class C extends P
{
public Object m1(){ return new Object; }
}
class C extends P
{
public String m1(){ return “durga”; }
}//in 1.4 CTE saying m1() in C cannot override found:string, req:object: in 1.5 ver
no CTE
* While implementing any interface method, we should declare that method as public
in the implemented class.(by default implements interface method is public and
abstract)
* An abstract method can be overridden as abstract. The child of the original child
class is responsible for the implementation.
class P{
public void m1()
{ } }//non abstract
abstract class C extends P{
public abstract m1(); }//valid abstract
5. While overriding the size of the CheckedException should not increase. There is no
rule for UnCheckedExceptions.
Example: Base or parent class :
public void m1()throws IOException
Derived or child class :
Method Hiding:-
This is exactly same as overriding except both parent & child class methods must be
declared as static. In the method hiding the method resolution take care by compiler
only based on the reference type.
Ex:
class P
{
static int x=10;
int y=20;
}
class C extends P
{
static int x=100;
int y=200;
}
class Sample
{
public static void main(String[] a)
{
P p=new C();
System.out.println(p.x+”,”+p.y); //10,20
C c=new C();
System.out.println(c.x+”,”+c.y); //100,200
P p1=new P();
System.out.println(p1.x+”,”+p1.y); //10,20
}
}
We can’t override in the child class. But if define exactly same variable in
child class.
Variable resolutions take care by compiler only based on the reference type.
Constructors
The purpose of Constructor is to perform of our creted object. Whenever we are
calling new operator for the creation of object, it calls constructor automatically to
provide initialization for the object.
class Student
{
String name; int rno;
Student(String name, int rno) ----> Constructor
{
this.name=name;
this.rno=rno;
}
public static void main(String a[])
{
Student s=new Student(“xxx”,101);
Student s1=new Student(“yyy”,102);
-------
------
}
}
Rules Of Constructor :
1. Constructor concept is applicable for every class including abstract class also.
2. Interface doesn’t have Constructor’s concept.
3. The name of the const4ructor and the name of the class must be same.
4. The allowed modifiers for the constructors are public, private, protected, and
default. If you are applying any other we will get a CTE saying “modifier xxx not
allowed her”.
5. We can’t give return type for the constructor even void also.
If we will give return type for the constructor that thing as a method instead of
constructor that thing as a method instead of constructor (so,there is no CTE). Ie., it
is legal (but stupid) to have a method whose name same as classname.
Default Constructor:-
If the programmer is not writing any constructor, then only compiler will generate a
default constructor.
Ie., either programmer written constructor or compiler generated must present in
your class but not both at a time.
Prototype of default constructor shown below:
a).Programmer written code:- class Test{}
Compiler generated code:-
class Test
{
Test()
{
super();
}
}
The first line inside a constructor must be a call to super class constructor
( by using super();) or a call to overload constructor of the same class. (by
using ‘this’ keyword).
If you are not writing the first line as either ‘super()’ or ‘this’ then compiler
will always keep a no arg call to super class constructor (super();).
Overloaded Constructors:
We are allowed to keep more than one constructor inside a class , which are
considered as overloaded constructors. We can’t override the constructors, because
they belong to the same Ex: class Test {
Test(int i){}
Test(){} ---->Overloaded Constructors
}
Constructors are not inherited and hence we are not allowed to override a
constructor.
while recursive method invocation we will get stackoverflowException But in
case of constructors we will get compile time error.
If we are writing any constructor in our class it is recommended to place
default constructor also. Otherwise we should take care while writing the
constructor child case.
If the parent class constructor throws some Checked Exception, while writing
child class constructors we should take care.In case of unchecked exception
no rule.
Example:
class P {
P(int i)
{
System.out.println(i);
}
}
class C extends P
{
C()
{
super(10); // valid (without super invalid)
}
}
Example: class P
{
P() throws Exception ----> checked exception
{}
}
class C extends P
{
C() // compile time error unhandled exception type exception
{}
}
abstract class
We can apply abstract keyword for the classes and methods .abstract keyword is not
possible for variables.If method declared as abstract we don’t know implementation
child class is responsible to provide the implementation for the parent class abstract
methods.
If a class contain at least one abstract method we should have to declare that
class as abstract other wise compile time error.
HttpServlet class doesn’t contain any abstract methods ,still the class is
declared as abstract because the methods present in HttpServlet can’t
provide any request ,response for the end user ,these methods are just for
sending error information.
It’s a good programming practice to use abstract methods ,abstract classes
and interfaces.
Example:
class Sam
{
abstract void m1(); //error
}
Example 2:
abstract class Xy
{
abstract void m1(); // valid
}
Example 3:
abstract class X
{
void m1() // valid
{
System.out.println(“valid”);
}
}
Example 4:
abstract class X
{
abstract void m2();
}
interface
An interface defines the contract between service provider and the client without
highlighting internal implementation.
i.e Interface describes the services ,what service provider provides and what client
get.
The main advantage of interface are :
1. we never high lite our implementation to the outside world,we can achieve
security for our implementation.
2. With out effecting outside world,we can enhance our internal implementation.
Interface is considered as 100% pure abstract class because we never keep
implementation inside interface. And hence all the methods present inside an
interface are abstract methods.
For the service provider point of view an interface defines the services provided by
that person.
From the client point of view an interface describes what services he required.
Declaring an interface:
interface Interf
{
public void m1();
public void m2();
}
class Bea implements Interf
{
public void m1()
{
System.out.println(“implementation m1”);
}
public void m2()
{
System.out.println(“implementation m2”);
}
public static void main(String arg[])
{
Interf i=new Interf();
i.m1();
}
}
If you want to provide implementation for any interface method ,it must be
declared as public .
The first concrete class which implements an interface must provide
implementation for all the interface methods other wise the class must
declared as abstract.
We can declare an interface (top level) with <default> and
public,abstract,strictfp modifiers.
interface methods Declarations:
All the interface methods by default abstract and public (either we are specify or not
specify) not concrete method.
Examples:
Void m1();
public void m1();
abstract void m1();
public abstract void m1();
All the above are same .
Hence the above four methods declaration are identical.
An interface method never be declared as native ,strictfp,private ,static,
synchronized and protected.
interface interf
{
int x=10;
public int x=10;
public static final int x=10;
final int x=10;
static int x=0;
}
Hence an interface we never declared as private ,protected and transient.
All the interface variables must perform initialization at the time of declaration.
Hence the following code will not compile.
interface Interf
{
int x;
}
Inside implement classes we are not allowed to change the value of interface
variable violation leads to compile time error.
Class Sample implement Interf
{
public static void main(String arg[])
{
x=20; //compile time error
}
}
A class can extend only one class at a time .But can interface can extend any
number interfaces.
A class can implement any number of interfaces at a time.But interface never
implement another interface.
Case 2:
The interface having same method name but different arguments.
Interface Inter
{
public void m1();
public void m1(int x);
}
case 3:
Same method name,same arguments but different written types.
Interface Left
{
public void m1();
}
Interface Right
{
public int m1();
}
Exceptional case :
We can’t provide implementation at a time for two or more interfaces having
methods with same signature but different return type .
Collection-Interface
The 1.2 release of the Java platform includes a new collections framework. A
collection is an object that represents a group of objects. A collections framework is
a unified architecture for representing and manipulating collections, allowing them to
be manipulated independently of the details of their representation. The Collection
interface is the root of the collection hierarchy. A Collection represents a group of
objects, known as its elements. Some Collection implementations allow duplicate
elements and others do not. Some are ordered and others unordered. The JDK
doesn't provide any direct implementations of this interface: It provides
implementations of more specific subinterfaces like Set and List. This interface is the
least common denominator that all collections implement.
Collection is used to pass collections around and manipulate them when maximum
generality is desired.Collection frame work define a set classes and interfaces which
can be used for representing a group of objects as single entity.In the case of c++
the corresponding collection frame work is known as STL(Standered template library)
and collection is known as container.
There are six collection interfaces. The most basic interface is Collection. Three
interfaces extend Collection: Set, List, and SortedSet. The other two collection
interfaces, Map and SortedMap, do not extend Collection, as they represent
mappings rather than true collections. However, these interfaces contain collection-
view operations, which allow them to be manipulated as collections.
Collection Interface:
It defines general methods ,which can be used for a group of individual objects.i.e a
collection represents a group of individual ibjects.
Note:
Collection is an interface to represent a group of individual objects where as
collections is an utility class for defining utility methods like sorting,searching… etc.
Collection Interface Methods:
This Interface defines general methods which can be applied on any collection object.
1.boolean add(Object obj)
2.boolean addAll(collection c)
3.boolean remove(Object o)
4.boolean removeAll(Collection c)
5.void clear()
6.boolean retainAll(Collection c)
removes all the elements in the collection except those present in c.
7.boolean contains(Object o)
8.boolean containsAll(Collection c)
9.boolean isEmpty()
10.int size()
returns the number of objects present in the collection
11.Object[] toArray()
mainly for improving the performance of the system.
12. Iterator iterator()
to return the objects one by one.
SortedMap-TreeMap-Properties
SortedMap:
It is interface.If you want to store the elements based on some sorting order of keys
we should go for the SortedMap.A SortedMap is a Map that maintains its mappings in
ascending key order. It is the Map analogue of SortedSet. The SortedMap interface is
used for apps like dictionaries and telephone directories.
SortedMap Methods:
1) Object firstKey() //Returns the firstkey of the sortedset
2) Object lasKey() // Returns the last key of the sortedset
3) SortedMap headMap( Object key) //Returns the SortedMap whose keys are
smaller than or equal to specified key
4) SortedMap tailMap( Object key) // Returns the SortedMap whose keys are greater
than or equal to specified key
5) SortedMap subMap( Object key1,Object key2) // Returns a SortedMap whose keys
are greater than or equal to the key1 but less than key2
6) Comparator comparator(): //Returns Comparator Object that defines the
underlying sorting technique.If the natural sorting order is used then returns null
TreeMap:
TreeMap Constructors:
TreeMap map=new TreeMap():
TreeMap map=new TreeMap(Comparatror c):
TreeMap map=new TreeMap(Map m):
TreeMap map=new TreeMap(SortedMap m):
import java.util.TreeMap;
import java.util.Comparator;
import java.util.TreeMap;
class Mycompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
return -i1.compareTo(i2);
}
}
output:
The TreeeMap Is {400=grapes, 300=apple, 200=grapes, 100=orange}
Properties:
Propertes Constructors:
Properties props=new Properties();
Methods:
getProperty(String key);
setProperty(String key,String value);
propertyNames();
load(InputStream stream);
store(OutputStream stream,String comment);
Map-Hashtable-HashMap-WeakHashMap-IdentityHashMap
MAP Interface:A Map is an object that maps keys to values. Maps cannot
contain duplicate keys: Each key can map to at most one value.
Note:
interface Map{
Interface Entry{ // inner interface entry
Object getKey();
Object getValue();
Object setValue(Object obj)
}
}
Hashtable:
Hashtable Constructors:
Hashtable table=new Hashtable();
Hashtable table=new Hashtable(int initialCapacity);
Hashtable table=new Hashtable(int initialCapacity,float fillRatio);
Hashtable table=new Hashtable(Map m);
Hashtable Demo:
import java.util.Hashtable;
output:
The Hashtable is {9=bbb, 8=aaa, 3=zzz, 2=sss, 24=yyy, 1=xxx}
HashMap:
HashMap Constructors:
1) HashMap map=new HashMap();
it Create the empty hashmap with the default initial capacity 16 and fillRatio 0.75
2) HashMap map=new HashMap(int initialCapacity);
it Create a HashMap with the specified nitialCapacity and default load factor
3) HashMap map=new HashMap(int nitialCapacity,float loadFactor);
4) HashMap map=new HashMap(Map m);
HashMapDemo Program:
import java.util.*;
public class HashMapEx1 {
public static void main(String... args) {
HashMap map=new HashMap();
map.put("orange",new Integer(1000));
map.put("apple",new Integer(2000));
map.put("banana",new Integer(3000));
map.put("grapes",new Integer(4000));
System.out.println("The Map "+map);
System.out.println(map.put(("orange"),new Integer(1001)));
System.out.println("map "+map);
Set s=map.keySet();
System.out.println("The Key Set"+s);
Collection values=map.values();
System.out.println("The Values Are "+values);
Set s1=map.entrySet();
System.out.println("The Entry Set"+s1);
}
}
output:
The Map {orange=1000, grapes=4000, apple=2000, banana=3000}
1000
map {orange=1001, grapes=4000, apple=2000, banana=3000}
The Key Set[orange, grapes, apple, banana]
The Values Are [1001, 4000, 2000, 3000]
The Entry Set[orange=1001, grapes=4000, apple=2000, banana=3000]
LinkedHashMap:
It is exactly similar to the HashMap except the following differences
HashMap:
LinedHashMap:
IdentityHashMap:
In case of HashMap JVM uses the equals() method to identify the duplicate keys
But if want to use the == operator to identify the duplicates we go for the
IdentityHashMap
Incase of IdentityHashMap two key reference i1 and i2 are equal if and only if bot i1
and i2 are pointing to the same object on the heap
WeakHashMap:
output:
finalize() Called
The Map{}
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Collection-List-Vector-ArrayList-Stack-LinkedList
Collection Interface :
The Collection interface is the root of the collection hierarchy. A Collection represents
a group of objects, known as its elements. Some Collection implementations allow
duplicate elements and others do not. Some are ordered and others unordered. The
JDK doesn't provide any direct implementations of this interface: It provides
implementations of more specific subinterfaces like Set and List. This interface is the
least common denominator that all collections implement. Collection is used to pass
collections around and manipulate them when maximum generality is desired.
It defines general methods ,which can be used for a group of individual objects.i.e a
collection represents a group of individual ibjects.
Note: Collection is an interface to represent a group of individual objects where as
collections is an utility class for defining utility methods like sorting,searching… etc.
List Interface:
Vector class:
Vector methods:
For adding objects
1.add(Object o) ----> from collection
2.add(int index, Object o) ---------> from list
addElement(Object o) ---------> Vector
for removing objects
1.remove(Object o) ---------> from collection
2.remove(int index) -----------> from list
3.removeElement(Object o) ----------> Vector.
4.removeElementat(int index) -------------> Vector
5.removeAllElements()
6.clear() ------------> from collection
For accessing objects.
1.Object get(int index)
2.Object elementAt(int index)
3.Object firstElement()
4.Object lastElement();
5.int size()
6.int capacity();
Constructors of Vector:
1.Vector v=new Vector()
create an empty Vector with default initial capacity 10.
If the Vector reaches its maximum capacity a new Vector object will create with a
capacity = current capacity * 2 i.e doubles.
2.Vector v=new Vector(int initialcapacity)
Constructs an empty vector with the specified capacity.
3.Vector v=new Vector(Collection c)
4.Vector v=new Vector(int initialcapacity,int incrementalcapacity)
Vector Example:
import java.util.*;
class VectorDemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement(“a”);
for(int i=0;i<10;i++)
{
v.addElement(new Integer(i));
}
System.out.println(v);
System.out.println(v.capacity()); // 10
v.add(“b”);
System.out.println(v.capacity()); // 20
}
}
Array List:
Constructors of ArrayList:
1.ArrayList a=new ArrayListA();
creates an empty arraylist with the default initial capacity 10.
If arraylist reaches its maximum capacity ,it creates a new arraylist object with the
new capacity as (Current capacity * 3/2 ) + 1;
2.arrayList a=new ArrayList(int initialcapacity)
creates an empty arraylist with the specified initial capacity.
3.ArrayList a=new ArrayList(Collection c)
Construct an equivalent arraylist for the given collection object.
ArrayList Example:
import java.util.*;
class ArraylistDemo
{
public static void main(String arg[])
{
ArrayList a=new ArrayList();
a.add(“aaa”);
a.add(“bbb”);
a.add(“new Integer(10)”);
a.add(null);
a.add(1,”ccc”);
System.out.println(a); // [aaa, ccc,bbb,10,null]
}
}
every collection class implemented clonable and serializable interfaces.
System.out.println(a instanceOf java.io.Serializable); // true
System.out.println(a instanceOf java.io.Clonable); // true
LinkedList:
LinkedList class contain the following methods for implementing Stacks and Queues.
1.void addFirst(Object o)
2.void addLast(Object o)
3.Object removeFirst()
4.Object removeLast()
5.Object getFirst()
6.Object getLast()
Constructors of LinkedList:
1.LinkedList l=new LinkedList();
create an empty LinkedList (initial capacity is not applicable) size != capacity
2.LinkedList l=new LinkedList(Collection c)
LinkedList Example
import java.util.*;
class LinkedListDemo
{
public static void main(String arg[])
{
LinkedList l=new LinkedList();
l.add(“laxman”);
l.add(new Integer(10));
l.add(null);
l.add(“laxman”);
l.add(0,”scjp”);
l.add(“gorantla”);
l.removeLast();
l.addFirst(“ccc”);
System.out.println(l); // [ccc,gorantla,scjp,10,null]
}
}
Stack Class:
It is the child class of Vector
Contain only one constructor
Stack s=new Stack();
Methods of stack class:
1.Object push (Object obj)
It pushes an element into stack and that element also return.
2.Object pop()
removes the top of the stack and the object is returned.
3.Object peek()
returns the element present on the top of the stack.
4.boolean empty()
returns true if the stack isempty otherwise false.
5.int search(Object o)
returns the offset from the top of the stack if the Object present else return -1.
Ex: s.search(“a”);
Stack example:
Import java.util.*;
Class StackDemo
{
public static void main(String arg[])
{
Stack s=new Stack();
s.push(“a”);
s.push(“b”);
s.push(“c”);
System.out.println(s); // [a,b,c]
System.out.println(s.search(“c”)); // 1
System.out.println(s.search(“a”)); // 3
}
}
insertion order should be preserved should be not LIFO.
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
SortedSet Interface:
If you want to represent a group of individual,unique set of objects ,where all the
objects are in some sorting order (either natural sorting order or customized sorting
order) then we should go for SortedSet.
SortedSet methods:
1.Object first()
returns the first element in sortedset
2.Object last()
return the last element in sortedset.
3.SortedSet headset(Object end)
returns the sorted set containing the elements which are lessthan end.
4.SortedSet tailSet(Object begain)
returns the sorted set that includes the elements which are greaaer than or equal to
begain.
5.SortedSet subset(Object begain,Object End)
return a sortedset that includes the elements which are greater than or equal to
begain but less than end.
6.Comparator comparator()
decribes underlying sorting technique if default sorting technique is used then it
simply returns null.
TreeSet class :
Constructors:
1.treeSet t=new TreeSet()
creates an empty TreeSet where the sorting technique is default natural order.
2.TreeSet t=new TreeSet(Comparator c)
creates an empty TreeSet ,where the sorting technique is specified by comparator
object .( this is for customized sorting).
3.TreeSet t=new TreeSet(Collection c)
4.TreeSet t=new TreeSet(SortedSet s)
reserved for future purpose.
TreeSet Example:
import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet t=new TreeSet();
t.add(“z”);
t.add(“k”);
t.add(“b”);
t.add(“f”);
System.out.println(t); // [b,f,k,z]
t.add(new Integer(10)); // class cast exception
}
}
In case of integers (10,15,20) it followes ascending order.
TreeSet t=new TreeSet()
t.add(null);
System.out.println(t);
t.add(“a”);
System.out.println(t); // nullpointer exception
Null acceptance:
For the empty TreeSet as the first element we are allowed to add null.
But after adding null if we are trying to add anyother ,we will get a RTE saying
NullPointerException”.If the treeset already contains some elements,If we are trying
to add null causes once again nullpointer Exception.
Comparator Interface:
If you want to define our own sorting we havwet to implement comparator interface.
This interface present in java.util package.
This interface contain the following two methods.
1.public int compare(Object o1,Object o2)
return –ve number if o1 comes before o2.
return +ve number If o1 comes after o2.
returns zero if o1 and o2 equal.
2.public Boolean equals(Object o)
by using comparator interface we can define our own customized sorting.
Write a program to insert integer object in the TreeSet where the Sorting
technique is descending order.
import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet t=new Treeset(new MyComparator());
t.add(new Integer(20));
t.add(new Integer(10));
t.add(new Integer(30));
t.add(new Integer(100));
System.out.println(t); // 10 ,20 ,30,100
}
}
class MyComparator implements Comparator
{
public int Compare(Object o1,Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
int i1=i1.intValue();
int i2=i2.intValue();
if(i1>i2)
return -1;
else
if(i1 > i2)
return +1;
else
return 0;
}
}
write a program to insert string objects into the TreeSet where the sorting
order is increasing order of String lengths.
import java.util.*;
class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new Treeset(new Mycomparator())
t.add(“aaaaaa”);
t.add(“bbbb”);
t.add(“ccc”);
System.out.println(t); // [ccc,bbbb,aaaaaa]
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
if(s1.length() < s2. length())
return -1;
else
if(s1.length() > s2.length())
return +1;
else
return 0;
}
}
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Labels: Collections(java.util) comments (0)
collection-set-HashSet-LinkedHashSet
Collection Interface:
The Collection interface is the root of the collection hierarchy. A Collection represents
a group of objects, known as its elements. Some Collection implementations allow
duplicate elements and others do not. Some are ordered and others unordered. The
JDK doesn't provide any direct implementations of this interface: It provides
implementations of more specific subinterfaces like Set and List. This interface is the
least common denominator that all collections implement. Collection is used to pass
collections around and manipulate them when maximum generality is desired.
It defines general methods ,which can be used for a group of individual objects.i.e a
collection represents a group of individual ibjects.
Note:
Collection is an interface to represent a group of individual objects where as
collections is an utility class for defining utility methods like sorting,searching… etc.
Set Interface:
A Set is a collection that cannot contain duplicate elements. As you might expect,
this interface models the mathematical set abstraction. It is used to represent sets
like the cards comprising a poker hand, the courses making up a student's schedule,
or the processes running on a machine.
This interface doesn’t contain any new methods.we have to use collection interface
methods.
Hash Set:
Constructors:
1.HashSet h=new HashSet();
Creates a new empty HashSet with default initial capacity 16 and load factor or fill
ratio 0.75.
2.HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet with specified initial capacity and default fill ratio is 0.75.
3.HashSet h=new HashSet(int int itialcapacity,float fillratio)
creates an empty HashSet with the specified initial capacity and specified fill ratio.
4.HashSet h=new HashSet(Collection c)
HashSet Example:
import java.util.*;
class HashSetDemo
{
public static void main(String arg[])
{
HashSet h=new HashSet();
System.out.println(h.add(“b”); // true
h.add(“b”);
h.add(“c”);
h.add(“d”);
h.add(null);
h.add(new Integer(10));
System.out.println(h.add(“d”); // flase
System.out.println(h); // depends on hash code number insertion order.
}
}
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Comparable Interface:
This is present in java.lang.package
Contains the following one method.
1.public int compareTo(Object o)
if returns –ve integer if o1 has to place before o2.
If returns +ve integer if o1 has to to place after o2.
If returns zero then o1 and o2 are equal.
All the wrapper classes and string class already implemented comparable interface. But
the StringBuffer doesn’t implement comparable interface.
Comparable Interface Example:
Interface comparable
{
public int compareTo(Object o)
{
TreeSet t=new TreeSet(0);
t.add(“a”);
t.add(‘z”);
System.out.println(t); // a,z (:: z.compareTo(“a”);)
System.out.println((“a”).compareTo(“z”)); //-25
System.out.println((new Integer(10).compareTo(new Intege(1)); // +1
}
}|
Marker or Tag Interface:
If an interface is marked for some ability such type of interfaces are called Marker
interfaces.
Ex: clonable,serializable
If an interface with out any method obviously accept ass marker interface.
Eventhough interface contains some methods,still we can consider as marker interface .If
it is marked for some ability.
Ex:Comparable interface.
Intreger i1=new Integer(10);
Integer i2=new Integer(20);
System.out.println(i2.compareTo(i1)); // -1
System.out.println(i1.compareTo(i2)); // +1
System.out.println(i1.compareTo(i1)); // 0
System.out.println(i1.compareTo(“a”)); // CTE nullpointer exception
Cloneable interface:
Uptaining exact copy of a plant ,a bird,an animal or a human being is called cloning.
Cloning in programming uptaining bit wist exact copy of an object is called cloning.
cloning Example:
clone() method:
Protected object clone() throws clone not supported exception.
This method can used to prouduced exactly duplicate copy of an object..
All the objects can’t produce cloned object ,only clonable objects can produce duplicate
copies .
An object is said to be conable if and only if the corresponding class implements clonable
interface.
By using the folling object class clone() method we can produced cloned objects
Protected object clone() throws clone supported exception
CheckedException so we should handle by using try catch or throws to the caller by
using throws clause.
Shallow cloning Example:
Class Student implements cloneable
{
String name;
String age;
Student(String name,String age)
{
This.name;
This.age=age;
]
Public Object clone()throws cloneNotSupportedException
{
Return this;
}
}
Class Student cloneDemo
{
Student s1= new Student(“hai”,”22”);
Student s2= (Student)s1.clone();
S2.name=”abc”;
System.out.println(s1.name);
Public static void main (String ar[])
{
StudentCloneDemo s1= new Student cloneDemo();
}
}
Deep cloning example:
Class Student implements cloneable
{
String name;
String age;
}
Student(String name ,String age)
{
This.name=name;
This.age=age;
}
Iterator,ListIterator,Enumeration
Enumeration:
This is cursor to retrive the objects one by one.
This interface contains the following two methods.
1.boolean hasMoreElements();
2.Object nextElement();
Enumeration Example:
Import java.util.*;
Class EnumDemo
{
public static void main(String arg[])
{
Vector v= new Vector();
For(int i=0;i<=10; i++)
{
v.addElement(new Integer(i);
}
System.out.println(v); // [0,1,2,3…….10]
Enumeration e=v.elements();
While(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
If(i.IntValue() % 2 ==0)
{
System.out.println(i);
}
}
}
Limitations:
1. We can get Enumeration Object only for legacy classes
(Vector,Stack,Hashtable,Properties,Dictionary,Enumeration)
2. While iterating the Objects of enumeration we can get only read-access.
i.e while iterating we are not allowed to perform any remove or modify operation.
Iterator:
This can be applied for any collection implemented class (legacy and non-legacy)
While iterating the objects we are allowed to perform remove operation also, in
addition to read operation.
This interface contain the following there methods
Boolean hasNext()
Object next();
Void remove()
Iterator Example:
Import java.util.*;
Class IteratorDemo
{
public static void main(String arg[])
{
ArrayList l=new ArrayList();
for(int i=0;i<=10;i++)
{
l.add(new Integer(i);
}
System.out.println(i); // 0,1,2,3,……9
Iterator itr=l.iterator();
While(itr.hasNext())
{
Integer i=(Integer)itr.next();
If(i.intValue() % 2==0)
{
System.out.println(i);
}
else
{
itr.remove();
}
}
System.out.println(l); [0,2,4,6,8]
}
}
}
List Iterator:
List iterator is the child interface of iterator .this can be applicable only for list
implemented classes (arraylist,linkedlist,vector and stack).
This is a bidirectional cursor .we can move either to forward or backward direction
While iterating ,we are allowed to replace existing element with the new element ,we
are allowed to add new elements and still we can perform remove operation also.
ListIterator defines the following methods.
1.boolean hasNext();
2.boolean hasPrevious();
3.Object next();
4.Object previous();
5.int nextIndex();
if there is no next element it just simply return the size of the list.
6.int previousIndex()
Return -1 if there is no previous index.
7.void remove()
8.void set()
9.void add()
ListIterator Example:
Import java.util.*;
Class ListIterDemo
{
public static void main(String arg[])
{
LikedList l=new LinkedList();
L.add(“laxman”);
l.add(“chandu”);
l.add(“ravi”);
l.add(“raju”);
System.out.println(l);
ListIterator lt=l.listIterator();
While(lt.hasNext())
{
String s=(String)lt.next();
If(s.equals(“laxman”))
{
lt.remove(); or lt.set(“scjp”);
}
}
System.out.println(l);
}
}
Thread creation
Multitasking:
* Executing several tasks simultaneously is the concept of Multitasking.
* The main objective of multitasking is to decrease response time of the system, so
that the performance of the system will increase.
1. By extending Thread
2. By implementing Runnable
* yield()
* join()
* sleep()
* Synchronization
* InterThread communication (wait, notify, notifyAll)
• Once the thread is started, there is no chance of starting the same thread once
again.
Violation leads to RTE saying Illegal Thread State Exception”.
• Thread t= new Thread();
t.start(); //no o/p
Thread Priorities:
• Thread class contains the fallowing methods for setting and getting priority of a
thread.
public final int getPriority();
public final void setPriority(int i);
• The valid range for the thread priorities 1 to 10 (1 is atleast and 10 is the highest)
• Thread class contains the fallowing predefined priority constraints.
MAX-PRIORITY ----> 10
NORM-PRIORITY ----> 5 (default)
MIN-PRIORITY ----> 1
• If you are trying to set the priority as greater than 10 or lessthan1, then we will
get a RTE saying “Illegal Argument Exception”
Example:
class MyThread extends Thread
{}
class Sample
{
public static void main(String a[])
{
Thread.currentThread().setPriority(10);
System.out.pritnln(Thread.currentThread().getPriority());
MyThread t= new MyThread();
System.out.pritnln(t.getPriority());//10 10
}
}
• The default priority for the maintained is 5. But we are allowed to change the
prority by using setPriority()
• The priority of any the thread is inherited from the parent thread.
• Thread scheduler uses these proroites to allocate CPU. The thread which is having
highest priority will get executes first. t1.setPriority(10);
Yield() :
1. yield()
2. join()
3. sleep()
• The thread which is executing yield() causes the current thread temperarly pause and
allow other waiting threads of same or high priority to execute.
• If there is no waiting thread, the same thread will execute immediately.
• If all the remaining threads are having low priority, then the same thread once again will
execute.
Method Signature:-
public static native yield();
• The yield() depends upon underlying platform. Some platforms may not support .Breaks
java’s programme independency.
join:
• If any executing thread calls join method on amy thread t, the current thread will go to
the blocked state until t completes.
Method Signature:
public final void join() throws InterruptedException
public final void join(long ms)throws InterruptedException
public final void join(long ms, int nanosec)throws InterruptedException
join Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“sita thread”);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
class JoinDemo
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
t.join(); //or t.join(3000);
for(int i=0;i<10;i++);
{
System.out.println(“Rama thread”);
}
}
}
sleep():-
• The thread which is executing sleep() will go to the sleep for the specified amount of
time.
MethodSignature:
public static void sleep(long ms) throws InterruptedException
public static void sleep(long ms, int nanoseconds)throws InterruptedException
sleep example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“child thread”);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
class SleepDemo
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
}
}
interrupt():
• The thread can interrupt any sleeping/waiting/blocked for joining by the fallowing
thread class method.
public void interrupt(); //this is instance method
interrupt example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“child thread”);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(“I got interrupted”);
}
}
}
}
class SleepDemo
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
t.interrupt();
}
}
summsrization table:
Thread Synchronization
Synchronization:
The keyword synchronized can be apply only for methods and blocks. Ie., We
can’t apply synchronized keyword for the classes and variables.
If a method (or block) declared as the synchronized at a time only one thread
is allowed to execute that synchronized area on any given object.
If a thread calls synchronized method on any object, first this thread got the
lock, it is allowed to any synchronized method on that object.
If a thread executing any synchronized method on the given object at that
time no other thread is allowed to execute any synchronized method on that
object.
If a thread executing any synchronized method the remaining threads are
allowed simultaneously to execute any non synchronized method on that
object.
Every Object in java has a lock. At the time of synchronization only the lock
concept will come into the picture.
Synchronization example:-
class Display
{
public synchronized void show(String name)
{
for(int i=0;i<10;i++)
{
System.out.println(“Good Morning:”);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e){}
System.out.println(name);
}
}
}
class MyThread extends Thread
{
Display d;
String name;
MyThread(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.show(name);
}
}
class SynchronizedDemo
{
public static void main(String a[])
{
Display d=new Display();
MyThread t1=new MyThread(d,”java”);
MyThread t2=new MyThread(d,”Sun”);
t1.start();
t2.start();
}
}
output:
good morning : java ......10 times after good morning: sun ......10 times
If we are not putting synchronized keyword we will get some irregular output like
goodmorning :good morning:java good morning:sun..........like that
Two threads can communicate with each other by using wait(), notify(),
notifyall()methods Signatures.
Public final void wait() throw interepedException.
Public final native void wait(longms)throws InterruptedException.
Public final void wait(long ms,int ns)throws InterruptedException.
Public final native void notify();
Public final native void notifyAll();
Why this methods are in object class instead of thread class?
Wait(),notify();notifyAll() cantain in object class, not in the thread class.because
these methods can be applied on common shared object,not on the thread.
Inorder to call wait(),notify(), notifyAll() on an object, we should be the owner of
that object.
We are allowed to call wait(),notify(),notifyAll() methods from the synchronized
context only(then only we will get the lock of that object and we will become owner
of that object )
If we call wait(),notify(),notifeAll() from non synchronized context, we will get a run
time Exception saying ”illegal monitar state Exception: not a owner”
If the thread call wait()method, first it releases the lock and then it will go for waiting
state, if the waiting thread gets ‘notification call’ or time expired’ or ’got interruption’
then it will go for another blocked state for getting lock.
Once the thread got the lock, it will go to the ready state.
After calling wait method immediately releases the lock but after giving notify call
the thread may not the lock immediately.
The only method which causes the releasing of lock is wait() method.
But in the case of sleep (), join () or yield () the thread never releases the lock.
Method results release of lock:
Wait()
Join()
Sleep()
Yield()
Notify() // releases the lock, but may not immediately
notifyAll()
A thread can acquire more then one lock at time .a thread releses the lock of an
object on which it calls the wait()method .it run releases all the locks.
Example:
Class Thread A
{
Public static void main(string[]args)throws interrupted Exception
{
ThreadB b =new threadB();
b.start();
synchronized(b)//thread got lock
{
System.out.pritnln(“iam calling wait method”);
b.wait();
System.out.pritnlnpln(“I got notification);
}
System.out.pritnlnpln(b.total);
}
}
Class ThreadB extends Thread
{
Int total=0;
Public void run()
{
Synchronized (this).//.thread got lock
{
System.out.pritnln(“iam starting calculation”);
for(int i=0;i<=1000;i++)
{
Total=total+i;
}
System.out.pritnln(“iam giving notification call”);
notify();//thread releases lock again
}
}
} //500 500.
Flow -- > 0 -->1 --> 2 --> 3 --> 4 ---> 5
Daemon Thread
The threads which are executing in the background to provide support for user
defined threads are called daemon threads.
Ex: garbage collector
Thread class contain the following method for checking whether the given thread is
daemon or not
Public final Boolean isDaemon();
Daemon thread Example:
Class DaemonThread
{
Public static void main(string []args)
{
s.o.pln(thread .currentThread().isDaemon());
}
}
Usually daemon threads running with low priority but based on our requirement we
can give high priority also, The daemon nature is inherited from the parent..ie of the
parent is the daemon thread then the child also daemon thread and the parent is the
non-daemon by default child also non-daemon.
Based on our requirement we are allowed to change the daemon nature of any
thread to the following method.
Public final setDaemon(Boolean b);
if b is true the thread will become daemon otherwise non-Daemon
Example:class sample extends thread
{
{
Public static void main(String[] a)
{
MyThread t=new MyThread();
t.start();
t.setDaemon(true);
System.out.println(t.asDaemon());
we are not allowed to change Daemon nature after starting a thread, validation leads
to RTE saying “illegal thread state Exception”
ie we are not allowed to change Daemon nature of main method it is already started
at the beginning only.
Whenever the last non-Daemon thread dead all the Daemon threads will be
terminated automatically
Class MyThread extends Thread
{
Public void run()
{
For(int i=0;i<10;i++)
{
s.o.pln(“childmethod”);
try
{
Thread.sleep(2000);
}
Catch(InterruptedException e) {}
}
}
}
Class DaemonThreadExample
{
public static void main(string[]args)threads IE
{
MyThread t=new Thread();
System.out.println(t.isDaemon());
t.setDaemon(true);
t.start();
thread.sleep(5000);
System.out.println(“end of main thread”);
}
}
After starting the thread we are allowed to change the priority of a thread but not
allowed to change the Daemon nature.
Thread DeadLock
If two threads are waiting for each other forever, that situation is considered as
deadlock. (a lock without key is the deadlock)
We can present the dead lock occurrence but we const resolve.
Dead lock Example:
Class A
{
Public synchrozied void foo(B b)
{
System.out.println(“thread t1 entered into foo”);
try
{
Thread.sleep(2000);
}
catch(IE e){}
System.out.println(“thread t1 calling B’s last method”)
b.last();
}
Public synchronized void last()
{
System.out.println(“a class last method”);
}
}
Class B
{
Public synchronized void bar(A a)
{
System.out.println(“thread t2 entered into bar”);
try
{
Thread.sleep(2000);
{
Catch(intereped Exceptiom e){}
System.out.println(“thread t2 calling Ab last method);
a.last();
}
Public synchronized void last()
{
System.out.println(“B class last method”);
}
}
class DeadlockExample
{
A a=new A();
B b=new B();
DeadLock(){
Thread.currentThread().setName("main thread");
Thread t=new Thread(this);
t.start();
b.bar();
}
Public static void main(string[]args)
{
Deadlock d=new Deadlock();
}
Public void run()
{
a.foo(b);
}
}
thread group
Every Java thread is a member of a thread group. Thread groups provide a
mechanism for collecting multiple threads into a single object and manipulating those
threads all at once, rather than individually. For example, you can start or suspend
all the threads within a group with a single method call. Java thread groups are
implemented by the thread group class in the java.lang package.
The runtime system puts a thread into a thread group during thread construction.
When you create a thread, you can either allow the runtime system to put the new
thread in some reasonable default group or you can explicitly set the new thread's
group. The thread is a permanent member of whatever thread group it joins upon its
creation--you cannot move a thread to a new group after the thread has been
created.
If you create a new Thread without specifying its group in the constructor, the
runtime system automatically places the new thread in the same group as the thread
that created it (known as the current thread group and the current thread,
respectively). So, if you leave the thread group unspecified when you create your
thread, what group contains your thread?
When a Java application first starts up, the Java runtime system creates
aThreadGroup named main. Unless specified otherwise, all new threads that you
create become members of the main thread group.
specified group. For example, the following code sample creates a thread group
(myThreadGroup) and then creates a thread (myThread) in that group.
The ThreadGroup passed into a Thread constructor does not necessarily have to be a
group that you create--it can be a group created by the Java runtime system, or a
group created by the application in which your applet is running.
Thread group Example:
public static void main(String[] args) {
new ThreadGroupDemo().work();
}
// List them.
Thread[] list = new Thread[g.activeCount()];
g.enumerate(list);
for (int i=0; i) {
if (list[i] == null)
continue;
Thread t = list[i];
System.out.println(i + ": " + t);
}
}
}
object class
Java.lang.package contain several utility classes which are mandatory for writing
simple to complex programs.There is no need to import java.lang.package as by
default it is available to our program
Java.lang.object class:
It is super class of any java class .all the predefined classes are user defined classes
either directly or indirectly extends java.lang.objectclass
This class contain several utility methods which can be applied on any java object.
.for every class parent class in object class
Class A extends B
{
// code
}
Means, Ie.for B,parent is object but for A parent is B only .so java supports
multilevel inheritance
The following are the 11 methods present in object class
1).public string to string()
For string representation of object.
2)public native int hashcode()
Returns the hashcode of an object
3)public Boolean equals(object obj)
For comparing the current object with the specified object
4)protected native object clone() throws clonesoft support Exception
To produced cloned object
5)protected void finalize()throws throwable
6)public final native class getclass()
7)public final viod wait()throws interrupted exception
8)public final void wait(longms)throws interrupted exception
9)public final void wait(long ms,int ns)throws interrupted exception
10)public final native void notify()
11)public final native void notifyAll()
1.tostring():
to String Example:
Class Sample
{
String name;int rollno;
Student(string name,int rollno)
{
This.name=name;
This.name=rollno;
}
Public static void main(string[]args)
{
Student s1=new student(“visvam”,101);
System.out.println(s1);
}
Public string tostring()
{
//return get class().getName()+’@’+
Integer.toHexstring(hashcode());
//return”this is student object”;
Returnname+”……”+rollno;
}
2.Hashcode():
HashCode Example:
String s1=new string(”visvam”);
String s2=new string(“visvam”);
System.out.println(s1.hasgcode());
System.out.println(s2.hasgcode());
hashcode()---when ever an object is created jvm allocates a number for that object
which is considered as hashcode().
Most of the cases the hashcode saving is unique for every object
Jvm uses this hashcode while saving objects to hashtable,hashmap or hashset.
Hashcode never represents the address of an object.
Oppropriate way of overriding of hashCode method:
Ex: class Student
{
String name,int rollno;
Student(string name,int rollno)
{
This.name=name;
This.name=rollno;
}
Public int hashcode()
{
return rollno
}
Public string tostring()
{
return name+”-----“+rollno;
}
Public static void main(string[]args)
{
String s1=new string(“java”,101);
{
System.out.println(s1); // java ...... 101
}
Public int hashcode()
{
retuen rollno;
}
It is highly recomonded to override hashcode .In our classes.overriding hashcode is
appropriate if and only if every object we have to assign a different hashcode.This is
helpful for the jvm to save object in hashcode,hashmap,hashset and serching also.
3.Equals()
Student s1=new student(“viswam”,101);
Student s1=new student(“surya”,102);
Student s1=new student(“surya”,102);
System.out.println(s1==s2); // false
System.out.println(s1.equal(s2)); // false
System.out.println(s2==s3); // false
System.out.println(s2.equals(s3)); // false
System.out.println(s2==s2); // true
System.out.println(s2.equals(s2)); // true
= = Operator:
This is meant for reference comparision always s1==s2 is true if and only ig both s1
and s2 pointing to the same object on the heap.
Ex: string s1=”visvam”;
Thread t1=new Thread()
System.out.println(s1==t1);
we can’t apply==operator for incomparable types.validation leads to CTE saying
incomparable types.
S1==null is always “false”(no CTE&RTE)
equals()method :
The equals method available in object class meant for reference or address
comparision only(similar to==operator)but,we can override equals() in our class for
content comparision.
Overriding of .equals()
===> public Boolean equals(object o)
{
String name1=this.name;
Int rollno=this.rollno;
Student name2=s2.name;
Int rollno2=s2.rollno;
If(name1.equals(name2)&rollno1==rollno2)
Return true;
else
return false;
}
===>then System.out.println(s2.equals(s3)); //true
System.out.println(s1.equals(s2)); // false
====> in string class. .Equals() method is already overridden for context
comparision. Object class.equals method. Satisfy the following two conditions.
1.this is always for address comparision
2.it never rise CTE&RTEs even the arguments are different types.
If the arguments are different types .equals() is simply return false.
public boolean equals(object o)
{
try
{
Name 0=this.name1;
Rollno1=this.rollno1;
Student s=(student)0;
Name2=this.name2;
Rollno2=this.rollno2;
If(name1.equals(name2)&rollno1=rollno2)
return true;
else
return false;
}
Catch(classcastException e)
{
return false;
}
}
Then==>s.o.pln(s1.equals(“visvam”));
Catch(nullpointerException e)
{
Return false;
}
Then==> s.o.pln(“null”));
String class
Once we created a string object we are not allowed to perform any changes in
the existing String object.
If you want to perform any changes (by using concat() or any other), with the
changes a new String object will create.
Hence String objects are considered as Immutable
In the case of StringBuffer, once we created a StringBuffer object, we are
allowed to perform any changes in the existing StringBuffer object only.
Hence StringBuffer object is mutable
In the String class .equals() is overridden for content comparision. Here the
content of s1 and s2 are equal, that’s why s1.equals(s2) returns true.
In the String class .equals() is not overridden for content comparision.
whenever we calling .equals()
Method on the StringBuffer object, Object class .eqauals() method will execute,
which is meant for address comparision only.
Hence s3.equals(s4) returns false eventhough the contents of s3 and s4 are same.
Difference between the ways of creating String objects:-
1. String s1=”durga”;
2. String s2=new String(“durga”);
• In the first case, the JVM will check, is the any String object with content durga in
the “String Constant Pool”. If there is no such object then only a new String object
will create and s1 will pointed to that object.
• If the object already present then s1 will simply refers to that object instead of
creating a new object.
• In the second case, two String objects will create, one is on the heap, for the other
one in the “String Constant Pool” (If the object is not already present) and s2 will
pointing to heap object.
Ex: String s=”viswan”;
s.concat(“sw”);
* In this content, three objects are created. One is on heap and another two on
“String Constant Pool”
String s=”abcdefgh”;
System.out.println(s.subString(3)); //defgh
System.out.println(s.subString(4,7)); //efg
7. public String toUpperCase():
String s= “ A New Moon”;
System.out.println(s.toUpperCase()); // A New Moon
8. public String toLowerCase()
String s= “ A New Moon”;
System.out.println(s.toLowerCase()); // A New Moon
9. public String trim()
String s=”viswan”;
System.out.println(s.trim()); //viswan
---> Leading or trailing blackspaces removed but not in the middle.
10. public int indexOf(char ch)
---> Returns the index of the first occurance of the specified character.
---> Returns -1, if there is no such character.
String s=”durgascjp”;
s.indexOf(d); //0
11. public int lastIndexOf(char ch)
---> Returns the last occurrence index of the specified character.
String s=”durga”;
String y=s.toUpperCase();
String s=s.toLowerCase();
System.out.println(s==x);//true
System.out.println(s==y); // false
• After applying any method of the contest of the String has to change then only a
new String object will create with the corresponding changes.
Ex1:
String s1=”abc”; s1 ---> abc
String s2=”def”; s2 ---> def <--- s3
String s3=”s2”; s2 ---> ghi
String s2=”ghi”;
S.o.p(s1+s2+s3); //abcghidef
Ex 2:
String x=new String(“xyz”);
y=”abc”;
x=x+y;
total objects are 4 ---> 2 on heap, 2 on string constant pool
StringBuffer , StringBuilder
StringBuffer:
String objects are immutable where as StringBuffer objects are mutable.
Ex: String s=”viswan”;
s.concat(“sw”); -----> Immutability
System.out.println(s);//viswan
Constructors Of StringBuffer:
StringBuffer s= new StringBuffer();
---> Creates an empty StringBuffer object with default initial capacity 16.
class SBDemo
{
public static void main(String a[])
{
StringBuffer s=new StringBuffer();
s.append(“abcdefghijklmnop”);
System.out.println(a.capacity());
}
}
---> If we add q then //34=(16+1)*2
• When ever StringBuffer reaches its max capacity a new StringBuffer object is
created with the new capacity is (current capacity + 1)*2 ---> (16+1)*2=34
• First time only this can be valid. Afterwards the capacity increases with the
increase of characters only.
StringBuffer sb=new StringBuffer(int initialcapacity)
• Creates an empty StringBuffer object with the specified capacity.
StringBuffer sb=new StringBuffer(String s);
• Creates an equivalent StringBuffer object for the given String and with a capacity
equal to (length of String + 16).
Ex: StringBuffer s=new StringBuffer(“durga”);
System.out.println(s.capacity()); // 5+16=21
Length of the string “durga” =5
* This operation can result in the StringBuffer with the specified length. The Extra
characters will be removed.
If the StringBuffer is lessthan the specified length padded or appended with space
characters to the required length.
Ex: StringBuffer s=new StringBuffer(“viswan”);
s.length(3);
System.out.println(s); //vis
Chaining Of Methods :
• In the case of String and StringBuffer, the return type of most of the methods are
String or StringBuffer only, on that return type we are allowed to call another
method, as a result chaining of methods is possible, in the case of String and
StringBuffer.
Ex: StringBuffer sb= new StringBuffer(“durga”);
s1.m1().m2().m3().m4().m5().m6();
Example:
class Sample
{
public static void main(String a[])
{
StringBuilder sb=new StringBuilder(“surya”);
s.append(“software”);
s.reverse();
s.delete(3,5);
System.out.println(s);
}
}
//surya //suryasw
//erawtfosayrces //erafosayrces
Wrapper Class
The Wrapper classes have introduced for the fallowing two purposes by SUN people.
1. To wrap primitives into object form so that we can handle primitives also just like
objects.
2. We can get several utility functions for primitives.
• The fallowing are the wrapper classes.
Type --------- Class
byte ---------> Byte
short ---------> Short
int ---------> Integer
long ----------> Long
float ----------> Float
double ----------> Double
char ----------> Character
boolean ----------> Boolean
• Every wrapper class except Character class contain parseXxx() for converting a
String object to corresponding primitive.
Ex: String s=”10”;
int i=Integer.parseInt(s);
double d=Double.parseDouble(s); //10.0
long l=Long.parseLong(s);
Wrapperclass--------- parseXxx()
Byte ------------> parseByte(String s)
Short -------------> parseShort(String s)
Integer -------------> parseInt(String s)
Long -------------> parseLong(String s)
Float -----------> parseFloat(String s)
Double ------------> parseDouble(String s)
• Boolean class contain a static method getBoolean() method for converting a string
to Boolean primitive.. -----> 1.4 version
String s=”123”;
int i=Integer.parseInt(s);
double d=Double.parseDouble(s);
System.out.println(i); //123
System.out.println(d); //123.0
Boolean b=getBoolean(“viswan”);
System.out.println(b); //false
Second version of parseXxx() :-
• All the integral wrapper classes (byte, short, integer, long) contains second version
of parseXxx().
public static primitive parseXxx(String s,int radix)
Ex: int i=Integer.parseInt(“10101100”,2);
System.out.println(i); //172
long l=Long.parseLong(“12”,8);
System.out.println(l); //10
• java support max – radix is 36(base)
System.out.println(Character.MAX-RADIX); //036
toString() method:
1st version:-
• All the wrapper classes contains an instance toString() method for converting
wrapper class object to corresponding String object.
• public String toString();
Integer i=new Integer(10);
String s= i.toString();
System.out.println(s); // 10
Boolen B=new Boolean(“surya”);
String s=B.toString();
System.out.println(s);//false
2nd Version:
• Every wrapper class contain a static toString() method for converting a primitive to
String object.
• This is available in all wrapper classes and object class also includes Boolean and
Character classes.
• public static String toString(10);
Ex: String s1=Integer.toString(10);
System.out.println(s);
String s1=Boolean.toString(true);
String s1=Integer.toString(‘a’);
System.out.println(s1);
System.out.println(s2);
3rd Version:
• Integer and Long classes contain the 3rd version of the toString() method for
converting given primitive to String of sprcified radix.
• public satic String toString(30,2);
Ex: String s= Integer.toString(30,2);
System.out.println(s); //”11110”
toString(primitive, int radix)
4th version:
• public static String to xxxString(primitive) //int/long
• The version of toString() is available in the Integer and Long classes only. The
possible to xxxString() methods are, toBinaryString, toHexString and tooctalString
for converting the given primitive to the corresponding String form.
String s=Integr.toBinaryString(100); //1100100
String s=Integr.toOctalString(100); //144
String s=Integr.toHexString(100); //64
• All the wrapper class objects are immutable and all the wrapper classes are final
classes.
• ‘void’ is also one type of wrapper class.
• String class and all the wrapper classes are immutable.
• The fallowing are the final classes.
-->String
--> StrringBuffer
--->Math
AutoBoxing , AutoUnBoxing
AutoBoxing:
• Automatic conversion by the compiler from primitive type to the corresponding object
form is called AutoBoxing.
Ex: int i=10; //Compile time error in 1.4 but valid in 1.5
Integer I=i;
• Compiler first constructs the integer object and then assigned that object to the variable.
AutoUnBoxing:
• Automatic conversion from wrapper class object to primitive type by the compiler is
called AutoUnBoxing.
Ex: Integer I= new Integer(10);
int i= I; //CTE :1.4
// valid in 1.5
* The compiler coverts Integer object to primitive and that primitive value will assign to
variable i.
* Because of these new autuboxing or auto unboxing features, the importance of wrapper
classes is not that much in the 1.5 version.
AutoBoxing in expressions:
Integer y=10;
Integer x=y;
Y++;
System.out.println(x); // 10
System.out.println(y); // 11
System.out.println(x==y); // flase
Wapper class objects are immutable .if you want to perform any changes with those
changes a new wrapper class object will create.
Special cases:
case1:
Integer i1=new Integer(10);
Integer i2=new Integer(10);
System.out.println(i1==i2); //false
Case2:
Integer i1=new Integer(10);
Integer i2=10;
System.out.println(i1==i2); //false
Case3:
Integer i1=100;
Integer i2=100;
System.out.println(i1==i2); //true
Case4:
Integer i1=1000;
Integer i2=1000;
System.out.println(i1==i2); //false
In the case of autoboxing compalier won’t create any new object If an existing already
created object mapped with the reqired one . the existing object should be created bt the
autoboxing only.
This poosibility will occur in the following cases.
1.By using autoboxing. If it is required to create a new wrapper object, other wise
compiler won’t create any new object, if already an object is present in the fallowing
cases. these Objects are Boolean and Byte.
2. Character object ranges from 0 to 127 ------> (‘\u0000’ to ‘\u0007f’).
3. For the integer and short if the value is less than or equal to 127.
4. For the long of the value is less than or equal to 127 L .
But Long l=10; //invalid
CTE: incompatable types
Found:int , req: java.lang.Long
Similarly Float f= 10; //invalid - CTE: incompatable types
Found: int, req: java.lang.Float
Case5:
Boolean b1=true;
Boolean b2=true;
System.out.println(b1==b2); // true
Case6:
Boolean b3=flase;
Boolean b4=flase;
System.out.println(b3==b4); // true
Special case:
Example:
class Sample
{
static Integer I1=10; ---->I1: Initialized
public static void main(String a[])
{
m1(I1); ---> I1 : auto unboxing
}
public static void m1(int i)
{
Integer I2=i; ----> I2: auto boxing
System.out.println(I2); //10
}
}
above example executes fine.
But
class Sample
{
static Integer I1; // not Initialized
public static void main(String a[])
{
m1(I1); // null pointer exception
}
public static void m1(int i)
{
Integer I2=i;
System.out.println(I2);
}
}
Static variables by default initialized with null, which can’t be
autoboxing/autounboxing.Hence Run time exception.
In java widening followed by autoboxing is not allowed.Hence the above code raise a
CTE saying m1(java.lang.long) in sample can not be applied to (byte).
i.e Byte --------> Long is not possible.
But byte ----->long is possible.
Widening followed by autoboxing is not allowed. But the reverse is allowed in java i.e
autoboxing follwed by widening is possible.
Class Sample
{
static void m1(Object o)
{
System.out.println(“object”);
}
public static void main(String arg[])
{
byte b=5;
m1(b); // object
}
}
i.e byte -----> Byte -----> Object
i.e Here autoboxing is followed by widening .
class Samle
{
static void m1(byte… b)
{
System.out.println(“byte……”);
}
static void m1(byte b,byte… b1)
{
System.out.println(“byte, byte….”);
}
public static void main(String arg[])
{
byte b=5;
m1(b); // CTE saying reference to m1 is ambiguous.
}
}
Here both methods are matched because of var-args feature.Hence compailer can’t give
any precedence results in CTE
Static variable by default initialized with null,which can’t be autoboxing /autounboxing
enum
We can keep enum outside the class or inside the class.If we are declaring
enum outside the class,the allowed modifiers are public ,<default>.we can
declare enum with in a class the allowed modifiers are public
,<default>,protected,private.
We never allowed to declare enum inside a method,violation leads to compile
time error saying enum type must not be local.
Enum types is allowed to used as argument for the switch statement.
Example:
Enum Beer
{
KF,RC,H5;
}
class Sample
{
public static void main(String arg[])
{
Beer b= Beer.KF;
Switch(b)
{
case KF:
System.out.println(“too Bitter”);
break;
case RC:
System.out.println(“too Hot”);
break;
case H5:
System.out.println(“too strong”);
break;
}
}
}
until 1.4 version the allowed arguments for the switch statement are
byte,short,int,char.But 1.5 version onwords in addition to these arguments
Byte,Short,Character,Integer and enum also.
Values() method:
Enum contains a predefined method values to list the constants available in that
enum.
Example :
enum Month
{
Jan,Feb,Mar,Apr;
}
class Client
{
public static void main(String arg[])
{
Month[] m=Month.values();
for(Month m1:m)
{
System.out.println(m1); // Jan,Feb,Mar,Apr
}
}
enum never participated in inheritance hierarchy because every enum class implicitly
extends java.lang .enum .Thats why we never allowed to create a child classfor the
enum.As Month enum already extends java.lang.enum hence it never allowed to
extend any other.
Enum Month extends Some ---> not possible
If we are writing any enum it is extending java.lang.enum class.Hence it never
extends any thing else.So inheritance concept not applicable for enums.
Example:
Enum Beer
{
KF(65),RC(50),H5(100),KO;
int price;
Beer(int price)
{
this.price=price;
}
public int getPrice()
{
return price;
}
Beer()
{
this.price=100;
}
}
class Sample
{
public static void main(String arg[])
{
Beer b=Beer.KF;
System.out.println(b); //KF
System.out.println(Beer.KF.ordinal());
System.out.println(b.price); //65
System.out.println(b.getPrice()); //65
Beer[] s=Beer.values();
for(Beer s1:s)
{
System.out.println(s1+”……….”+s1.getPrice());
}
}
}
• When ever enum is loaded into the memory, all the enum constants will be
assigned and JVM calls Constructor automatically. The programmer is not allowed to
call enum constructor explicitly.
• The Constructors of enum can be overloaded if the enum contain both enum
constants, instance variables, the first line should be enum constants and ends with
semicolon.
i.e.
enum Beer
{
KF, RC //invalid ; missing
int price;
}
enum Beer
{
int price; //invalid because the 1st stmt should be enum constants.
KF, RC;
}
enum Beer
{
KF, RC;
int price; //valid
}
Ordinal Value
• The position of enum constant is important and indicated by their ordinal values.
We can ordinal value for any enum constant by the fallowing method.
System.out.println(Month.JAN==Month.FEB); //false
enum Month
{
Jan,Feb,Jan; //invalid,CTE:Jan already defined
}
But
enum Month
{
Jan,Feb,JAN; //valid, due to case sensitive jan!=JAN
}
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Labels: java.lang comments (0)
Cloneable interface:
Uptaining exact copy of a plant ,a bird,an animal or a human being
is called cloning.
Cloning in programming uptaining bit wist exact copy of an object is
called cloning.
cloning Example:
clone() method:
Protected object clone() throws clone not supported exception.
This method can used to prouduced exactly duplicate copy of an
object..
All the objects can’t produce cloned object ,only clonable objects can
produce duplicate copies .
An object is said to be conable if and only if the corresponding class
implements clonable interface.
By using the folling object class clone() method we can produced
cloned objects
Protected object clone() throws clone supported exception
CheckedException so we should handle by using try catch or throws
to the caller by using throws clause.
Shallow cloning Example:
Class Student implements cloneable
{
String name;
String age;
Student(String name,String age)
{
This.name;
This.age=age;
]
Public Object clone()throws cloneNotSupportedException
{
Return this;
}
}
Class Student cloneDemo
{
Student s1= new Student(“hai”,”22”);
Student s2= (Student)s1.clone();
S2.name=”abc”;
System.out.println(s1.name);
Public static void main (String ar[])
{
StudentCloneDemo s1= new Student cloneDemo();
}
}
Deep cloning example:
Class Student implements cloneable
{
String name;
String age;
}
Student(String name ,String age)
{
This.name=name;
This.age=age;
}
An Exception is an abnormal and unexpected and also unwanted event that disturbs
the normal flow of the program.
Ex: FileNotFoundExceptionArithmaticException etc..
Default Exception Handling Mechanism in JAVA:
class Sample
{
public static void main(String a[])
{
doStuff();
}
public static void doStuff()
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
System.out.println(10/0);
}
}
RTE: Exception in thread “main” Java.Lang.Arithematic Exception: /by zero
At Sample . doMoreStuff(Sample.java)
At Sample . doStuff(Sample.java:9)
At sample . main(Sample. java :5)
• If an exception is raised inside any method is r3esponsible for the creation of
exception object. (here doMoreStuff() is responsible )
• The Exception object must contain the fallowing information.
1. Name of the Exception(Java.Lang.ArithematicException)
2. Description of the Exception (/ by zero)
3. The position at which the exception raised. (stack trace).
• Now the method handover that exception object to the JVM. JVM will come with
that exception object and it will check, is there any exception object and it will check
is there any exception handler inside that method abnormally and removes the
corresponding entry from the stack.
• Now the method handover that exception object to the JVM. JVM will come with
that exception object and it will check, is that any exception handler inside that
method. If there is no exception handler then JVM blindly terminate that method
abnormally and removes the corresponding entry from the stack.
• JVM will check for the caller(doStuff()) containing any exception handling code. If
the caller also doesn’t contain any exception handling code, then JVM simply
terminate that method also and remove the corresponding entry from the stack.
• This process will continue, until main() method. If the main() also doesn’t have any
exception handling code then JVM terminates main() abnormally and handover the
responsibility of the exception handling to default exception handler.
• Now Default Exception handler print the exception information to the end user
CommonExceptions and Errors:
Exceptions or errors may be thrown by either JVM(JVM Exceptions) or thrown
explicitly by application developers or API programmers(programmatic exception).
1. NULLPOINTER EXCEPTION:
Class Sample
{
Static int[] a;
Static String name;
public static void main(String a[])
{
System.out.println(a.length);
}
}
System.out.println(a[o]); // null pointer exception (NPE)
System.out.println(name.length); //NPE
This is child class of RuntimeException. It is unchecked exception.
This is thrown by JVM when attempting to acess an object with a reference variable
whose current value is null.
Ie., on null if we are applying any operation we will get NullPointerException.
2. STACK OVERFLOW ERROR:-
• This is child class of virtual machine error.
• It is unchecked
Throwable ----> Error ---> VMError ---> StackOverFlowError
Ex:class Sample
{
public static void m1()
{
m1();
}
public static void main(String a[]){ m1(); } // stack overflow error
}
StackOverflow error is thrown by JVM when a method recurses too deeply.
class Sample
{
Sample() { new Sample(); }
public static void main(String a[]) { Sample s= new Sample(); }//Exception in main
thread stack overflow error
}
3. ARRAY INDEXOUTOF BOUNDS EXCEPTION:
• This is a child class of IndexOutOfBoundsExcption.
Throwable ---> Exception ---> RunTimeException ---->
IndexOutOfBoundsException---> ArrayIndexOutOfBoundsException,
StingIndexOutOfBoundsException
• It is an unchecked exception thrown by JVM when we are accessing an array
element with
Invalid index.
Ex:
class Sample
{
public static void main(String a[])
{
Int[] a=new int[6];
System.out.println(a[5]); //0
System.out.println(a[7]); //RTE: ArrayIndexOutOfException
System.out.println(a[-2]); //----do----
System.out.println(a[-2.5]); //CTE: PLP req: int found:double
}
}
4. CLASS CAST EXCEPTION:
Class Sample
{
public static void main(String a[]))
{
String s=”anu”;
Object o=(Object)s;
String s1=(String)O;
System.out.println(“hai”);
}
}
• It is the child class of RTE
• It is unchecked exception, thrown by JVM when attempting to cast a reference
variable to a type the fails to cast a reference variable to a type the faith the IS- A
test.
----> Object o=new Object();
String s=(String)o; // Class Cast Exception
----> StringBuffer s1= (StringBuffer)s;
Partially
Checked vs Fully Checked :
A Checked Exception is said to be Fully Checked Exception if and only if all its child
classes are also checked. Otherwise it is Partially Checked Exception.
Ex: IOException is Fully Checked Exception
Exception is Partially Checked
Throwable is Partially Checked
finally block:
try
{
System.out.println(10/0);
}
catch(AE e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“catch”);
}
• The cleanup code, we have to keep inside finally block because irrespective of
exception occurred or not occurred or handled or not handled, the finally block will
always execute.
Example:
try
{
System.out.println(“hai”);
}
catch( NULL pointer exception e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“finally”);
}
output:
hai
finally
Samples:
1. try{} catch(X e){} -->valid
2. try{}catch(X e){}finally{} -->valid
3. try{}finally{}catch(X e){} --> invalid
4. try{}finally{} -->valid
i.e , try --> catch --> finally is the only order.
Only try{} ---> invalid,
Only catch{} ----> invalid
Only finally{} ----> invalid
Note: try without catch & catch with out try invalid
Example:
catch(..){}
finally{}
CTE: catch with out try
‘Throw’ keyword:
public static void main(String a[])
{
try
{
Throw new AithmeticException()
}
}
By using ‘throw ‘ keyword, over created customized exception objects are handed
over to JVM.
Example:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any statement, violation leads to CTE saying
“unreachable statement”.
Example:
class Sample
{
static ArithmeticException e;
public static void main(String[] a)
{
throw e; //invalid
}
}
output: NullPointerException
‘e’(is in instance area) is not pointing “ArithmeticException’ here.
static ArithmeticException e=new ArithmeticException();
Example:
class Sample
{
public static void main(String a[])
{
Throw new Exception(); //invalid
}
}//CTE: “Unreported Exception Java.lang.Exception must be caught” or declared to
be thrown.
• Inside a program if there is any chance of throwing a checked exception explicitly
or implicitly we have to handle that checked exception by using try - catch or we
have to delegate the responsibility or exception handling to the caller. Violation leads
to CTE saying Unreported Exception xxx; must be caught or declared to be thrown.
throws , throw
“throws” Keyword :We can ‘throws’ keyword for delegating the responsibility of
the Exception handling to the caller.
Ex:
class Sample
{
public static void main(String a[])throws InteruptedException
{
doStuff();
}
public static void doStuff()throws IE
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
Thread.sleep(1000);
}
}
without ‘throws’ CTE: Unreported Exception java.lang.interuptedException ; must be
caught or declared to be thrown. To avoid CTE(compile time error) another way in
using try ---> catch block.
Ex:
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(IOException e){} --->CTE (fullychecked exception)
}
}
CTE: exception java.io.IOException is never thrown in the body of the corresponding
try statement.
If we are keeping the catch block for fully checked exception there should
may be a chance of raising exception in the corresponding try block otherwise
CTE saying XXXException is never thrown in the body of corresponding try
statement.
Case 1:
try
{
System.out.println(“hai”);
}
catch(ArithematicException e) //valid no CTE(compile time error)
{ //unchecked exception }
Case 2: try
{
System.out.println(“hai”);
}
catch(Exception e) //valid no CTE
{
//Partially checked exception
}
Case 3:
try
{
System.out.println(“hello”);
}
catch(IOException e) //invalid CTE
{
// fully checked exception
}
Example:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any statement, violation leads to CTE saying
“unreachable statement”.
Customized Exceptions :
Based on the programming required sometimes we have to design our own
Customized Exceptions.
Ex: Insufficient funds Exception
too young Exception
too old Exception
throw Example:
class TooYoungException extends RunTimeException
{
TooYoungException(String s)
{
super(s);
}
class Sample
{
public static void main(String a[])
{
int i=Integer.parseInt(arg[0]);
if(i>85)
throw new TooYoungException(“please wait some more time, you eill get married”);
else if(i<10)
throw new TooYoungException(“ur age is already crossed”);
else
throw new TooYoungException(“very soon you will get match”);
}
}
java File
File:
A File Object is an abstract representstion of name of a file or directory.
f.createNewFile();
System.out.println(f.exists());
}
}
2. class Sample
{
public static void main(String aff[])
{
File f=new File(“laxman.txt”);
If(!f.exists())
f.mkdir();
File f1=new File(“laxman”,”laxman txt”);
F1.createNewFile();
System.out.println(f1.exists());
}
}
3. Class Samle
{
public static void main(String ah[])
{
File f=new File (“laxman123”); ------------->already exists
String[] s=f.list();
for(String s1:s)
{
System.out.println(s1);
}
}
With the same name there may be a chance of a file or a directory .From java code
creating the file followed by creating the directory with the same name allowed and
File object represents a file only.
After creating the directory ,if we are creating file with tha same name we will get
RTE saying IOException:Access is denied
File f=new File(“dir1”,”file1.txt”);
This file object represents a file named with file1.txt which will present in the
directory
f.writeNewFile();
If the directory is not present then f.createNewFile() results a RTE saying
IOException:The system can not find the path specified.
If we call list() method on java file object which represents a physical file instead of
directory.it just simply return null.
If applied on directory it returns the content of the directory.
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
FileReader class:
If is the child class of abstract class reader this can be used for reading charater data
from a file.
FileReader Constructors:
1.FileReader fr=new FileReader(String fname)
2.FileReader fr=new FileReader (Filename f)
if the file is not found these constructors raise RTE saying FileNotFound Exception
Methods:
1. int read()throws IOException
return the Unicode of the next charater if it is exists else---1.
2.int read(char[] ch)
returns the number of charaters from the file and populated in the specified array.
3.void close()
the flushing is not reqired while reading data .so MISSING
File Reader Examples:
FileReader fr=new FileReader(“laxman.txt”);
System.out.println(“fr.read());
Char[] ch =new char[200];
Fr.read(ch);
For(char c1:ch)
System.out.println(c1);
Fr.close();
BufferedReader:
By using this we can improve the performance.It contain a separate method readLine() to read
single line at a time instead of single charater.
So this is the more convenient class for reading charater data from a file
Constructors:
1.BufferedReader br=new BufferedReader(Reader r)
2.BufferedReader br=new BufferedReader(Reader r,int size)
Methods:
1.int read()throws IOException
to read a single character
2.int read(char[] ch)throws IOException
to read an array of character
3.String readLine()
to read nextline a single line.
If there is no next line return null
BufferedReader Example:
FileReader fr=new FileReader(“laxman.txt”);
BufferedReader br=new BufferedReader(fr);
String s=br.readLine();
While(s!=null)
{
System.out.println(s);
S=br.reaadLine();
}
br.close();
}
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
FileWriter:
This is a child class of writer .this class can be used for writing charater data.
FileWriter constructors:
1.FileWriter fw=new FileWriter(Filename)
create a filewriter object to the given file if the file having this name ,doesn’t exists
this constructor automatically creates the corresponding file also.But this is not
possible in the case of File constructor.
2.FileWriter fw=new FileWriter(File f)
create FileWriter object for the specified File f .if the file is not already present this
constructor wilol create automatically the file also.
3.FileWriter fw=new FileWriter(String file name,Boolean append)
If the second argument is true the data append to the existing content .If it is false
,then the old data is over ridden by new data.
4.FileWriter fw =new FileWriter (File f, boolean append) ------>By default flase.
Methods of FileWriter:
1.void write(int ch)throws IOException
the Corresponding character can be written to the file.
2.void write(String s)throws IOException
writes a String to the file
3.void write(char[] ch)throws IOException
writes a charater array data ti the file
4.void flush()
to guarented that the last character of the data should be written to the file
5.void close()
To the close file writer object
6.void write(int unicodevalue)throws IOException
File writer Example:
Import java.io.*;
Class Sample
{
public static void main(String aff[])
{
File f=new File(“file1.txt”);
System.out.println(f.exists());
FileWriter fw =new FileWriter(f);
System.out.println(f.exists());
Fw.write(100);
Fw.write(“laxman software”);
Char[] ch={‘L’,’a’,’x’,’m’,’a’,’n’};
Fw.write(ch);
Fw.close();
Fw.flush();
}
}
To overcome this ,SUN people has introduced buffered reader and bufferwriter class
BufferedWriter:
we can create a bufferedwriter object over any writer object.
Construtors:
BufferedWriter bf=new BufferedWriter(Writer w);
BufferedWriter bw=new BufferedWriter(Writer w,int size);
Where size is the size of the buffer
Methods:
1.void write(int i)throws IOException
To write one charater
2.void write(String s)throws IOException
to write the given string
3.void write(char[] ch)throws IOException
4.void newLine()
to insert a new line character
5.void flush()
6.void close()
Q.when compare with java.io.BufferedWriter to java.io.FileWriter which capability
exists as a method in only one of .
a.closing system
2b.flushing the stream
c.writng to the stream
d.marking the location in the stream
e.writing the line separator to the string (valid)
Buffered Writer Example:
Class Sample
{
public static void main(String args[])
{
FileWriter fw=new FileWriter(“laxman.txt”);
BufferedWriter bw=new BufferedWriter(fw);
Bw.write(100);
Bw.write(“laxman”);
Bw..newLine();
Bw.write(“scjp”);
Bw.newLinw();
Bw.write(“srnagar”);
Bw.flush();
Bw.close();
Fw.close();
}
}
When ever we are closing the BufferedWriter autpmaticaly the stream opened by
fileWriter is also closed.
PrintWriter:
The most convenient class for writing any kind of text data .It has enhanced in 1.5
version.
Constructors:
1.PrintWriter p=new PrintWriter(String name)
2.PrintWriter p=new PrintWriter(File name)
3.PrintWriter p=new PrintWriter(Writer w)
Methods:
1.void write(int ch)------> to write character
2.void write(String s)-----> to write String
3.void write(char[] ch)-----to write character
4.void print(int i) -----directory add the int
5.void print(String s)
6.void print(char[] ch)
7.void print(boolean b)
8.void print(char ch)
9.void print(long l)
10.void println(int i) -----directory add the int
11.void println(String s)
12.void println(char[] ch)
13.void println(boolean b)
14.void println(char ch)
15.void println(long l)
PrintWriter Example:
Import java.io.*;
Class Sample
{
public static void main(String add[])throws IOException
{
PrintWriter pw=new PrintWriter(“laxman.txt”);
Pw.write(100);
Pw.print(100);
Pw.print(true);
Pw.print(“laxman”);
Pw.print(“scjp”);
Pw.print(“Hyderabad”);
Pw.flush();
Pw.close();
}
}
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Java Serialization(serializable):
The process of saveing an object data to a file is called serialization.
writeObject(o)
The process of retrieving an object data from the file is called deserialization.
By using read object method of ObjectInputStream we can achieve deserialization.
ObjectInputStream ----->FileInputStream------>abc.txt
serialization Example:
class Dog implements Serializable
{
int i=10;
int j=20;
transient int k=30;
}
public class Myser1 {
public static void main(String arg[])throws Exception
{
Dog d1=new Dog();
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);
Object Graphs:
When ever we are saving an objects to the file all the objects which are reachable
from that object by default saving to the file.This group of object is called
ObjectGraph.
Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class SerDemo2
{
public static void main(String arg[])throws Exception
{
Dog1 d=new Dog1();
FileOutputStream fos=new FileOutputStream("abc1.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream fis=new FileInputStream("abc1.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog1 d1=(Dog1)ois.readObject();
System.out.println(d1.c.i);
System.out.println(d1. c.r.j);
}
}
When ever we are saving an object to the file.All the object present in its objects
graph by default will save to the file .Hence all the objects present in the object
graph also must be serializable .voilation leads to RTE saying NotSerializable
Exception”.
Example:
class Dog implements serializable
{
Cat c=new Cat();
}
Class Cat
{
Int j=20;
}
Class SerialDemo
{
public static void main(String arg[])
{
Dog d=new Dog();
FileOutputStream fos=new FileOutputStream(“abc.txt”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
Oos.writeObject(d);
FileInputStream fis=new FileInputStream(“abc.txt’);
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d1=(Dog)ois.readObject();
System.out.println(d1.c.j);
System.out.println(d1. c.j);
}
}
Customized Serialization:
During default serialization there may be a chance of loss of information .To over
come these problems ,we can perform customized serialization .
We can perform customized serialization by using the following two call back
methods.
1.private void writeObject(OutputStream os)
JVM calls this writeObject method at the time of serialization.
2.private void readObject(inputStream is)
the JVM calls this method at the time of deserialization automatically.
The above two methods are called by JVM automatically at the time of serialization
and deserialization .Hence these methods are considered as call back methods.
Customized Serialization Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
Date Format
Before going learn about Date Format We have to know the Locale class.
DateFormat:
The representation of date is varied from location to location ,we can format the date for a specific
locale by using date format class.It is available in java.text.package.It is an abstract class we are
not allowed to create an instance of date format by using constructor.
DateFormat d=new DateFormat() -------->not valid
Getting DateFormat object for the default locale:
public static DateFormat getInstance();
public static DateFormat getDateInstance();
public static DateFormat getDateinstance(int style);
the allowed styles are :
DateFormat.FULL(0);
DateFormat.LONG(1);
DateFormat.MEDIUM(2);
DateFormat.SHORT(3);
Getting DateFormat Object for the specific locale:
public static DateFormat getDateInstance(int style,Locale l)
Formating and parsing date:
Public String format(Date d) ----->from java date format to locale specific date format
Public Date parse(String s) throws parseException //from locale specific format to date format.
Demo:
For India,italy
DateFormat in=DateFormat.getDateInstance(0,new Locale(‘pa”,”In”);
DateFormat us=DateFormat.getDateInstance(0);
DateForamt it=DateFormat.getDateInstance(0,new Locale.ITALY);
System.out.println(“India style:”+in.format(new Date()); // Sunday,febravary 3,2008
System.out.println(“us style:”+us.format(new Date()); // Sunday Febravary 3, 2008
System.out.println(“Italy style:”+it.format(new Date()); // dominica 3,febravary 2008.
Getting DateFormat object for representing both date and time.
Public static DateFormat getDateTimeInstance();
Public static DateFormat getDateTimeInstance(int date style, int time style);
Public static DateForamt getDateTimeInstance(int date style, int time style, locale l);
Demo:
DateFormat in=DateFormat.getDateTimeInstance(0,0,Locale.UK);
System.out.println(in); // 03 , febravary 2008 12:10:50 0’clock IST
Us: Sunday febravary 3,2008 12:10:50 pm IST
Thank you for visiting Java Examples.For regular updates request you to subscribe to my RSS
Feed or register your Email Subscription for updates directly into your mail box.
Before Going to learn about Number Format Batter know about Locale Class
Number Format:
By using number format object we can represent the number specific to a particular
region (a particular locale).This class present in java .text package.It is an abstract
class we are not allowed to create object by using constractor.
i.e NumberFormat nf=new NumberFormat() -----> not valid
Example to Display the currency value 1234.343 for locations India .Italy
and us:
Import java.text.NumberFormat;
Import java.util.*;
Class NFDemo
{
Public staic void main(String arg[])
{
double d=123456.789;
Locale India=new Locale(“pa”,”IN”);
NumberFormat nf=NumberFormat.getCurrencyInstance(India);
String s=nf.format(d);
Systm.out.println(“india notation is:”+s);
NumberFormat nf=NumberFormat.getCurrencyInstance(locale.ITALY);
String s=nf.format(d);
Systm.out.println(“india notation is:”+s);
NumberFormat nf=NumberFormat.getCurrencyInstance(locale.UNITEDSTATES);
String s=nf.format(d);
Systm.out.println(“india notation is:”+s);
}
}
}
output:
INR123,456.789
C1 123.456.789
$123,456.789
we can set the maximam and minimum number of digits for integer and fractional
parts.For this we can use the following methods of NumberFormat class.
public void setMaximumFractionalDigits(int n);
public void setMinimumFractionalDigits(int n);
public void setMaximumIntegerDigits(int n);
public void setMinimumIntegerDigits(int n);
Example:
Import java.text.*;
Import java.util.*;
Class NFDemo
{
public static vopid main(String arg[])
{
double d=123.456;
NumberFormat nf=NumberFormat.getInstance();
Systm.out.println(nf.format(d)); //123.456
nf. setMaximumFractionalDigits(2);
System.out.println(nf.format(d)); //123.46
nf.setMinimumFractionalDigits(5);
System.out.println(nf.format(d)); //123.45600
nf.setMaximumIntegerDigits(2);
System.out.println(nf.format(d)); //23.456
The most significant bits will be lost
nf.setMinimumIntegerDigits(6);
System.out.println(nf.format(d)); //000123.456
}
}
Constructors
The purpose of Constructor is to perform of our creted object. Whenever we are
calling new operator for the creation of object, it calls constructor automatically to
provide initialization for the object.
class Student
{
String name; int rno;
Student(String name, int rno) ----> Constructor
{
this.name=name;
this.rno=rno;
}
public static void main(String a[])
{
Student s=new Student(“xxx”,101);
Student s1=new Student(“yyy”,102);
-------
------
}
}
Rules Of Constructor :
1. Constructor concept is applicable for every class including abstract class also.
2. Interface doesn’t have Constructor’s concept.
3. The name of the const4ructor and the name of the class must be same.
4. The allowed modifiers for the constructors are public, private, protected, and
default. If you are applying any other we will get a CTE saying “modifier xxx not
allowed her”.
5. We can’t give return type for the constructor even void also.
If we will give return type for the constructor that thing as a method instead of
constructor that thing as a method instead of constructor (so,there is no CTE). Ie., it
is legal (but stupid) to have a method whose name same as classname.
Default Constructor:-
If the programmer is not writing any constructor, then only compiler will generate a
default constructor.
Ie., either programmer written constructor or compiler generated must present in
your class but not both at a time.
Prototype of default constructor shown below:
a).Programmer written code:- class Test{}
Compiler generated code:-
class Test
{
Test()
{
super();
}
}
The first line inside a constructor must be a call to super class constructor
( by using super();) or a call to overload constructor of the same class. (by
using ‘this’ keyword).
If you are not writing the first line as either ‘super()’ or ‘this’ then compiler
will always keep a no arg call to super class constructor (super();).
Overloaded Constructors:
We are allowed to keep more than one constructor inside a class , which are
considered as overloaded constructors. We can’t override the constructors, because
they belong to the same Ex: class Test {
Test(int i){}
Test(){} ---->Overloaded Constructors
}
Constructors are not inherited and hence we are not allowed to override a
constructor.
while recursive method invocation we will get stackoverflowException But in
case of constructors we will get compile time error.
If we are writing any constructor in our class it is recommended to place
default constructor also. Otherwise we should take care while writing the
constructor child case.
If the parent class constructor throws some Checked Exception, while writing
child class constructors we should take care.In case of unchecked exception
no rule.
Example:
class P {
P(int i)
{
System.out.println(i);
}
}
class C extends P
{
C()
{
super(10); // valid (without super invalid)
}
}
Example: class P
{
P() throws Exception ----> checked exception
{}
}
class C extends P
{
C() // compile time error unhandled exception type exception
{}
}
Java Generics
Example:
ArrapList l=new ArrayList();
l.add(“laxman”);
l.add(new Integer(10));
String n1=(String)l.get(0);
String n2=(String)l.get(1);
To resolve the above two problems Sun people provided generics concept in the 1.5
version.
Hence by using generic we can provide type safely for the collection objects and we
can resolve explicit type casting problems.
i.e no need to type cast at the time of retrieving elements from the collection.
INTRODUCTION TO NETWORKING:
The Java execution environment is designed so that applications can be easily
written to efficiently communicate and share processing with remote systems. Much
of this functionality is provided with the standard Java API within the java.net
package.
TCP/IP Protocols:
Three protocols are most commonly used within the TCP/IP scheme and a closer
investigation of their properties is warranted. Understanding how these three
protocols (IP, TCP, and UDP) interact is critical to developing network applications.
IP is the keystone of the TCP/IP suite. All data on the Internet flows through IP
packets, the basic unit of IP transmissions. IP is termed a connectionless, unreliable
protocol. As a connectionless protocol, IP does not exchange control information
before transmitting data to a remote system—packets are merely sent to the
destination with the expectation that they will be treated properly. IP is unreliable
because it does not retransmit lost packets or detect corrupted data. These tasks
must be implemented by higher level protocols, such as TCP.
It is important to realize that these domain names are not used nor understood by
IP. When an application wants to transmit data to another machine on the Internet,
it must first translate the domain name to an IP address using the DNS. A receiving
application can perform a reverse translation, using the DNS to return a domain
name given an IP address. There is not a one-to-one correspondence between IP
addresses and domain names: A domain name can map to multiple IP addresses,
and multiple IP addresses can map to the same domain name.
Java provides a class to work with IP Addresses, InetAddress.
Most Internet applications use TCP to implement the transport layer. TCP provides a
reliable, connection-oriented, continuous-stream protocol. The implications of these
characteristics are:
Reliable. When TCP segments, the smallest unit of TCP transmissions, are
lost or corrupted, the TCP implementation will detect this and retransmit
necessary segments.
Because of these characteristics, it is easy to see why TCP would be used by most
Internet applications. TCP makes it very easy to create a network application, freeing
you from worrying how the data is broken up or about coding error correction
routines. However, TCP requires a significant amount of overhead and perhaps you
might wish to code routines that more efficiently provide reliable transmissions given
the parameters of your application. Furthermore, retransmission of lost data may be
inappropriate for your application, because such information's usefulness may have
expired.
An important addressing scheme which TCP defines is the port. Ports separate
various TCP communications streams which are running concurrently on the same
system. For server applications, which wait for TCP clients to initiate contact, a
specific port can be established from where communications will originate. These
concepts come together in a programming abstraction known as sockets.
For some applications, UDP is more appropriate than TCP. For instance, with the
Network Time Protocol (NTP), lost data indicating the current time would be invalid
by the time it was retransmitted. In a LAN environment, Network File System (NFS)
can more efficiently provide reliability at the application layer and thus uses UDP.
As with TCP, UDP provides the addressing scheme of ports, allowing for many
applications to simultaneously send and receive datagrams. UDP ports are distinct
from TCP ports. For example, one application can respond to UDP port 512 while
another unrelated service handles TCP port 512.
Scheme-name is a URL scheme such as HTTP, FTP, or Gopher. Host is the domain
name or IP address of the remote system. Port is the port number on which the
service is listening; since most application protocols define a standard port, unless a
non-standard port is being used, the port and the colon which delimits it from the
host is omitted. File-info is the resource requested on the remote system, which
often times is a file. However, the file portion may actually execute a server program
and it usually includes a path to a specific file on the system. The internal-reference
is usually the identifier of a named anchor within an HTML page. A named anchor
allows a link to target a particular location within an HTML page. Usually this is not
used, and this token with the # character that delimits it is omitted.
Java and URLs:
Java provides a very powerful and elegant mechanism for creating network client
applications allowing you to use relatively few statements to obtain resources from
the Internet. The java.net package contains the sources of this power, the URL and
URLConnection classes.
In general, a URL can be broken into several parts. The previous example of a URL
indicates that the protocol to use is http (HyperText Transport Protocol) and that the
information resides on a host machine named www.ncsa.uiuc.edu. The information
on that host machine is named demoweb/url-primer.html. The exact meaning of this
name on the host machine is both protocol dependent and host dependent. The
information normally resides in a file, but it could be generated on the fly. This
component of the URL is called the file component, even though the information is
not necessarily in a file.
A URL can optionally specify a "port", which is the port number to which the TCP
connection is made on the remote host machine. If the port is not specified, the
default port for the protocol is used instead. For example, the default port for http is
80. An alternative port could be specified as:
http://www.ncsa.uiuc.edu:8080/demoweb/url-primer.html
This anchor is not technically part of the URL. Rather, it indicates that after the
specified resource is retrieved, the application is specifically interested in that part of
the document that has the tag chapter1 attached to it. The meaning of a tag is
resource specific.
An application can also specify a "relative URL", which contains only enough
information to reach the resource relative to another URL. Relative URLs are
frequently used within HTML pages.
The relative URL need not specify all the components of a URL. If the protocol, host
name, or port number is missing, the value is inherited from the fully specified URL.
The file component must be specified. The optional anchor is not inherited.
GetURLApp.java
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
public class GetURLApp
{
public static void main(String args[])
{
try
{
if(args.length!=1) error("Usage: java GetURLApp URL");
System.out.println("Fetching URL: "+args[0]);
URL url = new URL(args[0]);
BufferedReader inStream = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = inStream.readLine())!= null)
{
System.out.println(line);
}
inStream.close();
}
catch (MalformedURLException ex)
{
error("Bad URL");
}
catch (IOException ex)
{
error("IOException occurred.");
}
}
Each of the above set methods has a corresponding get method to retrieve the value
of the parameter or general request property. The specific parameters and general
request properties that are applicable are protocol specific.
The following methods are used to access the header fields and the contents after
the connection is made to the remote object:
getContent
getHeaderField
getInputStream
getOutputStream
getContentEncoding
getContentLength
getContentType
getDate
getExpiration
getLastModified
provide convenient access to these fields. The getContentType method is used by the
getContent method to determine the type of the remote object; subclasses may find
it convenient to override the getContentType method.
In the common case, all of the pre-connection parameters and general request
properties can be ignored: the pre-connection parameters and request properties
default to sensible values. For most clients of this interface, there are only two
interesting methods: getInputStream and getObject, which are mirrored in the URL
class by convenience methods.
More information on the request properties and header fields of an http connection
can be found at:
http://www.w3.org/hypertext/WWW/Protocols/HTTP1.0/draft-ietf-http-spec.html
Sockets are often used in client-server applications: A centralized service waits for
various remote machines to request specific resources, handling each request as it
arrives. In order for clients to know how to communicate with the server, standard
application protocols are assigned well-known ports. On UNIX operating systems,
ports below 1024 can only be bound by applications with super-user (for example,
root) privileges, and thus for control, these well-known ports lie within this range, by
convention. Some well known ports are shown in the following table.
Port
Service
21 FTP
23 Telnet
25 SMTP (Internet Mail Transfer)
79 Finger
80 HTTP
For many application protocols, you can merely use the Telnet application to connect
to the service port and then manually emulate a client. This may help you
understand how client-server communications work.
Client applications must also obtain, or bind, a port to establish a socket connection.
Because the client initiates the communication with the server, such a port number
could conveniently be assigned at runtime. Client applications are usually run by
normal, unprivileged users on UNIX systems, and thus these ports are allocated from
the range above 1024. This convention has held when migrated to other operating
systems, and client applications are generally given a dynamically-allocated port
above 1024.
Because no two applications can bind the same port on the same machine
simultaneously, a socket uniquely identifies a communications link. Realize that a
server may respond to two clients on the same port, since the clients will be on
different systems and/or different ports; the uniqueness of the link's characteristics
are preserved.
Java has a number of classes, which allow you to create socket-based network
applications. The two classes you use include java.net.Socket and
java.net.ServerSocket.
This class implements server sockets. A server socket waits for requests to come in
over the network. It performs some operation based on that request, and then
possibly returns a result to the requester.
The actual work of the server socket is performed by an instance of the SocketImpl
class. An application can change the socket factory that creates the socket
implementation to configure itself to create sockets appropriate to the local firewall.
ServerExample.java
import java.io.*;
import java.net.*;
import java.util.Date;
This class implements client sockets (also called just "sockets"). A socket is an
endpoint for communication between two machines. The actual work of the socket is
performed by an instance of the SocketImpl class. An application, by changing the
socket factory that creates the socket implementation, can configure itself to create
sockets appropriate to the local firewall.
import java.io.*;
import java.net.*;
When receiving a message, you could potentially wait forever until one arrives in your mailbox.
Once one does, you can read the postcard. Meta-information appears on the postcard that
identifies the sender through the return address. As the previous analogies suggest, UDP
programming involves the following general tasks:
• Creating an appropriately addressed datagram to send.
• Setting up a socket to send and receive datagrams for a particular application.
• Inserting datagrams into a socket for transmission.
• Waiting to receive datagrams from a socket.
• Decoding a datagram to extract the message, its recipient, and other meta-information.
This class represents a datagram packet. Datagram packets are used to implement a
connectionless packet delivery service. Each message is routed from one machine to another
based solely on information contained within that packet. Multiple packets sent from one
machine to another might be routed differently, and might arrive in any order.
Example for DatagramPacket :
import java.net.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;
public class MyConnectionPool {
Vector connections= null;
static MyConnectionPool instance=null;
public static final int MAX_CONNECTIONS=10;
//removeAllConnections objects
public synchronized void removeAllConnections() {
if (connections==null) {
return;
}
try {
int sz= connections.size();
for (int i=0; i < sz/2; i++) {
Connection c= (Connection) connections.elementAt(i);
c= null;
connections.remove(i);
}
if (connections!= null && connections.size() > 0) {
connections.removeAllElements();
}
connections= null;
}catch (Exception e) {
System.out.println( "Error "+ e);
}
instance =null;
}
//getInstance...
public static MyConnectionPool getInstance() {
if (instance ==null)
instance= new MyConnectionPool();
return instance;
}
package funds;
short s=40;
s=s+1; // error because max(int,short,int)
// The above error in case of byte and short only we will get
int i=20;
i=i+1; // no error because max(int,type of a,type of b)
package funds;
}
abstract void m1();
}
public class AbstractConst extends AbstractDemo
{
public void m1()
{
System.out.println("m1 implementation");
}
public static void main(String arg[]){
AbstractConst a=new AbstractConst();
}
}
output:
this is abstruct class constructor
abstract class with out abstract methods
package funds;
// abstract class with out any abstract method
/* Sun people flow the same thing In case of Servlet API HttpServlet
is abstract class but there is no abstract methods in that class */
output:
this m1 impl
this m2 imple
with out main with out static block
package something;
output:
hi I can print
Exception in thread 'main' java.lang.NoSuchMethodError:main
Method Overloading
Method Overloading:
Two methods having the same name are not allowed in the case of C-language, for
every data type even though the functionality in the same; we should maintain
different method names. It increases the complexity of the programming. But in
java, two methods having the same name is allowed irrespective of parameters. We
can maintain the same method name for similar type of functionality. It simplifies
the programming. Such types of methods are called Overloaded methods.
• Two methods are said to be overloaded if and only of they have the same method
name, but different parameter list(at least order).
• The signatures of the two overloaded methods must be different.
Example:
public void m1(){}
private int m1(int i){}
• Here m1() & m1(int i) are overloaded. We never consider return type, access
modifier and throws class in overloading.
Example:
class Sample
{
public void m1()
{
System.out.println(“no arg”);
}
public void m1(int i)
{
System.out.println(“ int arg”);
}
public void m1(double d)
{
System.out.println(“ double arg”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1();
s.m1(10);
s.m1(10.5);
}
}
s.m1(10L);//double arg
s.m1(‘a’);//int arg
}
}
In the case of overloading the method resolution performed by the compiler is based
on the reference type.
package oops;
}
Code to demonstrate method overloading by extending
another class.
package oops;
class Superclass
{
public void m1()
{
System.out.println("no arg");
}
}
package oops;
s.m1(10); //int
s.m1(10.5); // double
s.m1('a'); // char
}
sample code method overloading abiguous problem
package oops;
}
method overloading by passing objects
package oops;
}
example code static binding
//In the case of overloading the method resolution performed by the compiler is
based on the reference type.
package oops;
class Animal
{
}
}
}
variable argument method vs normal method
class VarargNor
{
static void m1(int i)
{
System.out.println("Int");
}
static void m1(int... i)
{
System.out.println("var-arg int");
}
public static void main(String a[])
{
int i=10;
m1(i); //int
m1(i,i); //var-arg int
}
}
widening autoboxing
Method Overloading
Method Overloading:
Two methods having the same name are not allowed in the case of C-language, for
every data type even though the functionality in the same; we should maintain
different method names. It increases the complexity of the programming. But in
java, two methods having the same name is allowed irrespective of parameters. We
can maintain the same method name for similar type of functionality. It simplifies
the programming. Such types of methods are called Overloaded methods.
• Two methods are said to be overloaded if and only of they have the same method
name, but different parameter list(at least order).
• The signatures of the two overloaded methods must be different.
Example:
public void m1(){}
private int m1(int i){}
• Here m1() & m1(int i) are overloaded. We never consider return type, access
modifier and throws class in overloading.
Example:
class Sample
{
public void m1()
{
System.out.println(“no arg”);
}
public void m1(int i)
{
System.out.println(“ int arg”);
}
public void m1(double d)
{
System.out.println(“ double arg”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1();
s.m1(10);
s.m1(10.5);
}
}
s.m1(10L);//double arg
s.m1(‘a’);//int arg
}
}
In the case of overloading the method resolution performed by the compiler is based
on the reference type.
class Baseclass
{
public void sm()
{
System.out.println("super class");
}
}
class P
{
public Object m1()
{
System.out.println("super");
return new Object();
}
}
C c=new C();
c.m1(); //child
c.m2(); //parent m2
c.m3(); //child m3
Pc p2=new C();
p2.m1(); //child
p2.m2(); //parent m2
p2.m3(); //error
}
}
instance methods ,static methods overriding issues
DEMO 1:
// Super class instance method,sub class static method
package oops;
import java.io.FileNotFoundException;
import java.io.IOException;
class Parentclass
{
public void sm()
{
System.out.println("super class");
}
}
public class OREx extends Parentclass{
Demo 2:
// super class static method sub class instance method
package oops;
import java.io.FileNotFoundException;
import java.io.IOException;
class Parentclass
{
public static void sm()
{
System.out.println("super class");
}
}
public class OREx extends Parentclass{
package oops;
class Superclass
{
// super class default m1 method
void m1()
{
System.out.println("Super class method");
}
// super class private m2 method
private void m2()
{
System.out.println("Super class method");
}
// super class public m3 method
public void m3()
{
System.out.println("Super class method");
}
// super class protected m4 method
protected void m4()
{
System.out.println("Super class method");
}
}
public class Subclass extends Superclass {
//If not provide proper allowed modifiers it leads compiler error
//cannot reduce the visibility of the inherited method from super
class
output:
Super class method
Super class method
Super class method
Super class method
checked exception issues in method overriding Examples
Demo1:
// super class method throws unchecked exception
// sub class method no throws
package oops;
class Parentclass
{
public void sm()throws Exception
{
System.out.println("super class");
}
}
public class OREx extends Parentclass{
public void sm() // valid
{
System.out.println("sub class");
}
public static void main(String a[])
{
OREx s=new OREx();
s.sm(); // sub class
}
}
Demo2:
// super class ,Sub class methods throws unchecked exception
package oops;
class Parentclass
{
public void sm()throws Exception
{
System.out.println("super class");
}
}
public class OREx extends Parentclass
//Super ,Sub classes throws same exception noerror
public void sm()throws Exception
{
System.out.println("sub class");
}
public static void main(String a[])throws Exception
{
OREx s=new OREx();
s.sm(); // sub class
}
}
Demo3:
// super class method no throws
// sub class method throws unchecked exception
package oops;
class Parentclass
{
public void sm()
{
System.out.println("super class");
}
}
public class OREx extends Parentclass{
DEMO 1:
package oops;
import java.io.FileNotFoundException;
import java.io.IOException;
class Parentclass
{
public void sm()throws IOException
{
System.out.println("super class");
}
}
public class OREx extends Parentclass{
Demo 2:
package oops;
import java.io.FileNotFoundException;
import java.io.IOException;
class Parentclass
{
public void sm()throws FileNotFoundException
{
System.out.println("super class");
}
}
public class OREx extends Parentclass{
DEMO 3:
package oops;
import java.io.FileNotFoundException;
import java.io.IOException;
class Parentclass
{
public void sm()throws FileNotFoundException
{
System.out.println("super class");
}
}
public class OREx extends Parentclass{
class Parentclass
{
public void sm()
{
System.out.println("super class");
}
}
public class OREx extends Parentclass{
Demo 1:
// super class final method sub class non-final method
package oops;
class Superclass
{
final void m1()
{
System.out.println("Super class method");
}
}
public class Subclass extends Superclass {
Demo 2:
// super class non-final method, sub class final method
package oops;
class Superclass
{
void m1()
{
System.out.println("Super class method");
}
}
public class Subclass extends Superclass {
{
System.out.println("Sub class method");
}
public static void main(String[] args) {
Subclass s=new Subclass();
s.m1(); // sub class
}
we can override synchronized method
package mythread;
class Baseclass
{
public synchronized void sm()
{
System.out.println("super class");
}
}
super:
super is a keyword which is used to refer the super class from a sub class .It means
super can refer the super class instance variables ,super class constructors and also
super class methods(instance ,static).super keyword never use in static area like
static methods,static blocks.....Because instance variables,constructors ,instance
methods these things we will get when the object is created then only we will get.
Example code super:
class One
{
int i;
One()
{
System.out.println("no arg constructor");
}
One(int i)
{
this.i=i;
}
void show()
{
System.out.println("super class method"+i);
}
}
class Two extends One
{
int i;
Two()
{
super();
}
Two(int x,int y)
{
super(x); //calling super class constructor
i=y;
}
void show()
{
System.out.println("sub class method");
super.show(); // calling super class method
System.out.println("super class variable"+super.i); //get super class variable
}
}
class Const
{
public static void main(String arg[])
{
Two t1=new Two();
Two t=new Two(100,200);
t.show();
}
}
this:
this is used to call the present class parameter constructor,present class
methods(instance,static),present class instance variables.this keyword never use in
static area like static methods,static blocks.....Because instance
variables,constructors ,instance methods these things we will get when the object is
created then only we will get.
Example code this:
class Sample
{
int n;
Sample()
{
this(100); // this class constructor
this.display(); // this class method
}
Sample(int n)
{
this.n=n; // this class instance variable
}
void display(){
System.out.println("n="+n);
}
}
class ThisDemo
{
public static void main(String arg[])
{
Sample s=new Sample();
}
}
If the Implementation for all the methods declared in the Interface are not
provided , the class itself has to declare abstract, other wise the Class will not
compile.
If a class Implements two interface and both the Intfs have identical method
declaration, it is totally valid.
If a class implements tow interfaces both have identical method name and
argument list, but different return types, the code will not compile.
Java.lang is the Package of all classes and is automatically imported into all Java
Program
Interfaces: Clonable , Comparable, Runnable
Abstract Class means - Which has more than one abstract method which doesn’t
have method body but at least one of its methods need to be implemented in derived
Class.
The Number class in the java.lang package represents the abstract concept of
numbers. It makes sense to model numbers in a program, but it doesn't make sense
to create a generic number object.
All the methods declared in the Interface are Abstract, where as abstract
class must have atleast one abstract method and others may be concrete.
In abstract class keyword abstract must be used for method, where as in
Interface we need not use the keyword for methods.
Abstract class must have Sub class, where as Interface can’t have sub
classes.
An abstract class can extend only one class, where as an Interface can extend
more than one.
What are access specifiers and access modifiers ?
Accesss specifiers
Public
Protected
Private
Access modifiers
Public
Abstract
Final
Static
Volatile
Synchronized
Transient
Native
• Public : The Variables and methods can be access any where and any package.
• Protected : The Variables and methods can be access same Class, same Package &
sub class.
• Private : The variable and methods can be access in same class only.
All the objects have Finalize() method, this method is inherited from the
Object class.
Finalize() is used to release the system resources other than memory(such as
file handles& network connec’s.
Finalize( ) is used just before an object is destroyed and can be called prior to
garbage collection.
Finalize() is called only once for an Object. If any exception is thrown in the
finalize() the object is still eligible for garbage collection.
Finalize() can be called explicitly. And can be overloaded, but only original
method will be called by Ga-collect.
Finalize( ) may only be invoked once by the Garbage Collector when the
Object is unreachable.
Object : Object is a Super class for all the classes. The methods in Object class as
follows.
Object clone( )
final void notify( )
Int hashCode( )
Boolean equals( )
final void notify( )
Void finalize( )
String toString( )
Final Class getClass( )
final void wait( )
Class : The Class class is used to represent the classes and interfaces that are
loaded by the JAVA Program.
String: String is Immutable and String Is a final class. The String class provides for
strings whose value will not change.
One accessor method that you can use with both strings and string buffers is the
length() method, which returns the number of characters contained in the string or
the string buffer. The methods in String Class:-
toString( )
equals( )
indexOff( )
LowerCase( )
charAt( )
compareTo( )
lastIndexOff( )
UpperCase( )
getChars( )
subString( )
trim( )
getBytes( )
concat( )
valueOf( )
toCharArray( )
replace( )
ValueOf( ) : converts data from its internal formate into human readable formate.
String Buffer : Is Mutable , The StringBuffer class provides for strings that will be
modified; you use string buffers when you know that the value of the character data
will change.
In addition to length, the StringBuffer class has a method called capacity, which
returns the amount of space allocated for the string buffer rather than the amount of
space used.
The methods in StringBuffer Class:-
length( )
append( )
replace( )
charAt( )
setCharAt( )
capacity( )
insert( )
substring( )
getChars( )
ensureCapacity( )
reverse( )
setLength( )
delete( )
Wraper Classes : are the classes that allow primitive types to be accessed as
Objects.
These classes are similar to primitive data types but starting with capital letter.
Number
Byte
Boolean
Double
Short
Character
Float
Integer
Long
primitive Datatypes in Java :
According to Java in a Nutshell, 5th ed boolean, byte, char, short, long float, double,
int.
Float class : The Float and Double provides the methods isInfinite( ) and isNaN( ).
isInfinite( ) : returns true if the value being tested is infinetly large or small.
isNaN( ) : returns true if the value being tested is not a number.
Character class : defines forDigit( ) digit( ) .
ForDigit( ) : returns the digit character associated with the value of num.
digit( ) : returns the integer value associated with the specified character (which is
presumably) according to the specified radix.
Observable Class: Objects that subclass the Observable class maintain a list of
observers. When an Observable object is updated it invokes the update( ) method of
each of its observers to notify the observers that it has changed state.
Observer interface : is implemented by objects that observe Observable objects.
Instanceof( ) :is used to check to see if an object can be cast into a specified type
with out throwing a cast class exception.
Inner class : classes defined in other classes, including those defined in methods
are called inner classes. An inner class can have any accessibility including private.
Downcasting : is the casting from a general to a more specific type, i.e casting
down the hierarchy. Doing a cast from a base class to more specific Class, the cast
does;t convert the Object, just asserts it actually is a more specific extended Object.