You are on page 1of 81

Chapter-1

Core Java

Lecture-1:

INTRODUCTION TO JAVA

Java is a general-purpose Object Oriented programming language

developed by Sun Microsystems of USA in 1991.Originally called

Oak by James Gosling, one of the inventors of Java.

Java features:

 Compiled and Interpreted

 Platform independent and portable

 Object Oriented

 Robust and Secure

 Distributed

 Familiar, Simple and small

 Multithreaded and Interactive


 High Performance

 Dynamic and Extensible

Java Environment:

Java environment include a large number of development tools and

hundreds of classes and methods.

The development tools are part of the system known as Java

Development Kit(JDK) and the classes and methods are part of

Java Standard Library(JSL),also known as the

application Programming Interface(API).

Java Development Kit (JDK):

The Java Development Kit comes with a collection of tools that are

used for developing and running Java programs. They include

 appletviewer (for viewing Java applet)

 javac(Java Compiler)

 java(Java Interpreter)

 jdb(Java debugger)

 javadoc(for creating HTML documents)


 javah(for C header file)

Application Programming Interface(API):

The java standard library or API includes hundred of classes and

methods grouped into several functional packages, most common

packages are

Language support package(java.lang.*)

Utilities package(java.util.*)

Input/Output package(java.io.*)

Networking package(java.net.*)

Databases package(java.sql.*)

Process of Building & running java application program:


Text editor

java source code javadoc HTML file

javac

java class file javah header file

java jdb

java program output


Fig.1.1:Program development process

Types of java program:

Java program can be developed in two ways as follows

 stand alone application

 web applets

Stand alone application can be executed by java interpreter and we

applets can be executed by java enabled web browser for example

internet explorer.

Format of Java program:

class classname

public static void main(String args[ ])

System.out.println (“java is better than C++”);

}
}

Java Virtual Machine (JVM):

Java compiler produces an intermediate code known as byte code

for a machine that does not exist. This machine is called the java

virtual machine(JVM) and it exists only inside the computer

memory.

It is a simulated computer and does all major functions of a real

computer.

Process of Compilation:

java source code java compiler byte code

Virtual machine

Process of converting byte code into machine code:

byte code java interpreter machine code

real machine

The virtual machine code is not machine specific.

DATA TYPES IN JAVA


Data type specify the size and type of values that can be stored.
Every variable in java has

a data type.

Data type can be divided into two types as follows

 primitive data type

 non-primitive data

Primitive data type can be divided into two types as follows

 Numeric

 Non Numeric

Numeric is divided into integer and floating point.

Integer is divided into byte, short, int, long

Floating point is divided into float and double.

Non-numeric can be divided into char(character) and Boolean.

Non-primitive data type can be divided into 3 types as follows

 classes

 interfaces

 arrays
Different types can be described in table as follows:

Table 1.1.Data Type

Data Type Size Minimum Maximum


value value
byte 1 byte -128 127

short 2 byte -32,768 32,767

int 4 byte -2,147,483,648 2,147,483,647

long 8 byte

float 4 byte 3.4e-038 3.4e+038

double 8 byte 1.7e-308 1.7e+308

char 2 byte

boolean 1 bit

VARIABLE
A variable is an identifier that denotes a storage location used to
store a data value. A

variable may take different values at different times during the


execution of the program.

Variable names may consist of alphabets, digits, underscore (_)


and dollar character,

Subject to the following conditions:

 They must not begin with a digit.

 Upper case and lower case are distinct.

 It should not be a keyword.

 White space is not allowed.

 Variable names can be of any length.

OPERATORS

They are used to manipulate primitive data types. Java operators


can be classified as unary, binary, or ternary—meaning taking one,
two, or three arguments, respectively.
A unary operator may appear before (prefix) its argument or after
(postfix) its argument. A binary or ternary operator appears
between its arguments.
Java operators fall into eight different categories:
Assignment arithmetic, relational, logical, bitwise,
compound assignment, conditional, and type.
Assignment Operators =
Arithmetic Operators - + * / % ++
--

Relational Operators > < >= <= == !=

Logical Operators && || & | ! ^

Bit wise Operator & | ^ >> >>>

Compound Assignment Operators += -= *= /=


