Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
313 views

Java Full Notes

This document discusses the history and features of the Java programming language. It provides details on: - The differences between Java, C, and C++ in areas like header files, pointers, data types, and inheritance. - How Java enabled interactive web content through the use of applets and incorporation into HTML pages. - The Java development kit (JDK) which includes tools like a compiler and interpreter to develop and run Java programs. - Key Java packages like those for input/output, networking, GUI development, and applets.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
313 views

Java Full Notes

This document discusses the history and features of the Java programming language. It provides details on: - The differences between Java, C, and C++ in areas like header files, pointers, data types, and inheritance. - How Java enabled interactive web content through the use of applets and incorporation into HTML pages. - The Java development kit (JDK) which includes tools like a compiler and interpreter to develop and run Java programs. - Key Java packages like those for input/output, networking, GUI development, and applets.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Father of java - James Gosling

 Difference between java and c: -


I. Java doesn‟t support the concept of header file.
II. Java doesn‟t support the pointer type (Explicit pointer type).
III. It doesn‟t contain the C data type like struct, union, & enum.
IV. It doesn‟t include the C unique statement keywords goto, sizeof &
typedef.
V. It doesn‟t define the type modifier keyword that is auto, extern, register,
signed, and unsigned.
VI. It doesn‟t support have a pre-processor like C that is #define, #inlcude.
VII. It doesn‟t support any mechanism for define variable arguments to
function.
VIII. Java requires the function with no argument must be declared with
empty parenthesis and not be the void keyword as done in C language.
IX. It has array some new operator such as instanceof, unsigned rightshift
(>>>), conditional, logical etc.
X. It adds labeled break and continued statement.
 Difference between java and C++: -
I. Java doesn‟t support header file.
II. Java doesn‟t support operator overloading.
III. Java has replace the destructor function with a finalize function.
IV. It doesn‟t support the concept of multiple inheritance classes.
V. A new feature is added called as inheritance in java.
VI. Every variable and method is declare within a class and forms part of
that class.
VII. It doesn‟t support global variable.
VIII. It doesn‟t support generic program.
IX. It doesn‟t have template classes as in C++.
X. It doesn‟t support pointer concept.

 Write a program in java to display a message.


class BCA
{
public static void main (String args[])
{
System.out.println (“I love U”);
}
}

 Java and internet: -Hotjava is a web browser that runs applets on internet. So,
java is strongly connected with the internet. Now, user can easily compile
applets program on the internet& run them locally by using a web browser like
hotjava. They can even use this web browser to download & applet located in a
remote computer. Anywhere in the internet in the world and run the application
on its computer by using the browser.
Father of java - James Gosling
There is another important application that is
internet user can also setup their website containing java applet that can be
used another remote use of internet. This ability of java that had made popular
in the world.

 Java and WWW: -WWW is an open-ended information retrieval system


designed to be used in the internet, internet‟s distributed environment. This
system contains web pages that provide both information and controls. It is
open through any direction. We can negative any new part from any particular
part. There is no restriction to follow the same path all the way every time.
It is made possible with the help of a language called
HTML. Web pages contain HTML tags that enable us to find, retrieve,
manipulate&display document worldwide. Java could be easily incorporated
into web system. Before java, www was limited to the display of still images
and texts.
However, the incorporation of java into webpage has
made it capable of support animation, graphics, games and a wide range of
special effects. With the support of java the web has become more interactive
and dynamic.

 Java support system: -


I. Internet connection: -A local computer should be connected to
the internet.
II. Web server: - It is a program that accept request for information
and sends the required documents.
III. Web browser: - It is a program that provides access to www and
runs java applet.
IV. HTML: - It is a language for creating hypertext for the web.
V. Applet tag: - It is used for placing java applet in HTML
document.
VI. Java code: - It is used for defining java applet.
VII. Byte code: - It is compile java code that is refers to in the applet
tags and transfer to the user computer.

 Java environment: - It includes a large number of developments tools


and 100 of classes and methods. The development tools are part of the
system known as JDK (java development kit) and the classes and
methods are part of the JSL (java standard library)also known as API
(application programming interface).
Father of java - James Gosling
 JDK: - It is a collection of tool that are used for developing & running
java program. It include –
I. Applet viewer (for viewing java applet): -It enables us to run java
applet without actually using a java compatible browsers.
II. Javac (java compiler): -It transmits java source code to byte code
files that the interpreter can understand.
III. Java(java interpreter): -It runs java applet and application
program by reading and byte code files.
IV. Javap (java disk assembler): - It enables us to convert byte code
files into a program description.
V. Javah (java, for C header file): -It produce header file for use
with relative methods.
VI. Javadoc (for creating HTML document): -It creates HTML
format documentation from java source code file.
VII. JDK(java debugger): - It helps us to find errors in our program.

 JSL (java standard library): -It is also called „API‟ (application program
interface). It includes 100 of classes and methods grouped into several
function packages the most commonly used packages are: -
I. Language support interface (java LAN): -It is beneficial
appearance of java. It is by default package of java. A collection
of classes and methods required for implementing basic features
of java.
II. Utility package (java utility): -A collection of classes to provide
utility function such as date and time vector class is related to
java.util package.
III. Input/ output package (I/O package): -A collection of classes
required for input/ output manipulations.
IV. Networking package (java.net): -A collection of classes for
communicating with other computer through internet on network.
V. AWT (Abstract window tool/kit): - It contain classes that
implements platform independent GUI.
VI. Applet package (java.applet): -It is smallest package of java. It
includes a set of classes that allows us to create java applet.
 Overview of java: - Programmers can develop two types of java program that
is : -
I. Stand alone applet: -They are the programs written in java to carry out
certain task to stand alone local computer. These are two steps: -
a) Compiling source code into byte code by using java compiler (Javac).
b) Executing byte code by using java interpreter (java).
II. Web applet: -Applet are small java program which we can develop
simple animated, graphics, to complex game and utilities we can also
use web enabled java compatible browser like internet explorer for
running applet. If applet viewer is not available.
Father of java - James Gosling
 JVM (java virtual machine): -All language compilers translate source code
into machine code for specific computer. Java compiler produces an
intermediate code known as byte code for a machine that doesn‟t exit but it is
known as java virtual machine.
It is a simulated computer within the computer and does all
the method functions of real computer. Virtual machine code is not an actual
machine code the machine code is generated by java interpreter by acting as
intermedia between virtual machine and real machine.
 Programming structure with java: -
