Java Full Notes
Java Full Notes
Java and internet: -Hotjava is a web browser that runs applets on internet. So,
java is strongly connected with the internet. Now, user can easily compile
applets program on the internet& run them locally by using a web browser like
hotjava. They can even use this web browser to download & applet located in a
remote computer. Anywhere in the internet in the world and run the application
on its computer by using the browser.
Father of java - James Gosling
There is another important application that is
internet user can also setup their website containing java applet that can be
used another remote use of internet. This ability of java that had made popular
in the world.
JSL (java standard library): -It is also called „API‟ (application program
interface). It includes 100 of classes and methods grouped into several
function packages the most commonly used packages are: -
I. Language support interface (java LAN): -It is beneficial
appearance of java. It is by default package of java. A collection
of classes and methods required for implementing basic features
of java.
II. Utility package (java utility): -A collection of classes to provide
utility function such as date and time vector class is related to
java.util package.
III. Input/ output package (I/O package): -A collection of classes
required for input/ output manipulations.
IV. Networking package (java.net): -A collection of classes for
communicating with other computer through internet on network.
V. AWT (Abstract window tool/kit): - It contain classes that
implements platform independent GUI.
VI. Applet package (java.applet): -It is smallest package of java. It
includes a set of classes that allows us to create java applet.
Overview of java: - Programmers can develop two types of java program that
is : -
I. Stand alone applet: -They are the programs written in java to carry out
certain task to stand alone local computer. These are two steps: -
a) Compiling source code into byte code by using java compiler (Javac).
b) Executing byte code by using java interpreter (java).
II. Web applet: -Applet are small java program which we can develop
simple animated, graphics, to complex game and utilities we can also
use web enabled java compatible browser like internet explorer for
running applet. If applet viewer is not available.
Father of java - James Gosling
JVM (java virtual machine): -All language compilers translate source code
into machine code for specific computer. Java compiler produces an
intermediate code known as byte code for a machine that doesn‟t exit but it is
known as java virtual machine.
It is a simulated computer within the computer and does all
the method functions of real computer. Virtual machine code is not an actual
machine code the machine code is generated by java interpreter by acting as
intermedia between virtual machine and real machine.
Programming structure with java: -
I. Documentation section (optional): -It comprises a set of comments
lines giving the name of program and other detail.
a. // this program -Single line comment
b. /* java program*/ -Multiline comment
c. /** program description**/ - Documentation description
comment.
II. Package statement (optional): -It declares packages name and
inform the compiler that defines in a program belongs to its package.
III. Import statement(optional): -It is similar to hash (#) include in C
and C++. If we use import statement in java.
IV. Interface statement (optional): -It is like a class but include a group
of method declaration. It is used only when the access the concept of
multiple inheritance in a program implementation. It is a new
concept in java.
V. Class definition (optional): -Java program may contain multiple
class definition. Classes are the primary and essential element of
java program.
These classes are used to map the objects of
real world problems. The number of classes used depends on the
complexity of the problem.
VI. Main method class (essential): -Since, every java stand alone
program requires a main method as its starting point then this class
is essential part of java program.
The main method create object of various classes and
establishes communication between them on reaching the end of
main, the program terminates and control passé to the operating
system.
I. Keyword: -
abstract, case, const, else, float, int, if, null,
protected, public, private, static, try, catch, throw, finally, thread,
boolean, cast, continue, switch, while, for, do, stands, break,
implements, interface, operator, super, var, default, true, false,
future, import, long, outer, rest, void, byte, char, final, generic,
inner, negative, package, return, synchronized, transient, volatile,
byvalue, class, double, finally, goto, instanceof, new, delete, short,
this, strifp, assert, enum and etc.
II. Identifier: - They are programmer design tokens. They are used for
many classes, methods, variables,objects, labels, packages&interfaces in
a program.
III. Literals: -In java, literals are a sequences of characters (digits, letters
and other special character) that represent constant values to be stored in
variables.
Java specifies five major types of literals that is
1. Integer literals 2. Floating point literals
3. Character literals 4. String literals
5. Boolean literals
IV. Separator: -They are symbols used to indicate where groups of codes
are divided & arrange they basically defined the shape &function of our
code.
Variable: -
Scope of variable: -In java, variable are actually classify into three
types that is: - a.
Instance variable b. class variable c.
Local variable
Instance & class variable are declared inside a class.
Instance variable are created when the objects are instantiated. So, they
are associated with the objects. They take different value for each object.
On the other hand, class variable are global to
a class & belongs to the entire set of objects that class creates. Only one
memory location is created for each class variable. The variables
declared & use inside program block that are define between an opening
& ending curly brasses { }.
Father of java - James Gosling
Note: - 1. These variables are visible to the program only from the beginning in
the program block to the end of the program block.
2. Java doesn‟t support the global variable.
Data type: -
Data type
Character type: -The character type in java required two byte for storage as
compared to char in c and c++ because java user Unicode to represent
character. It can hold only a single character. The range of char is from 0 to
6555. There is no negative character.
Boolean type: -It is used when we want to test a particular condition during
the execution of a program and performing logical operations. It can only two
possible values i.e. true or, false. The keyword to represent Boolean type is
Boolean.
Note: -1.The two values true and false have been declared as keyword in java
language. It uses only one bit for storage.
2. Java uses a new data type. i.e byte it holds one byte memory space
for location . The range of byte type is -128 to +127 and 0 to 255
Father of java - James Gosling
Symbolic constant:
Syntax: - final type symbolic_name= value;
Or, static type symbolic_name= value;
Ex-
Final float PI=3.14;
Static double=3.14;
Write a program to find the area of circle, if enter the radius.
Static float PI = 3.14;
class circle
{
public static void main (string args[ ])
{
int r;
double area = PI*r*r;
System.out.println(“area=”+area);
}
}
Write a program to find the sum of two number using command line.
class sum
{
Public static void main (string args[ ])
{
int x,y,z;
x= Interger.parseInt (args[0]);
y= Interger.parseInt (args[1]);
z=x+y;
System.out.println (“sum of entered number=”+z);
}
}
Type casting: -The process of converting one data type to another data type is
called type casting.
Ex- int to float, float to int.
Syntax:- Data type var1= (type) variable;
int v;
float long=(float) v;
Casts that results in no lose of information:-
From to
i. Byte short, char, int, long, float, double
ii. Short int, long, float, double
iii. Char int, long, float, double
iv. int long, float, double
v. long float, double
vi. float double
Father of java - James Gosling
Standard default value: -In java, every variable has a default value. If
we don‟t initialize a variable when it is first created then java provides
default value that variable type automatically.
Type of variable default value
i. Byte 0 (byte)
ii. Short 0 (short)
iii. int 0
iv. long 0L
v. float 0.0f
vi. double 0.0d
vii. char null character
viii. boolean false
ix. reference null
Operator in java: -
1. Unsigned right-shift operator (>>>): -It is also called unsigned shift
operator with zero fill. It works like right-shift operator (>>) but fills
zero from the left.
2. Instance of operator: -It is an object reference operator and returns to if
the object on the R.H.S. This operator allows us to determine whether
the object belongs to a particular class or, not.
Ex- student instance of class BCA.
It is true if the object student belongs to the class BCA otherwise
it is false.
3. Dot operator: -It is use to access the instance variable and methods of
class object.
Ex- student.age // reference to the variable age.
Note: -It is also use to access classes and sub-packages from a
package.
Import.java.long.math;
Scanner method: -
Write a program to input two numbers and print their sum using
java.util package.
import java.util.scanner;
class add
{
public static void main (string args[ ])
{
int x,y,z;
scanner s=new scanner (System.in);
System.out.println(“input the 1st number”);
x=s.nextInt ( );
System.out.println(“input the 2nd number”);
y=s.nextInt ( );
z=x+y;
System.out.println(“sum=”+z);
}
}
Write a program to input two numbers and print their sum using
java.util package.
import java.util.scanner;
class area
{
public static void main (string args[ ])
{
Double x, y, area;
scanner s=new scanner (System.in);
System.out.println(“input the 1st number”);
x=s.nextDouble ( );
System.out.println(“input the 2nd number”);
y=s.nextDouble ( );
area=x*y;
System.out.println(“Area=”+area);
}
}
Father of java - James Gosling
B
Fig: -Representation of single inheritance
II. Multilevel inheritance: -In this type of inheritance one class inherit
from a sub-class, thereby making this derived class the base class for the
new class.
A
C
Fig: -Representation of multilevel inheritance
III. Hierarchical inheritance: -In this type of inheritance, one base class is
inherited by many sub-classes that is one super class and many sub-
classes.
A
B C D
Fig: -Representation of hierarchical inheritance
Father of java - James Gosling
IV. Hybrid Inheritance: -It is a combination of single and multiple
inheritances. Hybrid inheritances can be achieved in java by using an
interface, If we try to achieve it using only classes then it will give an
error. A
B D
C
Fig: -Representation of hybrid inheritance
Syntax: - class <sub-class name>extends <super classes>
{
var declearation;
method decleartion;
}
Ex - class BCA extends MCA
{
int x, y;
}
Extends: -The keyword extends signify that the properties of the super class
are extended to the sub-class. It indicates that we are making the sub-class. It
indicates that we are making a new class which inherits the property of existing
class.
WAP to show the concept of single inheritance.
class sum
{
void calculate (int x, int y)
{
int z;
z = x +y;
System.out.println (“sum = ”+z);
}
}
class add extend sum
{
public static void main (string args[ ])
{
add A1 = new add ( );
A1.calculate(10,15);
}
}
Father of java - James Gosling
WAP to show the concept of multilevel inheritance.
class sum
{
void reverse (int x)
{
int mod, rev = 0;
for ( ;num>0; num=num/10)
{
mod = num%10;
rev = (rev*10)+mod;
}
System.out.println (“reverse = ”+rev);
}
}
class ram extend sum
{
int sum (int x, int y)
{
return(x + y);
}
ram r = new ram;
r.reverse (521);
}
class rahul extend ram
{
public static void main (string args[ ])
{
rahimr1 = new rahim ( );
r1.sum(100,15);
}
}
Using super keyword with constructor/(sub-class constructor method): -
A sub-class constructor is used to construct the instance variable of both the
sub-class and the super class. The sub-class constructor uses the keyword
superto invokethe constructor method of the super class. The keyword super
is used in the following condition: -
I. Super may only be used within a sub-class constructor method.
II. The call to super class constructor must appear as the first statement
within the sub-class constructor.
III. The parameter in the super called must match the order & type ofthe
instance variable declared in the super class.
Father of java - James Gosling
WAP to illustrate the concept of single inheritance through the super
keyword.
class room
{
int l, b;
room (int x, int y)
{
l = x; b = y;
}
int area()
{ return(l * b); }
}
class guest extend room
{
int h;
guest (int x, int y, int z)
{
super (x, y);
h = z;
}
int volume ()
{ return(l * b * h); }
}
class test
{
public static void main (string args[ ])
{
guestg = new guest (1, 2, 3);
int a = g.area( ); // super class mehtod
int v = g.volume ( ); // sub class method
System.out.println (“area = ”+a);
System.out.println (“volume= ”+v);
}
}
Visibility control: - It is possible to inherit all the members of a class by a
sub-class using the keyword extends.The variable & methods of a class are
visible everywhere in the program. However, it may be necessary in some
situation to restrict the access to certain variable and method from outside the
class.
We can achieve this in java by applying visibility modifiers to
instance variables and methods. They are also known as access modifier. Java
provides basically several types of modifier that is public, private, protected
and package (friendly access).
Father of java - James Gosling
WAP to show the concept of hierarchical inheritance.
class name
{
void sum (double x, double y)
{ System.out.println (“sum= ”+(x +y)); }
}
class monu extend name
{
monu m = new monu;
m.sum (5.7, 3.2);
}
import java.util.*;
class prakash extend name
{
public static void main (string args[ ])
{
int num, mod, rev =0;
System.out.println (“enter the number”);
scanner s = new scanner ( );
num = s.next int ( );
for ( ;num>0; num= num/10)
{
mod = num % 10;
rev = (rev*10)+ (mod*mod*mod);}
}
if (rev == num)
System.out.println (“number is Armstrong”);
else
System.out.println (“number isn't
Armstrong”);
prakash p = new prakash ( );
p.sum (10,20);
}
}
Visibility control provides different levels of protections.
1. Public: - In public access specifier, any variables or, method is visible to
the entire class in which it is define. Members declared as public are
accessible anywhere in the class and they are also inherited by all sub-
class.
2. Private: -A private member of class is accessible only to the member of
class itself. It is visible between public access. It is not directly access by
the object of a class. They cannot be inherited by sub-class. The main
purpose of private access specifier to hide data.
Father of java - James Gosling
3. Protected: - A protected member of a class is accessible to member of
that class and member of its sub-class. It can also be access by member of
other class in the same package.
4. Package: -It is also known as default access. If we do not specify any of
the access specifier then the scope is friendly. A class, variable or, method
that has friendly access is accessible to all the classes packages.
In java, friendly is not a keyword. It is a term that is
used for the access level when no access specifier has been accessified.
Note:-packages acts as containers to group related classes together. It is
similar to a source file in C.
WAP to show the concept of hybrid inheritance.
class raj
{
void division (int x, int y)
{
System.out.println (“sum = ”+(x/y));
}
}
class raja extend raj
{
rajar = new raja;
r.division( 10, 5);
void multiply (int x)
{
System.out.println (“square = ”+(x *x));
}
}
class prem extend raj
{
prem = p = new prem( );
void sum (int a, int b)
{
System.out.println (“sum =”(a+b));
}
p.division (50, 10);
}
class virat extends prem, raja
{
public static void main (string args[ ])
{
virat v = new virat ( );
v.multiply (10);
v. sum (5, 10);
}
}
Father of java - James Gosling
Final class: - Sometimes we may like to prevent class being further sub-class
for security reasons. A class that cannot be sub-classes is called a final sub-
class. That is cannot be inherited. It is achieved in java by using the keyword
in final.
Note: -
1. Any attempted to inherit final classes will produce an error that is
the compiler will not allow it.
2. Declaring a class final prevents any un-wanted extensions to the
class.
For Ex-
Final class X
{
……………….
}
class Y extends class X //illegal.
{
……………….
} // error cannot sub-class.
Father of java - James Gosling
Finalizer method: - As we known that a constructor method is used to
initialize an object when it is declared this process is known as initialization.
Similarly java support a concept called finalizer which is just opposite to
initialization.
We know that java run time is an automatic garbage
collection system. It automatically passes of the memory resources used by
the object but objects may hold other non-object resources, such as file
descriptions, window system fonts. The garbage collector cannot free these
resources.In order to free these resources we must use a finalizer method. It is
similar to destructor in c++.
The finalizer method is simply finalized & can be added to
any class. Java calls that method whenever it is about to reclaim the space for
that object. The finalize method should explicitly task to be perform.
Syntax: -
finalize ( )
{
…………….. // body
}
Abstract classes & methods: -
An abstract class is a class that contains zero or, more abstract. It allows
the implementation of a behavior in different ways. An abstract method is a
without method body. An abstract method is written when the same method
has to perform different task depending on the object calling it.
Both the abstract classes an abstract method should be
declare by using keyword abstract. The classes & method declare using the
abstract modifier is incomplete.
Abstract means ignoring the non-essential detail of
an object & concentrating own its essential detail.
Limitation: -
I. An abstract class cannot be instantiated because the class is
incomplete.
II. Sub-class must override the abstract method of the super class.
III. A class has one or, more abstract method.
IV. A class inherits an abstract method & does not override it.
V. The abstract modifier is the opposite of the final modifier.
VI. An abstract class must be sub-class whereas final class cannot be sub-
class.
Father of java - James Gosling
WAP to illustrate the concept of abstract class and method.
import java.lang.*;
abstract class check
{
abstract void calculate (double x);
}
class test extend check
{
void calculate(double x)
{
System.out.println (“square =”+(x*x));
}
}
class find extend check
{
Void calculate (double x)
{
System.out.println (“root =”+math.sqrt(x));
}
}
Array
Array: - Array is a collection of similar elements. Array is a pre-defined class
present in java.lang package. It is a final class which cannot be inherited. In
java array holds both primitive data type as well as object references.
In java when the programmer develop has to follow three
steps: -
I. Array declaration: -
int arr [ ]; here „arr ‟is a reference of
at the declaration time of array. Programmers never specify the size of
the array.
II. Array Construction: - arr= new int [5]; at the construction of the
array programmer is bound to specify the size of the array.
String
String: -In java, string is a pre-define class is in java.lag package. It is a final
class & it is immutable in nature.
In java, String is not a character array & is not null
terminated. String class is used to string of fixed length.
Syntax: - string <string_name>
<string_name>= new string (“string”);
Ex- string name;
name = new string (“Rahul”);
or,
string name = new string (“suman”);
WAP to show the concept of constructing one string from another.
class suman
{ public static void main(String args[ ])
{ string ch= “BCA”;
string s1 = new string (ch);
string s2 = new string (s1);
system.out.print(s1);
system.out.print(s2);
}
}
String array : -We can also create & use array that contains string.
Ex- string arr[ ] = new string [5];
Method Description
1. s1.setcharAt It modifies the n character to x.
2. s1.append(s2) It appends the string s2 to s1 at the end.
3. s1.insert(N,s2) It inserts the string s2 at the position N of the
string s1.
4. s1.setLength(n) It sets the length of the string s1 to n.
i. If n less than s1.length() then s1 is truncated.
ii. If n greater than s1.length() then zero's are added to s1.
Father of java - James Gosling
String buffer constructor: -It defines four constructors: -
I. StringBuffer( ): -It is the default constructor which are no
parameter, it reserve rooms for 16 character without re-allocation.
II. StringBuffer(int size): -It accepts an integer argument that explicitly
set the size of the buffer.
III. StringBuffer(string str): -It accepts a string argument that sets the
initial content of the string buffer object & reserve rooms for 16 more
character without re-allocation.
IV. StringBuffer(Charsequence chrs): -It creates an object taht
contains the character sequence content in char.
Method description
I. delete( ) It delete a sequence of character from
specified string.
II. deleteCharAt( ) It delete the character at the index
specified by LOC(lines of code). It
returns the resultive StringBuffer
objects.
WAP to show the concept of delete ( ) & deleteCharAt ( ).
class polo
{
public static void main (string args[ ])
{ StringBuffer sb= new StringBuffer("This is a text");
sb.delete(4,7);
System.out.println("after delete"+sb);
sb.deleteCharAt(0);
System.out.println("after delete charAt"+sb);
}}
Father of java - James Gosling
import java.util.*;
class sunit
{ public static void main( String args [ ])
{
Vector list = new Vector ();
int length = args.length;
for (int i=0; i<length; i++)
{ list.addElement(args[i]); }
list.insertElementAt ("Champion",2);
int size= list.size( );
String s[ ] = new String [size];
list.CopyInto(S);
System.out.println("list of elements =");
for (int i=0; i<size; i++)
{System.out.print(s[i]);
}
}}
Note: -This program represents the use of array, string & vector.
Wrapper Class: -It form a very important part of the java.lang package. They
encapsulate simple primitive type in the form of classes. It is useful whenever
we need object representation of primitive types.
In addition to make primitive types, behave like object, then
we have to prefer wrapper classes. It also provides method for converting
string to various data types and also type specification methods.
All numeric wrapper classes extend the abstract super class
number. There are basically six numeric wrapper classes - double, float, byte,
short, long, Integer.
The wrapper class in java.lang are as well as follows: -
Primitive data types Wrapper class
i. byte Byte
ii. char Character
iii. int Integer
iv. long Long
v. float Float
vi. double Double
vii. boolean Boolean
viii. short Short
Father of java - James Gosling
Write a program to show the concept of wrapper class & its method.
class test
{
public static void main( String args [ ])
{
String S = args[0];
Byte b = Byte.Valueof(s);
Short s1 = Short.Valueof(s);
Integer i = Integer.Valueof(s);
Long l = Long.Valueof(s);
System.out.println ("outputs are as follow :");
System.out.println (b);
System.out.println (s1);
System.out.println (i);
System.out.println (l);
}}
Method of wrapper class: - The wrapper classes have a number of unique
methods for handling primitives data types & objects.
1. Converting primitive numbers to object numbers using constructor method.
constructor calling conversion action
a. Integer int val=new Integer(i); primitives integer to integer objects
b. Float flaot val=new Float(f); primitives float to float objects
c. Double double val=new Double(d); primitives double to double objects
d. Long long val=new Long(l); primitives long to long objects
2. Converting object number to primitives number by using type value( )
method
constructor calling conversion action
a. int i=intvar.int_value( ); Object to primitive integer
b. float f=floatvar.float_value( ); Object to primitive float
c. double d=doublevar.double_value( ); Object to primitive double
d. long i=longvar.long_value( ); Object to primitive long
3. Converting number to string by using to String( ) method
constructor calling conversion action
a. str = Integer.toString(i); Primitive integer to string
b. str = float.toString(f); Primitive float to string
c. str = double.toString(i); Primitive double to string
d. str = long.toString(i); Primitive long to string
4. Converting string object to numeric object by using the static method
Valueof ( )
constructor calling conversion action
a. Integer var=Integer.Valueof(str) convert a string to integer object
b. float var=Float.Valueof(str) convert a string to float object
c. Double var=Double.Valueof(str) convert a string to double object
d. Long var=Long.Valueof(str) convert a string to long object
Father of java - James Gosling
5. Converting numeric string to primitive numbers by using parseInt( ) method
constructor calling conversion action
a. int i =Integer.parseInt(str); converts string to primitive integer
b. long i =Long.parseLong(str); converts string to primitive long
Package:-
Java provides a powerful group related classes & interfaces together in
a single unit is called packages.
In other word, packages are group of classes, interfaces &
sub-packages. It provides convenient mechanism for managing a large group
classes & interfaces.
Note: -1. Package is similar to class library in other languages.
2. In fact, Packages act as containers for classes.
Benefits of packages: -
By organizing our classes into packages, we achieve
the following benefits.
I. The classes contained in the packages of other programs can be easily
re-used.
II. In packages classes can be unique compared with classes in other
packages it means that two classes into different packages can have the
same name they may be referred by their fully qualified name
comprising the package name & the class name.
III. It provides a way to „Hide‟ classes thus preventing other program or,
packages from accessing class that are meant for internal use only.
IV. Package also provides a way for separating design from coding.
V. First we can design classes & decide their relationship & then we can
implement the java code needed for the methods.
VI. It is possible to change the implementation of any method without
affecting the rest of the design.
Java
Using a Package: -
package mypackage;
public class BCA
{
public void show( )
{
System.out.println(“Have a nice Day”);
}
}
This source file should be named BCA.java & stored in the sub-
directory mypackage. Now, Compile this java file the resultant
BCA.class will be store in the same sub-directory.
Import mypackage.BCA;
class Demo
{
public static void main (string args[ ])
{
Bca b = new Bca ( );
b.show( );
}
}
It is a simple program that imports the class Bca from the mypackage.
The source file should be saved as demo.java and then compile. The source
file and the compile file would be saved in the directory of which
mypackage was a sub-directory. Now, we can run the program & obtain the
result.
Father of java - James Gosling
Multithreading: -
Thread: -It can be defined as the sequential flow of control
within a program. It is not a program on its own but runs within a program.
Thread also has a begging, sequence, and end. Every
program has at least one thread that is called the primary thread. We can
create more threads when necessary infect, all main programs are the
example of single thread program.
} End
start start
1. By creating a thread class: - Define a class that extend Thread class &
override its run( ) method with the code required by the thread.
2. By converting a class to a thread: - Define a class that implements
runnable interface. It has only one method run( ) that is to be define in the
method with the code to be executed by the thread.
Extending the Thread class: - we can make our class runnable as thread by
extending the class java.lang.thread. It gives us access to all the thread method
directly. It includes the following steps: -
I. Declare the class as extending the Thread class.
II. Implement the run( ) method that responsible for executing the
sequence of code, that the thread will execute.
III. Create a thread object & call the start( ) method to initiate the thread
execution.
A. class X extends Thread
{
………………….. // statements
…………………..
}
B. public void run( )
{
………………….. // thread code
…………………..
}
when we start the new thread, java calls the
thread‟s run( ) method. So it is the method where all the action
takes place.
Father of java - James Gosling
C. Starting new thread: -To actually create & run an instance
of our Thread class. We must write the following statement.
X x1= new X( );
x1.start( ); // invokes run( ) method
WAP to create threads by using the Thread class & also execute them.
class x extends Thread
{
public void run( )
{
for (int i=1; i<=5; i++)
{ System.out.println (“\t From thread x: i=”+i);
}
System.out.println (“Exit from x”);
}
}
class y extends Thread
{
public void run( )
{
for (int j=1; j<=5; j++)
{ System.out.println (“\t From thread y: j=”+j);
}
System.out.println (“Exit from y”);
}
}
class y extends Thread
{
public void run( )
{
for (int k=1; k<=5; k++)
{ System.out.println (“\t From thread z: k=”+k);
}
System.out.println (“Exit from z”);
}
}
class test
{
public static void main(string args[ ])
{
new x( ).start( );
new y( ).start( );
new z( ).start( );
} }
x x1=new x ( ); x1.start( ); in place of new x( ).start( );
Father of java - James Gosling
Stopping & blocking a thread: -
Stopping a thread: - Whenever we want to stop a thread from running for
the we may do so b calling it stop( ) method.
For Ex- x1. Stop( );
This statement causes the thread to make to the dead state. A thread will
also make to the dead state automatically when it reaches the end of its
method.
Note: - The stop( ) method may be used when the pre-mature death of a
thread is desired.
Blocking a thread: - A thread can also be temporarly suspended or,
blocked from entering to the runnable & sub-sequently running state by
using either of the following threads methods.
i. sleep( ):- It is blocked for a specified time.
ii. suspended( ): - It blocked until further orders.
iii. wait( ): - It blocked until certain condition occur.
This method causes the thread to go into the blocked
(or, not runnable) state. The thread will return to the runnable state when
the specified time is elapsed in the case of sleep( ), The resume( ) method
is invoked in the case of suspend. The notify method is called in the case of
wait( ) method.
Life cycle of thread: -
Dead
Fig: - The run( ) method terminates
New born
start( ) stop( )
yield( )
running thread
runnable thread
The current thread: - Every program that we crate has at least one thread. We
can access this thread by using the currentThread( ) method of the thread class.
This method is static method & hence, we do not have to create an
object of the Thread class to invoke the method.
Object
Throwable
Error Exception
Syntax: - i. try
{
…………….}
finally
{
……………}
ii. try
{
…………..}
catch(……….)
{
……………}
catch(……….)
{
……………}
finally
{
……………}
WAP to show the concept of try, catch & finally block exception handling.
class error
{
public static void main(string args[ ])
{
int a[ ] = { 5,10};
int b = 5;
try
{
int x = a[2]/b-a[1];
}
catch(ArithmeticException e)
{ System.out.println(“division by Zero”);
}
catch(ArrayindexOutOfBoundsException e)
Father of java - James Gosling
{ System.out.println(“Array Index Error”);
}
catch(ArrayStoreException e)
{ System.out.println(“Wrong Data Type”);
}
finally
{
int y = a[1]/a[0];
System.out.println(“y=”+y);
}
}
}
Throw statements: -We may want to throw an exception when a user enters a
wrong login Id or, Password. We can use the throw statement to do so. The
throw statement takes a single argument, which is an object of the Exception
class.
Exceptions are thrown with the help of the “throw” keyword. The
“throw” keyword is used to indicate that an exception has occurred. The
operand of throw is an object of any class that is derived from the class
“Throwable”.
Syntax: -
throw Throwable instance;
EX-
throw Throw-object;
The compiler gives an error it the object Throw object does not belong
to a valid Exception class. The throw statement is commonly used in
programmer defined exceptions.
class ABC
{
public static void main (string args[ ])
{
try
{
if (flag < 0)
}
throw new NullPointerException ( );
}
}
Throws Statements: - If a method is capable of raising an exception that if
does not handle, it must specify that the exception has to be handled by calling
method. This is done using the throws statement. The throws statement is used
to specify by the method.
Father of java - James Gosling
WAP to show the concept of thrown
class ThrowsExcep
{
public static void main(string args[ ])
{
ThrowsArithmeticException
System.out.println(“Inside main”);
int i=0;
int j = 40/i;
System.out.println(“The statementis not primted”);
}
}
Born
Begin
(load applet) stop( )
Dead End
Exit of Browser
Fig: - An applets state transition diagram
Every java applet inherit the set of default behavior from the
applet class as the result, when an applet is loaded it undergoes a series of
changes in its state. The applet state include: -
1. Born or, initialization state
2. Running state
3. Idle state
4. Dead state or, destroyed state
1. Born State: - Applet enter the initialization state when it is first loaded. This is
archived by calling the init( ) method of Applet class. The applet is born.
At this state we may to do the following, if required: -
a. create object needed by the applet
b. setup initial value
c. load images or, font
d. setup colors
The initialization occurs only once in the applet‟s life cycle.
To provide any of the behavior mention above, we must overwrite the init( )
method.
public void init( )
{
……………….. // work to perform
}
Father of java - James Gosling
2. Running State: - Applet enters in the running state when the system calls the
start( ) method of Applet class. This occurs automatically after the applet is
initialize. Starting can also occur if the applet is already in “stopped” (idle)
state.
For Ex- we may leave the webpage containing the applet
temporarily to another page & return back to the page. It again starts the applet
run. Unlike, init( ) method, the start( ) method may be called more than once.
We may override the start( ) method to create a thread to control
the applet.
public void start( )
{
……………… // Action
}
3. Idle or, stopped state: - An applet becomes idle when it is stop from running.
Stopping occurs automatically when we leave the page containing the currently
running applet. We can also do so by calling the stop( ) method explicitly.
If we use a thread to run the applet, then we must the use stop( )
method to terminate the thread. We can archive this by overriding the stop( )
method.