Vous êtes sur la page 1sur 84

Java Programming 5th CE IT

Note: This Document is typed by Abhishek Dubey , Hanuman and Vishrut Bhatt
1. Explain characteristics or features of java?
• Features of java are listed below.
• Compiled and Interpreted
• Platform-Independent and portable
• Object-oriented
• Robust and Secure
• Distributed
• Familiar, Simple, Small
• Multithreaded and Interactive
• High Performance
• Dynamic and Extensible

 Compiled and Interpreted


Basically a computer language is either compiled or interpreted. Java combines both
approaches thus making java a two-stage system.
 First java complier translates source code into bytecode instruction. Bytecode
is not machine instruction.
 Therefore, in the second stage, java interpreter generates machine code the can
directly executed by the machine that is running the java program.

 Platform-Independent and portable


Java supports the feature portability. Java programs can be easily moved from one
computer system to another, anywhere and anytime. Change and upgrades in
operating system processors and system resources will not force any change in java
programs. This is the why java has become a popular language for programming on
Internet which interconnected different kinds of system worldwide. Java ensures
portability in two ways:
• First java complier generates bytecode instructions that can be
implemented on any machine.
• Secondly the size of the primitive data types is machine independent.
• Object-oriented
Java is a truly object-oriented language. Almost everything in java is an object
Program code and data reside within objects and classes. Java comes with an
extensive set on classes, arranged in packages that can be used in programs by
inheritance.
• Robust and secure
Robust:
Java is a more robust language. It provides many protection to ensure reliable code. It
has strict compile time and run time checking for data types. It is designed as a
garbage-collected language, which relieves the programmers virtually from all
memory management problem. Java also incorporates the concepts of exception
handling, which capture serious errors and eliminates all kind of risk of crashing the
system.

Prepared by Amit Shah 1 L J Polytechnic


Java Programming 5th CE IT

Secures:
Security becomes an important issue for a language which is used for programming
on Internet. Threat of viruses and abuse of resources are everywhere. Java system not
any verifies all memory access but also ensure that no viruses are communicated with
an applets. The absence of pointers in java ensures that programs cannot again access
to memory locations without Proper authorization.
• Distributed
Java is also known as distributed language for creating applications on networks,
which has ability to share both data and programs. Java applications can open and
access remote objects on Internet as easily as they can do in a local system. This
enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.
• Familiar, simple and small
Java is a very small and simple language. Many features of C and C++ that are either
redundant or sources of unreliable code are not part of Java For example, Java does
not use pointer, pre-processor header files, go to statement and many others. It also
eliminates operator overloading and multiple inheritance.
Familiarity is another stinking features of Java. To make the language look familiar to
the existing programmers, it was modelled on C and C++ languages. Java uses many
constructs of C and C++.
• Multithreaded and interactive
Multithreaded means handling multiple tasks simultaneously. Java supports
multithreaded programs. This means that we need not to wait for application to
complete one task before beginning another. This feature improves the interactive
performance in graphics application.
• High Performance
Java Performance is very impressive for an interpreted language, mainly due to the
use of intermediate bytecode. The incorporation of multithreading enhances the
execution speed of java programs.
• Dynamic and Extensible Dynamic
Java is also a Dynamic language. Java is capable dynamically linking in new class
libraries, methods and objects. Java can also determine the type of class through a
query, making it possible to either dynamically link or abort the program, depending
on the resources.
Java programs support functions written in either languages such as C and C++,
known as native methods.

Prepared by Amit Shah 2 L J Polytechnic


Java Programming 5th CE IT

2. Difference between Java and C


Java C
Java is an object oriented language and has C is a procedure oriented language has
mechanism to define class and objects. mechanism for creating procedures.
Java does not include the c unique statement C has unique keywords sizeof for memory
keywords sizeof and typedef management and typedef.
Java does not contain the datatypes, struct C support the user defined datatype , struct
and union. and union.
Java does not support explicit pointer type C supports an explicit pointer type.
statements.
Java does not have a pre processor and C supports only simple breaks and continue
therefore we cannot use # define , #include statement.
and #ifdef
Java adds labeled break and continue C supports only simple break and continue
statements. statement.

3. Difference between Java and C++


Java C++
Java is true object oriented language. C++ is basically C with object oriented
extension.
Java does not support operator overloading. C++ support operator overloading.
Java does not have template classes C++ have template classes
Java does not support multiple inheritances C++ supports multiple inheritances of classes.
of classes. This is accomplished using a new
feature called “INTERFACE”.
Java does not use pointer. C++ uses pointer.
Java has replaced the destructor function C++ has the destructor function.
with a finalize () function.
There are no header files in java. C++ includes header files in program.
4.) Describe the structure of java program.
A java program may contain many classes of which only one class defines a main method
classes contain data type declaration and executed statements. To write a java program, we
first define classes & then put them together. A java program may contain one or more
sections as show in fig.
Documentation Section Suggested
Package Statement Optional
Import Statement Optional
Interface Statement Optional
Class Definitions Optional
Main Method Class{
Main Method Optional
Definition}

Prepared by Amit Shah 3 L J Polytechnic


Java Programming 5th CE IT

• Documentation Section
The documentation section comprise a set of comment lines - giving the name of
program, the author & other details, Which the programmer would like to refer to at a
later stage. Comments must explain why & what of classes & how of algorithms. This
would help in maintaining the program. In addition to the two styles of comments /**-
------**/ known as documentation comment. This form of comment is used for
generating documentation automatically.
• Package Statement
This first statement allowed in a java file is a package statement. This statement
declares a packages name & informs the compiler that the classes defined here belong
to this package.
Exp:-
Package Student;
• Import Statement
The next thing after a package statement may be a number of import statement. This
is similar to the #Include statement in C.
Exp: - import student. test;
This statement instructs the interpreter to load the test class contained in the package
student. Using import statements we can have access to classes that we are part of
other named packages.
• Interface Statement
An interface is like a class but includes a group methods declaration. This is also
known as “optional section” & is used only when we wish to implement the multiple
interface features in the program.
• Class Definition
A Java program may contain multiple class definitions. Classes are the primary and
essential of a 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.
• Main Method Class
Since every Java standalone program requires a main method as its starting
point, this class is the essential part of a Java program. A simple program may
contain only this part. The main method creates objects of various classes and
established communications between them. On reaching the end of main, the
program terminates and the control passes back to the operating system.

Prepared by Amit Shah 4 L J Polytechnic


Java Programming 5th CE IT

5 What is JVM (Java Virtual Machine)?


OR
What is Byte code?
OR
Explain write once run anywhere?
OR
What is platform independent?
Compiler translates source code into machine code for specific computer( platform
dependent). But the Java compiler produces an intermediate code known as Byte code.
This machine is called as Java Virtual Machine(JVM) and only exist inside the
computer memory.

Java Program Java Compiler Virtual Machine

Source Code Byte Code


The output produced by the Java compiler is not executable code. It is byte code,
highly optimized set of instruction executed by Java run time system or JVM. JVM
is an interpreter for the bytecode. The virtual machine code generated by Java
Interpreter is not machine specific, but it acts as an intermediary between the virtual
machine and real machine as shown in fig.
Byte Code JVM Machine Code

Virtual Machine Real Machine


Above figure shows how Java works on typical computer. The Java object framework (
Java API) acts as an intermediary between the user program and virtual machine
which in turn acts as operating system and Java object framework.
6 Explain Java security and portability.
Security becomes an important issue for a language which is used for programming
on Internet. Threat are everywhere. Java system not only ensure that no viruses are
communicated with an applet. The absence of pointers in Java ensures that programs
cannot gain access to memory locations without proper authorization.
Java supports the feature portability. Java programs can be easily moved from one
computer system to another anywhere and anytime. Changes and upgrades in operating
systems. Processors and system resources will not force any changes in Java programs.
This is the reason Why Java has become a popular language for programming.
Internet which interconnects different kinds of systems worldwide. Java ensures portability in
two ways:-
I. First, Java compiler generates bytecode instruction that can be implemented on any
machine.
II. Secondly, the size of the primitive data types is machine independent
SHORT QUESTIONS
1. Why Java source file should be given the same name as that of class?
ANSWER: - After a program is successfully compiled it creates a file with .class
extension, which contains bytecode version of program .When program is compiled each

Prepared by Amit Shah 5 L J Polytechnic


Java Programming 5th CE IT

individuals class is put into its own output file named after the class and using the .class
extension. This is the reason to give the java source file the same name as that of class.
2. Write down the different type of main in JAVA?
ANSWER: - signature of the main () method can be any of these:
Public static main (String args [])
Public static main (String [] args)
Static public void main (String args [])
3. Explain comment line styles in Java.
ANSWER: - Three styles of comment notation are used in Java:--
A.) Any text between ‘//’ and the end of line is a comment.
B.) The starting with ‘/*’ and terminating with ‘*/’ make up multiple line comments.
C.) Special form starting with ‘/**’ and terminating with ‘**/’ is used to create comments
that can be processed by the Java doc program to produce HTML formatted
documentation.

7. Explain the data types in Java.


Name Default values Width Range
Boolean False 16bit True or false
Char Null or ‘140000’ 16bit 0 to 216-1 ( 0 to 65535)
Byte 0(byte) 8bit -27 to 27-1(-128 to 127)
Short 0(short) 16bit -215 to 215-1(-32768 to 32767)
Int 0 32bit -231 to 231-1(-214783648 to 214783647)
Long 0L 64bit -263 to 263-1
float 0.0f 32 bit -231 to 231-1
double 0.0d 64 bit -263 to 263-1

8. Rules for variables. (Identifiers)


 It is used to denote classes, methods and variables.
 It may contain only letters (uppercase or lowercase), dollar signs, numbers or
underscore (_).
 The first character cannot be a number.
 It cannot be the same as any keyboard or the Boolean or null literals(true , false , null)
 Java is case sensitive, hence “anil” and “ANIL” are different.
Ex: Avgtotal , count , a4 , $test , this_is_ok , _first are valid identifiers.
Java allows two or more statements to be grouped into blocks of code also called as code
blocks, which is done by enclosing the statements between the opening curly braces and
closing curly braces. {}

Prepared by Amit Shah 6 L J Polytechnic


Java Programming 5th CE IT

9 Explain operator.
Prefix operator op ++a
Postfix op operator a++
Operators that require two operands are binary operators.
Syntax: op1 operator op2
Ternary operators are those that require three operands.
Syntax :
Expr ? op1 : op2
1) Arithmetic operator.
operator Use description
+ Op1+op2 Adds op1 and op2
-(unary) -op1 Negates op1(-ve op1)
- Op1-op2 Subtracts op2 from op1
* Op1*op2 Multiples op1 by op2
/ Op1/op2 Divides op1 by op2
% Op1%op2 Computes the reminder of dividing op1 by op2.
int x=2; X%10 =2
double y=42.3; Y%10=2.3
+(unary) +op Promotes to int if it’s a byte , short or char.

2) Relational operator.
Compares two values and determines the relationship between them. The outcome of the
expression is a Boolean value.
operator Use Returns true if

> Op1>op2 Op1 is greater than op2


>= Op1>=op2 Op1 is greater than or equal to op2

< Op1<op2 Op1 is less than op2


<= Op1<=op2 Op1 is less than or equal to op2
== Op1==op2 Op1 and op2 are equal
!= Op1=op2 Op1 and op2 are not equal