I. Documentation section (optional): -It comprises a set of comments
lines giving the name of program and other detail.
a. // this program -Single line comment
b. /* java program*/ -Multiline comment
c. /** program description**/ - Documentation description
comment.
II. Package statement (optional): -It declares packages name and
inform the compiler that defines in a program belongs to its package.
III. Import statement(optional): -It is similar to hash (#) include in C
and C++. If we use import statement in java.
IV. Interface statement (optional): -It is like a class but include a group
of method declaration. It is used only when the access the concept of
multiple inheritance in a program implementation. It is a new
concept in java.
V. Class definition (optional): -Java program may contain multiple
class definition. Classes are the primary and essential element of
java program.
These classes are used to map the objects of
real world problems. The number of classes used depends on the
complexity of the problem.
VI. Main method class (essential): -Since, every java stand alone
program requires a main method as its starting point then this class
is essential part of java program.
The main method create object of various classes and
establishes communication between them on reaching the end of
main, the program terminates and control passé to the operating
system.

 Java tokens: - A java program is a collection of tokens, white space, literals. It


includes five types of tokens that is identifier, litters, keyword, operator and
separator.
Father of java - James Gosling

I. Keyword: -
abstract, case, const, else, float, int, if, null,
protected, public, private, static, try, catch, throw, finally, thread,
boolean, cast, continue, switch, while, for, do, stands, break,
implements, interface, operator, super, var, default, true, false,
future, import, long, outer, rest, void, byte, char, final, generic,
inner, negative, package, return, synchronized, transient, volatile,
byvalue, class, double, finally, goto, instanceof, new, delete, short,
this, strifp, assert, enum and etc.
II. Identifier: - They are programmer design tokens. They are used for
many classes, methods, variables,objects, labels, packages&interfaces in
a program.

III. Literals: -In java, literals are a sequences of characters (digits, letters
and other special character) that represent constant values to be stored in
variables.
Java specifies five major types of literals that is
1. Integer literals 2. Floating point literals
3. Character literals 4. String literals
5. Boolean literals
IV. Separator: -They are symbols used to indicate where groups of codes
are divided & arrange they basically defined the shape &function of our
code.

1. ( ) Parenthesis: -It is used to enclose parameters in methods


definition & invocation. It is also used in typecast operator.
2. { } Curly braces: - It define a block of code, classes, method and
local scope.
3. [ ] Subscript: - It is used to declarer array type and dereferencing
array values.
4. ; Semicolon: - It is used to separate statement and also indicate end
of statement.
5. , Comma: - It is used to separate consecutive identifier in a variable
declaration. It is also used to chain statement together inside a for
loop statement.
6. . Period:- It is used to separate package name from a reference
variable.
Father of java - James Gosling
 Java statement /statement: - Statement is an executable combination of
tokens ending with a semicolon mark. They are usually executed in sequence
in the order in which they appear. Java implements several types of statements:
I. Empty statement: - It is same as C and C++. They do nothing and are
used during program development and place holder.
II. Labeled statement:- Any statementmay begin with statement such
labeled must not be keywords. Labels in java are used as argument of
jump statement. It is identical C and C++except their used with jump
statement.
III. Expression:-It is same as C and C++. Generally, java has 7 types
expression statement that is
assignment, pre-increment, pre-decrement, post- increment,
post- decrement, method call and expression statement.
IV. Selection statement:-It is same as C and C++. It selects one of the
several control flows. There are three types of selection statements in
java that is if, if…..else & switch statement.
V. Iteration: -It is same as C and C++. It specifies how and when looping,
when takes place. There are three types of iteration statement that is for,
while, do…..while.

VI. Jump statement: -These statement passes control to begging or end of


the current block or to a labeled statement. Such labeled must be in the
same block & continue labels must be an iteration statement. These are
four types of jump statement that is break, continue, throw, and
return.
VII. Synchronization statement: -These are now available in C and C++.
They are used for handling issues with multi-threading.
VIII. Guarding statement: -It is same as C++ except finally statement. They
are used for safe handling of code that may cause exceptions (such as
division by zero). These statement use the keyword that is try, catch,
throw, throws & finally.

 Variable: -
 Scope of variable: -In java, variable are actually classify into three
types that is: - a.
Instance variable b. class variable c.
Local variable
Instance & class variable are declared inside a class.
Instance variable are created when the objects are instantiated. So, they
are associated with the objects. They take different value for each object.
On the other hand, class variable are global to
a class & belongs to the entire set of objects that class creates. Only one
memory location is created for each class variable. The variables
declared & use inside program block that are define between an opening
& ending curly brasses { }.
Father of java - James Gosling
Note: - 1. These variables are visible to the program only from the beginning in
the program block to the end of the program block.
2. Java doesn‟t support the global variable.
 Data type: -
Data type

Primitive (Intrinsic) Non- primitive

Numeric Non-numeric class Interface Array

Integer floating Character Boolean


point
In java these are four types of integer that is byte,
short, int & long. All the four integer types will have signed positive &
negative value.
Note: - 1. Unsigned & positive only integers are not supported by java
language.2.We can makeintegers long by appending the letter L or, l at
the end of the number.
Ex- 2L
 Floating point: -Real numbers are also known as floating point numbers.
Note: - 1.The float types are single precision numberwheredouble types are
double precision types.
2. The floating point numbers are usually double precision
number.
3. If we want to represent single precision number then we must
append from to the number.
Ex – 1.23F
1. Floating point types support a special value which is known as
NAN (not a number). It is used to represent the result of operation such
as dividing zero by zero where an actual number is not produce.

 Character type: -The character type in java required two byte for storage as
compared to char in c and c++ because java user Unicode to represent
character. It can hold only a single character. The range of char is from 0 to
6555. There is no negative character.
 Boolean type: -It is used when we want to test a particular condition during
the execution of a program and performing logical operations. It can only two
possible values i.e. true or, false. The keyword to represent Boolean type is
Boolean.
Note: -1.The two values true and false have been declared as keyword in java
language. It uses only one bit for storage.
2. Java uses a new data type. i.e byte it holds one byte memory space
for location . The range of byte type is -128 to +127 and 0 to 255
Father of java - James Gosling
Symbolic constant:
Syntax: - final type symbolic_name= value;
Or, static type symbolic_name= value;
Ex-
Final float PI=3.14;
Static double=3.14;
 Write a program to find the area of circle, if enter the radius.
Static float PI = 3.14;
class circle
{
public static void main (string args[ ])
{
int r;
double area = PI*r*r;
System.out.println(“area=”+area);
}
}
 Write a program to find the sum of two number using command line.
class sum
{
Public static void main (string args[ ])
{
int x,y,z;
x= Interger.parseInt (args[0]);
y= Interger.parseInt (args[1]);
z=x+y;
System.out.println (“sum of entered number=”+z);
}
}

 Type casting: -The process of converting one data type to another data type is
called type casting.
Ex- int to float, float to int.
Syntax:- Data type var1= (type) variable;
int v;
float long=(float) v;
 Casts that results in no lose of information:-
From to
i. Byte short, char, int, long, float, double
ii. Short int, long, float, double
iii. Char int, long, float, double
iv. int long, float, double
v. long float, double
vi. float double
Father of java - James Gosling
 Standard default value: -In java, every variable has a default value. If
we don‟t initialize a variable when it is first created then java provides
default value that variable type automatically.
Type of variable default value
i. Byte 0 (byte)
ii. Short 0 (short)
iii. int 0
iv. long 0L
v. float 0.0f
vi. double 0.0d
vii. char null character
viii. boolean false
ix. reference null
 Operator in java: -
1. Unsigned right-shift operator (>>>): -It is also called unsigned shift
operator with zero fill. It works like right-shift operator (>>) but fills
zero from the left.
2. Instance of operator: -It is an object reference operator and returns to if
the object on the R.H.S. This operator allows us to determine whether
the object belongs to a particular class or, not.
Ex- student instance of class BCA.
It is true if the object student belongs to the class BCA otherwise
it is false.
3. Dot operator: -It is use to access the instance variable and methods of
class object.
Ex- student.age // reference to the variable age.
Note: -It is also use to access classes and sub-packages from a
package.
Import.java.long.math;

4. New operator: -when we create an instance of class then we need to


allocate memory, we need to use new operator.
Syntax : -<class_name><obj.name> =new class_name;
Ex- BCA b=new BCA( );
Father of java - James Gosling

Scanner method: -
 Write a program to input two numbers and print their sum using
java.util package.
import java.util.scanner;
class add
{
public static void main (string args[ ])
{
int x,y,z;
scanner s=new scanner (System.in);
System.out.println(“input the 1st number”);
x=s.nextInt ( );
System.out.println(“input the 2nd number”);
y=s.nextInt ( );
z=x+y;
System.out.println(“sum=”+z);
}
}
 Write a program to input two numbers and print their sum using
java.util package.
import java.util.scanner;
class area
{
public static void main (string args[ ])
{
Double x, y, area;
scanner s=new scanner (System.in);
System.out.println(“input the 1st number”);
x=s.nextDouble ( );
System.out.println(“input the 2nd number”);
y=s.nextDouble ( );
area=x*y;
System.out.println(“Area=”+area);
}
}
Father of java - James Gosling

I/O Method(data stream): -


 Write a program to input two numbers and print their sum using I/O
package.
import java.io.DataInputstream;
class sumio
{
public static void main (string args[ ])
{
DataInputstream in=new DataInputstream
(System.in);
int x, y, add=0;
try
{
System.out.println(“input the 1st number”);
x=IntegerparseInt (in.readLine( ));
System.out.println(“input the 2nd number”);
y=IntegerparseInt (in.readLine( ));
}
catch (Exception e)
{
add =x+y;
}
System.out.println(“Area=”+area);
}
}
 Write a program to input two numbers and print their sum using I/O
package. (buffer reader)
importjava.io.*;
class sumbuffer
{
public static void main (string args[ ])
throws IO Exception
{
BufferReader br=new BufferReader(new
InputStreamReader (System.in));
System.out.println(“input the 1st number”);
string S1 = br.readLine ( );
int x = Integer.parseInt(S1);
System.out.println(“input the 2nd number”);
string S2 = br.readLine ( );
int x = Integer.parseInt(S2);
int z = x + y;
System.out.println(“sum=”+z);
} }
Father of java - James Gosling
 Write a program to input three numbers and print their sum of first two
numbers and product of last two numbers.
import java.io.DataInputstream;
class add
{
public static void main (string args[ ])
{
DataInputstream in=new DataInputstream
(System.in);
int x, y, z, add=0, prod=1;
try
{
System.out.println(“input the number”);
x=IntegerparseInt(in.readLine( ));
y= IntegerparseInt(in.readLine( ));
z= IntegerparseInt(in.readLine( ));
}
catch (Exception e)
{
add =x+y;
prod = y*z
}
System.out.println(“add of 1st two no=”+add);
System.out.println(“product of last two no=”+add);
}
}
 Write a program to input temperature in Fahrenheit and print their sum
using I/O package.
import java.util. scanner;
class temp
{
public static void main (string args[ ])
{
Double , ℃;
scanner s=new scanner(System.in);
System.out.println(“input the temperature”);
x=s.nextDouble ( );
℃ = ( -32)*5/9;
System.out.println(“temp=”+℃);
}
}
Father of java - James Gosling
 Write a program to input two numbers and print their swap value.
importjava.util. scanner;
class swap
{
public static void main (string args [ ])
{
scanner s = new scanner(System.in);
System.out.println(“enter two numbers”);
int x = s.nextInt( );
int y = s.nextInt( );
int z = x;
x = y;
y = z;
System.out.println(“swap value x=”+x);
System.out.println(“swap value y=”+y);
}
}

 Program based on If ………else


 Write a program to input age of candidates, if the age is greater
than 18 then display message eligible for voting.
import java.util.*;
class age
{
public static void main(string args[ ])
{
scanner s = new scanner(System.in);
System.out.println(“enter the age”);
int x = s.nextInt( );
if(x>=18)
System.out.println(“eligible for voting”);
else
System.out.println (“not eligible for voting”);
}
}
Father of java - James Gosling
 Write a program to input a numbers and check odd or even using
command line.
import java.util.*;
class test
{
public static void main (string args [ ])
{
int num;
System.out.println (“enter the number”);
num = Integer.parseInt (args [0]);
if (num%2==0)
System.out.println (“number is even”);
else
System.out.println (“number is odd”);
}
}

 Write a program to input 4 numbers and check among biggest.


import java.util.*;
class big
{
public static void main (string args [ ])
{
scanner s = new scanner (System.in);
System.out.println (“enter the number”);
int x = s.nextInt ( );
int y = s.nextInt ( );
int z = s.nextInt ( );
int z1 = s.nextInt ( );
if ((x>y)&&(x>z)&&(x>z1))
System.out.println (“1stnumber is greater”+x);
else if((y>z)&&(y>z1))
System.out.println (“2ndnumber is greater”+y);
else if (z>z1)
System.out.println (“3rdnumber is greater”+z);
else
System.out.println (“4thnumber is greater”+z1);
}
}
Father of java - James Gosling
 Command line argument: - There may be occasions when we may like our
program to act in a particular way depending on the input provide at the time
of execution. It is achieved in java program by using command line argument.
Command line arguments are parameters that are supplied
to the application program that are time of execution. We can write java
programs that can perceive and use the argument provided in the command
line. Recall the signature of the main method use in our program.
As we know that arguments is declare as an array of strings
(known as string objects).Any argument provided in the command line (at the
time of execution) are passed to array argument in its elements. We can
simply access the array element and use them in the program as we wish.
The individual elements of array are accessed by using an
index or, subscript like args[i]. The value of I denotes the position of the
element inside the array.
Note:- Java subscript begins with 0 and not 1.
 Print the days name in java using switch:-
import java.util.*;
class week
{
public static void main (string args[ ])
{
scanner s = new scanner (System.in);
System.out.println (“enter the number of days”);
int x = s.nextInt ( );
switch (x)
{
case 1:
System.out.println (“Today is Monday”); break;
case 2:
System.out.println (“Today is Tuesday”); break;
case 3:
System.out.println (“Today is Wednesday”); break;
case 4:
System.out.println (“Today is Thursday”); break;
case 5:
System.out.println (“Today is Friday”); break;
case 6:
System.out.println (“Today is Saturday”); break;
case 7:
System.out.println (“Today is Sunday”); break;
default:
System.out.println (“please inter valid number”);
}
}
}
Father of java - James Gosling
 Shows the vowel &consonant in java using switch:-
import java.util.*;
class vowel
{
public static void main (string args[ ])
{
scanner s = new scanner (System.in);
System.out.println (“enter the character”);
int x = s.nextInt ( );
switch (x)
{
case „a‟:
case „A‟:
System.out.println (“Character is vowel”);
break;
case „e‟:
case „E‟:
System.out.println (“Character is vowel”);
break;
case „i‟:
case „I‟:
System.out.println (“Character is vowel”);
break;
case „o‟:
case „O‟:
System.out.println (“Character is vowel”);
break;
case „u‟:
case „U‟:
System.out.println (“Character is vowel”);
break;
default:
System.out.println (“Character is consonant”);
}
}
}
 Write a program to print the 10 natural number:-
import java.util.*;
class natural
{
public static void main (string args[ ])
{
for (int i=1;i<11;i++)}}
System.out.println (“number is”+i);
} }
Father of java - James Gosling
 Write a program to print the 10 natural number using do while loop:-
import java.util.*;
class natural
{
public static void main (string args[ ])
{
do
{
int i=1;
System.out.println (“number is”+i);
i++;
while (i<11);
}
}
}
 Write a program to input a number and print the factorial of them using
loop:-
import java.util.*;
class factorial
{
public static void main (string args[ ])
{
scanner s = new scanner (system.in);
System.out.println (“enter a number”);
int x = s.nextInt ( );
for ( ; x>0; )
{
int fact =1;
fact = fact*x;
x--;
}
System.out.println (“factorial”+fact);
}
}
Father of java - James Gosling
 Write a program to input a number and print the factorial of them using
loop:-
import java.util.*;
class fact
{
public static void main (string args[ ])
{
scanner s = new scanner (system.in);
System.out.println (“enter a number”);
int x = s.nextInt ( );
for (int i=1; i<x;i++)
{
int fact =1;
fact = fact*x;
}
System.out.println (“factorial”+fact);
}
}
 Write a program to input a number and print their reverse using loop:-
import java.util.*;
class fact
{
public static void main (string args[ ])
{
scanner s = new scanner (system.in);
System.out.println (“enter a number”);
int x = s.nextInt ( );
while (x>0)
{
int mod = x%10;
int rev=0;
rev = (rev*10)+ mod;
x=x/10; }
System.out.println (“reverse number=”+rev);
}
}
Father of java - James Gosling
 Write a program to input a number and print the sum of its digit using
loop:-
import java.util.*;
class fact
{
public static void main (string args[ ])
{
int x, sum=0, mod;
scanner s = new scanner (system.in);
System.out.println (“enter a number”);
x = s.nextInt ( );
do
{
mod = x%10;
sum = sum + mod;
x=x%10;
}
while (x>0);
System.out.println (“sum of digits=”+sum);
}
}
 Write a program to input a number and check it is Armstrong or, not
using loop:-
import java.util.*;
class fact
{
public static void main (string args[ ])
{
int x, sum=0, mod;
scanner s = new scanner (system.in);
System.out.println (“enter a number”);
x = s.nextInt ( );
for ( ;x>0;x = x/10;)
{
mod = x%10;
sum = sum + (mod*mod*mod);
}
if (sum==x)
System.out.println (“number is Armstrong”);
else
System.out.println (“number is not Armstrong”);
}
}
Father of java - James Gosling
 Write a program to input a number of term and generate Fibonacci series
up to entered number :-
import java.util.*;
class fib
{
public static void main (string args[ ])
{
int x=1, fib=0, term;
scanner s = new scanner (system.in);
System.out.println (“enter the number of term”);
term = s.nextInt ( );
System.out.println (“Fibonacci series are :”);
for ( ; x>term; x = x+1)
{
int a=0; int b=1;
fib = a + b;
System.out.println (fib);
a = b; b = fib;
}
}
}
 Write a program to input a number and check it is prime or, not :-
import java.util.*;
class prime
{
public static void main (string args[ ])
{
int num, i, count = 0;
scanner p = new scanner (system.in);
System.out.println (“enter the number of term”);
num = p.nextInt ( );
for (i =2; i<num; i++)
{
if (num % i ==0)
{ Count++; }
if (count ==1)
{
System.out.println (“number is not prime”);
}
if (count ==0)
{
System.out.println (“number is prime”);
}
} }
}
Father of java - James Gosling
OR,
import java.util.*;
class prime1
{
public static void main (string args[ ])
{
int num, i, count = 0;
scanner p = new scanner (system.in);
System.out.println (“enter the number of term”);
num = p.nextInt ( );
for (i=2; i<num; i++)
{
if (num ==i)
{
System.out.println (“number is prime”);
break;
}
if (num % i ==0)
{
System.out.println (“number is not prime”);
break;
}
}
}
}
OR,
import java.util.*;
class prime2
{
public static void main (string args[ ])
{
int num, i=1, count = 0;
scanner p = new scanner (system.in);
System.out.println (“enter the number of term”);
num = p.nextInt ( );
while (i<= num)
{
if (count ==2)
System.out.println (“number is prime”);
else
System.out.println (“number is not prime”);
}
}
}
Father of java - James Gosling
 Labeled loops statement: -As we know that a simple break statement causes
the controlto jump outside the nearest loop and simple continue statement
restart the current loop.
If we want to jump outside a nested loops or, to continue a
loop that is outside the current one then we may have to used labeled break
and label continue statement.
In java, we can give a label to a block of
statements.
A table is any valid java identifier, name, followed by a colon (:). To
give a label to a loop, place it before it loop with a colon in the end.
Format: -
Loop 1: for (……….)
{……………..
}
A block of statements can be also labeled.
Block 1:
{………..
Block 2: {………..}
}
 WAP to illustrate the concept of labeled loop. Or, WAP to show the use of
continue and break statement in the concept of labeled loop.
class loop
{
public static void main (string args[ ])
{
Loop 1: for (int i = 1; i < 100; i++)
{
System.out.println (“”);
}
if (i>=10)
break;
for (int j =1; j<100)
{
System.out.println (“ * ”);
if (j==i)
continue loop1;
}
}
}
Father of java - James Gosling
 Class and Objects: -A class is a blue print or, a template for creating
different object which define its property&behavior.A class is a keyword &
also has the concept of user define data type. A class can contain field and
method to describe the behavior of an object.
Note: - In java, a class must not be terminated with a semicolon.
 Defining of class: - If we define a class then we create variables of that type
using declaration that are similar to the basic type declaration.
In java, these variables are termed as instance of classes, which
are the actual objects.
Syntax: -class <class_name>
{
field declaration;
method declaration;
}
Ex- class ABC
{
int x, y, z;
void show ( );
}
 Fields: -It is a variable inside the class.
 Methods: -It defines the operation that can be performing in java