%=
<<= >>= >>>=

Conditional Operator ?:

Lecture-2:

ARRAYS

An array is a group of homogeneous data items share a common

name. The java array enables the user to store the values of the

same type in contiguous memory allocations. Arrays are always a


fixed length abstracted data structure which can not be altered

when required.

The Array class implicitly extends java.lang.Object so an array is


an instance of Object.

Advantages of Java Array:

1. An array can hold primitive types data.


2. An array has its size that is known as array length.
3. An array knows only its type that it contains. Array type is
checked at the compile-time.

Disadvantages of Java Array:

1. An array has fixed size.


2. An array holds only one type of data (including primitive
types).

Declaring an array:

Declaring an array is the same as declaring a normal variable

except that you must put a set of square brackets after the variable

type. Here is an example of how to declare an array of integers

called a.

public class Array


{
public static void main(String[] args)
{
int[] a;
}
}

An array is more complex than a normal variable so we have to

assign memory to the array when we declare it. When you assign

memory to an array you also set its size. Here is an example of

how to create an array that has 5 elements.

public class Array


{
public static void main(String[] args)
{
int[] a = new int[5];
}
}

Instead of assigning memory to the array you can assign values to


it instead. This is called initializing the array because it is giving
the array initial values.

public class Array


{
public static void main(String[] args)
{
int[] a = {12, 23, 34, 45, 56};
}
}

Using an array:
You can access the values in an array using the number of the

element you want to access between square brackets after the

array's name. There is one important thing you must remember

about arrays which is they always start at 0 and not 1. Here is an

example of how to set the values for an array of 5 elements.

public class Array


{
public static void main(String[] args)
{
int[] a = new int[5];
a[0] = 12;
a[1] = 23;
a[2] = 34;
a[3] = 45;
a[4] = 56;
}
}

A much more useful way of using an array is in a loop. Here is an

example of how to use a loop to set all the values of an array to 0

which you will see is much easier than setting all the values to 0

seperately.

public class Array


{
public static void main(String[] args)
{
int[] a = new int[5];
for (int i = 0; i < 5; i++)
a[i] = 0;
}
}

Sorting an array

Sometimes you will want to sort the elements of an array so that

they go from the lowest value to the highest value or the other way

around. To do this we must use the bubble sort. A bubble sort uses

an outer loop to go from the last element of the array to the first

and an inner loop which goes from the first to the last. Each value

is compared inside the inner loop against the value in front of it in

the array and if it is greater than that value then it is swapped. Here

is an example.

public class Array