Note:- only byte , short , int , long , float , double and characters operands may be comp[ared
to see which is greater or less than the other.

Prepared by Amit Shah 7 L J Polytechnic


Java Programming 5th CE IT

 Java support five binary conditional operators (Boolean logical operators)

A B A|B A&B A^B !A


0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0

3) Logical operator
Operator Use Returns true if
&& op1&&op2 op1 and op2 are both true, conditionally Evaluates op2
|| op1||op2 either op1 or op2 is true, conditionally evaluates op2
!(Not) ! op1 op is false
4) Short Circuit:
Under specific conditions the && and || operators do not Evaluate both operands.
Case 1: In the statement if (x>0) &&(y>0). If the result of first (x>0) is evaluated as false
Than the compiler knows that the result can be false, so the right operand (y>0)is and
evaluated.
Case 2: In the statement if (x>0) || (y>0), if the result of the false operand is evaluated as
true then the compiler knows that the result can be true,so the right operand (y>0)
is not evaluated.
5) Bitwise Operator:
A Bitwise operator allows you to perform bit manipulation in data.
Operator Use Operation
>> op1>>op2 Shift bits of op1 right by distance op2.
<< op1<<op2 Shift bits of op1 left op1 left by distance op2
>>> op1>>>op2 Shift bits of op1 right by distance op2
& op1&op2 bitwise and
| op1 | op2 bitwise or
^ op1 ^ op2 bitwise xor
~ ~op1 bitwise complement(Not)
 The three shift operation (>>= <= >>>) simply shift the bits of the left hand operand
over by the number of position indicated by the right hand operand.
The shift occur in the direction indicated by operator itself.

Prepared by Amit Shah 8 L J Polytechnic


Java Programming 5th CE IT

Right Shift (>>):


Divides the value by two and discards any remaindesr.
Note:
Java uses two’s complement to store negative numbers. High order bit represents sign.
13>>1 Shift the bits of the integer 13 to the right by one position.

1101 is binary representation of 13 , 0110 is the result of shifting one bit to right ->
6.
35>>2 001000 11->35>>2 = 0000100->8
 Shift the bits of the integer 35 to the right by two position. While shifting
right, the top(leftmost) bits exposed by the right shift are filled in with the
previous contents of top bit. This is called sign extension and serves to
preserve when you shift them to right.
 -8>>1 11111000 -> -8>>1 = 11111100 -> -4
 Bute x=-1;x=x>>>5;

The above is illegal because results of x>>>5 is int and can’t be assigned to x
which is byte.

x=(byte)(x>>>5) //Perfectly legal

 A right shift of 1 bit is equivalent to, but more efficient than, dividing the left
hand operand by 2.

Left Shift (<<) (Multiply by two) :

A left shift of 1 bit is equivalent to Multiplying by 2.


Eg: 35<<2 00100011-> 35 <<2
10001000 -> 140
 Shift the bits of the integer 35 to the left by two position. While shifting left,
the top(rightmost) bits exposed by the left shift are filled in with the zero on
the right. This means that when a left shift is applied to int operand, bit are lost
once they are shifted past position 31.
 -8 << 1 11111000 -> -8 << 1 = 11110000 -> -16
 byte a=64; byte x= a<<2;
The above is illegal because result by a<<2 is int and can’t be assigned to x
which is byte.
byte (a<<2) //Perfectly legal

Unsigned Right Shift (>>>) :

 35>>>2 00100011->35 >>> 2 = 00001000 ->8

Shift the bits of the integer 35 to the right by two positions. While shifting
right, the top (leftmost) bits exposed by the right shift are filled in with
zero.This does not number when you shift them to right.

Prepared by Amit Shah 9 L J Polytechnic


Java Programming 5th CE IT

 -8 >>>1

11111111 11111111 11111111 11111111000 -> -8 >>>


1
01111111 11111111 11111111 11111100 ->
214783644

Here actually 32 bit value is Shifted.

 Byte x = - 1; x = x >>> 5;
The above is illegal because result of x >>> 5 is int and can’t be assigned
to x which is byte.

X=(byte) (a << 2) //Perfectly legal.

10 Explain Type conversion and Casting:

 There are two type of Conversion.


1. Widening Conversion.
2. Narrowing Conversion.

1) Widening Conversion: It is also called automatic Conversion or implicit


Conversion.
 When destination type is larger than the source type widening conversion take
place.
 The compiler converts primitives by promotion according to the following rules :

 If either operand is of type double, the other is converted to double.


 Otherwise, if either operand is of type float the other is converted to float.
 Otherwise, if either operand is of type long the other is converted to long.
In all other situations both operands are converted to int primitives.
Type promotion rules are as follows:
• First all byte and short values are promoted to int.
• Then, if any one operand is long, the whole expression is promoted to long.
• Then, if any one operand is float, the whole expression is promoted to float.
• Then, if any one operand is double, the whole expression is promoted to double.
Eg: byte b=5; short s = 5;
Short are = b*5;
results in error because multiplication is promoted to int and ur trying to assign int value
to short type variable
byte b = 2; byte b1 = 3;
B = b*b1;
The above code will not work because before multiplying, both b and b1 will be converted to
int and int can’t be assign to byte.

Prepared by Amit Shah 10 L J Polytechnic


Java Programming 5th CE IT

Narrowing conversion:
-It is also called explicit or cast operator.
-When destination type is smaller then the source type then narrowing conversion take
place.
-A cast simply an explicit type conversion it has general form: (target-type) value to.
Here, target-type specifies to convert the specified value to
Ex: When a float is cast into int type its fraction part is lost and the value is truncated.
Int i;
Float f = 12121.121f;
i = (int) f;
o/p: i = 12121
11 Explain Control Statements
• If-else:
The general form of it statement is:
if(condition)
Statement 1;
else
Statement2;
• If the condition 1 is true then state1 is executed ,otherwise statement2 is executed In
case will both state ments be executed.
• Wap to find number is odd or even
class A{
public static void main(String args[]){
int no = 20;
int no = Integer parse Int(args[0]);//For fetch the value user//
if(no%2 = = 0)
System.out.println(“no is even”);
else
System.out.println(“no is odd”);
}
}
2 . if-elseif-(ladder):
Form is:
If (condition)
Statement;

Prepared by Amit Shah 11 L J Polytechnic


Java Programming 5th CE IT

Else if (condition)
Statement;
:
:
:
Else
Statement;
The if statement are executed from top-down. As soon as one of the condition controlling the
if is true the statement associated with that if is executed and the rest of ladder is by passed. If
none of the condition is executed. Else act as a default condition.
Wap to demonstrate if-else if statement

class IfElse{
public static void main(String args[]) {
int month=4;
String season;
if(month==12 || month==1 || month==2)
season=”Winter”;
elseif(month==3 || month=4 || month=5)
season=”Spring”;
elseif(month==6 || month==7 || month==8)
season=”Summer”;
elseif(month==9 || month==10 || month==11)
season=”Autumn”;
else
season=”Bogus Month”;
System.out.println(“April is in the”+season+”.”);
}
}

O/P: April is in the Spring.


3> Nested-if:
The general form of Nested-if is:
if(condition)
if(condition)

Prepared by Amit Shah 12 L J Polytechnic


Java Programming 5th CE IT

Statement;
else
statement;
else
statement;
A nested-if is an if statement that is the target of another if or else. When you nest if, the
main theme to remember is that an else statement always refer to the nearest if statement.
That is within the same block as the else and that is not already associated with an else.
WAP to find maximum between 3 numbers using Nested-if.
class A {
public static void main(String args[]) {
int a=20,b=10,c=30;
if(a>b){
if(a>c) {
System.out.println(“Max is : ”+a)
}
else {
System.out.println(“Max is : ”+c);
} }
else{
if(b>c) {
System.out.println(“Max is : ”+b);
}
else {
System.out.println(“Max is : ”+c);
}
} } }

4> Switch-case:
The general form of Switch-case is:
switch(expression)
{
case value1:
statement;
break;

Prepared by Amit Shah 13 L J Polytechnic


Java Programming 5th CE IT

case value2:
statement;
break;
.
.
.
.
.
case valueN:
statement;
break;
default
default statement;
}

The expression must be of type byte, short, int or char; each of the values specified in the
case statements.
Must be of a type compatible with the expression. Each case value must be unique literal.
(that is, it must be a constant, not a variable). Duplicate case values are not allowed.
The switch statement works like this: the value of the expression is compared with each of
the literal values in the case statements. If a match is found, the code sequence following that
case statements is executed. If none of the constant. Matches the value of the expression, then
the default statements is executed. However, the default statements is optional. If no case
matches and no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. When a
break statement is encountred, execution branches to the first line of code that follows the
entire switch statement. This has the effect of “jumping out” of the switch.
Here is a simple example that uses a switch case.

class sampleswitch
{
public static void main(string args[])
{
for(int i=0; i<6; i++)
switch(i)
{
case 0:

Prepared by Amit Shah 14 L J Polytechnic


Java Programming 5th CE IT

System.out.println(“I is zero”);
break;
case 1:
System.out.println(“I is one”);
break;
case 2:
System.out.println(“I is two”);
break;
default:
System.out.println(“is greator than 3”);
}}
The break statement is optional. If you omit the break, execution will continue on into the
next case.
Explain Iteration statements or looping
• WHILE:
while(condition)
{
//body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long
as the conditional expression is true. When condition becomes false, control passes to the
next line of code immediately following the loop. The only braces are unnecessary if only a
single statement is being repeated.
Ex:-
class while{
public static void main(string args[]) {
int n=10;
while(n>0){
System.out.println(“tick”+n);
n--;
}}
}
o/p: tick 10
tick 9
:
:

Prepared by Amit Shah 15 L J Polytechnic


Java Programming 5th CE IT

tick 1
• DO-WHILE:
do
{
//body of loop
} while(condition);

Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat
otherwise, the loop terminates. Condition Must be a Boolean expression
class DoWhile{
public static void main(String arg[]){
int n=10;
do{
System.out.println(“tick”+n);
n--;
}while(n>0);
}
}
o/p:
tick 10
tick 9
|
tick 1

3 for:
for(intilization;condition;interaction)
{
//body
}
The for loop operates as follow. When the loop first starts, the initialization portion of the
loop is sets the value of the loop controls the loop control variable, which acts as counter that
controls the loop. The initialization expression is only executed once.
Next condition is evaluated. This must be a Boolean expression, It usually test the loop
control variable against a target value If this expression is true, then the body of the loop is
executed if it is false, The loop terminates next the interaction portion of the loop is executed
.This is usually an expression that increments or decrements the loop control variable. The

Prepared by Amit Shah 16 L J Polytechnic


Java Programming 5th CE IT

loop then iterates, first evaluating the body of the loop and then executing the interaction
expression with each pass controlling expression is false.
class ForTick{
public static void main(String arg[])
{
int n;
for (n=10;n>0;i++)
System.out.println(“tick”+n);
}}
o/p:
tick 10
tick 9
|
tick 1
Nested loop:-
General Form of nested for.
for(initialization; test condition; increment)
{
for(initialization; test condition; increment)
{
//body for iner loop;
}
}
Ex
class Nested{
public static void main(String arg[]){
int i,j;
for(i=0;i<10;i++){
for(j=0;j<10;j++){
System.out.println(“.”);
}
System.out.println(“”);
}}
}

Prepared by Amit Shah 17 L J Polytechnic


Java Programming 5th CE IT

Explain jump statements:


Java support three jump statement:
1)break,
2)continue,
3)return.
The Statement transfer control to another part of program.
1.break:-
The break statement has three uses.
• It terminates a statement Sequence in a switch statement
• It can be used to exit a loop.
• It can be used has a form of go to.
• Using break to exit a loop.
When a break statement is encountered inside a loop. The loop is terminated and
program control resumes at the next statement following the loop.
Example:-
class breakloop{
public static void main(string args[]){
for (int i=0; k100;i++){
if(i==10)
break;
System.out.println(“i”;+i);
}
System.out.println(“loop complete”);
}}
Output:-
i=0
i=1
i=2
i=3
loop complete
-Using break as a form of go to
-It is also called label break general form of label break is:
Break label;
Label is the name of a label that identifies a block of code. When this form of break executes
control is transferred out of the named block of code must enclose the break statement, but it
does not need to be the immediately end of using block. This means that you can use a

