Core Java Ex 1
Core Java Ex 1
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.
java Literals
A constant value which can be assigned to a variable is known as
Literal.If we are assigning any outside range value for any data type, we will
get a compile time error saying Possible Loss of Precision found int required
byte.
For the integral data types (int, byte, short, long): we are allowed to specify
a literal value of any any one of the following three forms.
---> Decimal literal (normal way)
--->Octa literal (prefixed with 0 )
--->Hexa decimal (prefixed with 0x )
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
Vailation leads to compail 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
Java Variables
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 all
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.out.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
Coding Standards
Java coding standards:
Sun recommended the following for the naming conventions.
1. In case of classes:
The first letter should be capitalized and if the several words are linked
together to form the name ,the first letter of the inner words should be upper
case.
For the classes the names should be nouns.
Ex: Student, Customer, Employee etc.
2. In case of Interfaces:
For the interfaces the names should be adjective and follows camel case.
Ex:
Runnable .Serializable,cloneable,Comparable,Movable etc
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
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.
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
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)
Ex: int a=10+’a’ => 10+97=107
double b=10+12.5 => 10.0+12.5=>22.5;
For representing infinity, there are no constant; define in the integer class.
Hence 0/0 results is sum time exception saying arithmetic exception
System.out.println(10/0); //Runtime Exception by zero .
System.out.println(10.0/0); //infinity
System.out.println(10.0f/0); //infinity
But in the float and double classes for representing infinity constants are
defined.
System.out.println (Float. POSITIVE_INFINITY); // infinity
System.out.println( Float NEGATIVE_ INFINITY); //-infinity
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:
1. runtime exception (unchecked)
2. only in the cone of integer arithmetic.
3. / and % only there two operators result in Arithmetic exception.
String concatenation operation:-
‘+’ is the only operator in java which in overloaded. We can one for
arithmetic addition and for string concatenation.
String a=”java”.
int b=30;
int c=20;
int d=10;
System.out.println (a+b+c+d);→java302010;
System.out.println(b+a+c+d);→ 30java2010
System.out.println(b+c+d+a); →60java
System.out.println(b+c+a+d);→50java10.
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.
ie. 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”);
}
}
Abstract methods should be overridden in the child class to provide
implementation.But final methods are not allowed to override. Hence
abstract and final combination is illegal for methods also.
A final class never allowed to contain abstract methods. But a final methods
is allowed to keep inside abstract class.i,e final method in abstract class
is valid But abstract method in final class is not valid.
Abstract is the keyword which can be applied for classes and methods
only.i.e we can’t use abstract keyword for a variable.
final is the keyword which can be applied for classes ,methods and variables.
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
For the local variables the only allowed modifier is final.
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:
The keyword static can be use for classes, methods, variables
We can not apply static keyword for the top level classes, but we can
apply inner classes.
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 abstract and static 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();
}
}
For the native methods already implementation is available but abstract
method means implementation is not available .hence abstract and native
combination is illegal for the methods
Native methods already implementation is available we are not providing any
implementation. Hence nativemethod declaration should be ends with
semicolon
Native and strictfp combination is illegal for methods because old
languages may not fallow IEEE 754 standerd for floating point.
We can override a native method
We can overload a native method
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 TransientDemo implements Serializable
{
int i=10;
int j-20;
public static void main(string args[])throws exception
{
TransientDemo t1=new TransientDemo();
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);
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
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 this
volatile keyword.
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:
In object-oriented programming, a class is a programming language
construct that is used as a blueprint to create objects. This blueprint
includes attributes and methods that the created objects all share.
Usually, a class represents a person, place, or thing - it is an abstraction of a
concept within a computer program. Fundamentally, it encapsulates the state
and behavior of that which it conceptually represents. It encapsulates state
through data placeholders called member variables; it encapsulates behavior
through reusable code called methods.
More technically, a class is a cohesive package that consists of a particular
kind of meta data. It describes the rules by which objects behave; these
objects are referred to as instances of that class. A class has both an
interface and a structure. The interface describes how the class and its
instances can be interacted with via methods, while the structure describes
how the data is partitioned into attributes within an instance. A class may
also have a representation (meta object) at run time, which provides run
time support for manipulating the class-related meta data. In object-oriented
design, a class is the most specific type of an object in relation to a specific
layer.
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:
In its simplest embodiment, an object is an allocated region of storage.
Since programming languages use variables to access objects, the terms
object and variable are often used interchangeably. However, until memory
is allocated, an object does not exist.
Any language present objects and this should not be confounded with the
most powerful concept of object-orientation.
{
int i=10;
void mone()
{
System.out.println("java");
}
public static void main(String arg[])
{
Sam s=new Sam(); //Here is the Object
}}}
Abstraction
Hiding internal implementation is called Abstraction.
Advantages:
Security
Enhancement easy
we can enhance the internal implementation with out effecting outside world.
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.
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
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(){}
}
For Number class Byte/Short/Integer is co-variant return types or classes.
Hence in case of overriding as the return type we can keep child class objects
also.
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
2. final methods can’t be overridden.
3. private methods never participate in the in the overriding because
these methods are not visible in the child classes.
4. While overriding decreasing access specifier is not allowed.
Violation leads to CTE.
class P{
public void m1()
{ } }//non abstract
abstract class C extends P{
public abstract m1(); }//valid abstract
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 default constructor is always no argument constructor.
The access modifier of the default constructor is same as access modifier of
the class (public & default only).
The default constructor contains only one statement which is ‘no arg call to
super class Constructor ‘ (super();)
b) Programmer written code:-
class Test {
Test(int i)
{
System.out.println(“constructor”);
}}
Compiler generated code:-
class Test {
Test(int i)
{
super();
System.out.println(“constructor”);
}}
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
{}
}
Date 3/11/2010.
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.
Abstract method has declaration only and should not have any
implementation.
This is the way of decorating abstract method .we should not keep curly
braces at end.
If a class contain at least one abstract method we should have to declare
that class as abstract other wise compile time error.
An abstract class is not compulsory to have an abstract method.i.e abstract
class may contain zero number of abstract methods also.this is for
restricting object creation.
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 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.
case 3:
Same method name,same arguments but different written types.
Interface Left
{
public void m1();
}
Interface Right
{
public int m1();
}
class Central implement Left,Right
{
public static void main(String arg[])
{
public void m1() // error
{
}
public int m1() // error
{
}
}
}
In the above class same method signature m1 is not allow .violation leads to
compile time error.
Exceptional case:
We can’t provide implementation at a time for two or more interfaces having
methods with same signature but different return type .
Variable Naming conflicts:
interface Left
{
int x=10;
}
interface Right
{
int x=100;
}
class Central implement Left,Right
{
public static void Main(String arg[]
)
{
System.out.println(x); // reference to x is ambiguous both variables
System.out.println(Right.x);
System.out.println(Left.x);
}}
we can resolve variable naming conflicts using interface name.(i.e instead of
x we have to specify left.x or right.x).
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.
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:
It implements the SortedMap interface.
The underlying datastructure for the TreeMap is Red-Black Tree Insertion
order is not preserved
Duplicate keys are not allowed but values may be duplicated
Heterogeneous objects are not allowed for the keys but values may be
heterogeneous.
As first entry null key insertion is possible to the empty treemap but after if
you try to add any other entry we will get the NullPointerException
If you are trying to add an entry with the null key to an already exsting
treemap we will get the NullPointerException
There is no restriction for null values
If natural sorting order is used then the keys must be comparable otherwise
classCastException
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);
}
}
Methods:
getProperty(String key);
setProperty(String key,String value);
propertyNames();
load(InputStream stream);
store(OutputStream stream,String comment);
Note:
interface Map{
Interface Entry{ // inner interface entry
Object getKey();
Object getValue();
Object setValue(Object obj)
}
}
Hashtable:
The underlying datastructure for the HashTable is the Hastable itself.
Heterogeneous values are allowed for both keys and values
null insertion is allowed for both keys and values for the first
element violation leads to NullPointerException
Almost all methods or Hashtable are synchronized hence it is thread
safe Insertion order is not preserved and the objects are arranged
based on hashcode
Duplicate objects for values but keys are not to be duplicated
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;
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:
Underlying datastructure is Hashtable
Insertion order is not preserved
While iterating we can not give guarantee for processing order.
Hence we can not use it for caching
LinedHashMap:
Underlying datastructures are hashtable and doubly linkedlist
Insertion order of elements is preserved
While iterating elements we can give guarantee for processing
order.Hence we can use for caching
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
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.
List Interface:
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: The underlying datastructure for array List is growable array or
resizable array.
Insertion order is preserved.
Duplicate objects are allowed.
Hetrogeneous objects are allowed.
Null insertion is possible any number of times.
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
ArrayList and Vector classes implemented Random Access interface.Any
element in ArrayList and Vector we can access with same speed.Hence
ArrayList is best suitable for retrivel operation.
ArrayList is a non-synchronised one introduced in 1.2 version.It is a non-
legacy class which has high performance.But we can’t achieve security.Where
as vector is a synchronized in 1.0 version .It is a legacy class which has
low performance But we can achive security.
In ArrayList ,there is a possibility for data corruption as it is thread
safe.ArrayList is the worrest choice,If your frequent operation is insertion or
deletion in the middle,because it reqires so many internal shift operations .
LinkedList:
The underlying data structure for LinkedList is DoublyLinkedList.
Insersion order is preserved.
Duplicate objects are allowed.
Null insertion is possible any number of times.
Hetrogeneous objects are also allowed.
It implemented serializable and clonable interfaces but not
RandomAccess interface.
LinkedList is the best choice if your frequent operation is insertion or deletion
in the middle.
LinkedList the worest choice if your frequent operation retrieval operation.
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]
}}
TreeSet class :
The underlying datastructure for the treeset is balancedtree.
Duplicate objects are not allowed.
Insertion order is not preserved, but all the elements are arranged in some
sorting order.
Null insersion is possible but only one.
Hetrogeous objects are not allowed, voialtion leads to runtime exception
saying classcast exception.
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.
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;
}
}
import java.util.*;
class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new TreeSet(new MyComparator());
t.add(new StringBuffer(“aaa”);
t.add(new StringBuffer(“bbb”);
t.add(new StringBuffer(“ccc”);
t.add(new StringBuffer(‘ddd”);
System.out.println(t);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s1.compareTo(s2);
//return s2.compareTo(s1);
}
}
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.
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:
The underlying data structure for the set is Hashtable.
Elements are inserted based on the hash code, hence insertion order
is not possible.
If we are trying to add a duplicate object no chance of getting RTE or CTE
add() just simply returns false.
Hetrogeneous objects are allowed.
Null insertion is possible but only once.
HashSet is the best choice for searching operations.
Hashset implemented serializable and clonable interface.
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.
}
}
Cloneable interface:
Cloning in programming uptaining bit wist exact copy of an object is
called cloning.
cloning Example:
Class sample() implements cloneable
{
Int i=10;
Public static void main(string args[])throwsClone notSupportedEexception
{
Sample s1=new sample();
Sample s2=s1;
Sample s3=(sample)s1.clone();
S1.i=1000;
System.out.println(s3.i);
System.out.println(s1==s3);
we should type cast otherwise
CTE:in compatable types
Found: Object reqired=sample
The class must implements cloneable interface otherwise at runtime clone()
results cloneNotsupportException
Example:
Class sample implements clonable
{
Int i=10;
Public static void main(string[]args)throws cloneNot support Exception
{
Object o=new object();
Object o2=o.clone();
}
CTE:clone() has protected access in java.lang.object
The protected numbers we can access, from with in the same package or
from outside package but from outside package,the protected number can be
accessed b using child class reference only.ie we can’t use parentclass
reference to access protected number from outside package,validation
leadsto CTE.
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 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.
Process Based Multitasking:-
* Executing several tasks simultaneously where each task is a independent
program.
* Example typing a java program in the Editor, playing MP3 player,
Downloading a file from the internet
* All the tasks are independent of each other and executes simultaneously.
* This type of multitasking is useful at OS level.
* CGI fallows process based multitasking.
Thread Based Multitasking:-
* Executing several tasks simultaneously, where each task is a separate
inependent part of the same program. That independent part is called the
Thread.
* Servlets followThread Based MultiTasking.
* Java itself provide support for multithreading by introducing several library
classes.
* We can use in games/animation programme.
* Creating a thread in two ways.
1. By extending Thread
2. By implementing Runnable
* yield()
* join()
* sleep()
* Synchronization
* InterThread communication (wait, notify, notifyAll)
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.
Advantage: Prevent data corruption, achieve security.
Limitation: Because of synchronized keyword 2 threads are not allowed to
execute concurrently on any object, hence the waiting time of the threads
will increase, which results in low performance of the system.
A class can contain both synchronized and non synchronized methods.
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 nay non synchronized
method on that object.
Every Object in java has a lock. At the time of synchronization only the lock
concept will conme 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
If the thread call wait()method,first it releases the lock and thenit 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 immedeatly 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 immediatly
noifyAll()
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 releses 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 callector
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 runnigg 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 n non-daemon by default child also non-
daemon. // Child and parents should daemon incase of daemon
Based on our requirement we are allowed to change the daemon nature of
any thread b 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.
The Default Thread Group:
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 a
ThreadGroup named main. Unless specified otherwise, all new threads that
you create become members of the main thread group.
Creating a Thread Explicitly in a Group
A thread is a permanent member of whatever thread group it joins when its
created--you cannot move a thread to a new group after the thread has been
created. Thus, if you wish to put your new thread in a thread group other
than the default, you must specify the thread group explicitly when you
create the thread. The Thread class has three constructors that let you set a
new thread's group:
public Thread(ThreadGroup group, Runnable target)
public Thread(ThreadGroup group, String name)
public Thread(ThreadGroup group, Runnable target, String name)
Each of these constructors creates a new thread, initializes it based on the
Runnable and String parameters, and makes the new thread a member of
the specified group. For example, the following code sample creates a thread
group (myThreadGroup) and then creates a thread (myThread) in that group.
ThreadGroup myThreadGroup = new ThreadGroup("My Group of Threads");
Thread myThread = new Thread(myThreadGroup, "a thread for my 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 class ThreadGroupDemo {
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”));
* In this content, three objects are created. One is on heap and another two
on “String Constant Pool”
• “String Constant Pool” never allows Garbage Collection.
• Heap durgasw String Constant Pool software
• I the object does not have any references in the “String Constant
Pool”, still this is not eligible for the Garbage Collection.
• All the objects present in the “String Constant Pool” destroy,
whenever the JVM restarted.
What is the output and how many String objects are created.
String s1=”spring”;
String s2=s1+”summer”;
s1.concat(“fall”);
s2.covcat(“s1”);
s1+=”winter”;
System.out.println(s1+ “,”+s2);
output: spring , springsummer
string constant pool: spring, summer, fall, winter
Heap: springsummer, springfall, springwinter, springsummerspring
Advantage Of StringConstantPool:
String s1=”you can’t change me”;
String s2=”you can’t change me”;
System.out.println(s1==s2); // true
System.out.println(s1.equals(s2)); //true
String s3=new String(“you cannot change me”);
System.out.println(s1==s3);//false
System.out.println(s1.equals(s3)); //true
String s4=”you can’t” + “change me”;
System.out.println(s1==s4);
String s5=”you can’t”;
String s6=s5+”change me”;
System.out.println(s1==s6); //false
If final String s7=”you can’t”
System.out.println(s1==s7); //true
String s8= s7+”change me”;
s1==s8; //true.
• In our programme., if any String object is repeatedly going to use, we can
keep only one copy in the String Constant Pool and shared by several
required references. Instead of creating several same content object, we are
creating only one object, this is very efficient w.r.t to memory point of view.
• As several refernces pointing to the same object in the StringConstantPool,
by using any references , if you allowed to use the content of that object, the
remaining references have to suffer.
• Hence once we created a string object we are not allowed to change
content.
• If you want to perform any changes, with those changes a new String
Object wil create . Hence the String Objects are declared as the Immutable.
• StringConstantPool ---> Performance is improved. (advantages)
----> Immutability ( disadvantages)
Interning Of Strings:
String s1=new String(“viswan”);
String s2=s1;
String s3=s1.intern();
S1==s3; //false
String s4=”viswan”;
s4==s3; //true
• Intern() method used to point the String constant pool object
instead of heap object.
String Class Constructors:
1. String s=new String(String s);
2. String s=new String();
3. String s=new String(StringBuffer s1);
4. StringBuffer s1=new StringBuffer(“xxx”);
5. String s=new String(byte[]);
Ex: byte[] b={100,101,102,102}
String s=new String(b);
System.out.println(s); //”defg”
6. String s=new String(char[]);
Ex: Char[] ch={a,b,cd};
String s=new String(ch);
System.out.println(ch); // abcd
String Class Methods (only some imp):
1. public char charAt(int index):
This method returns the character located at the string’s specified index.
Remember that String indexes are zero based.
2. public String concat(String s):
This method returns a string with the value of the String passed into the
method appended to the end of the String used to invoke the method.
The overloaded + and += operators perform the same function of concat()
method.
Ex: String s=”durga”;
s=s.concat(“sw”);
s=s+”sw”;
s+=”sw”;
System.out.println(s); //durgasw
3. public Boolean equals IgnoreCase(String s):
This method returns Boolean value ie., true or false depending on whether
the value of the string in the argument is the same as the value of the String
used to invoke the method.
Ex: String s=”DURGA”;
System.out.println(s.equalIgnoreCase(“Durga”); //true
s.equals(“Durga”); //false
4. public int length():
length() is the method in the case of String objects where as ‘length’ is the
variable in the case of Arrays.
Ex: String s= “durga”;
System.out.println(s.length); //CTE
System.out.println(s.length());// 5
5. public String replace(char old, char new):
String x=”ababab”;
System.out.println(x.replace(‘a’,’b’); //bbbbbb
6. a). public String substring(int begin):
String x=”0123456789”;
System.out.println(s.subString(6)); //6789
b). public String substring(int begin, int end):
System.out.println(s.subStrin(5,8)); //567
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
* This operation can result in the StringBuffer with the specified length. The
Extra characters will be removed.
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
2nd 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.
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.
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
It defines a list of named constants.This is interdused in 1.5 version.
Java enum is powerful than c,c++ enums because java enum may
contain methods ,constructors and instance variables in addition to
constants.But c,c++ enum contain only constants.
Example:
enum Month
{
Jan,Feb,Mar,Apr…….;
}
Example:
enum Beer
{
KF,RC,H5,H2,…….;
}
No variables in enum.At the end ( ; ) no need to specify (optional)
Use:we can reduce the number of bugs by using enumeration because We
are providing a set of predefined values for the variables.
Enum Example code:
enum Month
{
Jan,Feb,Mar,Apr;
}
class Sample
{
public static void main(String arg[])
{
Month m=Month.Mar;
System.out.println(m); // Mar
}
}
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.
Enum Month
{
JAN,FEB;
public static void main(String a[])
{
Month[] m=Month.values();
for(Month m1:m)
System.out.println(m1);//JAN,FEB
}
}//Save:Month.java, Run:Java Month
So just like a normal class, we can run enum also.
System.out.println(Month.JAN==Month.FEB); //false
So we can compare the constants declared in enum. Otherthan ‘=
=’operators, remaining <=, >=,<,> will gave CTE.
Duplicate constants can’t be declared. So, constants are unique.
enum Month
{
Jan,Feb,Jan; //invalid,CTE:Jan already defined
}
But
enum Month
{
Jan,Feb,JAN; //valid, due to case sensitive jan!=JAN
}
Comparable Interface and clonable interface
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;
}
P
artially 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
try , catch , finally
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
Control Flow in try, catch, finally block :
try
{
Stmt1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
finally
{
Stmt 5;
}
Stmt 6;
‘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.
java All Reader classes
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.readLine();
}
br.close();
}
java All writer classes
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();
}
}
while inserting the data ,the programmer is responsible to insert separately
the line separator(\n).
When we are reading the data ,we have to put inside the char array.
we should know the size of the array in advance otherwise it will be a
probleam .
we have to read the data charater by charater which increase the number of
IO operations and decreses the performance of the system.
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();
}
}
{
Dog d1=new Dog();
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);
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
Number Format class
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 default constructor is always no argument constructor.
The access modifier of the default constructor is sane as access modifier of
the class (public & default only).
The default constructor contains only one statement which is ‘no arg call to
super class Constructor ‘ (super();)
b) Programmer written code:-
class Test {
Test(int i)
{
System.out.println(“constructor”);
}}
Compiler generated code:-
class Test {
Test(int i)
{
super();
System.out.println(“constructor”);
}}
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
The problems of legacy collections:
There is no type safety for the collection objects.
Suppose we are constructing array list object to that we can add any kind of
object.
Suppose if our requirement is to add only String objects,by mistake if we are
adding any non string objects,still the compiler compiles the code without
raise any problem.
But at the time of retrieving these objects we may get class cast exception.
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);
Hence these is no type safety for the collection objects.
While retrieving the elements from the collection object we should explicitly
perform type casting even though we know the type of elements present in
the collection.
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.
i.e no need to perform explicit type casting so,generics are nothing but
parametrized collections because by using this we can define the type
parameter.
To add any kind of objects to the ArrayList we can declare generic arraylist
as follows
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.
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.
Connection-oriented. TCP sets up a connection with a remote system by
transmitting control information, often known as a handshake, before
beginning a communication. At the end of the connect, a similar closing
handshake ends the transmission.
Continuous-stream. TCP provides a communications medium that allows for
an arbitrary number of bytes to be sent and received smoothly; once a
connection has been established, TCP segments provide the application layer
the appearance of a continuous flow of data.
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.
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
http://java.sun.com/index.html#chapter1
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.*;
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
Certain header fields are accessed frequently. The methods:
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.
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.
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 TCP SOCKET CLASSES :
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.
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.*;
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;
}
Struts Flow
When we deploy our application in the server, at first the container reads the
information from web.xml file.Here ActionServlet object will be created and
init() of ActionServlet will be called.Here ActionServlet is the backbone to the
whole application.
When client send a rewuest using .jsp extension , getters() and reset() of
FormBean will be called. When client fill the form and press on submit
button, then setters() and validate() will be called.
If the data is not valid ,then the form redirects to another page which is
specified in struts-config.xml file. If the data is valid , then only Action class
object will be created.
In Action class , have execute() which have return type of ActionForward. We
can specify the business logic in Model and provide that object in execute().
After completion of business logic execution , then it forwards to another
page ( either success or failure) , whichis specified in struts-config.xml file.