{
public static void main(String[] args)
{
int[] a = {3, 5, 1, 2, 4};
int i, j, temp;
for (i = 4; i >= 0; i--)
for (j = 0; j < i; j++)
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}

2D arrays:

So far we have been using 1-dimensional or 1D arrays. A 2D array

can have values that go not only down but also across. Here are

some pictures that will explain the difference between the 2 in a

better way.

All that you need to do to create and use a 2D array is use 2 square
brackets instead of 1.

public class Array


{
public static void main(String[] args)
{
int[][] a = new int[3][3];
a[0][0] = 1;
}
}

CONTROL STATEMENTS
Java Control statements control the order of execution in a java

program, based on data values and conditional logic. There are

three main categories of control flow statements;

Selection statements: if, if-else and switch.

Loop statements: while, do-while and for.

Transfer statements: break, continue, return, try-catch-finally and


assert.

We use control statements when we want to change the default


sequential order of execution

Selection Statements

The If Statement

The if statement executes a block of code only if the specified

expression is true. If the value is false, then the if block is skipped

and execution continues with the rest of the program. You can

either have a single statement or a block of code within an if

statement. Note that the conditional expression must be a Boolean

expression.

The simple if statement has the following syntax:


if (<conditional expression>)
<statement action>

The If-else Statement

The if/else statement is an extension of the if statement. If the

statements in the if statement fails, the statements in the else block

are executed. You can either have a single statement or a block of

code within if-else blocks. Note that the conditional expression

must be a Boolean expression.

The if-else statement has the following syntax:

if (<conditional expression>)
<statement action>
else
<statement action>

Switch Case Statement

The switch case statement, also called a case statement is a

multi-way branch with several choices. A switch is easier to

implement than a series of if/else statements. The switch statement

begins with a keyword, followed by an expression that equates to a

no long integral value. Following the controlling expression is a


code block that contains zero or more labeled cases. Each label

must equate to an integer constant and each must be unique. When

the switch statement executes, it compares the value of the

controlling expression to the values of each case label. The

program will select the value of the case label that equals the value

of the controlling expression and branch down that path to the end

of the code block. If none of the case label values match, then none

of the codes within the switch statement code block will be

executed. Java includes a default label to use in cases where there

are no matches. We can have a nested switch within a case block

of an outer switch.

Its general form is as follows:

switch (<non-long integral expression>) {


case label1: <statement1>
case label2: <statement2>
...
case labeln: <statementn>
default: <statement>
} // end switch
When executing a switch statement, the program falls through to

the next case. Therefore, if you want to exit in the middle of the

switch statement code block, you must insert a break statement,

which causes the program to continue executing after the current

code block.

Iteration Statements

While Statement

The while statement is a looping construct control statement that

executes a block of code while a condition is true. You can either

have a single statement or a block of code within the while loop.

The loop will never be executed if the testing expression evaluates

to false. The loop condition must be a boolean expression.

The syntax of the while loop is

while (<loop condition>)


<statements>

Do-while Loop Statement


The do-while loop is similar to the while loop, except that the test

is performed at the end of the loop instead of at the beginning. This

ensures that the loop will be executed at least once. A do-while

loop begins with the keyword do, followed by the statements that

make up the body of the loop. Finally, the keyword while and the

test expression completes the do-while loop. When the loop

condition becomes false, the loop is terminated and execution

continues with the statement immediately following the loop. You

can either have a single statement or a block of code within the do-

while loop.

The syntax of the do-while loop is

do
<loop body>
while (<loop condition>);

Below is an example that creates A Fibonacci sequence


controlled by a do-while loop

public class Fibonacci {

public static void main(String args[]) {


System.out.println("Printing Limited set of
Fibonacci Sequence");
double fib1 = 0;
double fib2 = 1;
double temp = 0;
System.out.println(fib1);
System.out.println(fib2);
do {
temp = fib1 + fib2;
System.out.println(temp);
fib1 = fib2; //Replace 2nd with first number
fib2 = temp; //Replace temp number with 2nd
number
} while (fib2 < 5000);
}

For Loops

The for loop is a looping construct which can execute a set of


instructions a specified number of times. It’s a counter controlled
loop.

The syntax of the loop is as follows:

for (<initialization>; <loop condition>; <increment


expression>)
<loop body>

The first part of a for statement is a starting initialization, which

executes once before the loop begins. The <initialization> section


can also be a comma-separated list of expression statements. The

second part of a for statement is a test expression. As long as the

expression is true, the loop will continue. If this expression is

evaluated as false the first time, the loop will never be executed.

The third part of the for statement is the body of the loop. These

are the instructions that are repeated each time the program

executes the loop. The final part of the for statement is an

increment expression that automatically executes after each

repetition of the loop body. Typically, this statement changes the

value of the counter, which is then tested to see if the loop should

continue.

All the sections in the for-header are optional. Any one of them

can be left empty, but the two semicolons are mandatory. In

particular, leaving out the <loop condition> signifies that the loop

condition is true. The (;;) form of for loop is commonly used to

construct an infinite loop.

CLASSES
A class is nothing but a blueprint or a template for creating

different objects which defines its properties and behaviors. Java

class objects exhibit the properties and behaviors defined by its

class. A class can contain fields and methods to describe the

behavior of an object.

A class has the following general syntax:

<class modifiers>class<class name>

<extends clause> <implements clause>{

// Dealing with Classes (Class body)

<field declarations (Static and Non-Static)>

<method declarations (Static and Non-Static)>

<Inner class declarations>

<nested interface declarations>

<constructor declarations>

<Static initializer blocks>

}
Below is an example showing the Objects and Classes of the Cube

class that defines 3 fields namely length, breadth and height. Also

the class contains a member function getVolume().

public class Cube {

int length;

int breadth;

int height;

public int getVolume() {

return (length * breadth * height);

METHODS

Methods are nothing but members of a class that provide a service

for an object or perform some business logic. Java fields and

member functions names are case sensitive. Current states of a

class's corresponding object are stored in the object's instance


variables. Methods define the operations that can be performed in

java programming.

A method has the following general syantax:

return type method-name( arguments ) {

// code statements }

Lecture-3:

INHERITANCE:

Java Inheritance defines an is-a relationship between a superclass

and its subclasses. This means that an object of a subclass can be

used wherever an object of the superclass can be used. Class

Inheritance in java mechanism is used to build new classes from

existing classes. The inheritance relationship is transitive: if class x

extends class y, then a class z, which extends class x, will also

inherit from class y.

The mechanism of deriving a new class from an old class is called


inheritance.
The inheritance allows subclasses to inherit all the variables and
methods of their parent classes.

Defining a Sub-class:

A sub-class is defined as follows:

class sub-class-name extends super-class-name

variables declarations;

methods declarations;

The keyword extends signifies that the properties of the super-


class-name are extended to the sub-class-name.

Types of inheritance:

 Single inheritance (only one super-class)

 Multiple inheritance (several super-class)

 Hierarchical inheritance (one super class, many subclasses)

 Multilevel inheritance (derived from a derived class)

Single inheritance:
It is an inheritance in which there is one super-class and one sub-
class.

Example:

class room

int length;

int breadth;

room(int x,int y)

length=x;

breadth=y;

int area( )

return (length * breadth);


}

class bedroom extends room

int height;

bedroom(int x,int y,int z)

super(x,y);

height=z;

int volume( )

return( length * breadth * height);

class inhertest

public static void main(String args[ ] )

bedroom room1=new bedroom(14,12,10);


int area1=room1.area( );

int volume1=room1.volume( );

System.out.println(area1);

System.out.println(volume1);

Multiple inheritance:

In this type more than one super-class having single sub-class


derived.

A B

Hierarchical inheritance:

In this type one super-class is having more than one sub-class.


A

B C D

Multi-level inheritance:

In this type derived class is derived from a derived class.

Lecture-4:
C
EXCEPTION HANDLING

Definition: An exception is an event, which occurs during the

execution of a program, that disrupts the normal flow of the

program's instructions.

The purpose of exception handling mechanism is to provide a

means to detect and report an exceptional circumstance so that

appropriate action can be taken. The mechanism suggests


incorporation of a separate error handling code that performs the

following tasks.

Find the problem(Hit the exception)

Inform that an error has occurred(Throw the exception)

Receive the error information(catch the exception)

Take corrective actions(Handle the exception)

Diagram and Syntax of exception handling code:

try block
Statement that cause an exception
(Exception object creater)

Throws
exception object

Catch block
Statement that handle the exception
(Exception handler)

Fig.1.2

Syntax:
try

statement; //generates an exception

catch(Exception-type e)

statement; //processes the exception

Example:

class error1

public static void main(String args[ ])

int a = 10 ;

int b = 5 ;

int c =5 ;

int x , y;

try
{

x = a / (b-c) ; //Exception here

catch( ArithmaticException e )

System.out.println(“division by zero “);

y = a / (b+c);

System.out.println( “y = “ + y);

}}

Multiple catch statements :

try

statement ;

catch ( Exception-Type-1 e)

{
statement ;

catch ( Exception-Type-2 e)

statement ;

catch ( Exception-Type-N e)

statement;

Using Finally Statement

try try
{ {

statement ; statement;

} }

finally catch ( )

{ {

statement; statement

} }

catch( )

statement;

finally

statements;

Throwing our own Exceptions


This can be done using keyword throw as follows:

throw new Throwable_subclass ;

Example :

import java.import.Exception;

class MyException extends Exception

MyEcxeption(String message)

super(message) ;

class TestMyException

public static void main(String args[])

int x=5,y=1000;

try

{
float z =(float) x / (float) y;

if(z<0.01)

throw new MyException (“Number is too small”);

catch (MyException e)

System.out.println(“Caught my exception”);

System.out.println(e.getMessage());

finally

System.out.println(“I am always here”);

}
Lecture-5

MULTITHREADING

Multithreading is a conceptual programming paradigm where a

program ( process ) is divided into two or more subprograms

( processes ), which can be implemented concurrently. For

example, one subprogram can display an animation on the screen

while another may build the next animation to be displayed. This is

something similar to dividing a task into subtasks and assigning

them to different people for execution independently and


class ABC
simultaneously.
{
Beginning

Single-Threaded
body of execution

End
}
Single-Threaded Program

Main Thread

Main Method
module

Once initiated by the main thread, the threads A,B and C run

concurrently Start
and share the resources Start
Start jointly. It is like people living

in joint families and sharing certain resources among all of them.

The ability of a language to support multithreads is referred to as

Thread A Thread B Thread C


concurrency. Since threads in Java are subprograms of a main

application program and share the same memory space, they are

known as lightweight threads or lightweight processes.

Multi-Threaded Program
Thread States
Threads can be in one of four states:

● New

● Runnable

● Blocked

● Dead

Each of these states is explained in the sections that follow.

New Threads

When you create a thread with the new operatorfor example, new

THRead(r)the thread is not yet running.

This means that it is in the new state. When a thread is in the new

state, the program has not started

executing code inside of it. A certain amount of bookkeeping


needs to be done before a thread can run.

Runnable Threads

Once you invoke the start method, the thread is runnable. A

runnable thread may or may not actually be

running. It is up to the operating system to give the thread time to

run. (The Java specification does not


call this a separate state, though. A running thread is still in the

runnable state.)

Blocked Threads

A thread enters the blocked state when one of the following actions

occurs:

● The thread goes to sleep by calling the sleep method.

● The thread calls an operation that is blocking on input/output,

that is, an operation that will not

return to its caller until input and output operations are complete.

● The thread tries to acquire a lock that is currently held by

another thread.
Fig 1.5.Life cycle of Thread

A thread moves out of the blocked state and back into the runnable
state by one of the

following pathways.

Dead Threads

A thread is dead for one of two reasons:

● It dies a natural death because the run method exits normally.


● It dies abruptly because an uncaught exception terminates the

run method.

In particular, you can kill a thread by invoking its stop method.

That method throws a ThreadDeath error

object that kills the thread. However, the stop method is

deprecated, and you should not call it in your own

Declaring a thread:

The thread class can be extended as follows:

class mythread extends Thread

…………..

………….

Implementing the run( ) method

public void run( )

………….

……………
}

Starting a new thread:

Mythread athread = new Mythread( );

athread.start( )

Example:

class A extends Thread

public void run( )

for ( int i=1 ; i< =5 ;I++)

System.out.println(“from thread A” + i);

System.out.println(:Exit from A”);

}}

class B extends Thread

public void run( )


{

for ( int i=1 ; i< =5 ;I++)

System.out.println(“from thread B” + i);

System.out.println(:Exit from B”);

}}

class C extends Thread

public void run( )

for ( int i=1 ; i< =5 ;I++)

System.out.println(“from thread C” + i);

System.out.println(:Exit from C”);

}}