Prepared by Amit Shah 18 L J Polytechnic


Java Programming 5th CE IT

labelled break statement to exit form a set of nested block. But you cannot use break to
transfer control to a block of code that does not enclose the break statement.
Example:-
class break {
public static void main (string args[]) {
boolean t = true;
First: {
Second: {
Third: {
if(t)
break second;
System.out.println(“this won’t execute”);
}
System.out.println(“this is after second block.”);
}
}
}
Output:-
Before the break
This is after second block.
Continue:-
During the loop operations, it may be necessary to skip a part of the body of the loop
under contain condition the continue statement causes the loop to be continues with the
next iteration after skipping any statements in between the continue statement in tells the
compiler “skip or omit the statement mentioned and continue with the next iteration” in
while and go loop ,the continue the control to go directly to the test condition and then
continue the iteration process. In the case of for loop, the increment section of the loop is
executed before the test condition is evaluated.
Example:-
class continue{
public static void main(string args[]) {
for(int i=0; i<10;i++)
System.out.print(i+” ”);
if (i%2==0)
continue;
System.out.println(“ “);
}

Prepared by Amit Shah 19 L J Polytechnic


Java Programming 5th CE IT

}
}
Output:
0 1
2 3
4 5
6 7
8 9
Label continue:-
The general form of label continue is:
Continue label;
The label is the name of label ,which identifies statement will terminate the loop &
continue with next iteration.
Ex:-
class continuelabel{
public static void main(String args[]){
for(int i=0;i<10;i++){
for (int j+0; j<10;j++)
{
if (j>i){
System.out.println(“”+(i*j));
}}
System.out.println():
}}
Output:-
01
02 4
.
.
.
0 9 18 27 36 45 54 63 72 81
Return:-
The return statement terminates the method in which it is executed return causes execution to
return to java runtime system.
Ex:-

Prepared by Amit Shah 20 L J Polytechnic


Java Programming 5th CE IT

class return {
public static void main(string args[]){
boolean t=true;
System.out.println(“before the return”);
if(t)
return;
System.out.printl(“this wont execute”);
}
}
Outpit:-
Before the return.
Class
What is class ?
Class is a user-defined data type all data & method are encapsulates within the class. The data
& function written within the class are called as a member of a class. The variable & method
are called instance method.
In java, these data items are called field and function are called method.\
Syntax:-
class classname
{
type instance_variable1;
type instance_variable2;

type instance_variableN;
return-type method_name1(Parameter list);
{
}
return-type method_name2(Parameter list);
{
}
return-type method_nameN(Parameter list);
{
}
}

Prepared by Amit Shah 21 L J Polytechnic


Java Programming 5th CE IT

// A Program that use Box class file name=boxdemo.java


class box{
double width;
double height;
double depth;
}
class boxdemo{
public static void main(String ar[]){
box mybox=new box();
double v1;
mybox.width=10;
mybox.height=20;
mybox.depth=30;
v1= mybox.width* mybox.height* mybox.depth;
System.out.println(“Volume of “+v1);
}
}
Object
Object is a class variable. An object is a block of memory that contains space to store all the
instances variables. Creating an object is also referred as instantiating an object. Objects are
created by using new operator. The new operator creates an object of the specified class and
returns a reference to the object created.
Adding method to box class.
class box{
double width;
double height;
double depth;
void vol(){
System.out.println(“Volume is “);
System.out.println(width*height*depth);
}}
class boxdemo{
public static void main(String ar[]){
box mybox=new box();
mybox.vol();}
}

Prepared by Amit Shah 22 L J Polytechnic


Java Programming 5th CE IT

Returning a value:
class box{
double width;
double height;
double depth;
double volume(){
return width * height * depth;
}
}
class boxdemo4{
public static void main(String args[]){
box mybox1=next box();
box mybox2=next box();
double vol;
mybox1.width=10;
mybox1.height=20;
mybox1.depth=15;
mybox2.width=3;
mybox2.height=6;
mybox2.depth=9;

vol=mybox1.volume();
System.out.println(“volume is ”+vol);
vol=mybox2.volume();
System.out.println(“ volume is ” +vol);
}}
->> Adding a method that takes PARAMETER.
class Box{
double width;
double height;
double depth;

double volume(){
return width * height * depth;
}

Prepared by Amit Shah 23 L J Polytechnic


Java Programming 5th CE IT

void setDim(double w, double h, double d)


{
width = w;
height= h;
depth = d;
}}
class boxDemos
{
public static void main(String args[]){
Box mybox1= next Box();
Box mybox2 = new Box();
double vol;
mybox1.setdim(10,20,15);
mybox2.setdim(3,6,9);
vol = mybox1.volume();
System.out.println(“volume is”+vol );
vol = mybox2.volume();
System.out.println(“volume is”+vol );
}
}
O/P :- Volume is 3000
Volume is 162

Constructor:-
Constructor is a special member function whose task is to initialized class object . It is
special because the class name and constructor name is always same.
Characteristics of constructor:-
• The class name and constructor name should always be same.
• Constructor do not have explicit return type not even void , because the implicit return
type of constructor is class itself.
• Constructor code automatically called when object of a class is created.
• When in a class, constructor is not provided the default constructor is created . It will
initialized all the instance variable with 0.
• When a parameter is provided , it is called parameterized Constructor.
class Box
{

Prepared by Amit Shah 24 L J Polytechnic


Java Programming 5th CE IT

double width;
double height;
double depth;
box ( )
{
System.out.println(“ constructing box”);
width=10;
height=10;
depth=10;
}
double volume ( )
{
return width * height * depth;
}}
class boxdemo6{
public static void main(String args[]){
Box mybox1=new box();
Box mybox2=new box();
double vol;
vol=mybox.volume();
System.out.println(“volume”+vol);
}}
Output:
Constructing box
Constructing box
Volume is 1000.0
Volume is 1000.0

Parameterized constructor: When the parameters are added to the constructor or when
constructor takes parameter then it is called as parameterized constructor.
class Box
{
double width;
double height;
double depth;

Prepared by Amit Shah 25 L J Polytechnic


Java Programming 5th CE IT

box (double w1, double h, double d)


{
width =w;
height =h;
depth=d;
}
double volume(){
return width*height*depth;
}
}
class boxdemo7{
public static void main(String args[]){
Box mybox1=new box(10,20,15)
Box mybox1=new box(3,6,7);
volume vol1;
vol=mybox1.volume();
System.out.println(“volume is”+vol);
vol=mybox2.volume();
System.out.println(“volume is”+vol);
}}
Output:
Volume is 3000.0
Volume is 162.0
The this keyword:
This keyword will always point to the current object.
• This can be used inside any method to refer to the current object.
• This is always a reference to the object on which the method was called.
• The must common reason for using this keyword is to hide instance variable. when
local variable has the same name as an instance variable, the local Variable hides the
instance Variable
Example
class Box
{
double width,height,depth;
Box(double width,double height,double depth)

Prepared by Amit Shah 26 L J Polytechnic


Java Programming 5th CE IT

{
this.width=width;
this.height=height;
this.depth=depth;
}
double volume(){
return width*height*depth;
}
}
class BoxDemo7{
public static void main(String args[]){
Box mybox1=newBox(10,20,15);
Box mybox2=newBox(3,6,9);
double vol;
System.out.prinln(“volume is”+vol);
vol=mybox2.volume();
System.out.prinln(“volume is”+vol);
}
}
Output:-
Volume is 3000.0
Volume is 162.0

Garbage Collection
• Object are dynamically allocated by using new operator
• Such object are destroyed and their memory must be released for later reallocation
• In java destruction of object take place automatically
• This is achieve by a process called Garbage Collection.
• Garbage Collection process runs on allow priority thread.
• The Garbage Collection knows how to release memory allocated with new.
• Any object is eligible for Garbage Collection when your program can no longer
reference it.
• Local variables are eligible for Garbage Collection when your program can no longer
reference it.
• An object is available for Garbage Collection on if it is set to ’null’.

Prepared by Amit Shah 27 L J Polytechnic


Java Programming 5th CE IT

• Garbage Collection is guaranteed with the objects with no reference.


• We can not exactly predict when the Garbage Collection will occur.
• You can explicitly make a call to the garbage collection by calling System.gc(); or
Runtime getRuntime.gc(); but this does not guarantee when it will happen.
• If you want to perform some task when your object is about to be garbage collected
you can override java.lang object method called finalize()
Finalize() Method
• It is protected does not throws a throwable object.
Protected void finalize()throws throwable
{
//finalization code
}
• Garbage Collection before performing clean-up calls the finalize().It is called just
prior to Garbage Collection.
• It is not called when an object goes out of code.
• It is a finalize method exit it is guaranteed to be executed only once but you
cannot know when or even if whether finalize() method will be executed.
• finalize() should be used for closing files and other resources which you think are
not Garbage Collection.
An object is available for gc, if you have either set it to null or you have redirected the
variable that was originally referring to it, so that it now refers to a different object.
To make sure that an object to be garbage collected remove all references to it.
• Method Overloading
When more method are created having same name, but different declaration of parameter list
with different then the method are same to be overloaded And the process is called method
overloading. Java supports polymorphism through method overloading – “ One interface
multiple methods “
Method overloading is used when objects are required to perform similar tasks but using
different input parameters. When we call the method in an object, Java first matches the
method name and then number and type of parameters to execute-this is the process known as
polymorphism-object oriented concept.
Example:
class OverloadDemo
{
void test( ){
System.out.println(“No parameters”);
}
void test(int a){

Prepared by Amit Shah 28 L J Polytechnic


Java Programming 5th CE IT

System.out.println(“a:”+a);
}
void test(int a,int b){
System.out.println(“a and b:” +a+ “ ” +b);
}
double test(double a){
System.out.println(“double a:” +a);
return a*a;
}
}
class Overload{
public static void main(String args[]){
OverloadDemo ob=new OverloadDemo( );
double result;
ob.test( );
ob.test(10);
ob.test(10,20);
result = ob.test(123.2);
System.out.println(“Result of ob.test (123.2): result”);
}
}
Output:
No parameters
a : 10
a and b : 10 20
double a : 123.2
result of ob.test (123.2) : 15178.24

Overloading Constructor
Like method constructor can also be overloaded. Since the constructor in a class have the
same name as the class, their signature are differentiated by their parameter list.
Example:
class Box{
double width;
double height;

Prepared by Amit Shah 29 L J Polytechnic


Java Programming 5th CE IT

double depth;
Box (double w, double h, double d){
width = w;
height = h;
depth = d;
}
Box ( ){
width = -1;
height = -1;
depth = -1;
}
Box (double len){
width = height = depth = len;
}
double volume(){
return width*height*depth;
}
}

class overloadcons{
public static void main (string args[])
}
Box mybox1 = new Box (10,20,15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol =Mybox1.volume();
System.out.println (“volume of mybox1 is”+ vol);
vol = Mybox2.volume();
System.out.println (“volume of mybox2 is”+ vol);
vol = Mycube.volume();
System.out.println (“volume of mycube is”+ vol);
}}
Output:-
volume of mybox1 is 3000.0

Prepared by Amit Shah 30 L J Polytechnic


Java Programming 5th CE IT

volume of mybox 2 is -1.0


volume of mycube is 343.0

Using objects as parameter