programming.
Syntax: - type <method_name>
{
args list; //method body; }
Ex- class cube
{
int len, breath, height;
int get ( )
{
return ( len * breath * height);
}
}
 Object: -In java, object is essentially a block of memory that contains space, to
store all the instance variable. Creating an object is also referred to as
instantiating an object.
In java, the new keyword is used to create new
objects. There are basically three steps when creating an object of a class.
I. Declaration: -A variable declaration with a variable name with an object type.
II. Instantiation: -The new keyword is used to create the object.
III. Initialization: -The new keyword is followed by a call to a constructor. This
call initializes the new object.
For Ex- creation of an object
Rectangle rect;
rect = new rectangle ( );
or, rectangle rect = new rectangle;
Father of java - James Gosling
 Accessing class member: -Whenever we create object then we should assign
values to those variable in order to use them in our program. All variables must
be assign values before they are used.
Since, we are outside the class we cannot access the
instance variable and the method directly. To do this, we must used concerned
object and the dot operator.
Format: -object name. Variable name = value;
Ex- objname. method name (parameter);
The instance variable and methods of the rectangle class may be accessed
and assign values as follows.
Ex- rect1. Length =10;
rect2. Breath = 20;
or,
rect. Length =10;
rect. Breath = 20;
or, rect area (10,20);

 WAP show the concept of class & object.


class student
{
string name = ram;
int roll =100;
void show ( )
{
System.out.println (“name=”+name);
System.out.println (“roll =”+roll);
}
}
class test
{
public static void main (string args [ ])
{
student s = new student ( );
s.show ( );
}
}
Father of java - James Gosling
 Access specifier: -It specifies how to access the members of a class or, a class
itself. We can use access specifier before a class and its member.
These are follows:-
I. Private: -The private members of a class are not accessible anywhere
outside the class. They are accessible only within the class by the
method of that class.
II. Public: -The public members of a class are accessible everywhere
outside the class. So, any other program can read them & use them.
III. Protected: -The protected members of a class are accessible outside
the class but, generally within the same directory.
IV. Default: -If no access specifier is written by the programmer, then the
java compiler uses a default specifier. Default member are accessible
outside the class but within the same directory.
Note: - 1.We generally use private for instance variable and public for
methods. In java classes cannot be declare by using private.
2. An operation, perform by an object is referred to as method.

 WAP program to define method in a class and its area.


class student
{
float r;
void show ( )
{
System.out.println (“area=”);
System.out.println (3.14*r*r);
}
}
class test
{
public static void main (string args [ ])
{
area s = new area ( );
a.r = 4
a. show ( );
}
}
Father of java - James Gosling
 WAP to define a class rectangle & find its area if the length and breadth
are given. using class and object.
class rectangle
{
int l, b;
void get ( )
{ int x, y;
l=x; b=y; }
}
int area ( )
{ int area1 =l*b;
return (area1); }
class test
{
public static void main (string args [ ])
{
rectangle rect = new rectangle ( );
rect.l = 15; rect.b = 100;
a = rect.l * rect.2;
System.out.println (“area=”+a);
}
}
 WAP to input the radius of circle and find the area using class & objects.
import java.util.scanner;
class circle
{
int radius;
double area ( )
{ return (3.14*radius*radius); }
}
class test
{
public static void main (string args [ ])
{
scanner s =new scanner (system.in);
circle c= new circle;
int r = 0; double area;
System.out.println (“input the radius of circle”);
r = s.nextInt ( );
c.radius = r;
area = c. area ( );
System.out.println (“area=”+area);
}
}
Father of java - James Gosling
 WAP to input the length and breadth and find the area.
import java.util.scanner;
class area
{
int l, b, x;
int area ( )
{
return (l*b);
}
public static void main (string args [ ])
{
scanner s =new scanner (system.in);
area a = new area;
System.out.println (“enter the number”);
l = s.nextInt ( );
b = s.nextInt ( );
x = a.area ( );
System.out.println (“area=”+x);
}
}
 Constructor: -It is a special member function because the name of constructor
is same name as the class name to belong. It is a special type of method that is
used to initialize the object. It is invoked as the time of object creation. It
constructs the value that is it provides data for the object so ti is called
constructor.
 Rules for creating java constructor: -
I. Constructor may must be same as class name.
II. It doesn‟t return any values.
III. It must have no explicit return type.
IV. It is automatically call & executed at the time of creating an object.
V. If nothing is passed to the objects, then the parameterized constructor
are called.
 Basically two types of constructor:-
I. Default Constructor: -It is also called implicit constructor. When a
constructor for a class is not defining, the JVM provides a default
constructor. A constructor have no parameter is known as default
constructor (no argument constructor).
Syntax: - class <class_name>
{
………… // default constructor
{…..}
}
Father of java - James Gosling
Ex- class test
{
………..test ( )
{
System.out.println(“default constructor”);
}
}
Ex - class test
{
test ( )
{
System.out.println(“default constructor”);
}
public static void main (string args [ ])
{
test t1 = new test ( );
}
}
 WAP to show the concept of default constructor, and also initialize the
instance variable.
class student
{
string n;
student ( )
{
n = “rama”;
}
}
void show ( )
{
System.out.println(“name = ”+n);
}
class check
{
public static void main (string args [ ])
student s = new student ( );
s.show ( );
}
 Parameterise constructor: - It is also called constructor with argument. A
constructor that has parameter is known as parameterise constructor. It is used
to provide different values to the district object.
These types of constructor is coded in the class definition while
creating an object of class, the values that are passed & the parameter of the
constructor should match the term of number, sequence, & data type .
Father of java - James Gosling
Syntax: - class <class name>
{
constructor name <args>;
}
Ex- class test
{
test ( int);
}
 WAP to initialize the instance variables by using paramterise
constructors.
class student
{
string name;
int age;
student ( )
{
name = “vikram”; age = 18;
}
student (string s, int i)
{
name = s ; age = I;
}
void show ( )
{
System.out.println(“Name = ”+name);
System.out.println(“Age = ”+age);
}
}
class demo
{
public static void main (string args[ ])
{
student s = new student ( );
s.show ( );
student s1 = new student ( “ram”, 100);
s1.show ( );
}
}
Father of java - James Gosling
 WAP to show the use of a constructor method to initialize an object at the
time of its creation.
class rectangle
{
int l, b;
rectangle (int x, int y)
{
l= x; b= y;
}
int area ( )
{ return ( l *b); }
}
class demo1
{
public static void main (string args[ ])
{
rectangle rect = new rectangle (5, 10);
int ar = rect.area ( );
s.show ( );
System.out.println (“Area = ”+area);
}
}
 Constructor overloading: - we can also overload the constructor method in a
class. The proper overload constructor is called based upon the parameter
specified when new is created.
Syntax: - class <class_name>
{ constructor name ( ) // default constructor.
{
} // method body
class name ( args1 , args2) // paramterise constructor
{
} // method body
}
Father of java - James Gosling
 WAP to illustrate the concept of constructor overloading in class.
class area
{ int l, b, h;
area ( )
{
System.out.println (“Areaof rectangle and square”);
}
area ( int x, int y)
{ l = x ; b = y;
System.out.println (“Areaof rectangle= ”+ (l*b));
}
area (int w)
{
s= w;
System.out.println (“Areaof square= ”+ s*s);
}
public static void main (string args[ ])
{
area a1 = new area ( );
area a2 = new area (10, 20 );
area a3 = new area ( 5);
}
}
 Method overloading: -It is one of the ways that java support polymorphism.
In java, it is possible to create methods that have the same name but different
signature. It is used when objects are required to perform similar task but using
different input parameter.
OR, If a class have multiple methods by same
name but different parameter it is known as method overloading, we perform
method overloading to figure out the program quickly. It is also known as
static polymorphism. In the concept of method overloading the argument list
could differ in
1. Number of argument 2. Data type of parameter
3. Sequence of data type of parameters
There are two ways to overload the methods in java.
I. By changing the number of arguments
II. By changing the data type
 Important points: -
I. When we called a method the compiler uses the signature of the
method to resolve the method to be invoked.
II. A class cannot have two methods having the same signature this is
because the compiler will not recognize which method to invoke if
more than one method have the same signature.
Father of java - James Gosling
Syntax: - return type method name (args 1)
{
…………….}
return type method name (args1, args2)
{
…………….}
Ex - int area (int x)
{
…………..}
int area (int a, int b)
{
……….}
 WAP to illustrate the concept of method overloading.
class test
{
public void display (char c)
{
System.out.println (c);
}
public void display (int num, char c)
{
System.out.println (+num “ ” +);
}
}
class check
{
public static void main (string args[ ])
{
test t = new test ( );
t.display ( „A‟);
t.display ( 02 ,„A‟);
}
}
 Static member: -The members that are declaring static are called static
members. The static keyword in java is used to memory management only. We
can apply static keywords with variable, methods, blocks, &nested class. It
belongs to the class than instance of the class.
It can be used without having any instance of that class at
all only the class is sufficient to invoke static method or, access a static
variable. Note: -
Static variable is shared by all the instances of that class. i.e. only one copy of
the static variable is maintained.
Father of java - James Gosling
 Methods declared as static have several restrictions.
I. It can only call other static method.
II. It can only access static data.
III. It cannot refer to this or, super in any way.
Syntax: - static data type variable;
Ex - static int x;
Static method syntax: - static return type method name (args list);
Ex - static int max (int x, int y);
 WAP to show the concept of static member in class.
class calculate
{
static float prod (float x, float y)
{
return (x * y);
}
static float div (float x, float y)
{
return (x/y);
}
}
class check
{
public static void main (string args[ ])
{
float a = calculate. prod (5.9, 10.2);
float b = calculate. div (a, 2.0);
System.out.println (“ The value of b = ”+b);
}
}
 Static block: - we can declare static block that gets executed exactly ones,
when the class is first loaded. It means that the statement within a static block
is executed first.
 WAP to demonstrate the concept of static member
class test
{ static int x = 15, y;
static void compute (int z)
{ System.out.println (“ The value of z = ”+z);
System.out.println (“ The value of x = ”+x);
System.out.println (“ The value of y = ”+y); }
static
{ System.out.println (“ static block initialize”);
y = x *5; }
public static void main (string args[ ])
{ compute (20); }
}
Father of java - James Gosling
 Nesting of method: -A method can be call by using only by its name by
another method of the same class. It is known as nesting of methods.

 WAP to show the concept of nesting of method.


class nesting
{
int n , m;
nesting (int a ,int b)
{
n = a ;m = b ;
}
int large
{
if (m>= n)
return (m);
else
return (n);
}
void show( )
{
int l = large( );
System.out.println (“ large value = ”+l);
}
class test
{
public static void main (string args[ ])
{
nesting n = new nesting (5, 2);
n.show( );
}
}
 Inheritance: - It is a situation in which derives a set of attributes & related
behavior from another class (parent class).
OR, The mechanism of deriving new class from an older one is
called inheritance. The older class is known as super-class and the new one is
called sub-class. The inheritance allows sub-classes to inherit all the variables
& methods of their parent classes.
Note: - 1. Java classes can be re-use in several ways.
2.This is basically done by creating new classes. Re-using the
property of existing ones.
Father of java - James Gosling
 Advantage: -
I. Reduce redundancy in code: -Code redundancy means inclusion
(write) of the same code in different places, leading to its unnecessary
replication of code. Inheritance allows us to re-use the code.
II. Maintain code easily: - Since the code reside at one place (in the super
class). So any changes made to the super class will automatically
changes the behavior of its sub-classes because the automatically inherit
the new behavior.
III. Extend the functionality: - We can extend the functionality of an
existing class by adding more methods to the sub-class.
Note: - Inheritance represents the DBMS IS A relationship. It is also
known as parent- child relationship.
 Types of inheritance: - There are several types of inheritance supported by
java.
1.Single 2. Multilevel 3. Hierarchical
4. Hybrid
Note: - Multiple inheritances are not supported in java. It means that a
class cannot extend more than one class. This concept is implemented by
using a secondary inheritance path in the form of interface. Inheritance
is a new concept in java.
I. Single inheritance: - When a class extends one class it is called as
single inheritance. In this type of inheritance only one super and sub-
class.
A

B
Fig: -Representation of single inheritance
II. Multilevel inheritance: -In this type of inheritance one class inherit
from a sub-class, thereby making this derived class the base class for the
new class.
A

C
Fig: -Representation of multilevel inheritance
III. Hierarchical inheritance: -In this type of inheritance, one base class is
inherited by many sub-classes that is one super class and many sub-
classes.
A

B C D
Fig: -Representation of hierarchical inheritance
Father of java - James Gosling
IV. Hybrid Inheritance: -It is a combination of single and multiple
inheritances. Hybrid inheritances can be achieved in java by using an
interface, If we try to achieve it using only classes then it will give an
error. A

B D

C
Fig: -Representation of hybrid inheritance
Syntax: - class <sub-class name>extends <super classes>
{
var declearation;
method decleartion;
}
Ex - class BCA extends MCA
{
int x, y;
}
 Extends: -The keyword extends signify that the properties of the super class
are extended to the sub-class. It indicates that we are making the sub-class. It
indicates that we are making a new class which inherits the property of existing
class.
 WAP to show the concept of single inheritance.
class sum
{
void calculate (int x, int y)
{
int z;
z = x +y;
System.out.println (“sum = ”+z);
}
}
class add extend sum
{
public static void main (string args[ ])
{
add A1 = new add ( );
A1.calculate(10,15);
}
}
Father of java - James Gosling
 WAP to show the concept of multilevel inheritance.
class sum
{
void reverse (int x)
{
int mod, rev = 0;
for ( ;num>0; num=num/10)
{
mod = num%10;
rev = (rev*10)+mod;
}
System.out.println (“reverse = ”+rev);
}
}
class ram extend sum
{
int sum (int x, int y)
{
return(x + y);
}
ram r = new ram;
r.reverse (521);
}
class rahul extend ram
{
public static void main (string args[ ])
{
rahimr1 = new rahim ( );
r1.sum(100,15);
}
}
 Using super keyword with constructor/(sub-class constructor method): -
A sub-class constructor is used to construct the instance variable of both the
sub-class and the super class. The sub-class constructor uses the keyword
superto invokethe constructor method of the super class. The keyword super
is used in the following condition: -
I. Super may only be used within a sub-class constructor method.
II. The call to super class constructor must appear as the first statement
within the sub-class constructor.
III. The parameter in the super called must match the order & type ofthe
instance variable declared in the super class.
Father of java - James Gosling
 WAP to illustrate the concept of single inheritance through the super
keyword.
class room
{
int l, b;
room (int x, int y)
{
l = x; b = y;
}
int area()
{ return(l * b); }
}
class guest extend room
{
int h;
guest (int x, int y, int z)
{
super (x, y);
h = z;
}
int volume ()
{ return(l * b * h); }
}
class test
{
public static void main (string args[ ])
{
guestg = new guest (1, 2, 3);
int a = g.area( ); // super class mehtod
int v = g.volume ( ); // sub class method
System.out.println (“area = ”+a);
System.out.println (“volume= ”+v);
}
}
 Visibility control: - It is possible to inherit all the members of a class by a
sub-class using the keyword extends.The variable & methods of a class are
visible everywhere in the program. However, it may be necessary in some
situation to restrict the access to certain variable and method from outside the
class.
We can achieve this in java by applying visibility modifiers to
instance variables and methods. They are also known as access modifier. Java
provides basically several types of modifier that is public, private, protected
and package (friendly access).
Father of java - James Gosling
 WAP to show the concept of hierarchical inheritance.
class name
{
void sum (double x, double y)
{ System.out.println (“sum= ”+(x +y)); }
}
class monu extend name
{
monu m = new monu;
m.sum (5.7, 3.2);
}
import java.util.*;
class prakash extend name
{
public static void main (string args[ ])
{
int num, mod, rev =0;
System.out.println (“enter the number”);
scanner s = new scanner ( );
num = s.next int ( );
for ( ;num>0; num= num/10)
{
mod = num % 10;
rev = (rev*10)+ (mod*mod*mod);}
}
if (rev == num)
System.out.println (“number is Armstrong”);
else
System.out.println (“number isn't
Armstrong”);
prakash p = new prakash ( );
p.sum (10,20);
}
}
Visibility control provides different levels of protections.
1. Public: - In public access specifier, any variables or, method is visible to
the entire class in which it is define. Members declared as public are
accessible anywhere in the class and they are also inherited by all sub-
class.
2. Private: -A private member of class is accessible only to the member of
class itself. It is visible between public access. It is not directly access by
the object of a class. They cannot be inherited by sub-class. The main
purpose of private access specifier to hide data.
Father of java - James Gosling
3. Protected: - A protected member of a class is accessible to member of
that class and member of its sub-class. It can also be access by member of
other class in the same package.
4. Package: -It is also known as default access. If we do not specify any of
the access specifier then the scope is friendly. A class, variable or, method
that has friendly access is accessible to all the classes packages.
In java, friendly is not a keyword. It is a term that is
used for the access level when no access specifier has been accessified.
Note:-packages acts as containers to group related classes together. It is
similar to a source file in C.
 WAP to show the concept of hybrid inheritance.
class raj
{
void division (int x, int y)
{
System.out.println (“sum = ”+(x/y));
}
}
class raja extend raj
{
rajar = new raja;
r.division( 10, 5);
void multiply (int x)
{
System.out.println (“square = ”+(x *x));
}
}
class prem extend raj
{
prem = p = new prem( );
void sum (int a, int b)
{
System.out.println (“sum =”(a+b));
}
p.division (50, 10);
}
class virat extends prem, raja
{
public static void main (string args[ ])
{
virat v = new virat ( );
v.multiply (10);
v. sum (5, 10);
}
}
Father of java - James Gosling

 Overriding method: -In a class hierarchy, when a method is a sub-class have


the same name and type signature as a method in its super class, them the
method in the sub-class is said to override the method in the super class.
In overriding, a sub-class method overrides the
definition of a super class method. If the method in the sub-class have the
signature of a method in the super class.
 Rules for overriding methods: -
I. The order of arguments and the name of the overriding method
should be identical to those of the super class method.
II. The return type of both the overridden (super-class) and the
overriding (sub-class) methods must be the same.
III. The overriding methods cannot be less accessible than themethod it
overrides. For Ex- If the method that overrides is declare as public
in the super-class then we cannot override it with the private
keyword in the sub-class.
IV. A method declare find out cannot be overridden.
V. A method declares static cannot be overridden.
VI. If a method cannot be inherited, then it cannot be overridden.
VII. An overriding method cannot raise more exception than those raise
by the method of the super-class.
 WAP to show the concept of overriding method.
class test
{ int x;
test (int x)
{ this.x=x; }
void show ( )
{ System.out.println (“ x =”+x); }
}
class check extends test
{ int y;
check (int x, int y)
{ super (x);
this.y = y; }
void show ( )
{ System.out.println (“ value of x =”+x);
System.out.println (“ value of y =”+y); }
}
class find
{ public static void main (string args[ ])
{ check c = new check (10, 20);
s.show ( ); }
}
Father of java - James Gosling
 Final class variable and method: -
 Final variable and methods: -
All methods and variables can be over ridden by default in sub-
classes. If we wish to prevent the sub-classes from overriding the
member of super class then we can declare them as final by using the
keyword final as a modifier.
Syntax: - final <data type> var name = const value;
Ex – final int PI = 3;
Final method syntax: -
final<return type> method name ( )
{
………….
}
Ex – final void show ( )
{
…………
}

 Restriction of final modifier : -


I. A final class cannot be inherited.
II. A final method cannot be change (overridden) by a sub-class.
III. Final data member cannot be change after initialization.
IV. All methods and data members in a final class are implicitly final.

 Final class: - Sometimes we may like to prevent class being further sub-class
for security reasons. A class that cannot be sub-classes is called a final sub-
class. That is cannot be inherited. It is achieved in java by using the keyword
in final.
Note: -
1. Any attempted to inherit final classes will produce an error that is
the compiler will not allow it.
2. Declaring a class final prevents any un-wanted extensions to the
class.
For Ex-
Final class X
{
……………….
}
class Y extends class X //illegal.
{
……………….
} // error cannot sub-class.
Father of java - James Gosling
 Finalizer method: - As we known that a constructor method is used to
initialize an object when it is declared this process is known as initialization.
Similarly java support a concept called finalizer which is just opposite to
initialization.
We know that java run time is an automatic garbage
collection system. It automatically passes of the memory resources used by
the object but objects may hold other non-object resources, such as file
descriptions, window system fonts. The garbage collector cannot free these
resources.In order to free these resources we must use a finalizer method. It is
similar to destructor in c++.
The finalizer method is simply finalized & can be added to
any class. Java calls that method whenever it is about to reclaim the space for
that object. The finalize method should explicitly task to be perform.
Syntax: -
finalize ( )
{
…………….. // body
}
 Abstract classes & methods: -
An abstract class is a class that contains zero or, more abstract. It allows
the implementation of a behavior in different ways. An abstract method is a
without method body. An abstract method is written when the same method
has to perform different task depending on the object calling it.
Both the abstract classes an abstract method should be
declare by using keyword abstract. The classes & method declare using the
abstract modifier is incomplete.
Abstract means ignoring the non-essential detail of
an object & concentrating own its essential detail.
 Limitation: -
I. An abstract class cannot be instantiated because the class is
incomplete.
II. Sub-class must override the abstract method of the super class.
III. A class has one or, more abstract method.
IV. A class inherits an abstract method & does not override it.
V. The abstract modifier is the opposite of the final modifier.
VI. An abstract class must be sub-class whereas final class cannot be sub-
class.
Father of java - James Gosling
 WAP to illustrate the concept of abstract class and method.
import java.lang.*;
abstract class check
{
abstract void calculate (double x);
}
class test extend check
{
void calculate(double x)
{
System.out.println (“square =”+(x*x));
}
}
class find extend check
{
Void calculate (double x)
{
System.out.println (“root =”+math.sqrt(x));
}
}

Array
 Array: - Array is a collection of similar elements. Array is a pre-defined class
present in java.lang package. It is a final class which cannot be inherited. In
java array holds both primitive data type as well as object references.
In java when the programmer develop has to follow three
steps: -
I. Array declaration: -
int arr [ ]; here „arr ‟is a reference of
at the declaration time of array. Programmers never specify the size of
the array.

II. Array Construction: - arr= new int [5]; at the construction of the
array programmer is bound to specify the size of the array.

III. Initialization of array: - In java array is initialized the index. The


initialization of the array means putting element into an array.
arr[0] = 1; arr[1] = 5;
 Representation of array in memory: - In java when the array is declared
it captures a chunk of memory from the stack. Array is constructed at the
run time. At the construction time by specifying the size of the array
through new operator garbage collection allocates. Consecutive memory
location from the heap.
Father of java - James Gosling
 Demonstrate the concept of Array.
public class test
{
public static void main(string args [ ])
{
int arr [ ] = new int [ 3 ] ;
arr [0] = 10;
arr [1] = 20;
arr [2] = 30;
System.out.println(arr [0]+ “\t” +arr[1] “\t” + arr[2]);
}
}
 Array range: -In java, all arrays store the allocated size in a variable
named len. We can access the len of an array via its len field.
Syntax: - array name.length;
Ex- int[ ] arr.5 = new int [5];
int array length = arr.length;
Note: -This information will be useful in the manipulation of array when
their sizes are not known.
 WAP to find the sum& average of the element present in the array.
import java.util.*;
public class suresh
{
public static void main(string args [ ])
{
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.println(“enter the size of array”);
int size = s.nextInt();
int arr[ ] = new int[size];
System.out.println(“enter the element of array”);
for(int i=0; i<arr.length; i++)
{
arr[i] = s.nextInt( );
sum+=arr[i];
}
float avg (float)(sum/arr.length);
System.out.println(“sum is”+sum “average is”+avg);
}
}
Father of java - James Gosling
 WAP to find the largest number from an array.
import java.util.*;
public class large
{
public static void main(string args [ ])
{
int arr[ ] =new int [5];
Scanner s = new Scanner(System.in);
System.out.println(“enter the element of array”);
for(int i=0; i<arr.length; i++)
{
arr[i]=s.nextInt( );
}
for(int i=0; i<arr.length; i++)
{
if(arr[0]>arr[i])
{ continue; }
else
{int x= arr[0];
arr[0] = arr[i];
arr[i]=x;
}
}
System.out.println(“largest no. in given array=”+arr[0]);
}
}
 WAP to find the biggest and smallest number.
public class big
{ public static void main(string args [ ])
{
int x, y , big=0, small = 0;
Scanner s = new Scanner(System.in);
System.out.println(“enter the size of array”);
y = s.nextInt();
int arr[ ] = new int[y];
System.out.println(“enter the element of array”);
for(x=0; x<arr.length; x++)
{ arr[x] = s.nextInt( ); }
++
for(x=0; x<arr.length; x )
{ if (arr[x]>big)
{ big = arr[x]; }
if (arr[x]<small)
{ small = arr[x]; }
System.out.println(“large no.” +big “small no.” +small);
} }
Father of java - James Gosling
 WAP to input the elements in an array & short them in ascending
order.

 2D–array: - It can be through as a rectangular display of elements with rows


& columns. Or,
It is a collection of a number of 1D arrays which are placed
one after another.
Syntax : - int [ ] [ ] array name;
Ex- int [ ] [ ] arr ;
 Creation of 2D array (in memory): -
int arr [ ] [ ] ;
arr = new int [3] [4];
or, int arr[ ] [ ] = new int [3] [4];
 WAP to show the concept of 2D array.
class check
{ public static void main (String args [ ])
{ int arr[ ] [ ] = new int [4] [ ];
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
}
}
as we known that all the elements are initialize to their default value of
according to value here the default value of references variable is null.
 Initialization of 2D array: - It may be initializes by following with a
list of initial value enclosed in curly braces.
For Ex- int arr [ ] [ ] = {0, 0, 0, 1, 1, 1};
int arr [ ] [ ] = {{0, 0, 0}, {1, 1, 1}};
int arr [ ] [ ] = {{0, 0, 0}
{1, 1, 1}};
Father of java - James Gosling
 WAP to show the concept of 2D array.
class matrix
{ public static void main(String args[ ])
{ int arr[ ] [ ] = new int [4] [5];
int i, j, k;
for (i=0; i<4; i++)
{ for (j=0; j<5; j++)
{ arr[i][j] = k;
k++; }
}
for (i=0; i<4; i++)
{ for (j=0; j<5; j++)
{ System.out.println(arr[i][j]+ “ ”);
}
System.out.println(“\n ”);
}
}
}
 WAP to input element of matrix & transpose its using 2D array.
class transpose
{ public static void main(String args[ ])
{ int arr[ ] [ ] = new int [3] [3];
int arr[ ] [ ] = new int [3] [3];
Scanner S = new Scanner (System.in);
System.out.println(“ enter the matrix element ”);
int i, j;
for (i=0; i<3; i++)
{ for (j=0; j<3; j++)
{ arr[i][j] = s.nextInt;
}
}
for (i=0; i<3; i++)
{ for (j=0; j<3; j++)
{ arr[i][j] = arr[j][i];
}
}
System.out.println( “Transpose of matrix is ”);
for (i=0; i<3; i++)
{ for (j=0; j<3; j++)
{ System.out.println(arr[i][j]+ “\t”);
}
System.out.println(“\n ”);
}
}
}
Father of java - James Gosling

String
 String: -In java, string is a pre-define class is in java.lag package. It is a final
class & it is immutable in nature.
In java, String is not a character array & is not null
terminated. String class is used to string of fixed length.
Syntax: - string <string_name>
<string_name>= new string (“string”);
Ex- string name;
name = new string (“Rahul”);
or,
string name = new string (“suman”);
 WAP to show the concept of constructing one string from another.
class suman
{ public static void main(String args[ ])
{ string ch= “BCA”;
string s1 = new string (ch);
string s2 = new string (s1);
system.out.print(s1);
system.out.print(s2);
}
}

 Length of string: -Like array, it is possible to get the length of string by


using the length method of the string class.
Ex- int v = name.length( );

 String array : -We can also create & use array that contains string.
Ex- string arr[ ] = new string [5];

 String method: -The string class defines a number of methods that


allows us to accomplish a verity of string manipulation task.

Method name Description


i. s2=s1.toLowerCase It converts the string s1 to all lowercase.
ii. s2=s1.toUpperCase It converts the string s1 to all uppercase.
iii. s2=s1.replace(„x‟,„y‟); It replace all appearances of x with y.
iv. s2=s1.trim( ); It remove white space at the beginning & end
of string s1.
v. s1.equlas(s2); It returns true, if s1 is equal to s2.
vi. s1.equalsIgnoreCase(s2); It returns true, if s1 is equal to s2, ignoring the
case of the character.
vii. s1.length( ); It return the length of s1.
viii. S1.charAt(n); It returns nth character of s1.
Father of java - James Gosling
ix. s1.CompareTo(s2); It returns negative, if s1 less than s2, positive if
s1 greater than & zero if s1 equal to s2.
x. s1.Concat(s2); It joins the s1 & s2 string.
xi. s1.SubStream(n); It gives sub-stream starting from nth character.
xii. S1.SubStream(m,n); It gives sub-stream starting from nth character
up to mth (not including mth)
xiii. String.Valueout(p); It create a string object of a parameter p
(simple type / object)
xiv. P.toStream( ); It create string representation of the object p.
xv. S1.indexOf(„x‟); It gives the position of the first occurrence of x
in the string s1.
xvi. S1.indexOf(„x‟,n); It gives the position of x that occur after nth
position in the string s1.
xvii. String.Valueout(var); It converts the parameter value to string
representation.
 WAP to show the concpet of touppercase() & tolowercase() of string class.
class CASE
{
public static void main(String args[ ])
{
String s={"Bca"};
System.out.println(toUpperCase(s));
System.out.println(toLowerCase(s));
}
}
 WAP to show the string method equals & equalsignorecase ( )
class demo
{
public static void main(String args[ ])
{
string s1="Hello";
string s2="Hello";
string s3="Good bye";
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.equals(s4));
System.out.println(s1+"equals ignorecase"+s4"="
+s1.equalsIgnoreCase(s4));
}
}
Father of java - James Gosling
 WAP to sort the given word in dictionary order.
Jitendra, Manoj, Upendra, Ankur, Radha.
class dictionary
{
Static string name[ ] ="Jitendra","Manoj","Upendra","Ankur","Radha"
public static void main(String args[ ])
{
int size = name.length ;
string temp= null;
for (int i=0;i<size;i++)
{
for (int i=0;i<size;i++)
{
if(name[j].CompareTo(name[i])<0)
{ temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
for (int i=0;i<size;i++)
{
System.out.println(name[i]);
}
} }
 WAP to concatenate one string to another using concat( ) function.
import java.util.Scanner;
class add
{
public static void main(String args[ ])
{
string s1;
string s2="Ram";
scanner s = new scanner (System.in);
System.out.println("enter the string");
s1 = s.nextLine( );
System.out.println(s1.Concat(s2));
}
}
Father of java - James Gosling
 WAP to find the length of inputted string.
class Ram
{
public static void main(String args[ ])
{
string s = "manmohan";
System.out.println("length of string="+s.length());
}
}
 WAP to input string & show the ASCII value of each character.
import java.util.Scanner;
class Asciivalue
{
public static void main(String args[ ])
{
scanner s = new scanner (System.in);
System.out.println("enter the string");
string s1 = s.nextLine( );
char ch[ ] s1.toCharArray( );
for(int i = 0;i<s1.length( );i++)
{
System.out.println(ch[i]+"="+(byte)ch[i]);
}
}
}
 WAP to input a string and check it is palindrome or, not.
import java.util.Scanner;
class palindrome
{
public static void main(String args[ ])
{
string original, rev=" ";
scanner s = new scanner (System.in);
System.out.println("enter the string");
original = s.nextLine( );
int length = original.length();
for(int i = length-1;i>=0;i--)
{
rev = rev +original.CharArray(); }
if(origianl.equals(rev))
System.out.println("palindrome");
else
System.out.println("palindrome");
}
}
Father of java - James Gosling
 WAP to input a string & check is how many vowel & consonant.
import java.util.Scanner;
class palindrome
{
public static void main(String args[ ])
{
scanner s = new scanner (System.in);
System.out.println("enter the string");
string str = s.nextLine( );
int count = 0,num = 0;
for(int i = 0;i<str.length();i++)
{
char ch=str.charAt(i);
if(ch=='A'|| ch=='a'|| ch=='E'|| ch=='e'|| ch=='i'||
ch=='I'|| ch=='o'|| ch=='O'|| ch=='u'|| ch=='U'||)
{
count = count+1; }
else
{
num = num+1; }
}
System.out.println("there are "+count+" vowels");
System.out.println("there are "+num+" consonant");
}
}
 StringBuffer: -It is a pre-defined class included in java.lang package. It
creates string of flexible length that can be modified in terms of both length &
content. It holds string that can be modify after they are created. We can insert
character & sub-string in the middle of a string or, append another string to
the end.
It will automatically grow to make room for such
addition & often has more character pre- allocated than are actually needed to
allow room or, growth.

Method Description
1. s1.setcharAt It modifies the n character to x.
2. s1.append(s2) It appends the string s2 to s1 at the end.
3. s1.insert(N,s2) It inserts the string s2 at the position N of the
string s1.
4. s1.setLength(n) It sets the length of the string s1 to n.
i. If n less than s1.length() then s1 is truncated.
ii. If n greater than s1.length() then zero's are added to s1.
Father of java - James Gosling
 String buffer constructor: -It defines four constructors: -
I. StringBuffer( ): -It is the default constructor which are no
parameter, it reserve rooms for 16 character without re-allocation.
II. StringBuffer(int size): -It accepts an integer argument that explicitly
set the size of the buffer.
III. StringBuffer(string str): -It accepts a string argument that sets the
initial content of the string buffer object & reserve rooms for 16 more
character without re-allocation.
IV. StringBuffer(Charsequence chrs): -It creates an object taht
contains the character sequence content in char.

 length ()and capacity: -The current length of StringBuffer can be found to


the length method where as the total allocated capacity can be found
through the capacity( )method.
General format: -int length( );
int capacity ( );
 WAP to show the concept of length( ) & capacity ( )of StringBuffer class.
class check
{
public static void main(string args[ ])
{
class StringBuffer sb = new StringBuffer("Sorry");
System.out.println("buffer="+sb);
System.out.println("length="+sb.length( ));
System.out.println("capacity="sb.capacity());
}
 WAP that finds initials from your full name & display them.
class check
{
public static void main(string args[ ])
{
string myname = "sunit kumar singh";
StringBuffer sb = new StringBuffer( );
System.out.println("enter name="+myname);
int length = myname.length( );
for(int i =0;i<length;i++)
{
if(character.isUpperCase(myname.CharAt(i)))
{
sb.append(myname.CharAt(i));
}
}
System.out.println("initial of the name is="+sb);
}
}
Father of java - James Gosling
 WAP to input a string & check whether it is palindrome or, not.
(StringBuffer class)
import java.util.*;
class palindrome
{
public static void main(string args[ ])
{
scanner s = new scanner(System.in);
string str = s.nextLine( );
StringBuffer sb1 = new StringBuffer(sb );
StringBuffer sb2 = new StringBuffer(sb1);
sb1.reverse ( );
System.out.println("original="+sb2);
System.out.println("after reverse="+sb1);
if(String.valueOf(sb1).CompareTo(string.valueOf(sb2))==0)
{System.out.println("palindrome"); }
else
{System.out.println("not palindrome");}
}
}
 WAP to print all the arguments in reverse order that is given in
command line.
class command
{
public static void main(string args[ ])
{
int a = args.length;
for (int i = a-1;i>=0;i--)
System.out.println("Args["+i+"]="+args[i]);
}
}
 WAP to reverse a specified string through the method reverse ( )of
StringBuffer class.
class suman
{
public static void main(string args[ ])
{
string sb = "ramu kaka";
StringBuffer s = new StringBuffer( );
System.out.println("reverse of given string =");
System.out.print(sb.reverse( ));
}
}
Father of java - James Gosling
 WAP to demonstrate the insert( ) method of StringBuffer class.
class suraj
{
public static void main(string args[ ])
{
StringBuffer sb = new StringBuffer("I like");
sb.insert(2,"you");
System.out.println(sb);
}
}
 WAP to demonstrate the concept of charAt( )and setCharAt( )method in
StringBuffer class.
class akash
{
public static void main(string args[ ])
{
StringBuffer sb = new StringBuffer("Hellow");
Hellow System.out.println("buffer before"+sb);
e System.out.println("charAt before"+sb.charAt(1));
sb.setCharAt(1,"I");
sb.setLength(2);
HI System.out.println("Buffer after="+sb);
I System.out.println("charAt after="+sb.charAt(1));
}
}
 delete ( ) & deleteCharAt( ): - We can delete character within StringBuffer
by using a method delete ( ) & deleteCharAt( ).

Method description
I. delete( ) It delete a sequence of character from
specified string.
II. deleteCharAt( ) It delete the character at the index
specified by LOC(lines of code). It
returns the resultive StringBuffer
objects.
 WAP to show the concept of delete ( ) & deleteCharAt ( ).
class polo
{
public static void main (string args[ ])
{ StringBuffer sb= new StringBuffer("This is a text");
sb.delete(4,7);
System.out.println("after delete"+sb);
sb.deleteCharAt(0);
System.out.println("after delete charAt"+sb);
}}
Father of java - James Gosling

 Vector: -It is a pre-defined class of java.util package. A vector allows us to


create dynamic array that can contain multiple objects. It provides method for
adding, removing & inserting a elements.
It can hold objects of any type & any number. The objects do not
have to be homogenous. Arrrays can be easily implemented as vectors.
syntax: - vector v = new vector ( ); // declaring without size.
vector v = new vector(5); // declaring with size.
A vector can be declare without specifying
accommodate & unknown number of items.
Advantage: -
I. It is convenient to use vector to store objects.
II. A vector can be used to store a list of object that may be vary in size.
III. We can add & delete object from the list as an when required.
Vector cannot handle primitive type like int, float, char,
double etc. Primitive data type may be converted into objects by
using the rapper classes contain in the java.lang package.
 Important Vector method: -
Method call/name meaning
i. list.addElement (item) It adds the item specification to the list
at the end
ii. list.elementAt (10) It gives the name of the tenth object
iii. list.size ( ) It gives the number of object present in
the list
iv. list.removeElement (item) It removes the specified item from the
list
v. list.removeElementAt (n) It removes the item stored in the nth
position of the list
vi. list.removeAllElement( ) It removes all the elements in the list
vii. list.CopyInto (array) It copies all items from list to array
viii. list.insertElementAt(item,n) It insert the item at nth position
ix. list.setElementAt (object,n,int index) It replaces the element at the index
with the object n
x. int capacity ( ) It return the number of element that will
fit into the currently allocated portion of
the vector object
 Constructor of vector: - Vector provides basically three different
constructors.
i. Vector (int): - It creates a new vector with the specified initial
capacity.
ii. Vector (int, int): - It creates a new vector with the specified initial
capacity & increment quantity.
iii. Vector ( ): -It creates a new vector with default initial capacity &
increment quantity.
Father of java - James Gosling
 Write a program to converts a string vector into an array of string &
display the string using the different method of vector class.

import java.util.*;
class sunit
{ public static void main( String args [ ])
{
Vector list = new Vector ();
int length = args.length;
for (int i=0; i<length; i++)
{ list.addElement(args[i]); }
list.insertElementAt ("Champion",2);
int size= list.size( );
String s[ ] = new String [size];
list.CopyInto(S);
System.out.println("list of elements =");
for (int i=0; i<size; i++)
{System.out.print(s[i]);
}
}}
Note: -This program represents the use of array, string & vector.

 Wrapper Class: -It form a very important part of the java.lang package. They
encapsulate simple primitive type in the form of classes. It is useful whenever
we need object representation of primitive types.
In addition to make primitive types, behave like object, then
we have to prefer wrapper classes. It also provides method for converting
string to various data types and also type specification methods.
All numeric wrapper classes extend the abstract super class
number. There are basically six numeric wrapper classes - double, float, byte,
short, long, Integer.
The wrapper class in java.lang are as well as follows: -
Primitive data types Wrapper class
i. byte Byte
ii. char Character
iii. int Integer
iv. long Long
v. float Float
vi. double Double
vii. boolean Boolean
viii. short Short
Father of java - James Gosling
 Write a program to show the concept of wrapper class & its method.
class test
{
public static void main( String args [ ])
{
String S = args[0];
Byte b = Byte.Valueof(s);
Short s1 = Short.Valueof(s);
Integer i = Integer.Valueof(s);
Long l = Long.Valueof(s);
System.out.println ("outputs are as follow :");
System.out.println (b);
System.out.println (s1);
System.out.println (i);
System.out.println (l);
}}
 Method of wrapper class: - The wrapper classes have a number of unique
methods for handling primitives data types & objects.
1. Converting primitive numbers to object numbers using constructor method.
constructor calling conversion action
a. Integer int val=new Integer(i); primitives integer to integer objects
b. Float flaot val=new Float(f); primitives float to float objects
c. Double double val=new Double(d); primitives double to double objects
d. Long long val=new Long(l); primitives long to long objects
2. Converting object number to primitives number by using type value( )
method
constructor calling conversion action
a. int i=intvar.int_value( ); Object to primitive integer
b. float f=floatvar.float_value( ); Object to primitive float
c. double d=doublevar.double_value( ); Object to primitive double
d. long i=longvar.long_value( ); Object to primitive long
3. Converting number to string by using to String( ) method
constructor calling conversion action
a. str = Integer.toString(i); Primitive integer to string
b. str = float.toString(f); Primitive float to string
c. str = double.toString(i); Primitive double to string
d. str = long.toString(i); Primitive long to string
4. Converting string object to numeric object by using the static method
Valueof ( )
constructor calling conversion action
a. Integer var=Integer.Valueof(str) convert a string to integer object
b. float var=Float.Valueof(str) convert a string to float object
c. Double var=Double.Valueof(str) convert a string to double object
d. Long var=Long.Valueof(str) convert a string to long object
Father of java - James Gosling
5. Converting numeric string to primitive numbers by using parseInt( ) method
constructor calling conversion action
a. int i =Integer.parseInt(str); converts string to primitive integer
b. long i =Long.parseLong(str); converts string to primitive long

Note: - parseInt( ) & parseLong( ) method through a number format Exception, if


the value of the str doesn't represent of integer.

 Interface: - An interface is basically a kind of class like classes, interfaces


contain methods & variable but with a major difference.
The difference is that interface defines only abstract method &
final fields. It means that they do not specify any code to implement method &
data field contain only constant. So, it is the responsibility of a class that
implements an interface to define the code for implementation of these
methods.
Note: -Interfaces are used to define a behavior protocol (standard
behavior) that can be implemented by any class anywhere in the
class hierarchy.
Syntax: - interface <interface_name>
{
var declaration;
method declaration; // interface body
}
 Variable are declared as follows:-
Static final type <var_name>=value;
Note: - All variables are declared as constant.
 Method declaration will contain any a list of methods without anybody
statement.
Syntax : - return type <method_name> (arguments);
Ex- 1. interface item
{
static final int code = 101;
void show ( );
}
2. interface Area
{
final static float pi = 3.142 f;
float calculate (float x, float y);
void show ( );
}
Father of java - James Gosling
 Important point related to interface: -
1. A class can implement many interface separate each interface has with a
comma in the class declaration.
2. An interface is not a substitute for multiple interfaces.
3. All the methods of an interface are abstract.
4. All the variables of an interface are public, static & final.
5. We need not specify above keyword when declaring methods &
variables.
6. We cannot declare a private or, protected variables or, method in an
interface. Since the method has to be overridden in a class.
7. The method is an interface cannot be final because a method that is
declared final cannot be modifying by any class.
 Steps for implementing an interface: -
1. import the interface
2. declare the class and
3. Use the implements keyword followed by the name of the interface.
Ensure that the class implements every method that has been
declared in the interface.
4. Save the file with the .java extension.
5. Compile the application created.
 Extending interfaces: - Like classes, interfaces can also be extended that is
can be extended for make the sub-interface of the interface.
The new sub-interfaces will inherit all the numbers of the super
interface in the manner similar to the sub-classes.
Note: - Extend keyword is used to derived new sub-interface with the
super interface.
Ex- interface MCA extends BCA
{
//body of MCA
}
 Implementing interface: - Interface are used as supper class whose property
are inherited by class. So, it is necessary to create a class that inherits the given
interface. For this purpose, implementing keyword is used.

Syntax: - 1. Class <class_name>implements <interface_name>


{…………….. \\ body of class
}
2. Class <class_name>extend superclass
implements interface1, interface2……
{…………….. \\ body of class
}
Father of java - James Gosling
 WAP to show the concept of implementing interfaces.
interface area
{ final static float pi=3.14f;
float compute (float x, float y);
}
class rectangle implements area
{
public float compute (float x, float y)
{
return (x*y);
}
class circle implements area
{
public float compute(float x, float y)
{
return(pi*x*x);
}
}
class test
{
public static void main (string args[ ])
{ rectangle rect = new rectangle ( );
circle cir = new circle ( );
area ar; // interface object
ar = rect; // area refer to rect object
System.out.println(“area of rectangle is”+ar.compute(10,20));
ar = cir ;
System.out.println(“area of circle is”+ar.compute(10,0));
}
}
Father of java - James Gosling
 WAP to implement the multiple inheritances through the multiple inheritances.
class student
{
int roll-number;
void get number(int n)
{ roll number = n; }
void put_number( )
{ System.out.println(“Roll no.”+ roll_number); }
}
class test extends students
{ float part1, part2;
void get marks(float m1, float m2)
{ part1 = m1;
part2 = m2;
}
void put marks ( )
{ System.out.println(“Marks Obtained”);
System.out.println(“Part 1=”+part1);
System.out.println(“Part 2=”+part2);
} }
interface sports
{
float sports_wt=6.0f;
}
class results extends test implements sports
{ float total;
public void putout ( )
{ System.out.println(“sports wt=”+sports_wt);
}
void display ( )
{ total = part1+part2+sports_wt;
put-number( );
put_marks( );
put_wt ( );
System.out.println(“total score=”+total);
} }
class hybrid
{ public static void main(string args[ ])
{
result student1= new results( );
student1 get_number(1,2,3,4);
student get_marks (27.5f,33.0f);
students1.display( );
}
}
Father of java - James Gosling

 Package:-
Java provides a powerful group related classes & interfaces together in
a single unit is called packages.
In other word, packages are group of classes, interfaces &
sub-packages. It provides convenient mechanism for managing a large group
classes & interfaces.
Note: -1. Package is similar to class library in other languages.
2. In fact, Packages act as containers for classes.

Java packages have sub-packages such as applet, I/O etc.


Each of these packages has a number of classes and interfaces as well as sub-
packages. Ex- The java awt (package) has a sub-package event under it.

 Benefits of packages: -
By organizing our classes into packages, we achieve
the following benefits.
I. The classes contained in the packages of other programs can be easily
re-used.
II. In packages classes can be unique compared with classes in other
packages it means that two classes into different packages can have the
same name they may be referred by their fully qualified name
comprising the package name & the class name.
III. It provides a way to „Hide‟ classes thus preventing other program or,
packages from accessing class that are meant for internal use only.
IV. Package also provides a way for separating design from coding.
V. First we can design classes & decide their relationship & then we can
implement the java code needed for the methods.
VI. It is possible to change the implementation of any method without
affecting the rest of the design.

 Classification of packages: - There are two types of packages.


(1) API Packages (2) User define Packages

I. API Packages: - Java API provide a large number of classes grouped


into different packages according to their functionality.

Java

Lang Util IO AWT .net applet


Frequently used API packages
Father of java - James Gosling
 Java system packages and their classes: -
Packages name Contents

i. Java.lang Language support classes these are


29 classes & 3 interfaces classes that java compiler itself use &
therefore they are automatically
imported. They include classes for
primitive type, strings, math functions,
threads and exceptions.
ii. Java.util It is basically language utility classes
34 classes &13 interfaces such as vectors, hash tables, random
numbers, date etc.
iii. Java.io Input/output support classes. They
50 classes & 14 interfaces provides facilities for the input and
output of data.
iv. Java.awt Set of classes for implementing
63 classes & 14 interfaces graphical user interface. They include
classes for windows, buttons, lists,
menus & so on.
v. Java.net Classes for networking. They include
client socket, server socket, classes for communicating with local
datagram socket, computers as well as with internet
multicast socket. Servers.
vi. Java.applet Classes for creating & implementing
1class & 3 interfaces, applet.
applet Context, stub &
avid clip interfaces

 Using System Packages: -The packages are organized in a hierarchical


structure. There are two ways of accessing the classes stored in a package. The
first approach is to use the fully qualified class name that we want to use. It is
done by using the dot operator. For Ex- java.awt.color
awt is the name of package in java & the hierarchy is
represented by separating by levels with . (dots).
This approach is perhaps the best & easiest one if we need
to access the class only ones or, when we need not have to access any other
classes of the packages.
In many situation we might want to use a class in a number of
places in the program or, we may like to use many of the classes contain in a
package. We may achieve this easily as follow.
Format: - import package_name.class_name;
or, import package_name.*;
Ex- import java.util.scanner;
import java.util.*;
Father of java - James Gosling
here import is a keyword, this statement must appears at the top of
the file before any class declaration.

II. User define Package: - When we create an application, we typically


create many classes. We can organize these classes by creating our own
packages. The packages that we create are called UDP.

 Creating our own packages: - It evolves the following steps: -


i. Declare the package at the begging of a file.
Format: - package package_name;
ii. Define the class that is to be put in the package & declare it public.
For Ex- public class class_name;
iii. Create a sub-directory under the directory where the main source files
are store.
iv. Store the listing as the class_name.java file in the sub-directory created.
v. Compile the .java file thus creates .class file in the sub-directory.

 Using a Package: -
package mypackage;
public class BCA
{
public void show( )
{
System.out.println(“Have a nice Day”);
}
}

This source file should be named BCA.java & stored in the sub-
directory mypackage. Now, Compile this java file the resultant
BCA.class will be store in the same sub-directory.
Import mypackage.BCA;
class Demo
{
public static void main (string args[ ])
{
Bca b = new Bca ( );
b.show( );
}
}
It is a simple program that imports the class Bca from the mypackage.
The source file should be saved as demo.java and then compile. The source
file and the compile file would be saved in the directory of which
mypackage was a sub-directory. Now, we can run the program & obtain the
result.
Father of java - James Gosling

 Multithreading: -
 Thread: -It can be defined as the sequential flow of control
within a program. It is not a program on its own but runs within a program.
Thread also has a begging, sequence, and end. Every
program has at least one thread that is called the primary thread. We can
create more threads when necessary infect, all main programs are the
example of single thread program.

Class xyz Beginning

{……………… Single threaded body

} End

 Multithreading: -It is conceptual programming paradigm where


a program, process is divided into two or, more sub-program (processes)
which can be implemented at the same time at the parallel.
For Ex- One sub-program can display an animation on the
screen while another build the next animation to be displayed. This is
something similar to dividing a task into sub-tasks & assigning them to
different people for execution independently & simultaneously.
A unique property of java is that it supports
multithreading that is, java enable us to use multiple flows a control in
developing programs.

Note: - A program that contains multiple flows of control is known as


multithreaded program.
Main Thread
…………………………
Main method module
……………………………
……………….

start start

………………… switching ………………… switching …………………


…………………… …………………… ……………………
…………………… …………………… ……………………
.. ..
Thread A Thread B Thread C

Fig: - A multithread program


Father of java - James Gosling
 Creating Threads: -it is very simple. Threads are implemented in the
form of object that contains a method called run( ). The run( ) method is
the heart & soul of any thread. It makes up the entire body of a thread & it
is only the method in which the thread‟s behaviors can be implemented.
For Ex-
public void run ( )
{
……………………… // statement for implementing thread
………………………
}
The run( ) method should be invoked by an object of
the related thread. It can be archived by creating the thread & initiating it
with the help of another method start( ).
A new thread can be created into two ways.
1. By creating a thread class 2. By converting a class to a thread

1. By creating a thread class: - Define a class that extend Thread class &
override its run( ) method with the code required by the thread.
2. By converting a class to a thread: - Define a class that implements
runnable interface. It has only one method run( ) that is to be define in the
method with the code to be executed by the thread.

 Extending the Thread class: - we can make our class runnable as thread by
extending the class java.lang.thread. It gives us access to all the thread method
directly. It includes the following steps: -
I. Declare the class as extending the Thread class.
II. Implement the run( ) method that responsible for executing the
sequence of code, that the thread will execute.
III. Create a thread object & call the start( ) method to initiate the thread
execution.
A. class X extends Thread
{
………………….. // statements
…………………..
}
B. public void run( )
{
………………….. // thread code
…………………..
}
when we start the new thread, java calls the
thread‟s run( ) method. So it is the method where all the action
takes place.
Father of java - James Gosling
C. Starting new thread: -To actually create & run an instance
of our Thread class. We must write the following statement.
X x1= new X( );
x1.start( ); // invokes run( ) method

 WAP to create threads by using the Thread class & also execute them.
class x extends Thread
{
public void run( )
{
for (int i=1; i<=5; i++)
{ System.out.println (“\t From thread x: i=”+i);
}
System.out.println (“Exit from x”);
}
}
class y extends Thread
{
public void run( )
{
for (int j=1; j<=5; j++)
{ System.out.println (“\t From thread y: j=”+j);
}
System.out.println (“Exit from y”);
}
}
class y extends Thread
{
public void run( )
{
for (int k=1; k<=5; k++)
{ System.out.println (“\t From thread z: k=”+k);
}
System.out.println (“Exit from z”);
}
}
class test
{
public static void main(string args[ ])
{
new x( ).start( );
new y( ).start( );
new z( ).start( );
} }
x x1=new x ( ); x1.start( ); in place of new x( ).start( );
Father of java - James Gosling
 Stopping & blocking a thread: -
 Stopping a thread: - Whenever we want to stop a thread from running for
the we may do so b calling it stop( ) method.
For Ex- x1. Stop( );
This statement causes the thread to make to the dead state. A thread will
also make to the dead state automatically when it reaches the end of its
method.
Note: - The stop( ) method may be used when the pre-mature death of a
thread is desired.
 Blocking a thread: - A thread can also be temporarly suspended or,
blocked from entering to the runnable & sub-sequently running state by
using either of the following threads methods.
i. sleep( ):- It is blocked for a specified time.
ii. suspended( ): - It blocked until further orders.
iii. wait( ): - It blocked until certain condition occur.
This method causes the thread to go into the blocked
(or, not runnable) state. The thread will return to the runnable state when
the specified time is elapsed in the case of sleep( ), The resume( ) method
is invoked in the case of suspend. The notify method is called in the case of
wait( ) method.
 Life cycle of thread: -

New thread Not Runnable


Runnable

Dead
Fig: - The run( ) method terminates

New thread New born


Start Stop

Active thread Dead


Ready Runnable
Killed thread
Yield
Stop

Blocked die thread not runnable

Fig:- state transition diagram of a thread


Father of java - James Gosling
During the life time of a thread, there are various states, it can enter. It includes
1. New born state 2. Runnable state
3. Running state 4. Blocked state
5. Dead state
I. New born state: - when we create a thread object, the thread is born & is said
to be in new born state. The thread is not yet scheduled for running. At this
stage, we can do only one of the following things with it-
a. schedule it for running by using start( ) method.
b. kill it by using stop( ) method.
Note: - If scheduled, it moves to the runnable state. If we attempts to use any
other method at this stage an exception will be thrown.

New born
start( ) stop( )

Runnable state Dead state


Fig: - scheduling a new born thread
II. Runnable state: -It means that the thread is ready for execution & is waiting
for the availability of the processor that is the thread has joined the queue of
threads that are waiting for execution.
If all threads have equal priority, then they are given time
slaps for execution in round-robin function. i.e first come first serve (FCFS)
manner. The thread that relinquishes (free) control joins the queue at the end &
again waits for its turn. This process of
assigning time to threads is known as time slicing. However, if we want a
thread to relinquishes control to another thread to equal priority before its turn
comes, we can do show by using the yield( ) method.

yield( )

running thread

runnable thread

Fig: - relinquishing control by using yield( )


Father of java - James Gosling
III. Running state: -Running means that the processor has given its chain to the
thread for its execution. The thread runs until it relinquishes control on its own
or, it is pre-empted by a higher priority thread. A running thread may
relinquish its control in one of the following situations: -

A. It has been suspended using suspend ( ) method. A suspend thread


can be re-vied by using the resume ( ) method.
This approach is useful when we want to suspend a thread
for some time due to certain reason but do not want to kill it.
Suspend( )

running runnable suspended( )

Fig: - Relinquishing control using suspend ( ) method


B. It has been made to sleep. We can put a thread to sleep for a specified
time period using the method sleep (time), where time is in
millisecond.
It means that the thread is out of the queue during
this time period. The thread re-enter the Runnable state as soon as this
time period is elapsed.
sleep( )

running runnable suspended( )

Fig: - Relinquishing control using sleep ( ) method


C. It has been told to wait until some events occur. This is done using
wait ( ) method. The thread can be schedule to run again using the
notify( ) method.
wait( )

running runnable waiting( )

Fig: - Relinquishing control using wait ( ) method


Father of java - James Gosling
IV. Block State: - A thread is said to be blocked when it is prevented from
entering into the Runnable state & sub-sequently the running state. This
happens when the thread is suspended, sleeping, or, waiting in order to satisfy
certain requirement.
A blocked thread is considered “not runnable” but not
dead and therefore fully qualifies to run again.
V. Dead State: - Every thread has a life cycle a running thread in its life when it
has completed executing its run ( ) method. It is a natural death. However, we
can kill it by sending the stop message to it at any state. Thus, causing a pre-
mature death to it.
A thread can be killed as soon. It is born or, while it is
running or, even when it is in “not runnable” (blocked) condition.

 The current thread: - Every program that we crate has at least one thread. We
can access this thread by using the currentThread( ) method of the thread class.
This method is static method & hence, we do not have to create an
object of the Thread class to invoke the method.

 WAP to show the concept of currentThread ( )


class test
{
public static void main(string args[ ])
{
Thread thisthread = thread.currentThread( );
try
{
for (int count=0; count<10;count+=2)
{
System.out.println(count);
Thread.sleep(1000);
}
}
catch(IntrruptedException e)
{
System.out.println(“He was interrupted ”);
}
}
}

 WAP to show the use of yield ( ), stop ( ) &sleep ( ) method of threads.


class x extend Thread
{ public void run( )
{ for( int i=1;i<=5;i++)
Father of java - James Gosling
{ if(i==1)
yield( );
System.out.println(“\t from thread x:i=”+i);
}
System.out.println(“exit from x”);
} }
class y extend Thread
{ public void run( )
{ for( int j=1;j<=5;j++)
{ System.out.println(“\t from thread y:j=”+j);
if(j=3)
stop( ); }
System.out.println(“exit from y”);
} }
class z extend Thread
{ public void run( )
{ for( int k=1;k<=5;k++)
{ System.out.println(“\t from thread z:k=”+k);
if(k=1)
try
{ sleep(1000 ); }
catch (Exception e)
{ }
}
System.out.println(“exit from z”);
} }
class threadmethod
{
public static void main(string args[ ])
{ x x1 = new x ( );
y y1 = new y ( );
z z1 = new z ( );
System.out.println(“start thread x”);
x1.start ( );
System.out.println(“start thread y”);
y1.start ( );
System.out.println(“start thread z”);
z1.start ( );
System.out.println(“end of main thread”);
}
}
Father of java - James Gosling
 Exception Handling: -

Object

Throwable

Error Exception

I/O Exception Run-time


Exception

Fig: - Hierarchy of class


An exception is a condition that is causes by the run-time error in a
program.
OR,
when an error is encountered during the execution of a program,
An exception is said to occur. It may happen because of the occurrence
of the certain events that arise at the time of execution.
For Ex- A number divided by zero in a program will cause
an error to occur. When an exception occurs the program terminates
abruptly and the control returns to the operating system.
The purpose of execution handling mechanism to
provide a means to detect & report an “exceptional circuminstance”. So
that appropriate action can be taken. The mechanism suggest
incorporation of a separate error handling code that perform the
following tasks: -
i. Find the problem (Hit the execution)
ii. Inform that an error has occur (through the exception)
iii. Receive the error information (Catch the exception)
iv. Take corporative action (handle the exception)
The error handling code basically consists of
two segments, one to detect errors & two throw exceptions and the other
to catch exception & to take appropriate actions.
Father of java - James Gosling
 WAP to show the concept of run-time error
class error
{
public static void main(string args[ ])
{
int a=10, b=5, c=5;
int x=a/(b-c); // division by zero
System.out.println(“x=”+x);
int y = a/(b+c);
System.out.println(“y=”+y);
}
}
 Common java Exception: -
Exception type cause of exception
i. ArithmeticException It is caused by math error such as
division by zero.
ii. ArrayIndexOutOfBoundExceptions It is caused by bad array indexes or
array size greater than actual.
iii. ArrayStoreException It is caused when a program tries to
store the wrong type of data in an array.
iv. FileNotFoundException It is caused by an attempt to access a
non-existent file.
v. IOException It is caused by general I/O failures such
as inability to read from a file
vi. NullPointerException It is caused by referencing a null object
or, attempt to access null object.
vii. NumberFormatException It is caused when a conversion between
strings & number fails or invalid
conversion of a string to a numeric flow.
viii. OutOfMemoryException It is caused when there is not enough
memory to allocate a new object.
ix. SecurityException It is caused when an applet tries to
perform an action not allowed by the
browser‟s security setting.
x. StackOverFlowException It is caused when the system runs out of
stack space.
xi. StringIndexOutOfBoundException It is caused when a program attempt to
access a non-existent character position
in string.
xii. ClassNotFoundException It is caused when unable to load
requested class.
xiii. AWTException In error.
xiv. EOFException End of file.
xv. IllegalAccessException Access to a class denied.
xvi. NoSuchMethodException A requested method doesn‟t exist.
Father of java - James Gosling
xvii. IntruptedException Thread Interrupted.
xviii. RunTimeException Base class for running java.lang
Exception.
xix. IllegalArgumentException It is caused when method received
illegal argument.
xx. Exception Root class of exception hierarchy.

 Exception handling Model: - Exception handling in java manage using five


keyword that is try, catch, throw, throws & final.
The basic concept of execution handling throwing, exception and
catching it.
I. Try & catch blocks: - A try block consists of a set of executable
statement that may generate & exception. A method, which may throw
an exception, can also be included in the try block.
A try block can be followed by one or, more catch block.
Exception thrown in the try blocks are caught in this catch block.
Note: - A catch block must always be associated with a try block &
cannot stand on its own.
 WAP to show the concept of try & catch for exception handling.
class exceptiondemo
{
public static void main(string args[ ])
{
try
{
string text = args[1];
System.out.println(text);
}
catch(Exception e)
{
System.out.println(“no argument given”);
}
}
}
 WAP to show the concept of error handling.
class error
{ public static void main(string args[ ])
{ int a=6,b=5,c=5,x,y;
try { s=a/(b-c); }
catch (ArithmeticException e)
{ System.out.println(“Division by zero”);
}
y= a/(b+c);
System.out.println(“y=”+y);
} }
Father of java - James Gosling
 Finally Statement: -When an exception is raised the rest of the statements in
the try block are ignored. Sometimes, it is necessary to process certain
statements, no matter whether an exception is raised or, not. The finally block
is used for this purpose.
OR,
Java supports another statement known as finally statement that
can be used to handle an exception that is not caught by any of the previous
catch statements finally block can be used to handle any exception generated
within a try block. It may be added immediately after the try block or, after or,
after the last catch block.

Syntax: - i. try
{
…………….}
finally
{
……………}
ii. try
{
…………..}
catch(……….)
{
……………}
catch(……….)
{
……………}
finally
{
……………}

 WAP to show the concept of try, catch & finally block exception handling.
class error
{
public static void main(string args[ ])
{
int a[ ] = { 5,10};
int b = 5;
try
{
int x = a[2]/b-a[1];
}
catch(ArithmeticException e)
{ System.out.println(“division by Zero”);
}
catch(ArrayindexOutOfBoundsException e)
Father of java - James Gosling
{ System.out.println(“Array Index Error”);
}
catch(ArrayStoreException e)
{ System.out.println(“Wrong Data Type”);
}
finally
{
int y = a[1]/a[0];
System.out.println(“y=”+y);
}
}
}
 Throw statements: -We may want to throw an exception when a user enters a
wrong login Id or, Password. We can use the throw statement to do so. The
throw statement takes a single argument, which is an object of the Exception
class.
Exceptions are thrown with the help of the “throw” keyword. The
“throw” keyword is used to indicate that an exception has occurred. The
operand of throw is an object of any class that is derived from the class
“Throwable”.
Syntax: -
throw Throwable instance;
EX-
throw Throw-object;
The compiler gives an error it the object Throw object does not belong
to a valid Exception class. The throw statement is commonly used in
programmer defined exceptions.
class ABC
{
public static void main (string args[ ])
{
try
{
if (flag < 0)
}
throw new NullPointerException ( );
}
}
 Throws Statements: - If a method is capable of raising an exception that if
does not handle, it must specify that the exception has to be handled by calling
method. This is done using the throws statement. The throws statement is used
to specify by the method.
Father of java - James Gosling
 WAP to show the concept of thrown
class ThrowsExcep
{
public static void main(string args[ ])
{
ThrowsArithmeticException
System.out.println(“Inside main”);
int i=0;
int j = 40/i;
System.out.println(“The statementis not primted”);
}
}

 Priority of Thread: - The java run-time environment executes threads based


on their priority. A CPU can execute only one thread at a time. Therefore the
thread that is ready for execution queue-up for processor time. Each thread is
given a slice of time after which it goes back into the thread queue.
The threads are schedule using fixed priority scheduling, which
essentially executes the threads depending on their priority related to one
another. Each thread have a priority that affects its position in the thread queue
of the processor. A thread with higher priority runs before thread with low
priority.
A thread inherits the priority from the thread that created it. We
can represent the priority of thread by an integer value in the range of 1-10.
The Thread class defines several priority constant that is min_priority is 1,
Nor_ priority is 5 and max_ priority is10. The default setting is norm_priority.
We can change the priority of a thread by using the
set_priority ( ) method of the thread class.
Format: -
a). Thread-name.SetPriority (int num);
b). Public final void SetPriority (int newPriority);
Whenever multiple threads are read for execution,
the java system select the highest priority of thread & executes it. For a thread
lower priority get control, one f the following things should happen.
i). It stops running at the end of run( ) method.
ii). It is made to sleep using sleep( ) method.
iii). It is told to wait using wait ( ) method.
However, if another thread of a higher priority comes
along, the currently running thread will be pre-empted by the incoming thread.
Thus, forceive the current thread to the runnable state.
Note: - The higher priority of thread pre-empts by lower priority threads.
Father of java - James Gosling
 WAP to show the concept of priority of thread.
class x extends Thread
{ public void run ( )
{ System.out.println(“Thread x started”);
for(int i=1; i<=4; i++)
{ System.out.println(“\t from thread x:i=”+i); }
System.out.println(“Exit from x”);
} }
class y extends Thread
{ public void run ( )
{ System.out.println(“Thread y started”);
for(int j=1; j<=4; j++)
{ System.out.println(“\t from thread y:j=”+j); }
System.out.println(“Exit from y”);
} }

class z extends Thread


{ public void run ( )
{ System.out.println(“Thread z started”);
for(int k=1; k<=4; k++)
{ System.out.println(“\t from thread z:k=”+k); }
System.out.println(“Exit from z”);
} }
class test
{
public static void main(string args[ ])
{
x x1 = new x ( );
y y1 = new y ( );
z z1 = new z ( );
Thread z.SetPriority (Thread.max_Priority( ));
Thread y.SetPriority (Thread x.get_Priority( ));
Thread x.SetPriority (Thread.min_Priority( ));
System.out.println(“start thread x”);
x1. Start( );
System.out.println(“start thread y”);
y1. Start( );
System.out.println(“start thread z”);
z1. Start( );
System.out.println(“End of main thread”);
}
}
 Synchronization: - When using two or, more threads in a program, it may so
happen that more than one thread wants to access a resource at the same time.
Father of java - James Gosling
For Ex- One thread might try to read the data from a file while the other tries to
changes the data in the same file.
In such a case, the data become inconsistent. What we need to do is,
allow one thread to finish its task completely & then allow the next thread to
execute. It must be ensured that a shared resource will be used by only one
thread at a time. The process by which this is archived is called
synchronization.
It is based on the concept of „monitor‟. A monitor is
an object that is used as a mutually exclusive lock. A monitor can be
considering similar to a small box, which can hold only one thread at a time. If
one thread enters the monitor all other thread must wait till the thread exists
from the monitor.
 Synchronized code: - There is no class called Monitor in java, rather
each object has its own implicit monitor that is automatically entered
when any of the object is synchronize methods is called.

For a thread to enter the monitor of an object the


programmer must invoke a method that has been created using the
synchronize keyword. As long as a thread executes within a synchronize
method, Any other thread or, synchronize method that tries to call it
would have to wait.
Code: -
Thread x
Synchronized method2( )
{
Synchronized method1( )
{
………….
}
}
Thread y
Synchronized method1( )
{
Synchronized method2( )
{
………….
}
}
Father of java - James Gosling
 WAP to demonstrate the working of Synchronization.
class one
{ Synchronized void show( )
{ int num;
{ System.out.print(“ ”+num);
try
{ Thread.sleep(1000); }
catch (IntrupptedExecution e)
{ System.out.println (“Stop”); }
System.out.println(“done”);
}
}
class two implements runnable
{ int number;
one one1 = new one ( );
Thread t;
public two (one one1_num, int n)
{ one1 = one1_num;
number = n;
t= new Thread(this);
t.start( );
}

public void run( )


{ ont.show(number); }
}
class test
{
public static void main (string args[ ])
{
one one1 = new one ( );
int digit = 10;
two s1 = new two(one1, digit++);
two s2 = new two(one1, digit++);
two s3 = new two(one, digit++); // wait for threads to end
try
{ s1.t.join( );
s2.t.join( );
s3.t.join( ); }
catch(InterruptedException e)
{ System.out.println(“Interrupted”); }
}
}
Father of java - James Gosling
 Implementing the runnable interface: - We can create threads in two ways
that is one by using the extended Thread class and another by implementing
the runnable interface. The Thread class is used for creating & running
threads.
The runnable interface declare the run( ) method that is required
for implementing thread in our program.
To do this, we must perform the following steps: -
1. Declare the class as implementing the runnable interface.
2. Implement the run( ) method.
3. Create a thread by defining and object that is instantiated from this
“runnable” class as the target of the thread.
4. Call the threads start( ) method to run the thread.
 WAP to show the use of runnable interface.
class x implements Runnable
{ public void run ( )
{ for (int i= 1;i< 10;i++)
{ System.out.println(“\t thread x: i”+i); }
System.out.println(“End of thread x”);
} }
class test
{ public static void main (string args[ ])
{ x x1 = new x ( );
Thread t = new Thread(x1); t.start( );
System.out.println(“End of main thread”);
} }
 Applet: -An applet is a smallest package in java. It has only one class and
three interfaces. An applet is a java program that can be embedded in an
HTML page & executed on a java enabled web browser. It is like small
executable code that needs a full application to certain it or, executes it.
An applet is created by sub-classing the
“java.applet.Applet” class. It includes several methods that help in controlling
the execution of applet. An applet is automatically loaded & executed when we
open a web page that contain its. The methods of applet are used to display
image, play video file & respond when we interact with it.
The environment of the applet is known as the context of the
applet. We can retrieve the context by using the getApplet context( ) method.
The life cycle of an applet is implemented by using the several method that is
init( ), start( ), stop( ), destroy( ).
By using applet, we can create multi-media games, quizzes &
various such interacts program or, the web. It can also perform arithmetic
operation, display graphics, play sounds, accept user input, create
animation & play interactive game.
Note: - 1. Use javac to compile applet & applet viewer to execute them.
2. We can view applets in any browser that is java enable.
Father of java - James Gosling
 Local & remote applets: -we can embed applet into web pages in two ways
that is
1. We can write our own applets and embed them into web pages.
2. We can download as applet from a remote computer system & them
embed it into a web page.
An applet developed locally & stored in a local
system is known as a local stored in a local system is known as a local applet.
When a web pages is trying to find a local applet, it doesn‟t need to use the
internet. So, the local system doesn‟t require the internet connection. It simply
searches the directory in the local system & locates & load specified applet.
A remote applet is that which is develop by someone else &
store on a remote computer connected to the internet. If our system is
connected to the internet when we can download the remote applet, we must
know the applet‟s address on the web. This address is known as URL & must
be specified in the applet‟s HTML documents as the value of the codebase
attributes.
Ex- codebase = http://www.netserve.com/applets
Note: - In the case of local applet, codebase may be absent or, may specify a
local directory.

 Difference between application & applet: -


application applet
i. Application are java program that i. It are the java program that are
are design to work on local system executed by a java compatible web
and do not need to a browser need. Browser.
ii. Application run within a java ii. Applets load & run all a java
compatible virtual machine on JVM. enabled web.
iii. The beginning point of an iii. The starting point of an applet
application is the main( ) method. is init( ) method.
iv. An application manage its own flow iv. The flow of execution of an applet is
of execution. partly control by the browser context.
v. It have no restriction about reading/ v. It cannot read/write from/to local file
writing from/to the local file system. system.
vi. Java application program use native vi. Applets are restricted from using
methods from other language such library from other languages such
++
as c or, c . as c or, c++.
Father of java - James Gosling
 Applet life Cycle: -

Born
Begin
(load applet) stop( )

start( ) Running stopped


Idle
paint( )
start( ) destroy( )
Dispaly

Dead End

Exit of Browser
Fig: - An applets state transition diagram

Every java applet inherit the set of default behavior from the
applet class as the result, when an applet is loaded it undergoes a series of
changes in its state. The applet state include: -
1. Born or, initialization state
2. Running state
3. Idle state
4. Dead state or, destroyed state

1. Born State: - Applet enter the initialization state when it is first loaded. This is
archived by calling the init( ) method of Applet class. The applet is born.
At this state we may to do the following, if required: -
a. create object needed by the applet
b. setup initial value
c. load images or, font
d. setup colors
The initialization occurs only once in the applet‟s life cycle.
To provide any of the behavior mention above, we must overwrite the init( )
method.
public void init( )
{
……………….. // work to perform
}
Father of java - James Gosling
2. Running State: - Applet enters in the running state when the system calls the
start( ) method of Applet class. This occurs automatically after the applet is
initialize. Starting can also occur if the applet is already in “stopped” (idle)
state.
For Ex- we may leave the webpage containing the applet
temporarily to another page & return back to the page. It again starts the applet
run. Unlike, init( ) method, the start( ) method may be called more than once.
We may override the start( ) method to create a thread to control
the applet.
public void start( )
{
……………… // Action
}
3. Idle or, stopped state: - An applet becomes idle when it is stop from running.
Stopping occurs automatically when we leave the page containing the currently
running applet. We can also do so by calling the stop( ) method explicitly.
If we use a thread to run the applet, then we must the use stop( )
method to terminate the thread. We can archive this by overriding the stop( )
method.

public void stop( )


{
……………… // Action
}
4. Dead State: - An applet is said to be dead when it is remove from memory. It
occurs automatically invoking the destroy( ) method when we quit the
browser.
Like initialization, destroying state occurs only once in the
applet‟s life cycle. If the applet has created any resources, like threads, we may
override the destroy( ) method to cleanup these resources.
public void destroy( )
{
……………… // Action
}
5. Display State(optional): -Applet move to the display state whenever it has to
perform some output operation on the screen. This happens immediately after
the applet enters into the running state.
The paints( ) method is called to accomplished this task. Almost
every applet we will have a paint method. Like other method in a life cycle.
The default version of paint( ) method does absolutely nothing we must
therefore override method if we want anything to display on the screen.
Father of java - James Gosling
public void paint(Graphics g )
{
……………… // Action
}
Note: - 1. The display state is not considered as art of the applet‟s life cycle.
2. In fact, a paint( ) method is defined in the applet class.
3. It is inherited from the Component( ) class a super class of Applet.

 Creating an executable applet: - Executable applet is nothing but the dot


class files of the applet, which is obtained by compiling the source code of the
applet. Compiling an applet is exactly the same as compiling an application.
Therefore, we can use the java compiler to compile the applet.
Step: - move to the directory containing to the source code & typing the
following command: -
 Javac file_name.java
 The compiled output file called the file_name.class is placed in the
same directory at the source.
 If any error message is receive, then we must check for error,
correct them & the compile applet again.
 Designing a web page: - In order to run a java applet, it is first necessary to
have a web page that references that applet. A web page is basically made up
off text HTML tags that can be interpreted by a web browser on an applet
view.
Like java source code, it can be prepared by using any ASCII text
editor. A web page is also known as HTML pages or, HTML document. Web
pages are store by using a file extension .HTML or, .HTM. such file is referred
as HTML file these file should be store in the same directory of the compile of
the applet.
As we know that, web pages include both texts that we
want to display HTML tags to web browser. A web paged is marked by an
opening HTML & closing HTML Tag. It is following three major section.
1. Comment section (Optional)
2. Head Section (Optional)
3. Body Section (Compulsory)
1. Comment section: -This section contains comment about the web page. It
is important to include comments that tell us what is going on the web
page. A comment line begins with a <! And ends with >.
For Ex- <! This is comment section>
Web browsers will ignore the text enclosed between them.
Although comments are important, they should be kept to a minimum as
they will be downloaded along with the applet.
Note: -It can be included anywhere in the web page.
2. Head section: -This section is defines with a starting <head> tag and
closing </head> tag. This section usually contains a title for the web page.
Father of java - James Gosling
Ex- <head>
<title>welcome to java applet</title>
</head>
The text enclosed in the tags <title>…….</title>will appear in the
title bar of the web browser when it display in the web pages.
3. Body section: -It is important section because this sections the entire
information about the web page & its behavior. We setup many option to
indicate how our must appear on the screen (like color, location, sound
etc).
Ex- <body>
<center>
<h>welcome to applet </h>
</center><br>
<applet………> </applet>
</body>
 Applet tag: -The applet <applet> tag supplies the name of applet to be loaded
& tells the browser how much space the applet resources. The ellipses in the
tag indicate that it contains certain attributes that must specify.
Ex- <applet code = bca.class width = 400 height = 300>
</applet>
This HTML code tells the browser to load the compiled java
applet bca.class which is in the same directory as the HTML file. It also
specify the display area for the applet output as 400 pixels width and 300
pixels height.
The applet tag <applet> specifies three important things: -
1. Name of the applet
2. Width of the applet (pixels)
3. Height of the applet (pixels)
 WAP to create applet with yellow background color and a message print
“Have a nice day”.
import java.awt.*;
import java.applet.*;
public class bca extend Applet
{ public void init ( )
{ setBackground(Color.yellow);
}
public void paint (Graphics g)
{ g.drawString (“Have a nice day”,50,100);
}
}
This byte code should be embedded into HTML code using
<applet> as well as follows :-
<HTML>
<applet code = “bca.class” height = 300 width = 300>
</applet> </HTML>
Father of java - James Gosling
Save this code with the name bca.HTML. This HTML page
contains the applet which can be open in the browser or, an applet_viewer.
For this purpose open any Browser & in the browser‟s address
bar, type .HTML file name along with the directory path.
The applet opens in the browser or, give the command at
cmd prompt as well as follow:-
c:\> appletviewer bca.class and press enter
to open the applet in applet viewer.
 Passing parameter to applet: -The applet tag us a surrounding type that is it
can contain other tags. Passing parameter to applet we use param tag. It is
written between <applet>……..</applet>.
The param tag has two attributes that is name and value. The
name attribute is the name of the parameter passed to the applet & the value
attribute is the value of the variable passed.
Ex- <applet……..>
<param name = color value = “Red”>
</applet>
Passing parameter to an applet code using param tag is something
similar to passing parameter to the main method by using command line
argument. To setup handle parameter, we need to do two things that is
i). Include appropriate <param……….> tag in the HTML document.
ii). Provide code in the applet to parse is parameter.
Parameters are passed on an applet when it is loaded. We
can define the init method in the applet to get hold of parameter define in the
param tag. This is done by using the get_parameter( ) methods this takes one
string argument representing the name of the parameter & returns a string
containing the value of a parameter.
 Write a program to show the concept of passing parameter of the applet.