class threadtest
{

public static void main(String args[ ])

new A( ).start( );

new B( ).start( );

new C( ).start( );

}}

Lecture-6
COLLECTIONS:

Collection classes and interfaces provides mechanism to deal with

collection of objects.All collections classes imports java.util.*

package.

The different concrete collection classes in java are as follows:

ArrayList:

It is an indexed sequence that grows and shrinks dynamically.

LinkedList:

An ordered sequence that allows efficient insertions and removal at

any position.

HashSet:

It is an unordered collection that rejects duplicates.

TreeSet:

It is a sorted set.

HashMap:

It is a data structure that stores Key/value associations.

TreeMap:

It is a map in which keys are sorted.


Example to implement ArrayList:

Import java.util.*;

Public class arraylistdemo

Public static void main(String args[ ] )

ArrayList<Integer> a1 = new ArrayList<Integer> ( ) ;

a1.add(10 );

a1.add( 20);

a1.add( 30);

a1.add( 40);

System.out.println(“Array list %s ; size:%d” a1.tostring( ) ,

a1.size( ) );

a1.remove(new Integer(30) );

a1.remove(0);
System.out.println(“Array list %s ; size:%d” a1.tostring( ) ,

a1.size( ) );

Lecture-7

I/O STREAMS
A stream in java is a path along which data flows.It has a source