class test
{
int a,b;
test (int i,int j){
a=i;
b=j;
}
boolean equals(test o){
if (o.a = = a&& o.b = = b)
{
if (o.a = = a&& o.b = = b)
return true;
else
return false;
}}
class passob{
public static void main(string args[]){
test ob1 = new test(100,22);
test ob2 = new test(100,22);
test ob3 = new test(-1,-1);
System.out.println(“ob1 == ob2”+ob1.equals(0b2));
System.out.println(“ob1 == ob3”+ob1.equals(0b3));
}
}
output:
ob1 == ob2 : true
ob1 == ob3 : false
• Call by value:
In call by value the method copies the value of an argument into formal parameter.
The formal parameter but changes the value in subroutine but there is no effect on
The argument , this process is called call by value

Prepared by Amit Shah 31 L J Polytechnic


Java Programming 5th CE IT

Example
class test {
void meth (int i , int j){
i*=2;
j/=2;
}
}
class callbyvalue{
public static void main(string args[]){
test 0b = new test();
int a=15, b=20;
System.out.println(“a and b before call:”+a+ “ “ +b);
Obmeth(a,b);
System.out.println(“a and b after call:”+a+ “ “ +b);
}}
o/p:
a and b before call:15 , 20
a and b before call:15, 20

Call by Reference:
In call by reference a reference to an argument is passed to the parameter inside the
subroutine [ this reference is used to access the actual argument specified in the call , this
means that change make to the parameter will after the argument used to subroutine:

Ex.
class test {
int a,b;

test (int i,int j)


{
a=i;
b=j;
}

void meth (test o)


{
o.a *=2;
o.b/=2;
}
}
class CallByRef

Prepared by Amit Shah 32 L J Polytechnic


Java Programming 5th CE IT

{
public static void main(String ar)
{
test ob=new test(15,20);
System.out.println(“ob.a and ob.b before call:”+ob.a+” “+ob.b);

ob.meth(ob);

System.out.println(“ob.a and ob.b after call:”+ob.a+” “+ob.b);


}
}

O/P:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10

Returning Object:
class test {
int a;

test (int i)
{
a=i;
}

test incrByTen()
{
test temp=new test(a+10);
return temp;
}
}

class Report{
public static void main(String ar[]){
test ob1=new test (2);
test ob2;

ob2=ob1.incrByTen();
System.out.println(“ob1.a”+ob1.a);
System.out.println(“ob2.a”+ob2.a);

ob2=ob2.incrByTen();
System.out.println(“ob2.a after second increase:”+ob2.a);
}}

O/P:
ob1.a 2
ob2.a 12
ob2.a after second increase 22

Prepared by Amit Shah 33 L J Polytechnic


Java Programming 5th CE IT

Recursion:
Recursion is the process of defining in term of itself. It allows a method to call itself.
The method is called itself, said to be recursive.
Ex.:
class Factorial {
int fact (int n) {
int result;
if(n==1)
return 1;
else
result=fact(n-1)*n;
return result;
}
}

class Recursion{
public static void main(String ar)
{
Factorial f=new Factorial();
System.out.println(“Factorial of 3 is “+ f.fact5(3));
System.out.println(“Factorial of 4 is “+ f.fact5(4));
System.out.println (“Factorial of 3 is “+ f.fact5(3));
} }
o/p
Factorial of 3 is6
Factorial of 4 is24
Factorial of 5 is120
Static keyword:
Static can be three Things:
 static variable
 static method
 static block
-> static variable:
When a member is declared static, it can be access before any object of its class is created
|-> static member can be used independent of any object outside of the class
In which they are declared by specifying Name of the class followed by the dot operator
Syntax: class.memeber;
ii) Static method:
 They can only call other static method
 They must only access static data

Prepared by Amit Shah 34 L J Polytechnic


Java Programming 5th CE IT

 They cannot refer to this or super in any way


 Static method cannot be made abstract and private
 we can declared static method as final protected, synchronize and public
 we cannot override a static method with a non static method
iii) Static Block:
 Though constructor can’t be declared as static java provides static block as
constructor a special syntax to allow for static initialize
 Use the class static keyword followed by a method body
 More than one static block can be declared
 All the static blocks or constructors are executed according to their order of
appearance
 Static blocks or constructor are executed as soon as the class loads
Ex
class usestatic{
static int a=3;
static int b;
static void meth(int x){
System.out.println(“x=” +x);
System.out.println(“a=” +a);
System.out.println(“b=” +b);
}
static{
System.out.println(“static block initialize”);
b=a*4;
}
public static void main(String args[]){
meth(42);
}}
o/p:
static block initlize
x=42
y=3
b=12
• Command line argument:
class CommandLine{
public static void main(String args[]) {
for(int i=o;i<args.length;i++)

Prepared by Amit Shah 35 L J Polytechnic


Java Programming 5th CE IT

System.out.println(“args[“+i+”]:”+args[i]);
}
}
• javaCommandLine: this is a test 100-1
C/P : args[0] : this
args[1] : is
args[2] : a
args[3] : test
args[4] : 100
args[5] : -1

INHERITANCE
• Definition:-
“The mechanism of deriving new class from old one is called inheritance. The old class is
known as base class or supper class or parent class. The new class is called as sub class. The
inheritance allows all sub classes to inherit all the variables and method of their parent
classes.”
class A{
int i,j;
void showij() {
System.out.println(“I and j:”+i+” “+j);
}
}
class B extend A {
int k;
void showk() {
System.out.println(“k:”+k);
}
void sum() {
System.out.println(“i+j+k:”+(i+j+k));
}
}
class simpleInheritance {
public static void main(String args[]) {
A superob=new A();
B subob=new B();

Prepared by Amit Shah 36 L J Polytechnic


Java Programming 5th CE IT

superob.i=10;
superob.j=20;
System.out.println(“contents of superob:”);
superob.showij();
System.out.println();
subob.i=7;
subob.j=8;
subob.k=9;
System.out.println(“contents of subob: ”);
subob.showij();
subob.showk();
System.out.println();
System.out.println(“sum of I, j and k in subob:”);
sumob.sum();
}
}
O/P:- Contents of superob:
i and j : 10 20
Contents of superob:
i and j : 7 8
k:9
sum of i, j and k in subob:
i+j+k : 24

• Member Access and inheritance:


Subclass includes all of the members of the its supers class, it cannot access those
members of the super class that have been declared as private.
class A{
int i ;
int j;
void setij ( int x , int y ){
i =x;
j =y;
}}
class B extends A{

Prepared by Amit Shah 37 L J Polytechnic


Java Programming 5th CE IT

int total ;
void sum() {
total = i + j;
}}
class Access{
public static void main (String args[]){
B subob = new B ( );
subob.setij (10,12);
subob.sum ( );
System.out.println(“ Total is :” + subob.total);
}
}
• A super class variable can reference a subclass object.
• A reference variable of a super class can be assign a reference to any sub class be
assign a reference to any sub class derived from that super class.
• When a reference to a subclass object is assigned to a super class reference variable.
You will have access only to that part or the object defined by the super class.
Super Keyword:- Whenever a subclass needs to refer to its immediate super class , it can be
do by using keyword super. The super has two general forms:
1.) It is used to access the member of super class that has been hidden by the member of
subclass .
2.) To first call the superclass constructor.
Accessing superclass Members:- Super always refer to the superclass in which it is used . It
has following format:
Super.member
Member can be either a method or an instance variable.
i) Accessing instance variables
class A
{
int i;
}
class B extends A
{
int i;
B(int a,int b){
super.i=a;
i=b;

Prepared by Amit Shah 38 L J Polytechnic


Java Programming 5th CE IT

}
void show(){
System.out.println(“i in superclass:”+super.i);
System.out.println(“i in subclass:”+i);
}
}
class usesuper{
public static void main(String args[]) {
B subOb=new B(1,2);
subOb.show();
}
}
O/P:-- i in superclass 1
i in subclass 2
ii) Accessing instance variables: If method overrides one of its superclass method you
can invoke the overridden method through the use of keyword super.

class superclass {
void printmethod(){
System.out.println(“printed in Superclass”);
}
}
class subclass extends superclass {
void printmethod(){
super.printmethod();
System.out.println(“printed in Subclass”);
}
public static void main(String args[])
{
subclass s = new subclass();
s.printmethod();
}
}
O/P: printed in superclass
printed in subclass

Using super to call superclass constructor : A subclass can call a constructor method defined
by its superclass by use of following form of super.
Super(parameter-list);
Here,parameter-list specifies any parameters needed by the constructor in the
superclass.Super() must always be the first statement executed inside a subclass’s
constructor.

Prepared by Amit Shah 39 L J Polytechnic


Java Programming 5th CE IT

Example:=>
class box{
double width;
double height;
double depth;
box(box ob){
width=ob.width;
height=ob.height;
depth=ob.depth;
}
box(double w,double h,double d){
width=w;
height=h;
depth=d;
}
box(){
width=-1;
height=-1;
depth=-1;
}
box(double len){
width=height=depth=len;
}
double volume(){
return width*height*depth;
}
}
class boxweight extends box{
double weight;
boxweight(box1.length ob)
{
super(ob);
weight=ob.weight;
}
boxweight(double w,double h,double d,double m){

Prepared by Amit Shah 40 L J Polytechnic


Java Programming 5th CE IT

super(w,h,d);
weight=m;
}
boxweight()
{
super();
weight=-1;
}
boxweight(double len,double m)
{
super(len);
weight=m;
}
}
class demosuper
{
public static void main(String args[])
{
boxweight mybox1=new boxweight (10,20,15,34.3);
boxweight mybox2=new boxweight (2,3,4,0.076);
boxweight mybox3=new boxweight ();
boxweight mycable =new boxweight (3,2);
boxweight mycable =new boxweight (mybox1);
double vol;
vol=mybox1.volume();
System.out.println(“Volume of mybox1 is :”+vol);
System.out.println(“Weight of mybox1 is :”+mybox1.height);
System.out.println();
Vol=mybox2.volume();
System.out.println(“Volume od mybox2 is :”+vol);
System.out.println(“Weight of mybox2 is :”+mybox2.height);
System.out.println();
vo1=mybox3.volume();
System.out.println(“volume of mybox3 is”+vo1);
System.out.println(“Weight f mybox3 is”+mybox3.weight);

Prepared by Amit Shah 41 L J Polytechnic


Java Programming 5th CE IT

System.out.println();
vo1=myclone.volume();
System.out.println(“Volume of my clone is”+vo1);
System.out.println(“weight of my clone is”+myclone.weight);
System.out.println();
v01=mycube.volume();
System.out.println(“volume of mycube is”+vo1);
System.out.println(“Weight of mycube is”+vo1);
System.out.println();
}
}

• When constructor are called:


Constructor are called in order of derivation from super class to sub class .This order is
same whether or not super is super .If super is not used then the default or parameter less
constructor of each super class will be executed.