import java.awt.*;
import java.applet.*;
{ public class ram extends Applet
{ String str;
public void init ( )
{ str = getParameter(“string”);
if (str=num)
str = “java”;
str = “Hellow”+str;
}
public void paint (Graphics g)
{ g.drawString(str,10,100);
}
}
Father of java - James Gosling
<html>
<head>
<title> welcome to java applet</title>
</head>
<body>
<applet code = ram.class
Width = 400
Height = 100>
<param name = “string value = ”applet>
</body>
</html>
 Displaying numeric values: -In applets, we can display numerical value by
first converting them into string and then using the drawString( ) method of
Graphics class. We can do this easily by calling the valueOf ( ) method of
string class.
 WAP to illustrate how an applet handles the numeric values.
import java.awt.*;
import java.applet.*;
public class add extends Applet
{
public void paint (Graphics g)
{
int x = 10, y = 20;
int sum = x+y;
String s = “sum :”String.valueOf(sum);
g.drawString(s,100,100);
}
}
<html>
<applet code=add.class width = 300 height = 300>
</applet>
</html>
 Getting input from the user: -As we know that applet works in a graphical
environment. So applet treats input as text string. We must first create an area
of the string in which user can type and edit input items (which may be of any
data type). We can do this by using the textfield class of the applet package.
Once textfields are created for receiving input, we can type the value in the
field & edit them if necessary. The text field contains items in string form.
They need to be converted to the right form, before they are used in any
computation. The results are then converted back to string for display.
Father of java - James Gosling
 WAP to input the value from user and display their sum using applet.
import java.awt.*;
import java.applet.*;
public class sum extends Applet
{
text field text1, text2;
public void init( )
{ text1 = new textfield(8);
text2 = new textfield(8);
add (text1);
add (text2);
text1.setText (“O”);
text2.setText (“O”); }
public void paint (Graphics g)
{
int x = 0, y = 0, z = 0;
String s1, s2, s;
g.drawString(“input a number in each box”,10,50);
try
{
s1 = text1.getText ( );
x= Integer.parseInt (s1);
s2 = text2.getText ( );
x= Integer.parseInt (s2);
}
catch (Exception e)
{ }
z=x+y;
s=String.valueOf(z);
g.drawString(“The sum is:”,10,75);
g.drawString(s,100,75);
}
public Boolean action (Event.event, object.obejct)
{repaint ( );
return true ; }
}
<html>
<applet code=sum.class width = 300 height = 300>
</applet>
</html>

You might also like