and a destination.

Input Stream reads the data from source and pass the data to

program.

Output Stream writes the data from program to destination.

Java Stream Classes:

Java stream classes is divided into two types

1. Byte Stream classes

2. Character stream classes

Byte stream classes:

Byte stream classes have been designed to provide functional

features for creating and manipulating streams and files for reading

and writing bytes.

Byte stream classes is divided into two types

1. InputStream classes

2. OutputStream classes

Different InputStream classes are

FileInputStream
DataInputStream

ObjectInputStream

BufferedInputStream

Different output Streams classes are

FileOutputStream

DataOutputStream

ObjectOutputStream

BufferedoutputStream

Character stream classes is divided into two types

1. Reader classes

2. Writer classes

Program to display contents of a file:

Import java.io*;

Public class typefile

Public static void main(String args[ ] ) throws IOException

int i ;
FileInputStream fin;

Try

Fin =new FileInputStream(args[ 0] );

Catch( FileNotFoundException e )

System.out.println(“file not found”);

Return;

Catch(ArrayIndexOutOfBoundException e)

System.out.println(“java filename”);

Return;

While(I =fin.read( ) ) ! = -1)

System.out.print( (char)i);

Fin.close( );
}}

Lecture-8

ABSTRACT WINDOWS TOOLKIT