Example:
class A{
A()
{
System.out.println(“inside A’s constructor”);
}
` }
class B extends A
{
B()
{
System.out.println(“inside B’s constructor”);
}
}
class c extends B
{
c()
{

Prepared by Amit Shah 42 L J Polytechnic


Java Programming 5th CE IT

System.out.println(“Inside C’s constructor”);


}
}
class callingcons
{
public static void main(String args[])
{
C o=new c();
}
}
Output:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
 Method Overridden:
When a method in subclass has the same name and type signature as a method in it
Superclass, then the method in the subclass is said to override the method in the superclass.
When an overridden method is called from within a subclass, It will always greater to the
version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden. The method defined in the superclass is inherited by its subclass
and is used by the object created by subclass.
Example :
class A
{
int i,j;
A(int a,int b)
{
i =a;
j=b;
}
void show () {
System.out.println(“I and j”+i+””+j);
}
}
class R extends A{
int k;

Prepared by Amit Shah 43 L J Polytechnic


Java Programming 5th CE IT

B(int a,int b,int c){


super (a,b);
k=c;
}
void show() // again over ride
{
System.out .println(“k:”+k);
}
}
class override
{
public static void main (String args[])
{
B subob=new B(1,2,3);
super.show();
}
}
output
k:3

DYANAMIC METHOD DISPATCH


Dynamic method dispatch is the mechanism by which a call to an override function is
resolved at runtime rather than compile time. It allows Java to (implement runtime
polymorphism)
A superclass reference variable can refer to a sub class object. This fact is used to resolve
calls to a override method at run time.
When an overridden method is called through a superclass reference, Java determines which
version of that method to execute based on the type of object being referred to at the time of
the call occurs. Thus this determination is made at run time.
class A
{
void callme()
{
System.out.println(“inside A’s callme method”);
}
}

Prepared by Amit Shah 44 L J Polytechnic


Java Programming 5th CE IT

class B extends A{
void call me(){
System.out.println(“inside b’s call me method”) ;
}}
class c extends A{
void call me(){
System.out.println(“inside c’s call me method”) ;
}
}
class dispatch{
public static void main (String args[]){
A a =new A();
B b =new B();
C c =new C();
A r;
r=a;
r.callme();
r=b;
r.callme();
r.c;
r.callme();
}
}
output
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method

ABSTRACT CLASSES AND ABSTRACT KEYWORD


When we require that certain method be overridden by subclasses. Then abstract type
modifier is used. Then abstract type modifier is used. They have no implementation specific
in superclass but subclass must override it. The general form of abstract method or abstract
class.
abstract class classname
{
}

Prepared by Amit Shah 45 L J Polytechnic


Java Programming 5th CE IT

abstract type_name(parameter_list)
}
}
An abstract method has no body means It defines method signature, return Value and the
exception it throws. If a class contain one or more abstract method then the class become
abstract. The class which inherits the abstract class must override the abstract method else
that class must be declared abstract. Object of abstract class cannot be created but reference
of abstract class can not create.
 Abstract class can contain concrete method.
 An abstract method can not be private, static, final or synchronized.
 Constructor can not be declared as abstract.
 Abstract class are used to act as a base class.
 A class can be abstract even though no method are declared as abstract.
Ex.
abstract class A
{
abstract void callme();
void callmetoo()
{
System.out.println(“This is a concrete method”);
}
}
class B extends A
{
void callme()
{
System.out.println(“B’s implementation of callme”);
}
}
class AbstractDemo
{
public static void main(“String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}

Prepared by Amit Shah 46 L J Polytechnic


Java Programming 5th CE IT

}
Final keyword:
The keyword final has three uses.
i) It can be used to create the equivalent of a named constant.
ii) Final is used to prevent overriding.
iii) Final is used to prevent inheritance.
i) Final variable:
 It is used to create the equivalent of a name constant.
 Variable can be declared as final but their contains can not be modified.
 Variable declared as final do not occupy memory on a per instance bases.
It is essentially a constant
 Variable declared as final must be initialized with some value.

ii) Final Method:


 Method can be declared as final.
 Final method cannot be overridden.
 If a method is declared final. It cannot be abstract.
 A final method optimizes code for speed.
 Class to final method cannot resolved at a compile time because they can
not be overridden. This is also on called late binding.

iii) Final class:


 Classes can be declared as final.
 Final classes cannot be inherited or extended. If attempt is made to inherit
that class will cause and error and compiler will not allow it.
 It is illegal to declare a class both abstract and final because abstract is
incomplete in itself and relies on its subclass to provide complete
information and final class cannot be inherited.
General form of final class.
final class A
{
…..
……
}

final class B extends class


{
…….
……
}

Example of final method


class A
{
final void meth()

Prepared by Amit Shah 47 L J Polytechnic


Java Programming 5th CE IT

{
System.out.println(“this is a final method”);
}
}
class B extends A
{
void meth()
{
System.out.println(“Illegal”);
}
}
Visibility control/access modifiers
Java provides four type of visibility modifier
• public
• friendly/default
• protected
• private
• Public:
Any variable or method the entire class.by declaring the variables or method as public
it is possible to make them visible to all the classes outside the class. A variables or
method declared as public has the more possible visibility and accessible everywhere
for example.

public int n;
public void addition()
{
……..
}
 Friendly Access
In the situation where no access modifiers is specified, the member defaults to a limited
version off public accessibility known as “friendly” level of access.
The basic difference between the “pubic” access and “friendly” access is that the public
modifier makes field visible in all accesses regardless or their Packages while the
friendly access make fields visible only in the same package, but not in other package.
 Protected:
Protected modifiers make the fields visible not only to all classes and subclasses in the
same package but also to subclasses in other packages.

Prepared by Amit Shah 48 L J Polytechnic


Java Programming 5th CE IT

The visibility level of a “protected” field are in between the public access and friendly
access. Non-subclasses in other packages can not access the “protected” members.
 Private access:
Private Fields provides highest degree of protection they are accessible only with their
own class. They can not .be inherited by subclasses and therefore not accessible in
subclasses.
A method declared as private behaves like a method declared as final. It prevents the
method form being subclasses
Non-private method can not be overridden in subclass and then make it private.
Rules visibility modifiers:
 Use public keyword if fields is to be visible everywhere.
 Use protected keyword if the fields is to be visible everywhere in current package and
also the subclasses in other packages.
 Use “default” keyword if the fields is nor be visible anywhere except in its only class.
Packages
Packages are container for classes that are used to keep the class name space
compartmentalize. Packages are Java’s way of grouping a variety of classes and interfaces
together. By organizing our classes into Packages we achieve the following benefits.
1. The classes contained in the Package of the other programs can be easily reused.
2. In packages classes can be unique compared with classes in other packages. That is
two classes in two different packages can have the same name. They may be referred
by their fully qualified name, compromising the packages name and the class name.
3. Packages provide a way to hide classes thus preventing other program or packages
from accessing classes that are meant for interval use only.
4. Packages also provide a way for separating design from coding. First we can design
classes and decide their relationships and the needed for the implement the java code
needed for the methods. It is possible to change the implementation of nay method
without affecting the rest of the design.
 Creating our own package involves the following steps:
1. Declare the package at the beginning of a file using the form.
Package package name;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files
are stored.
4. Store the listing as the class name. Java fie in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
 Remember that case is significant and therefore the subdirectory name must
match the package name.
Example:-
package Mypack;
public class Balance {
String name;
double bal;
public Balance (String n, double b) {
name=n;

Prepared by Amit Shah 49 L J Polytechnic


Java Programming 5th CE IT

bal=b;
}
public void show() {
if (bal < 0)
System.out.println(“”);
System.out.println(name+“: $” +bal);
}
}
class AccountBalance{
public static void main(String args[])
{
Balance current[]=new Balance[3];
current[0] = new Balance (“M.J. Patel”,123.23);
current[1] = new Balance (“Will Tell”,157.02);
current[2] = new Balance (“Rajnish Shrivastav”,-12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}
Scope of Access Specifier
Private No modifier Protected Public
Same Class Yes Yes Yes Yes
Same package sub class No Yes Yes Yes
Same package Non sub class No Yes Yes Yes
Different package sub class No Yes Yes Yes
Different package non sub class No No No Yes

Interfaces:
An interface is basically a kind of class like classes interfaces contain methods and variables
with a major difference. Using interface you can specify what a class must do, but not how it
does it.
 The general form of an interface:
Access specifier interfacename
{
Returntype methodname1(parameter list);

Prepared by Amit Shah 50 L J Polytechnic


Java Programming 5th CE IT

Returntype methodname2(parameter list);


Static final type variablename1=value;
Static final type variable name2=value;
…………………
Returntype methodname N(parameter-list);
Type final-variable N=value;
}
1. Access specifier is either public a not used. Whens no access specifier is included
then default access results and the interface is only available to other members of
the package in which it is declared. When it is declared public the interface can be
used by any other code.
2. Name is the name of the interface and can be any valid identifier.
3. The method in the interface do not provide any body not even our braces.
4. The method that implementing interface must be declared public. Also the type
signature of the implementing method must match exactly the type signature
specifies in the interface definition.
5. Any class implementing interface does not provide the body of a method in that
particular case that class should be declared has abstract.
6. Variables can be declared inside of the interface declaration. They are implicitly
final and static meaning they cannot be changed by the implementing class. They
must also be initialize with a constant value.
7. All methods and variables are implicitly public if the interface itself is declared as
public.
8. We cannot create the object of an interface but we can create the reference of the
interface.
9. We can implement any number of interface in class.
10. One interface can inherit another by use of the keyword extends.
EXAMPLE:-
interface CallBack
{
void Balance (int p)
}
class client implements CallBack
{
public void Balance (int p)
{
System.out.println(“Called from callback”+ p);
}
}
class AnotherClient implements CallBack{
public void Balance (int p)
{
System.out.println(“Called CallBack from Another Client”);

Prepared by Amit Shah 51 L J Polytechnic


Java Programming 5th CE IT

System.out.println(“The value of P is :-” + (p*p));


}
}
class MainDemo{
public static void main(String ar[]) {
CallBack c= new Client();
AnotherClient c1= new AnotherClient();
C=c1;
c.Balance(50);
}
}
OUTPUT:- Called from callback:400
Called CallBack from AnotherClient
The value of P is: 2500
 Syntax for implementing more than one interface and extending class.
class classname extends superclass implements interface1, interface2
{
Body of classname
}
 Example of extending interface

interface CallBack
{
void Meth();
}
interface CallBack1 extends CallBack
{
void Meth1();
}
interface CallBack2 extends CallBack1
{
void Meth2();
}
class client implemetns CallBack2
{
public void meth()
{
System.out.println (“In method”);
}
public void meth1()
{

Prepared by Amit Shah 52 L J Polytechnic


Java Programming 5th CE IT

System.out.println (“In method”);


}
public void meth2()
{
System.out.println (“In method”);
}
}
class MainDemo1
{
public static void main(String ar[[)
{
client C= new client();
C.meth();
C.meth1();
C.meth2();
}
}

EXECPTION HANDLING
 There are two types of error:
1. Compile time error
2. Run time error
 All syntax error will be detected and displayed by the java compiler and therefore
these errors are known as compile time error.
 Sometimes a program may compile successfully creating the classfile but may not run
properly. Such programs may provide wrong results due to wrong logic or may
terminate due to errors. This type of errors are called Run-time errors.
 Exception is an abnormal condition that arises in the code sequence at runtime. In
other word it is a runtime error.
 In java, exception is an object that decide the exceptional condition that arises in a
code sequence.
Java.lang.object

Java.lang.Throwable

Java.lang.Exception Java.lang.Error
Eg:- checked exception

Java.lang.RuntimeException
Eg:- Runtime exception

 General form of an exception handling block:


try
{
// block of code to terminate for errors
}
Prepared by Amit Shah 53 L J Polytechnic
Java Programming 5th CE IT

catch(Exception type1 exob)


{
// exception handler for Exception type1
}
catch(Exception type2 exob)
{
// exception handler for Exception type2
}
//……………
finally
{
//block of code to be executed before try blocks end.
}

 Common Java Exception


Exception Type Cause of Exception
1). Arithmetic Exception 1). Caused by math error such as division by zero
I/O.
2). ArrayIndexOutOfBoundsException 2). ArrayStoreException
3). Caused by bad array indexes. 3). Caused when a program tries to store the wrong
type of data in an array.
4). FileNotFoundException. 4). Caused by an attempt to access a non-existed file.
5). IOExecption 5). Caused by general IO failure such as inability to
read from file.
6). NumberFormatException 6). Caused when a conversion between strings and
number fails.
7). NullPointerException 7). Caused by referencing a null object.

 Using Try and Catch:


class Exec1{
public static void main(String ar[]) {
int a,d;
try{
d=0;
a=42/d;
System.out.println(“This will not be printed”);
}
catch(ArithmeticException){
System.out.println(“Division by zero”);
}
System.out.println(“\nAfter catch statement”);
}}

OUTPUT:-
Division by zero

Prepared by Amit Shah 54 L J Polytechnic


Java Programming 5th CE IT

After catch catch statement

Multiple catch classes:


class Multicatch{
public static void main (String ar[]){
try{
int a= ar.length;
System.out.println(“a=” + a);
int b= 42/a;
int c[]={1};
c[42]=99;
}
catch(ArithmeticException){
System.out.println(“Array index out of bound:”+e);
}
System.out.println(“After try/catch blocks”);
}
}
Nested try statements

class NestTry{
public static void main(String ar[]){
try{
int a=ar.length;
int b=42/a;
System.out.println(“a=”+a);
try{
if(a==1)
a=a/(a-a);
c[42]=99;
}
}
catch(ArrayIndexOutOfBoundsException){
System.out.printn(“Array index out of bound:”+e);
}
}
catch(ArithmeticException)
{
System.out.println(“Divide by 0”+e)
}
}
}

Throw : When we want to throw our own exceptions. We can do this by using the
keyword throw as follow:-
throw new Throwable_subclass;

Example:-

Prepared by Amit Shah 55 L J Polytechnic


Java Programming 5th CE IT

class Throwdemo
{
static void demopro()
{
try
{
Throw new NullPointerException(“demo”);
}
catch(NullPointerException e)
{
{
throwOne();
}
catch(IllegalAccessException e)
{
System.out.println(“caught”+e);
}}
}

O/P-- inside throwone


caught java.lang.IllegalAccessException : demo
Finally :- Finally creates a block of code that will be executed after a try/catch block has
completed and before the code following the try/catch block.
The finally block will executed whether or not an exception is thrown of an exception is
thrown,the finally block will execute even if no catch statement matches the excepton.
Example:
class FinallyDemo{
static void procA()
{
try{
System.out.println(“Inside procA throw new Runtime Exception (“demo”);
}
finally{
System.out.println(“procA’s final”);
}
}
static void procB(){
try
{
System.out.println(“Inside procB”);
}
finally{
System.out.println(“procB’s finally”);
}}
int x=5,y=1000;
try{
float z=(float)x/(float)y;
}

Prepared by Amit Shah 56 L J Polytechnic


Java Programming 5th CE IT

}
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”);
}
}}
O/P:
Caught My Exception
Number is too small
I am always here.
MULTITHREADED PROGRAMMING
1. Explain the life cycle of a thread
 The thread can enter into many states during its life time. The five types of states
are:
1) Newborn state
2) Runnable state
3) Running state
4) Blocked state
5) Dead state

New Thread Newborn

Stop
Start
Active Thread
Stop Dead

Running Runnable Killed


Thread Yield

Suspend Resume Stop


Wait notify
sleep
Blocked

 The Thread can be one state from there five states. It can move from one state one
state to another is various ways shown in figure.

Prepared by Amit Shah 57 L J Polytechnic


Java Programming 5th CE IT

1) Newborn state: When a thread object is created, the thread is born, and called as
thread is in New born state. In new born state the thread is not yet scheduled for
running.
 When the thread is in newborn states it can be
1) Either scheduled for running using start() method.
2) Or kill it using stop methods.

Newborn

Start Stop

Runnable State Dead

 Once, the thread is scheduled it can be moved to runnable state shown in figure.
The exception will be thrown if any attempt is made to use any method at this
stage.
2. Runnable State: The runnable state of a thread means that the thread is ready for
execution and is waiting for the availability of the processor. The threads which re
ready for execution are placed in queue. So the runnable state joins the queue of the
threads that are waiting for execution.
 If all threads have same priority then they are given a time slice for execution in
round robin fashion, fist-come-first-serve manner. The thread after compiling its
time slice, joins the end of queue again waits for its run for execution, And this
process of closing time to threads is known as time slicing
 To release the control of thread to another thread to equal priority before its turn
comes, yield() method can be used.

Running thread

Runnable Threads

3. Running State: Running state means that the processor has given its time to the
thread for its execution. The thread runs until it releases control on its own or it is
preempted by higher order priority thread. A running thread can relinquish its control
in any one of the following situations:
1) It is suspended using suspended method, which can be useful. When to
suspend thread for some time but do not want to kill.

suspend()

Prepared by Amit Shah 58 L J Polytechnic


Java Programming 5th CE IT

Resume

Running Runnable Suspended

2) It can be made to sleep. The thread can be made to sleep for specified time period
using the method sleep (time) where time is in milliseconds.
Sleep()

After()

Running Runnable Suspended


 In this period the queue is out of ready queue. As soon as the time
wait()

Notify

Running Runnable Waiting

 Period is over the thread is re-entered in runnable state shown in figure.


3). Thread is waiting until some event occurs. This is done using wait() method. The
thread can be scheduled to run again using the notify() method.
4. Blocked State:- The thread can be in blocked state when it is prevented from
entering into the runnable state and subsequently the running state. This may happen
when thread is suspended, sleeping or waiting in order to satisfy certain requirements.
A block thread is considered as “not runnable” but not dead and therefore fully
qualified to run again.
5. Dead State;- As every thread has a life cycle, a running thread ends its life when it
has completed executing its run() method. It is an natural dead of thread.
However thread can be killed by sending the stop message to it any state thus causing a
premature death of it. A thread can killed as soon as it is born, or while it is running or even
when it is in “not runnable” (blocked) condition.

2). Creating a Thread


 Java defines two ways to create a thread.
1) You can implement the Runnable interface.
2) You can extend Thread class.

1) Implementing Runnable:

Prepared by Amit Shah 59 L J Polytechnic


Java Programming 5th CE IT

The easiest way to create thread is to create a class that implements runnable interface. To
implements a runnable class need only implement single method call run which is declared
like this
public void run()
Following are the steps:
1) Declared the class as it is implementing runnable interface.
2) Implement run() method.
3) Crete thread by defining an object that instantiated from this “runnable” class as the target
of the thread.
4) Call the thread’s start() method to run the thread.
5) The run can call other methods, use other classes and declared variables, just like the main
thread can. The only difference is that run() establishes the entry point for another, concurrent
thread of execution within your program. The thread will end when run() returns.
The thread defines several constructors. The one that we will use is shown here:
Thread(Runnalbe threadob, String Threadname)
class NewThread implements Runnalbe
{
Thread t;
NewThread()
{
t=newthread (this , “Demo thread”);
system.out.println(“Child thred:”+t);
t.start();
}
public void run()
{
try
{
for(int i=5; i>0; i--)
{
System.out.println(“Child thread”+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println(“child interrupted”);
}
System.out.println(“Exiting child thread”);
}
}
class Threaddemo
{
public static void main(string arg[])
{
New newthread();

Prepared by Amit Shah 60 L J Polytechnic


Java Programming 5th CE IT

try
{
for(i=5; i>0; i++)
{
System.out.println(“Main method”+i);
Thread.sleep(1000);
}
}
catch(InterruptedException)
{
System.out.println(“Main thread interrupted”);
}
System.out.println(“Main thread existing”);
}
}
2). Extending Threadclass: To create a thread is to create a new class that thread and then
create am instance of that class. Extending a thread class includes following steps:
1. Declare the class extending the thread. The thread class cn be extended as follows:
class MyFirstThread extends Thread
{
……
}
2. Implement the run() method that is responsible for executing the sequence of code that the
thread with executed. The extending class must override the new thread. The run() method is
inherited by the class MyFirstThread implement the code to be executed by new thread
MyfirstThread. The implementation of run() will be like:
public void run()
{
-----
}
 When new thread is started with start, Java calls the thread run() method. So it is run()
where all the action takes place.
3. Create a thread object and call the start() method to initiate the thread execution. Following
statement creates new thread.
A) MyFirstThread T = new MyFirstThread().
B) T.start().
C) The start method will automatically call run() method.

Example:-

class NewThread extends Thread


{

Prepared by Amit Shah 61 L J Polytechnic


Java Programming 5th CE IT

NewThread()
{
super(“Demo Thread”);
System.out.println(“Child Thread”+ this);
start();
}
public void run()
{
for(int i=5; i>0; i--)
{
System.out.println(“Child thread”+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println(“child interrupted”);
}
System.out.println(“Existing child thread”);
}
}//class Newthread ends here
class ExtendThread
{
public static void main(string ar[])
{
new newthread();
try
{
for(i=5; i>0; i++)
{
System.out.println(“Main method”+i);
Thread.sleep(1000);
}
catch(InterruptedException){
System.out.println(“Main thread interrupted”);
}
System.out.println(“Main thread existing”);
}
}
Creating Multiple Thread
class NewThread implemtns Runnalbe
{
String name;
Thread T;
Prepared by Amit Shah 62 L J Polytechnic
Java Programming 5th CE IT

NewThread (String Threadname) {


name= threadname;
T=new Thread(this,name);
System.out.println(“New Thread:”+i);
T.start();
}
public void run() {
try {
for(int i=5; i>0; i--)
{
System.out.println(name +“:”+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name + “ interrupted”);
}
System.out.println(name + “Exiting thread”);
}
}
class MultiThreaddemo
{
public static void main(string ar[])
{
new newthread(“One”);
new newthread(“Two”);
new newthread(“Three”);
try
{
Thread.sleep(1000);
}
catch(InterruptedException) {
System.out.println(“Main thread interrupted”);
}
System.out.println(“Main thread existing”);
}
}
Thread Methods:
1). Sleep:- General form of sleep method is:
static void sleep(long milliseconds) throws InterruptedException
 The number of milliseconds to suspend is specified in milliseconds. This method may
throw can InterruptedException.

Prepared by Amit Shah 63 L J Polytechnic


Java Programming 5th CE IT

 The sleep() method has second form shown next, which allows you to specify the
period in terms of milliseconds and nanoseconds.

static void sleep(long milliseconds, int nanoseconds) throws


InterruptedException

 This second form is useful only in environments that allow timing period as short as
nanoseconds.
2).SetName:- You can name the thread by using Setname. The general form is:
final void SetName (String threadname)
3). getName:- we can obtain the name of thread by calling getname method. The general
form is:
final sting getName()
4). isAllive:- there are two ways to determine whether a thread has finish.
1. You can call isAllive() on the thread. And its general form is:
final boolean isAllive()
 The isAllive() method returns true, if the thread upon which it is called is still
running. If returns false otherwise.
2. Join():- This method is used to wait for a thread to finish. The general form is:
final void join() throws InterruptedException
 This method waits until the thread on which it is called terminates. Its name comes
from concept of the allow thread waiting until the specified thread joins it.
 Program of setName and getName method.

class CurrentThreadDemo {
public static void main (String arg[]) {
Thread t = Thread.currentThread();
System.out.println(“Current Thread:”+t);
t.SetName(“My Thread”);
System.out.println(“After name change”+t);
try {
for(int n=5; n>0 ; n--) {
System.out.println(n);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
System.out.println(“Main Thread Interrupted..”);
}

Prepared by Amit Shah 64 L J Polytechnic


Java Programming 5th CE IT

}
}//class current thread demo is over.

OUTPUT:- Current Thread: Thread(main,5,main)


After name change: Thread [My Thread, 5, main]
5
4
3
2
1
Program using yield(), start(), stop() and sleep() method.
class x extends Thread {
public void run() {
for(int i=1; i<5; i++) {
yield();
System.out.println(“It from thread” x: i =”+i”);
}
System.out.println(“It Exit from thread X”);
}
}//class x over
class B extends thread {
public void run() {
for(int j=1; j<5; j++)
{
System.out.println(“It from thread” B: j =”+j”);
if(j==3)
stop();
}
System.out.println(“It Exit from thread B”);
}
}//class B over
class C extends Thread
{
public void run()
{

Prepared by Amit Shah 65 L J Polytechnic


Java Programming 5th CE IT

for(int k=1; k<5; k++)


{
System.out.println(“It from Thread C: k=”+k);
if(k==1)
try
{
sleep(1000);
}
catch(Exception e)
{
}
}
System.out.println(“Exit from Thread C”);
}
}//class c over
class ThreadMethod
{
public static void main(String arg[])
{
X Thread = new X();
B Thread = new B();
C Thread = new C();
System.out.println(“Start Thread X”);
Threadx.start();
System.out.println(“Start Thread B”);
ThreadB.start();
System.out.println(“Start Thread C”);
ThreadC.start();
System.out.println(“End of Main Thread..”);
}
}// main class thread priority is over

Thread Priority
 We can set the priority of a thread.
 The thread priority can be assign by using set priority method. The general form is:

Prepared by Amit Shah 66 L J Polytechnic


Java Programming 5th CE IT

ThreadNAme.setPriority(int Number);
 Where the number is an integer value, or thread priority.
 The Thread class defines following priority contansts:
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
By default intNumber is set to NORM_PRIORITY.
 We can obtain the current priority setting by calling the getPriority method of thread.
Final int getPriority()
 Whenever higher priority thread come in the currently running thread will be pre-empted
by incoming thread, and thus it forces the current running thread to move to the runnable
state.
Thus, higher priority thread always pre-empted lower priority threads.
class X extends Thread
{
public void run()
{
system.out.println(“It Thread X started”);
for(int i=1; i<=4; i++)
{
system.out.println(“It from Thread X :=”+i);
}
system.out.println(“It Thread X started”);
}
}
class B extends Thread
{
public void run()
{
system.out.println(“It Thread B started”);
for(int j=1; j<=4; j++)
{
system.out.println(“It from Thread B : j=” +j);
}
system.out.println(“It exit from Thread B”);
}
}
class C extends Thread
{
Public void run()
{
system.out.println(“It Thread X started”);
for(int k=1 ; k<=4 ; k++)
{
system.out.println(“It From Thread C=”+k);
}

Prepared by Amit Shah 67 L J Polytechnic


Java Programming 5th CE IT

system.out.println(“It exit from Thread C”);


}
}
class ThreadPriority
{
public static void main(String args[])
{
X thread=newX();
B thread=newB();
C thread=newC();
threadC.SetPriority(Thread.MAX_PRIORITY);
threadX.SetPriority(Thread.MIN_PRIORITY);
system.out.println(“Start Thread X”);
threadX.start();
system.out.println(“Start Thread B”);
threadB.start();
system.out.println(“Start Thread C”);
threadC.start();
system.out.println(“End of Main Thread”);
}
}

Synchronization: - When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at a time. The process
by which this is achieved is called Synchronization.
 For example: One thread trying to read records from file while another thread is still
writing to the same file. In Java, this problem can be overcome by using the technique known
as Synchronization. The keyword synchronized is used.
 When method is declared as synchronized in Java creates a monitor and hands over to the
thread that calls the method for first time. A monitor is an object that is used as a mutually
exclusive lock, or mutex. Only one thread can own a monitor at a given time. When
a thread acquires a lock , it is said to have entered the monitor. As long as thread
holds the monitor, no other thread can enter the synchronized section of code.
Monitor is similar to key and the thread that holds there key can only open the
lock. These other threads are said to be waiting for the monitor.

We can use Synchronize keyword ahead of method or we can lock object by


putting object in Synchronize keyword.
synchronized returntype methodname
{
//code here is synchronized
}
Example- Synchronized void exe()
{
-------------------------------------------
-------------------------------------------
}

Prepared by Amit Shah 68 L J Polytechnic


Java Programming 5th CE IT

It is also possible to make a block of code as Synchronized as shown below


Synchronized (lock-object)
{
------------------------------
------------------------------
}

When a thread completes its work of using synchronized method, it will


handover the monitor to the next thread to use same resource.
Program without using synchronize
class callme
{
void call(String msg)
{
System.out.println(“[ “+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(“Interrupted”);
}
System.out.println(“]”);
}
}
class caller implements Runnable
{
String msg;
callme target;
Thread t;
public caller(callme trgt, String s)
{
target=trgt;
msg=s;
t=new Thread(This);
t.start();
}
public void run()
{
target.call(msg);
}

class synch
{
public static void main(String args[])

Prepared by Amit Shah 69 L J Polytechnic


Java Programming 5th CE IT

{
callme target=new callme();
caller ob1=new caller(target,”Hello”);
caller ob2=new caller(target,”Synchronized”);
caller ob3=new caller(target,”World”);
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println(“Interrupted”);
}
}
}
O/P- Hello [Synchronized [World]
]
]
Using synchronize keyword in method

class callme
{
Synchronize void call (String msg)
{
system.out.println(“[“+msg);
Try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
system.out.println(“Interrupted”)
}
system.out.println(“]”);
}
}
class caller implements Runnable{
String msg;
callme target;

Prepared by Amit Shah 70 L J Polytechnic


Java Programming 5th CE IT

Thread t;
public caller (callme targ, String s){
target=targ;
msg=s;
t=new thread(this);
t.start();
}
public void run(){
target.call(msg);
}
}
class synch{
public static void main(String args[]){
callme target=new callme();
caller ob1=new caller(target,”Hello”);
caller ob2=new caller(target,”Synchronized”);
caller ob3=new caller(target,”World”);
try {
Ob1.t.join();
Ob2.t.join();
Ob3.t.join();
}
catch(InterruptedException e){
System.out.println(“Interrupted”);
}
}
}
O/P- [Hello]
[Synchronized]
[World]
Example of locking object by synchronized
class callme
{
void call(String msg)
{
System.out.println(“[“+msg);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
system.out.println(“]”);
}
}
class caller implements Runnable
{
String msg;
callme target;
Thread t;

Prepared by Amit Shah 71 L J Polytechnic


Java Programming 5th CE IT

public caller(callme targ,String s)


{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run(){
synchronized(target){
target.call(msg);
}
}
}
class synch1{
public static void main(String args[]){
callmetarget=new callme();
caller ob1=new caller(target,”Hello”);
caller ob2=new caller(target,”Synchronized”);
caller ob3=new caller(target,”World”);
try{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e){
System.out.println(“Interrupted”);
}
}
}

Deadlock- When two threads have a circular dependency on a pair of synchronized objects,
then there is deadlock .When two or more threads are waiting to gain control of resource. Due
to some reasons, the condition on which the waiting threads relay on to gain control does not
happen. The result is called as deadlock.
For example, suppose the thread A must access Method1 before it can release Method2,but
thread B can not release Method1 untill it gets hold of Method2.Because there are mutually
exclusive conditions, a deadlock occurs.
Deadlock is a difficult error to debug for two reasons:
i) In general it occurs only rarely,when two threads time-slice in just the
right away

String and StringBuffer

Prepared by Amit Shah 72 L J Polytechnic


Java Programming 5th CE IT

 Java implements strings as object of type string. When you create a string object,you
creating a string that cannot be changed that is once a string object has been
created,you cannot changed the characters that compromise the string.
 Each time if you need an alter version of an existing string,new string object is created
the contains the modification. The original string is left unchanged.
 For those cases in which a modifiable string is desired there is a companion class to
string called StringBuffer whose objects contain string that can be modified after they
are created.
 Both string and StringBuffer class are defined in java.lang . thus they are available to
all programs automatically both are declared final which means that neither of these
classes may be subclasses.
 String length:
The length of a string is the number of characters in it. To obtain this value the
length() function is used . It has following general form:
Int length()
Example: String s1=”ABCDEF”;
Int length=s1.length();
System.out.println.(“the length of string s1 is:”length);
o/p: the length of string is: 6
 Character Extraction Method:

1) Char At():
To execute a single character from a string, you can refer directly to an
individual character via the char At() method. It has this general from:
Char char At (int where)
Here where is the index of the character that you want to obtain the value of
where must be non negative and specify a location within the string char At()
returns the character at the specified location for example.
Example: Char ch;
Ch=”abc”char At(1);
o/p: ch=b
2) getchars():
If you need to more than one character at a time, you us the getchars()
method. It has this general form:
Void getchars(int sourcestart,int sourceEnd,char target[],int target start);
Here sourcestrat specifies the index of the beginning of the substring,and
sourceEnd specifies the index of the desired substring. Array that will receive
the characters is specified by target. The index within target at which the
substring will be copied is passed in targetstart.
Example:
class getcharsDemo{

Prepared by Amit Shah 73 L J Polytechnic


Java Programming 5th CE IT

public static void main(String args[]){


String s =(”this is a demo of the getchars method:”);
int start=10;
int end=14;
char buf[]=new char[end-start];
s.getchars(start,end,buf,0);
System.out.println(buf);
}
}
o/p: demo
 string comparision:
1) equals
The function compare two string for equality. It has following general form:
Boolean equals(object str)
Here ,str is a string object being compared with the invoking string object. It returns
true if the the string contains the same charcter in the same order and false otherwise.
2) equalsIgnoreCase:
To perform a comparision that ignores case difference, call equalsIgnoreCase() when
it compare two string, it considers A-Z to be the same as a-z. It has following general
form:
Boolean equalsIgnoreCase(String str);
Here,str is the object being compared with invoking string Object. It ,too return true
if the string contain the same character in the same order, and false otherwise
EX:
class equalsDemo {
public static void main(String ar[]) {
String s1=”Hello”;
String s2=”Hello”;
String s3=”Good By”;
String s4=”Hello”;

System.out.println(“s1+”equals”+s2+”->”+s1.equals (s2));
System.out.println(“s1+”equals”+s3+”->”+s1.equals(s3));
System.out.println(“s1+”equals”+s4+”->”+s1.eqauls(s4));
System.out.println(“s1+”equalsIgnoreCase”+s4+”->”+s1.
equalsIgnorecase(s4));
}
}

O/P:
Hello equals Hello -> true
Hello equals Good By->false

Prepared by Amit Shah 74 L J Polytechnic


Java Programming 5th CE IT

Hello equals HELLO->false


Hello equalsIgnorecase Hello ->true
3) Startswith:
The startswith() method determines whether a given string begins with a specified
string. It has a general form:
Boolean startwith (String str)
Here,str is the string being tested. If the string matches true is returned otherwise false
is returned.
4) Endswith:
The endswith() method determines whether a given string ends with a specified
string. It has a general form:
boolean endswith(String str)
here, str the string being tested. If the string matches true is returned otherwise false
is returned.
Ex:
“Foobar” startswith (“foo”);
and
“foobar” endswith (“bar”);
Both function will returns true results. A second form of startwith() is as below:
boolean startwith(String str,int startIndex)
Here, startIndex specifies the index into the invoking string at which point the search
will begin for example,
“Foobar” Startswith (“bar”.3)
Returns true result.
Equals() versus ==:
The equals method compares the character inside a string Object. The ==operator
compares two object reference to see whether they refer to the same instance
Ex:
class EqualsNotEqualTo {
public static void main(String ar[])
{
String s1=”Hello”;
String s2=”new string (s1);
System.out.println(s1+”equals”+s2+”->”+s2.equals(s2));
System.out.println(s1+”==”+s2”->”+(s1==s2));
}
}
O/P:
Hello equals Hello -> true
Hello ==Hello ->false

Prepared by Amit Shah 75 L J Polytechnic


Java Programming 5th CE IT

CompareTo():
This function checks whether the string is less than or greater than or equal to the
other string. It has general form:
int compare To (string str)
Here, str is string being compare with the invoking string. The result of the
comparison is returned and is interpreted as Shown below:
Value Meaning
Less than zero Thi invoking string is less than str
Greater than zero The invoking string is greater than str
Zero The two strings are equal.

EX: WAP in java to read 10 strings from console and then print the stored on console.
import.Java.io.*;
public class sort {
public static void main(String ar[]) {
int i, j;
try{
InputSystemReader in = new InputStreamReader(BufferedReader br=new
BufferedReader(System.in);
System.out.println(“Enter the strings to be sort:”);
for (i=o;i<10;i++)
str[i]=br.readline();
System.out.println(“sorted string are:”);
for(i=0;i<10;i++){
for(i=i+1; j<10; j++){
if(str[i].compareTo(str[j]<0)
{
String temp =str[j];
str[j]=str[i];
str[i]=temp;
}
}
System.out.println(str[j]);
}
catch(Exception e)

Prepared by Amit Shah 76 L J Polytechnic


Java Programming 5th CE IT

{
System.out.println(e);
} }
}
Searching strings:
The string class provides two methods that allows you to search a string for a
specified character or substring.
I). Index of(): searching the first occurrence of a character or substring.
II).lastIndex of(): searching for the last occurrence of a Character or substring.
These, two methods are overload in several different ways. In all case the methods
return the index at which the character or substring was or an failure.
 To search for the first occurrence of character use int indexOf(int ch)
 To search for last occurrence of a character use int lastIndexOf(int ch)
Here, ch is the character being sought.
 To search for the first or last occurrence of a substring use.
int indexOf(string str)
int lastIndexOf(string str)
Here, str specifies the substring .
 We can specify a starting point for the search using these forms:

int indexOf(int ch, int startIndex)


int lastIndexOf(int ch,int startIndex)

int indexOf(string str, int startIndex)


int lastIndexOf(string str,int startIndex)
Here, startIndex specifies the index at which point the search begins. For indexOf()
the search runs from StartIndex to the end of the string. For lastIndexOf() the search
runs from startIndex to zero.

Modifying a string:
 Substring(): You can extract a substring using substring. It has two forms-
first is.
String substring (int startIndex)
Here, startIndex specifies the index at which the substring will begin. This
form returns a copy of the substring will begin. The form returns a copy of the
substring that begins at startIndex and runs to the end of the invoking string.
The second from of substring allows you to specify the beginning and ending
index of the substring.
String substring(int startIndex, int endIndex)

Prepared by Amit Shah 77 L J Polytechnic


Java Programming 5th CE IT

Here, startIndex specifies the beginning Index and endIndex specifies the
stoping point. The string returned contains all the characters from the
beginning index upto but not including the ending index.

 Concat():
We can concatenate two string using concat()
String concat(string str)
This method creates a new object that contains the invoking string with the
contents of str append to the end. Contact() performs the same function as
For example:
String s1=”one”;
String s2=s1.concat(“two”);
Puts the string “onetwo” into s2. It generates the same result as the following
sequence.
String s1=”one”;
String s2=s1+”two”;
 Replace():
The replace method replaces all the occurrence of the one character in the
invoking string with another character. It has the following general form:
String replace(char original, char replacement)
Here, original specifies the char be replaced by the character specified by the
replacement. The resulting string is return.
For example:
String s=”hello”.replace(‘1’,

Puts the string “HELLO” into s.


 Trim():
The trim() method returns a copy of the invoking string from which any
leading and trailing whitespace has been removed. It has the general from:
String trim()

Ex: string s=”Hello World” trim()


puts the string “Hello World” into s.
Changing the case of characters within a string.
The method toLowerCase() converts all the characters in a string from
uppercase to lowercase.
The method toUpperCase() converts all the characters in a string from
lowercase to uppercase
Non alphabetical characters, such as digits are unaffected. The general forms
of these methods are:
String toLowerCase()
String toUpperCase()

Prepared by Amit Shah 78 L J Polytechnic


Java Programming 5th CE IT

Both methods returns a string a string object that contains the uppercase or
lowercase equivalent of the invoking string.
Ex: class changecase {
public static void main(String args[]) {
String s=”this is a test”;
System.out.println(“original:”+s);
String upper=s.toUppercase();
String lower=s.tolowercase();
System.out.println(“uppercase:”+upper);
System.out.println(“lowercase:”+lower);
} }
O/P: original: This is a test
Uppercase: THIS IS A TEST
Lowercase: this is a test.
 StringBuffer:
StringBuffer is a class of string that provides much of the functionality of strings.
String represents fixed-length, immutable character sequences. In contrast
StringBuffer represents grow able and writable character sequences.
StringBuffer may have:character and substring inserted in the middle or appended to
the end. StringBuffer will automatically grow to make room for such additions and
after has more characters reallocated than are actually needed to allow room for
growth.
 StringBuffer Constructors:
StringBuffer defines the constructors:
StringBuffer()
StringBuffer(int size)
StringBuffer(string str)
The default constructor reserves room for an integer argument that explicitly sets the
size of the buffer.
The third version accepts a string argument that sets the initial contacts of the
stringBuffer object and reverse room for 16 more characters without reallocation.
 Methods of StringBuffer:

I). Length():
The current length of a stringBuffer can be found via the length() method.
The general form are:
int length()
int capacity()
Ex: class StringBufferDemo {

Prepared by Amit Shah 79 L J Polytechnic


Java Programming 5th CE IT

public static void main(String args[]){


StringBuffer sb=new StringBuffer(“Hello”);

System.out.println(“buffer=”+sb);
System.out.println(“length=”+sb.length());
System.out.println(“capacity=”+sb.capacity());
}
}
O/P: buffer=Hello
Length=5
Capacity=21
II).Setlength():
To set the length of the buffer within a StringBuffer Object, use
setlength(). Its general form is:
void setlength(int len)
Here, len specifies the length of the buffer, this value must be non
negative.
When you increase the size of the buffer, null added to the end of the existing
buffer. If you call setlength() with a value less than the current value returned
by length(),than the characters stored beyond the new length will be lost.
IV): CharAt() and setcharAt():
The value of the single character can be obtained from a stringBuffer via the
charAt() method, we can set the value of a character within a stringBuffer
using setcharAt(). The general form is:

char charAt(int where)


void setcharAt(int where, char ch)
for,charAt(), where specifies the index of the character being obtained for
setcharAt(), where specifies the index of the character being set and ch
specifies the new value of that character:
Ex: class setCharAtDemo{
public static void main(String ar[])
{
StringBuffer sb=new StringBuffer(“hello”);
System.out.println(“buffer before=”+sb);
System.out.println(“char(1) before=”+sb.charAt(1));
Sb.setCharAt(1,’i’);
Sb.setlength(2);
System.out.println(“buffer after=”+sb);
System.out.println(“charAt(1) after=”+sb.charAt(1));
} }
O/P: buffer before=hello
charAt(1) before=e
buffer after=Hi
charAt(1) after=i

Prepared by Amit Shah 80 L J Polytechnic


Java Programming 5th CE IT

V): append:
The append() method concatenates the string representation of any other type
of data to the end of the invoking StringBuffer object. It has overloaded
version for all the built in type and for object. Here, are few forms:
StringBuffer append(String str)
StringBuffer append(int sum)
StringBuffer append (object obj).

Ex: class appendDemo{


public static void main(String arg[]){
String s;
int a=42;

StringBuffer sb=new StringBuffer(40):


s=sb.append(“a=”).append(a).append(“1”).toString();

System.out.println(s);
}
}

O/P: a=42 !

VI): insert():
The insert() methods insert one string into another. It is overload to accept
values of all the simple type plus strings and objects. Few forms of insert()
method:
StringBuffer insert(int index,string str)
String Buffer insert(int index, char ch)
StringBuffer insert(int index,object obj)
Here, index specifies the index at which point the string will be inserted into
the invoking StringBuffer object.

Ex: class insertDemo{


public static void main(String arg[]) {
StringBuffer sb=new StringBuffer(“ I Java !”);

Sb.insert(2,”Like”);
System.out.println(sb);
}
}

O/P: I Like Java !

VII): reverse():
We can reverse the characters within a StringBuffer object using
reverse(). The general form is :

Prepared by Amit Shah 81 L J Polytechnic


Java Programming 5th CE IT

StringBuffer reverse()
This method returns the reversed object on which it was called.
Ex: class ReverseDemo {
public static void main(String arg[])
{
StringBuffer s=new StringBuffer(“abcdef”);

System .out.println(s);
s.reverse();
System.out.println(s);
}
}
O/P: abcdef
fedcba

VIII): Delete and deleteCharAt():


The StringBuffer has an ability to delete() and deletecharAt(). The general
forms are:
StringBuffer delete (int startIndex, int endIndex)
StringBuffer deleteCharAt(int ix)
The delete() method delete a sequence of the character from the invoking
object. Here , startIndex specifies the index of the first character to remove
and endIndex specifies and index one past the last character to remove. Thus
the substring deleted runs from:
startIndex to endIndex-1, the resulting StringBuffer object is returned.
The deleteCharAt() method deletes the character at the index specifies by loc.

Ex: class deleteDemo {


public static void main(String ar[])
{
StringBuffer sb=new StringBuffer(“this is a test”);
sb.delete(4,7);
System.out.println(“after delete:”+sb);
sb.deleteCharAt(0);
System.out.println(“after deleteCharAt:”+sb);
}
}
O/P: after delete : this a test
after deleteCharAt:his a test
IX): replace():
It replace one set of characters with another set inside a StringBuffer
object. General forms are:
StringBuffer replace(int startIndex, int endIndex, string str)

Prepared by Amit Shah 82 L J Polytechnic


Java Programming 5th CE IT

The substring being replaced is specified by the indexes startIndex and


endIndex. Thus the substring endIndex-1 is replaced. The replacement string is
passed in str.
Ex: class replaceDemo {
public static void main( String ar[])
{
StringBuffer sb=new StringBuffer(“this is a test”);
sb.replace(5,7”wass”);
System.out.println(“after replace:”+sb);
}
}

O/P:
after replace: this was a test

 Wrapper Classes:

1. Many built in, Java classes work with only with objects and not on primitive
data types. Therefore wrapper classes are provided which have methods to
convert primitive datatype, to objects and vice-versa.. the wrapper classes also
provide method for converting string to the various data type and vice-versa.
2. Wrapper classes are contained in the java.lang package. The wrapper class are
method static methods therefore those can be invoked using class name,that is
there is no need to instantiate wrapper classes to invoke their methods.
3. Below tables shows the simple data types and their corresponding wrapper
class type.

Simple data type Wrapper class


boolean Boolean
char Character
double Double
float Float
long Long
int Integer
byte Byte
short Short
4. Step to use wrapper class :
1) Define a class with appropriate data numbers and method.
2) Use wrapper class methods to convert primitive data type values to
object and vice-versa or string to primitive data type and vice-versa.

 The wrapper classes have a number of unique method for handling primitive
data and objects.

Prepared by Amit Shah 83 L J Polytechnic


Java Programming 5th CE IT

 Converting primitive numbers to object numbers using constructor methods:


Constructor calling Conversion action
Integer Intval=new Integer(i); Primitive integer to Integer object
Float floatva=new Float(f); Primitive float to Float object
Double doubleval=new Double(d); Primitive double to Double object
Long longval=new long(l); Primitive long to Long object
 Converting object numbers to primitive, numbers using type value method:
Method calling Conversion action
int i=Intval.invalue(); Object to primitive integer
float f=floatval.floatvalue(); Object to primitive float
long l=longval.longvalue(); Object to primitive long
double d=doubleval.doublevalue(); Object to primitive double
 Converting numbers to string using tostring() method.
Method calling Conversion action
str=Integer.tostring(i); Primitive integer to string
str=Float.tostring(f); Primitive float to string
str=Double.tostring(d); Primitive double to string
str=Long.tostring(l); Primitive long to string
 Converting string objects to numeric objects using the static method values
of
Method calling Conversion action
Doubleval=Double.value of (str); Converts string to Double object
Floatval=Float.value of (str); Converts string to Float object
Intval=Integer.value of (str); Converts string to Integer object
Longval=Long.value of (str); Converts string to Long object
 Coverts numeric strings to primitive numbers using parsing methods.

Method calling Conversion action


Int i=Integer.parseInt(str); Converts string to primitive integer
Long i=long.parselong(str); Converts string to primitive long
Float f=Float.parseFloat(str); Converts string to primitive float
Double d=Double.parseDouble(str); Converts string to primitive double

NOTE: All the parse methods throw a number format Exception of the
value of the str does not represent a number.

Prepared by Amit Shah 84 L J Polytechnic

Vous aimerez peut-être aussi