Abstract windows toolkit contains all the classes for creating user

interfaces and for painting graphics and images.

A user interface object such as button or a scrollbar is called in

AWT terminology , a component.


Component class is the root of all AWT components.

The different component classes are

Button

Label

TextField

Checkbox

Combobox

GridLayout

TextArea

Scrolbar

Program to describe Label , TextField and Button:

Import java.awt.*;

Import java.awt.event.*;

Import java.applet.*;

/* <Applet code = “temp.class” width=200 height=200> */

Public class temp extends Applet implements ActionListener

TextField tc,tf;
Button cal;

Public void init( )

Label lc = new Label( “ enter celcius “ Label.LEFT);

Label lf = new Label( “ Farhenhit is “ Label.LEFT);

tc= new TextField(5);

tf=new TextField(5);

tc.setText(“0”);

tf.setText(“0”);

cal=new Button(“calculate”);

add(lc);

add(tc);

add(lf);

add(tf);

add(cal);

cal.addActionListener(this); }

Public void actionPerformed(ActionEvent ae)

{
If(ae.getSource( ) = = cal) {

Double cel=Double.parseDouble(tc.getText( ) );

Tf.setText( String.valueOf(9.0/5/0*cel+32.0) ); }}}

Lecture-9

APPLET PROGRAMMING

Applets are small java programs that are primarily used in internet

programming. They can be transported over the internet from one

computer to another and run using the Applet viewer or any web

browser that supports Java.

Applet does not contain main() method.

Format of Applet program:

Import java.awt.*;

Import java.applet.*;

Public class appletclassname extends Applet

………………..

………………..
Public void paint(Graphics g)

………………..//Appletsoperations code

…………………

Applet Life cycle:

The different states of applet life cycles are

Born state or initialization state

Running state

Idle state

Dead state

Initialization state:

Applet enters initialization state when it is first loaded

Init( ) function is used.

Syntax

Public void init( )

{
…………//Action

……………..

Running State:

Applet enters running state when the system calls the start method.

Syntax

Public void start( )

…………………….//Action

…………………….

Idle or stopped state:

An applet becomes idle when it is stopped from running.

Syntax

Public void stop( )

……………….//action

……………….
}

Dead state:

An applet is said to be dead when it is removed from memory.

Syntax

Public void destroy( )

………………//Action

……………….

}
1.16.QUESTIONS AND SOLUTIONS FROM PREVIOUS
UNIVERSITY EXAMS

Q1.What is multithreading? Explain the life cycle of a thread.

SOLUTION:

Multithreading is a conceptual programming paradigm where a

program (process) is divided into two or more subprograms

( processes ), which can be implemented concurrently. For

example, one subprogram can display an animation on the screen

while another may build the next animation to be displayed. This is

something similar to dividing a task into subtasks and assigning

them to different people for execution independently and

simultaneously.

class ABC
{ Beginning

Single-Threaded
body of execution

End

}
Single-Threaded Program

Once initiated by the main thread, the threads A,B and C run

concurrently and share the resources jointly. It is like people living

in joint families and sharing certain resources among all of them.

The ability of a language to support multithreads is referred to as

concurrency. Since threads in Java are subprograms of a main

application program and share the same memory space, they are

known as lightweight threads or lightweight processes.

Main Thread

Main Method
module

Start Start
Start

Thread A Thread B Thread C

Multi-Threaded Program
Life cycle of a Thread:

Life cycle of a Thread can have four states:

● New

● Runnable

● Blocked

● Dead

Diagram for Life cycle of a thread:


New state of Thread:

When you create a thread with the new operator for example, new

Thread( ) the thread is not yet running. This means that it is in the

new state. When a thread is in the new state, the program has not

started executing code inside of it. A certain amount of

bookkeeping needs to be done before a thread can run.

Runnable state of a Thread:

Once you invoke the start method, the thread is runnable. A

runnable thread may or may not actually be running. It is up to the

operating system to give the thread time to run.

Blocked state of a Thread

A thread enters the blocked state when one of the following actions

occurs:

● The thread goes to sleep by calling the sleep method.

● The thread calls an operation that is blocking on input/output,

that is, an operation that will not return to its caller until input and

output operations are complete.


● The thread tries to acquire a lock that is currently held by

another thread. We discuss locks on page.

A thread moves out of the blocked state and back into the runnable
state by one of the following pathways.

Dead state of a Thread:

A thread is dead for one of two reasons:

● It dies a natural death because the run method exits normally.

● It dies abruptly because an uncaught exception terminates the

run method.

In particular, you can kill a thread by invoking its stop method.

That method throws a ThreadDeath error object that kills the

thread.

Q2.Write a program to create a user defined Exception called


“No Match xception”

that throws an arbitrary message when a string is not equal to


“INDIA”.

SOLUTION:

import java.import.Exception;
class NoMatchException extends Exception

NoMatchException(String message)

super(message) ;

class TestNoMatchException

public static void main(String args[])

String m;

Scanner s=new Scanner(System.in);

System.out.println(“enter a string”);

m=s.next( );

try

{
If(m!=”INDIA”)

throw new NoMatchException (“String is not india”);

catch (NoMatchException e)

System.out.println(“Caught NoMatchException”);

System.out.println(e.getMessage());

} } }

Q3.What are applets? Explain their usage. How are they

different from java programs?

SOLUTION:

Applets are small java programs that are primarily used in internet

programming. They can be transported over the internet from one

computer to another and run using the Applet viewer or any web

browser that supports Java. Applet does not contain main()

method.
Usage of Applet:

Applets can be used for internet programming.

It can be used to extend the capabilities of html web-pages.

Difference between java applet and Java programs:


---Java applets are small java
program used in internet ----Java programs are programs
programming by embedding used for applications
inside html documents. development.

---Java applets are embedded


inside html document and --Java programs cannot
enhance capabilities of html embedded inside html document.
webpages

--Java applets cannot have main()


method. --Java programs must have main
() method.
--Java applets can only be
executed in web browser or ---Java programs can be
appletviewer. executed by java interpreter.

Q.4. What is an interface ? Explain with a suitable example.


How multiple

Inheritance is implemented in java.

SOLUTION:
Interface is a class which consists of constant variables and
undefined methods. Interface can be treated as templates used by
different classes by inherit the interface. Interface cant create any
objects. It is only used by other classes those inherit it. Interface
can be used to implement multiple inheritances.
Syntax of Interface:

Interface interface-name
{
//Final or constant variables;
//Undefined methods;
}
Example of Interface:
Interface product
{
Final int productno;
Public void getdescription( );
}
Using interface for multiple inheritance:
Interface is used to implement multiple inheritances by inheriting a
class from multiple interfaces as below

Interface A Interface B
Class C

Example of interface to implement multiple inheritance:

Interface A
{
Final Int a;
Void getdata();
}
Interface B
{
Final int b;
Void putdata();
}
Class C implements A , B
{
Int c;
Void getdata()
{
a=4;
System.out.println(a);
}
Void putdata()
{
b=5;
System.out.println(b);
}}
Class test
{
Public static void main(String args[]) {
test t1;
t1.getdata();
t1.putdata(); } }
Q.5. Why is java more suitable as compared to other language.

SOLUTION:

Java is more suitable as compared to other languages because of


the following features

 Platform independent and portable

 Object Oriented

 Robust and Secure

 Distributed
 Familiar, Simple and small

 Multithreaded and Interactive

 High Performance

 Dynamic and Extensible

 Compiled and Interpreted

Platform independent and Portable

Java is platform independent because of byte code which can be

interpreted by any system. Because of platform independent java is

portable.

Object Oriented:

Java is purely object oriented programming language.Data hiding,

encapsulation,polymorphism,inheritance properties are present.

Robust and Secure:

Java is robust because Java works as usual when any extension is

made in java.Java is secure because of its byte code and case

sensitiveness.

Familiar, Simple and small


Java is easy to understandable ,small and familier.

Multithreaded and Interactive:

Java support multithreading because in java different parts of a

program can execute concurrently.

Dynamic and Extensible

Java works dynamically and can be easily extensible.

Q.6. What do you mean by byte code .Explain its working..

SOLUTION:

Byte code is a code formed by compiler in java having .class


extension

Java bytecode is the form of instructions that the Java virtual


machine executes. Each byte code opcode is one byte in length,
although some require parameters, resulting in some multi-byte
instructions.

To understand the details of the bytecode, we need to discuss how


a Java Virtual Machine (JVM) works regarding the execution of
the bytecode.
A JVM is a stack-based machine. Each thread has a JVM stack
which stores frames. A frame is created each time a method is
invoked, and consists of an operand stack, an array of local
variables, and a reference to the runtime constant pool of the class
of the current method. Conceptually, it might look like this:

Figure . A frame
The array of local variables, also called the local variable table,
contains the parameters of the method and is also used to hold the
values of the local variables. The parameters are stored first,
beginning at index 0. If the frame is for a constructor or an instance
method, the reference is stored at location 0. Then location 1
contains the first formal parameter, location 2 the second, and so
on. For a static method, the first formal method parameter is stored
in location 0, the second in location 1, and so on.

Q.7.How is platform independent feature of java implemented.


Explain role of main ( ) method in execution of java program.

SOLUTION:

Java is platform independent because of its byte code creation by


compiler that is handled by Java Virtual Machine.

Byte code is of .class extension and that can be executed by any


platform by their own interpreter.

Diagram for platform independence:

Java Source file(.java file)


Byte code (.class file)

Windows system Unix system Solaris system


(having JVM) (having JVM) (having JVM)

Windows Unix interpreter Solaris interpreter


interpreter

Exe file Exe file Exe file

Role of main() method:

Main( ) method is a static method that can automatically called


without use of any objects creation.

Main () method is the first method executed by CPU after that any
methods are executed.
All objects are created inside the main( ) method and methods are
called inside main( ) method.

Without main ( ) method no program is created in java application.


Q.7.Why exceptional errors occurs during execution of
program. Discuss usage of finally block.

SOLUTION:

Exceptional errors occurs during execution of program because in


the time of program execution some unusual condition occurs and
disrupts the normal flow of execution.

such as a number division by zero, file not found , array index out
of bound , arithmetic exception etc.

An exception is an event, which occurs during the execution of a

program, that disrupts the normal flow of the program's

instructions.

The purpose of exception handling mechanism is to provide a

means to detect and report an exceptional circumstance so that

appropriate action can be taken. The mechanism suggests

incorporation of a separate error handling code that performs the

following tasks.

Find the problem(Hit the exception)

Inform that an error has occurred(Throw the exception)


Receive the error information(catch the exception)

Take corrective actions(Handle the exception)

Diagram and Syntax of exception handling code:

try block
Statement that cause an exception
(Exception object creater)

Throws
exception object

Catch block
Statement that handle the exception
(Exception handler)
Usage of finally block.

Finally is a keyword used in exception handling mechanism?


Finally is
Written after try and catch statement .The statements written inside
finally is must execute whether there is exception found or not.
Syntax of Finally Statement

try try
{ {
statement ; statement;
} }
finally catch ( )
{ {
statement; statement }
Finally {
} Statement

You might also like