Overview of JAVA

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 62

Overview of JAVA:

C C++ JAVA
Stages of development of Java

HISTORY OF JAVA:
In 1979 “Vinod Khosla” reached America & started a company named Sun Microsystem. JAVA
was developed by “JAMES GOSLING” in 1991, at Sun Microsystem to program electronic
devices later on it was modified as internet programming language. Its mother language was
OAK.

Features of JAVA:
 Small
 Secure
 Robust (flexible)
 Architecture Neutral
 Multithreaded
 Compiled + Interpreted
 Platform Independent Language

When to use JAVA:


1. Standalone programs
2. Smallest of programs that run on browser (applet)
3. Serverside Programs (SERVELETS/JSP)
4. Used for distributed computing (RMI)
5. Compitible with other program (JNI)
6. Mobile computing

Features of OOP’s:
1. Classes & objects
2. Reusability
3. Inheritance
4. Polymorphism
5. Encapsulation
6. Abstraction
First Program in java to print hello world:
Since java is pure object oriented programming language therefore a simple program will also
start with class.

class Program
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}
class every program should have class to support Reusability (class is separate module with
respect to OOP). Every program is saved with the name of class. It is referred as beans on
internet
public is stand alone sharable program
static main program should be stable do not need objects.
void main it is declaration of main function, every compiler controlled language has main
function which guides compiler the starting of program. Void keyword ensures that main
function donot return any value.
String is default datatype in java. Each program in JAVA is a thread.
args[ ] or a[ ] array of output. For example: Hello World will be stored in array of args[] type.
Such that
args[0] = H, args[1] = e, args[2] = l, args[3] = l ……………………… args[10] = d.
Java converts all datatype in string for example:

class Program
{ In this case int a will be
public static void main(String args[]) converted to string and then
{ printed
int a=10
System.out.println(a);
}
}
System . out. println  is a stream to print output. JAVA always transfers data from one file to
other or from one medium to another in form of streams (continous flow of data)
System  it is class. In java name of all inbuild classes starts with capital letter.
out  it is object os System class, used with dot operator.
println  it is function of System class used to print output. It takes parameters in string. It prints
output in next line, to print output in same line we have function print.


Why prog is always saved with name of class (3 main reasons)
java file is converted into class file, compiler recognizes both file by their name.
as we use static in main its property is unchangeable , Name is also one of the property so it should also be
unchangeable.
A code is reusable so name should be stable, same for all users.
TROUBLE SHOOTING
to set environment

My computer
(Right click)

Properties

Tabbed window

Advanced

Environment variable

Path: C:\Jdk1.4\bin

Classes and Objects (instances)


Syntax to define a class in java:

class,<class name>
{
instances- variableset of variable defined inside class
methods/ functions.
}
obj are known as instance [changes value] with the user are instance variable]

struct emp Yes


{ Will run because c++ will treat it is as
char name [20]; class not as structure since c++ is both
int total- salary; procedural +OOPs language
}

Syntax to define obj in java: 

class A Obj
class name  A a = new A();  default Constructor
{  
instance
} object new operator

instances to generate reference.


*JAVA has no garbage collection.
Functions / Methods:
A program is set of instructions given to computer. These instructions initiate some action and
therefore known as executable instructions. In java executable instructions are specified through
methods or functions.
Two types of functions:
 Inbuild Functions
 Userdefined Functions

1. Need of function
There are many reasons for using functions:
1. To cope with complex problems: with functions we can divide complex task into
smaller and easily understood task.
2. To hide low level details: once method is defined user need not know how ethod is
implementing its task. Thus low level details get hidden with methods.
3. To reuse portion of code: when one task is implemented using method then whenever
such task is neededthe same method is used without rewriting the code.
4. To create conceptual units: we can create methods/functions to do one action as single
conceptual unit, one function can use another function to accomplish the task.

2. Function / Method Defination


A function must be defined before it is used anywhere in the program.
General Form
[access-specifier] [modifier] return-type function-name (parameter list)
{
body of the function
}
Where
access specifier  determines type of access of function, can be private, public or
protected
modifier  it can be final, native, synchronized, transient, volatile.
return_type  specifies type of value that return statement of function returns. It may be
any valid Java data type.
Parameter list  comma separated list of variables of function refered to as its
arguments or parameters.
The general form of parameter declaration list is:
function_name(type varname1, type varname2,………… type varnamen)

2.1. Function Prototype and Signature


A Function Prototype is first line of the function definition that tells the program about the type
of value returned by the function and number and type of arguments. With it compiler can
carefully compare each use of function with the prototype to determine whether the function is
invoked properly.
A Function Signature refers to number and types of arguments. It is part of function prototype.
Function Signature and return type makes function prototype.
3. Accessing / Calling a Function
A function is called (invoked or executed) by providing the function name , followed by the
parameters enclosed in paranthesis.
Example: To invoke function with prototype
float area (float, float);
The function call statement will be:
z = area (x, y);
where x, y, z are float variables.
The syntax of function call is similar to declaration, except the type specifiers are missing.

3.1. Actual and Formal Parameters


The parameters that appear in function definition are called formal parameters and the
parameters that appear in function call statement are called actual parameters.
// Method Defination
public int sum(int x,int y)
{
return (x+y);
}
In this x, y are formal parameters

// Method Call
int a=10,b=20;
int s = sum(a,b);
In this a, b are actual parameters

3.2. Call by Value and Call by Reference


The function is invoked in two manners Call by Value and Call by Reference. As they depict the
way in which arguments are passed to function therefore they are also known as Pass by Value
and Pass by Reference.
In java program any variable can be refered by two types:
 Value
 Address
When a varable is refered by its value it is known as Call by Value and when it is refered by its
address it is Call by Reference.

3.2.1. Call by Value (Pass by Value)


In this method function copied the value of actual parameters into the formal parameters that is
function creates its own copy of argument values and then uses them. In this method the change
is not reflected back to the original values.

Example to swap two numbers using Call by Value


class Value
{
void swap(int x,int y)
{
int z;
z=x;
x=y;
y=z;
System.out.println("Value on Swap a= "+x + " b= " +y);
}
public static void main(String args[])
{
int a=4,b=5;
Value obj=new Value();
System.out.println("Value before Swap a= "+a + " b= " +b);
obj.swap(a,b);
System.out.println("Value after Swap a= "+a + " b= " +b);
}
}
Output:
Value before Swap a= 4 b= 5
Value on Swap a= 5 b= 4
Value after Swap a= 4 b= 5

Benefit of this Method: In this method we cannot alter the variables that are used to call the
function because any change that occurs inside the function is on the function’s copy of
argument value. The original copy of argument value remains unchanged.

3.2.2. Call by Reference (Pass by Reference)


In this method function does not create its own copy of original values rather than it refers to
original values by different names i.e reference. The reference or memory location of original
variables is passed. When a function is called by reference the formal parameter becomes
reference to actual parameters in calling function.
Example to swap two numbers using Call by Reference
class Value1
{
int a=4,b=5;
void swap(Value1 obj)
{
int z;
z=obj.a;
obj.a=obj.b;
obj.b=z;
System.out.println("Value on Swap a= "+obj.a + " b= " +obj.b);
}
public static void main(String args[])
{
Value1 obj=new Value1();
System.out.println("Value before Swap a= "+obj.a + " b= " +obj.b);
obj.swap(obj);
System.out.println("Value after Swap a= "+obj.a + " b= " +obj.b);
}
} Output:
Value before Swap a= 4 b= 5
Value on Swap a= 5 b= 4
Value after Swap a= 5 b= 4

Benefit of this Method: This method is used when we want to change the original values using
function.

* In java all primitive types are passed by value and all reference types (objects, arrays) are
passed by reference.

4. Returning from a function


A function terminates when either a return statement is encountered or at sta

Constructors:
Constructors are special type of function, which are used to initiallize the variables of class and
have same name as that of class.

Properties of constructors:
1. They have same name as that of class.
2. Are used to initiallize the variables of class.
3. Donot have any return type.
4. No need to call them expilicitly are automatically called when object is created
There are three types of constructors in java.
1. Default constructors
2. Parameterized constructors
3. Copy constructors

Default constructors:
It is basis of all constructors. It donot have any parameters. If constructor is not created in a
program then compiler automatically creates a default constructor and initializes all variables to
0.
Syntax: (Program.java)
class Box
{
double width,depth,height; // declaration of global variables
Box() // declaration of default constructor
{
width= 10; // initializing variables in default constructor
depth= 12;
height= 30;
}
}
class Program
{
public static void main(String args[ ])
{
Box b = new Box(); // calling default constructor, when object is created
double volume = b.width * b.height * b.depth;
System.out.println(“Volume of Box is ” + volume);
}
}

Parameterised constructors:
It is another type of constructor. It can take any number of parameters as arguments.
Syntax: (Program.java)
class Box
{
double width,depth,height; // declaration of global variables
Box(double w, double d, double h) // declaration of Parameterised constructor
{
width= w; // initializing variables in Parameterised constructor
depth= d;
height= h;
}
}
class Program
{
public static void main(String args[ ])
{
Box b = new Box(10,12,30); // passing parameters to Parameterised constructor,
double volume = b.width * b.height * b.depth; // when object is created
System.out.println(“Volume of Box is ” + volume);
}
}

Copy constructors:
This constructor passes object as an parameter.
Syntax: (Program.java)
class Box
{
double width,depth,height; // declaration of global variables
Box() // declaration of default constructor
{
width= 10; // initializing variables in default constructor
depth= 12;
height= 30;
}
Box( Box b) // declaration of Copy constructor
{
width= b.width; // initializing variables in Copy constructor
depth= b.depth;
height= b.height;
}
}
class Program
{
public static void main(String args[ ])
{
Box b = new Box(); // calling default constructor, when object is created
Box b1 = new Box(b); // passing object b of default constructor to Copy constructor
double volume = b1.width * b1.height * b1.depth;
System.out.println(“Volume of Box is ” + volume);
}
}

example of contructor overloading:


Syntax: (Program.java)

class Box
{
double width,depth,height; // declaration of global variables
Box() // declaration of default constructor
{
width= 10; // initializing variables in default constructor
depth= 12;
height= 30;
}
Box(double w, double d, double h) // declaration of Parameterised constructor
{
width= w; // initializing variables in Parameterised constructor
depth= d;
height= h;
}
Box( Box b) // declaration of Copy constructor
{
width= b.width; // initializing variables in Copy constructor
depth= b.depth;
height= b.height;
}
}
class Program
{
public static void main(String args[ ])
{
Box b = new Box(); // calling default constructor, when object is created
Box b1 = new Box(100,120,300); // passing parameters to Parameterised constructor
Box b2 = new Box(b); // passing object b of default constructor to Copy constructor
double volume;
volume = b.width * b.height * b.depth;
System.out.println("Volume of Box is (Default Constructor)" + volume);
volume = b1.width * b1.height * b1.depth;
System.out.println("Volume of Box is (Parameterised Constructor)" + volume);
volume = b2.width * b2.height * b2.depth;
System.out.println("Volume of Box is (Copy Constructor)" + volume);
}
}

Inheritance:
It is property of object oriented pogramming in which one class inherits the property of other
class so as to insure resuablty of that class. This class can modify the property of inherited class
and can reuse it as and when needed. It insures child parent relationship.
The class which inherits the property of other class is called “Sub class/ derived class /child
class”
The class whose properties are inherited is called “Super class/ base class/ parent class”
There are five type of inheritances:
 Single level inheritance
 Multi level inheritance
 Multiple inheritance
 Heirarical inheritance
 Hybrid inheritance

Single level inheritance

Multi level inheritance

Multiple inheritance

Heirarical inheritance

Hybrid inheritance
A
A (Super
class)
B
B(Sub
class) C
Abstract class:
It is a special type of class in which we have atleast one abstract function.

Abstract Function

Package
There are two types of packages
 Inbuild Package
 Userdefined Package

Inbuild Packages
There are 5 inbuild packages in java:
Java.lang
Java.io

Multithreading:
Process

Source Code Buffer C.P.U

Ready queue
Buffer1
Java multithreading support the concept of Preemptive scheduling algo after definite time job
stops and restart again when next job executes for sometime.

run
Wait start
new Ready queue exit
C.P.U
*to increase processing size increase processing speed of C.P.U and decrease waiting time of jo

new

exit wait

run start

Small Program are called treads one main prog. can have many treads
Multithreading  Multiprogramming + time sharing

Java multithreading
Implemented in two different ways.
extends thread (class)
implement runnable (interface)
Thread class has many func. But runnable interface has only “run”() func
When we want to check property of thread then we use T.C and if we want to only run the
thread we will use Run interface.

Thread Class
Syntax of extending Thread class
class square extends Thread
{
public void run ()
{
}
}
class cube extends Thread
{
public void run ()
{
}
}
class Program
{
public static void main (String args[])
{
square S = new square(); // Thread S = new square();
cube C = new cube(); // Thread S = new cube();
S. start();
C. start();
}
}
In JAVA every prog. is a thread and have start () func.

Runnable Interface
Syntax of implementing Runnable 
class square implements Runnable
{
public void run ()
{
}
}
class cube implements Runnable
{
public void run ()
{
}
}
class Program
{
public static void main (String args[])
{
square S = new square();
cube C = new cube();
Thread t1 = new thread(S);
Thread t2 = new thread(C);
t1. start();
t2. start();
}
}

Example of multithreading
using extends Thread
class square extends Thread
{
public void run ()
{
System.out. println ( "finding square of numbers:");
for (int i=1; i<=10 ; i++)
{
System.out. println ("square of " +i+ " = " + i*i);
}
}
}
class cube extends Thread
{
public void run ()
{
System.out. println ( "finding cube of numbers:");
for (int i=1; i<=10 ; i++)
{
System.out. println ("cube of " +i+ " = " + i*i);
}
}
}
class Program
{
public static void main (String args[])
{
square S= new square();
cube C= new cube();
S. start();
C. start();
}
}
using implements Runnable

class square implements Runnable


{
public void run ()
{
System.out. println ( "finding square of numbers:");
for (int i = 1; i<= 10 ; i++)
{
System.out. println ("square of " +i+ " = " + i*i);
}
}
}
class cube implements Runnable
{
public void run ()
{
System.out. println ( "finding cube of numbers:");
for (int i = 1; i<= 10 ; i++)
{
System.out. println ("cube of " +i+ " = " + i*i*i);
}
}
}
class Program
{
public static void main(String args[])
{
square S = new square();
cube C = new cube();
Thread t1 = new Thread(S);
Thread t2 = new Thread(C);
t1. start();
t2. start();
}
}

Function of Thread class


sleep (no):- 3000 3 sec; static method can be used directly. (mostly used for flashing effect)
class square extends Thread
{
public void run ()
{
System.out. println ( "finding square of numbers:");
for (int i=1; i<=10 ; i++)
{
try
{
System.out. println ("square of" +i+ "=" + i*i);
Thread . sleep(1000);
}
catch (InterruptedException e)
{
System.out. println ( "Exception");
}
}
}
}
class cube extends Thread
{
public void run ()
{
System.out. println ( "finding cube of numbers:");
for (int i=1; i<=10 ; i++)
{
try
{
System.out. println ("cube of" +i+ "=" + i*i);
Thread . sleep(1000);
}
catch (InterruptedException e)
{
System.out. println ( "Exception");
}
}
}
}
class Program
{
public static void main (String args[])
{
square S= new square();
cube C= new cube();
S. start();
C. start();
}
}
Suspend () and Resume():
are automatically imported in main method.
w.r.t practical application S and R are used to avoid deadlock [] same func. Being access by
more than one thread[]
class square extends Thread
{
public void run ()
{
System.out. println ( "finding square of numbers:");
for (int i=1; i<=10 ; i++)
{
System.out. println ("square of" +i+ "=" + i*i);
}
}
}
class cube extends Thread
{
public void run ()
{
System.out. println ( "finding cube of numbers:");
for (int i=1; i<=10 ; i++)
{
System.out. println ("cube of" +i+ "=" + i*i*i);
}
}
}
class Program
{
public static void main (String args[])
{
Thread t1= new square();
Thread t2= new cube();
t1. start();
t2. start();
System.out. println ( "Suspending thread t1");
t1. suspend();
System.out. println ( "Suspending thread t2");
t2. suspend();
System.out. println ( "Resuming thread t1");
t1. resume();
System.out. println ( "Resuming thread t2");
t2. resume();
}
}

Resume ()print statement from where it has ended/ suspended.

get Priority () and set Priority():


To check the priority of thread  get priority()
To change the priority of thread  set priority()
Three type of priority
MIN_ PRIORITY(0)
 NORM_ PRIORITY(5) By default all thread have priority of 5.
 MAX_ PRIORITY(10)
If no of thread is more than 11 we cannot change priority. If two thread have same priority
then execution will be on the basis of FCFS.
Priority have disadvantage that we are changing priority from Round Robin to FCFS.
Main problem with Multithreading the priority of thread set first will be execute first not on
the basis of int. value it is executed in the basis of FCFS.

JAVA is not used to Build OS because it is not system programming language.


Set priority changes Round robin to FCFS.
If t1. set priority(4)
t2. set priority(6)
4 can be executed before it is possible.

Some important function: 


Set name():sets the name of the thread during runtime of code.
get name(): retrieves the name of the thread.
join(): combines the thread.
is Alive():checks whether thread is still alive or dead.

class PrintThread extends Thread


{
public PrintThread(String threadName)
{
setName(threadName);
}
public void run()
{
System.out.println(getName()+ "is going to sleep state");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("exception");
}
System.out.println(getName()+ "has done with sleeping");
}
public void check()
{
if(isAlive())
{
System.out.println(getName()+ "is alive");
}
else
{
System.out.println(getName()+ "is not alive");
}
}
}
class Program
{
public static void main (String args[])
{
PrintThread t1,t2,t3;
t1 = new PrintThread("Thread1");
t2 = new PrintThread("Thread1");
t3 = new PrintThread("Thread1");
System.out.println("starting threads");
t1.start();
t2.start();
t3.start();
t1.check();
t2.check();
t3.check();
System.out.println("Thread started");
try
{
t1.join();
t2.join();
t3.join();
}
catch(Exception e)
{
System.out.println("Exception");
}
t1.check();
t2.check();
t3.check();
System.out.println("Thread expired");
}
}

Syncronization
Critical
mutex
semaphores

P1, P2, P3, ….., Pn have no relation with one another are Mutual exclusion
P1 threads or mutex.
Func() is shared between P1, P2, P3, ….,
P2
Func()
P3

Pn
Semaphoresis to avoid the condition of deadlock.
Wait & signal two variables are used in this.
If wait =0 the func. is free.
And signal=1
When wait=1, signal=0 wait is opposite to the signal.
S/w implementation of semaphores with the help of JAVA prog.
Semaphores: always only one process to be executed.

TRICK:

Class 1
Class 1 Execute

Func()
Class 2
Critical section
Class 3
To call critical section func.

Synchronized void func()


{
}
class 2

(starts and call synchronized func ())
calls class 1 to execute synchronized function.
class 3

main program

class Callme
{
synchronized void call(String msg)
{
System.out.print("["+msg);
try
{
Thread. sleep (1000);
}
catch (InterruptedException e)
{
System.out.print("Exception");
}
System.out.print("]");
}
}

class Caller implements Runnable


{
String msg;
Callme target;
Thread t;
public Caller (String S, Callme targ)
{
msg=S;
target=targ;
t= new Thread(this);
t.start();
}
public void run()
{
target.call (msg);
}
}

class Program
{
public static void main (String args[])
{
Callme target = new Callme();
Caller t1= new Caller("Hello",target);
Caller t2= new Caller("Java",target);
Caller t3= new Caller("World!",target);
try
{
t1.t.join();
t2.t.join();
t3.t.join();
}
catch (InterruptedException e2)
{
System.out.print("Exception");
}
}
}

String and String Buffer


Difference between String and StringBuffer
String  The java String class is a part of java.lang package, is used to represent string of
characters. The String class is used to represent a string that is fairly ststic, changing
infrequently.
StringBuffer  The primrary limitations of the string class is that once the string is created you
cannot change it. If you need to store text that may need to be changed you should use the
StringBuffer class.

Basic String Methods


Basic String Methods are given along with example:
String Method Syntax/Meaning Example
length() Returns the length class Program
of the String {
public static void main(String args[])
{
String str= new String("JAVA");
int len=str.length();
System.out.println("Length of String is
"+ len);
}
}
toString() Is used to generate class Program
a string {
representation of public static void main(String args[])
the object {
Long mylong = new Long(43);
String str= mylong.toString();
System.out.println("String is "+str);
}
}
charAt() Returns the class Program
character at the {
specified location public static void main(String args[])
{
String str= new String("This is a
String");
char ch=str.charAt(8);
System.out.println("Character at
location 8 is "+ ch);
}
}
getChars(int, int, char[], Copies the class Program
int) specified number {
of characters from public static void main(String args[])
specified location {
into the char array String str= new String("Wish you were
here");
char charArray[]=new char[25];
str.getChars(5,13,charArray,0);
System.out.println(charArray);
}
}
class Program
{
public static void main(String args[])
{
String str= new String("Wish you were
here");
int len=str.length();
char charArray[]=new char[30];
charArray=str.toCharArray();
for (int i=0;i<len;i++)
System.out.println(charArray[i]+" ");
}
}
class Program
{
public static void main(String args[])
{
String str= new String("Wish you were
here");
int len=str.length();
byte buffer[]=new byte[30];
buffer=str.getBytes();
for (int i=0;i<len;i++)
System.out.println(buffer[i]+" ");
}
}
class Program
{
public static void main(String args[])
{
String str1= new String("abc");
String str2= new String("Abc");
if(str1.equals(str2))
System.out.println("str1 and str2 are
equal");
else
System.out.println("str1 and str2 are
not equal");
}
}
equalsIgnoreCase(object class Program
) {
public static void main(String args[])
{
String str1= new String("abc");
String str2= new String("Abc");
if(str1.equalsIgnoreCase(str2))
System.out.println("str1 and str2 are
equal");
else
System.out.println("str1 and str2 are
not equal");
}
}
regionMatches(int, class Program
String, int, int) {
public static void main(String args[])
{
String str1= new String("My favorite
language is Java");
String str2= new String("I like Java
language");
boolean
result=str1.regionMatches(24,str2,7,4);
System.out.println(result);
}
}
class Program
{
public static void main(String args[])
{
String str1= new String("My favorite
language is Java");
boolean result=str1.startsWith("My");
System.out.println("Result is "+result);
}
}
class Program
{
public static void main(String args[])
{
String str1= new String("My favorite
language is Java");
boolean result=str1.endsWith("Java");
System.out.println("Result is "+result);
}
}
compareTo(String) class Program
{
public static void main(String args[])
{
String str1= new String("DELHI");
String str2= new
String("CHANDIGARH");
if(str1.compareTo(str2)<0)
System.out.println("Str1 comes before
Str2");
else
System.out.println("Str1 comes after
Str2");
}
}
indexOf( char) class Program
{
public static void main(String args[])
{
String str= new String("Wish you were
here");
int index=str.indexOf('y');
System.out.println("First location of y
is "+index);
}
}
lastIndexOf( char) class Program
{
public static void main(String args[])
{
String str= new String("Wish you were
here");
int index=str.lastIndexOf('e');
System.out.println("Last location of e is
"+index);
}
}
class Program
{
public static void main(String args[])
{
String str= new String("Wish you were
here");
String substr=str.substring(5,13);
System.out.println("SubString is
"+substr);
}
}
concat(String) class Program
{
public static void main(String args[])
{
String str1= new String("Hello");
String str2= new String(" World");
String str3=str1.concat(str2);
System.out.println("Concatenated
String is "+str3);
}
}
replace(char, char) class Program
{
public static void main(String args[])
{
String str1= new String("Hi Mom");
String str2= str1.replace('o','u');
System.out.println("Replaced String is
"+str2);
}
}
trim() class Program
{
public static void main(String args[])
{
String str1= new String(" Hi Mom ");
int len;
len=str1.length();
System.out.println("Length of String
before trimming is "+len);
String str2= str1.trim();
len=str2.length();
System.out.println("Length of String
after trimming is "+len);
System.out.println("Trimmed String is
"+str2);
}
}
valueOf() class Program
{
public static void main(String args[])
{
String intStr=String.valueOf(100);
System.out.println("Int Value is
"+intStr);
String floatStr=String.valueOf(98.6F);
System.out.println("Float Value is
"+floatStr);
String
doubleStr=String.valueOf(3.1416D);
System.out.println("Double Value is
"+doubleStr);
}
}
class Program
{
public static void main(String args[])
{
String str=new String("This IS MiXeD
CaSe");
String lower=str.toLowerCase();
System.out.println("String in Lower
Case is "+lower);
}
}
class Program
{
public static void main(String args[])
{
String str=new String("This IS MiXeD
CaSe");
String upper=str.toUpperCase();
System.out.println("String in upper
Case is "+upper);
}
}

Program to concate two string into third string


class Program
{
public static void main(String args[])
{
String str1="This IS MiXeD CaSe";
String str2="Hello Java";
int l1,l2,i;
l1=str1.length();
l2=str2.length();
char ch1[]= new char[l1];
char ch2[]= new char[l2];
char ch3[]= new char[l1+l2];
ch1=str1.toCharArray();
ch2=str2.toCharArray();
for(i=0;i<l1;i++)
{
ch3[i]=ch1[i];
}
for(i=0;i<l2;i++)
{
ch3[l1+i]=ch2[i];
}
System.out.println("Concatenated String is : ");
for(i=0;i<(l1+l2);i++)
System.out.print(ch3[i]);
}
}
//Program to calculate number of vowels and digits in given string
class Program
{
public static void main(String args[])
{
String str1="This IS MiXeD 679CaSe";
int l1,i,c=0,j=0;
l1=str1.length();
//char ch1[]= new char[l1];
//ch1=str1.toCharArray();

for(i=0;i<l1;i++)
{
char ch1=str1.charAt(i);
if((ch1=='A')||(ch1=='E')||(ch1=='I')||(ch1=='O')||(ch1=='U')||(ch1=='a

')||(ch1=='e')||(ch1=='i')||(ch1=='o')||(ch1=='u'))
{
c++;
}
else if((ch1>='0') && (ch1<='9'))
{
j++;
}
}
System.out.println("Number of vowels is "+c);
System.out.println("Number of digits is "+j);
}
}

Array
Linear Search
import java.io.*;
class Arr
{
public static void main(String args[])throws IOException
{
int i,f=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[10];
for(i=0;i<10;i++)
{
System.out.println("Enter element of array");
String s1=br.readLine();
a[i] =Integer.parseInt(s1);
}
System.out.println("Enter element to be searched");
String s=br.readLine();
int n=Integer.parseInt(s);

for(i=0;i<10;i++)
{
if(a[i]==n)
{f=f+1;
}
}
if(f>0)
System.out.println("Element found "+ f +" time");
else
System.out.println("Element not found");
}
}
Binary Search
import java.io.*;
class Arr1
{
public static void main(String args[])throws IOException
{
int i,f=0,low,high,mid;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[10];
for(i=0;i<10;i++)
{
System.out.println("Enter element of array");
String s1=br.readLine();
a[i] =Integer.parseInt(s1);
}
low=0;
high=9;
System.out.println("Enter element to be searched");
String s=br.readLine();
int n=Integer.parseInt(s);
//first sort the array
while((low<=high)&&(f==0))
{
mid=(low+high)/2;
if(a[mid]==n)
f=mid;
else if(a[mid]>n)
high=mid-/7 1;
else
low=mid+1;
}
if(f>0)
System.out.println("Element found "+ (f+1) +" position");
else
System.out.println("Element not found");
}
}
Maximum and minium element in array
import java.io.*;
class Arr
{
public static void main(String args[])throws IOException
{
int i,f=0,min,max;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[10];
for(i=0;i<10;i++)
{
System.out.println("Enter element of array");
String s1=br.readLine();
a[i] =Integer.parseInt(s1);
}
min=a[0];
max=a[0];
for(i=1;i<10;i++)
{
if(min>a[i])
{min=a[i];
}
if(max<a[i])
{max=a[i];
}
}
System.out.println("Minimum element is "+min);
System.out.println("Maximum element is "+max);
}
}

Java.io Package (Java Streams)


Java Streams are used when we want to flow continous data from one program to other program.
If JAVA program giving O/PO/P stream
If JAVA program taking I/PI/P stream
Two type: (also called JAVA.io)

O/P stream
Source Java Destination

I/P stream

stream

Byte Character
stream stream

Function of I/P stream : 


1) int available():used to calculate no of bytes.
2) void mark (): to make the path of byte.
3) void reset ():sets a mark to start loc. Of string.
4) int read (): to read charater.
5) long skip ():to skip asset of charater of between.
6) void closed (): to close the stream.

Function of O/P stream : 


1) void close (): to close stream(to close stream is imp. When started.)
2) void write (): to write on I/P.
3) void flush (): When we store data on buffer then we need to clean buffer called flush.
Write
Source O/P
Java
flush

Buffer

Byte Stream

In Byte stream , these are following classes:


1) File I/P stream
2) File O/P stream
3) I/P stream
4) O/P stream
5) Buffered I/P stream
6) Buffered O/P stream
7) Byte Array I/P stream
8) Byte Array O/P stream
9) Data I/P stream
10) Data O/P stream
11) Print stream
12) Random access file
13) Sequence I/P stream
14) Push back I/P stream

1) File I/P stream with I/P stream


import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
InputStream f= new FileInputStream ("file.txt");
int size = f.available();
System.out.println("size to be read "+size);
}
}

2) File O/P stream with O/P stream


import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
String str= "Welcome to the world of Java";
byte b[]= str.getBytes();
OutputStream OS= new FileOutputStream ("file.txt");
for (int i=0; i<b.length; i++)
{
OS.write(b[i]);
}
System.out.println("Successfully completed");
OS.close();
}
}

3) Buffered I/P stream

4) Buffered O/P stream

5) Byte Array I/P stream

6) Byte Array O/P stream

7) Data I/P stream

8) Data O/P stream

9) Print stream

10) Random access file

11) Sequence I/P stream

12) Push back I/P stream


File O/P stream with O/P stream:
import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
String str= “Welcome to the world of Java”;
Byte b[]= str. Get Byte();
OutputStream OS= new file OutputStream (“file.txt”);
For (int i=0; i<b. length; i++)
{
OS. Write (b[i]);
}
System.out.println(“Successfully completed”);
OS. Close();
}
}

Byte Array Input stream :

import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
InputStream f1= new fileInputStream (“file2.text”)
Byte Array Input stream bais = new Byte Array input stream(file)
String str = bais . read ();
System.out.println(“str”);
Byte Array Input stream bais1 = new Byte Array input stream(f1,0,3);
String str1 = bais1 . read ();
System.out.println(“str1”);
}
}

Byte Array Output stream :

import java.io.*;
class pg
{
public static void main (String args[]) throws IOException
{
String str = "Abhilsaha";
byte b[]=new byte[20];
int l=str.length();
str.getBytes(0,l,b,0);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream f1 = new FileOutputStream("file.text");
baos.write(b);
baos.writeTo(f1);
baos.close();
f1.close();
}
}
Buffered Input stream :

import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
file InputStream f1= new fileInputStream (“file2.text”)
Buffered Input stream bis = new Buffered input stream(f1);
Int ch;
While((ch=bis.read())!=-1)
{
String Buffer Sb1= new string buffer();
Sb1.append ((char)ch);
System.out.println(“str”);
}
f1.close();
bis.close();
}
}

Buffered Output stream :

import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
String str = “Abhilasha”
Byte b [] =new byte[64]
Str. Get Byte(0, str.length(), b, 0);
Buffered Output stream bos = new Buffered Output stream(System.out);
Bos.write(b,0,64);
[bos.flush()];
bos.close();
}
}

Data Input stream :

import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
file InputStream fis= new fileInputStream (“file2.text”)
Data Input stream dis = new Data input stream(fis);
System.out.println(dis.read Char());
System.out.println(dis.read .Int());
System.out.println(dis.read float());
fis.close();
dis.close();
}
}

Data Output stream :

import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
file OutputStream fos= new fileOutputStream (“file2.text”)
Data Output stream dos = new Data Output stream(fos);
dos.write Char(‘J’);
dos.write .Int(6);
dos.write float(33.67f);
fos.close();
dos.close();
}
}

Character Stream
In this content are transferred in form of characters. In Byte stream , these are following
classes:

1) BufferedReader
2) BufferedWriter
3) CharArrayReader
4) CharArrayWriter
5) FileReader
6) FileWriter
7) InputStreamReader
8) OutputStreamWriter
9) PushBackWriter
10) PrintWriter
11) Reader
BufferedReader
import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
String str= "Welcome to Java";
FileWriter o1=new FileWriter("file1.txt");
BufferedWriter b1 = new BufferedWriter(o1);
b1.write(str);
b1.flush();
b1.close();
o1.close();
}
}

import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
String str;
InputStreamReader o1=new InputStreamReader(System.in);
BufferedReader b1 = new BufferedReader(o1);
System.out.println("Enter String");
str=b1.readLine();
System.out.println("You Typed :----> "+str);
b1.close();
o1.close();
}
}

BufferedWriter

CharArrayReader
import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
int l,k;
char x[]=new char[64];
char ch;
String str="This is the test string";
l=str.length();
str.getChars(0,l,x,0);
CharArrayReader car= new CharArrayReader(x);
for(int i=0;i<l;i++)
{
k=car.read();
ch=(char)k;
System.out.println("You Typed :----> "+ch);
}
car.close();
}
}

CharArrayWriter
import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
int l,k;
char x[]=new char[64];
char ch;
String str="This is the test string";
l=str.length();
str.getChars(0,l,x,0);
CharArrayWriter car= new CharArrayWriter();
for(int i=0;i<l;i++)
{
ch=(char)x[i];
System.out.println(ch);
}
car.close();
}
}
FileReader

FileWriter

InputStreamReader

OutputStreamWriter

PushBackWriter

PrintWriter

Reader

File Class

File f =new file(“file1.txt”)

S.N Function Name Description


o
1. f.exists() Boolean function check file exists or not.
2. f.isFile() Checks file is file or directory.If file returns T or F
3. f.isDirectory() Checks file is file or directory.If file returns F or T
4. f.getName() Function returns the name of file.str =f.getName()
5. f.canRead() Checks if we can perform read func. or not.
6. f.canWrite() Checks if we can perform write func. or not.
7. f.setReadonly() Now we can only read file.
8. f.isHidden() Checks wheather file is hidden or not.
9. f.lastModified() Returns value in terms of millisec when last modified
starting date is 1.Jan 1970. D.T should always be long to
store it.
10. f.length() Returns length of the file.
11. f.setslastModified(t) Changes time but in milli sec.
12. f.getPath() Returns the complete path of file.
13. f.toURL() To checks a site on internet.
14. f.toURI() Returns the html pages inside site.
15. f.delete() To delete file.
16. f.renameTo(f1) To change name of file.f1 =new name.
17. mkdir() Used to make directory.
18. mkdirs() Used to make directory with in directory.
19. dir.list() Files and folders inside directory.
20. dir.listfiles() Shows only files inside directory.
21. f.getAbsolutePath() Tells the absolute path (Total Path).
22. f.getCononicalPath() Returns files of this directory eg Java/bin/

Applets:
It is used for GUI programming in java.
1. Java Appplet Coordinates
Increasing x

Increasing y

2. Applet Life Cycle


create

initialize start

stop

destroy

3. Generic structure of Applet


Two packages are imported in Applet:
1) java.applet.*;  which contain Applet class and Applet Viewer.
2) Java.awt.*;  which contain Abstract Window Toolkit components.

 Components: buttons, textarea, text field etc.


 Container: frontend on which we transfer components.
 Window: o/p shown on browser is window

1) in applet every class is subclass of Applet class.


2) When we want to transfer components on container we need to initialize container first.
3) Three different methods to use applet program.
Some basic functions:
S. No Function Name Description
1 init() It is used to initialize applet
2 start() It is used to start applet
3 stop() It is used to stop applet
4 destroy() It is used to destroy applet
5 paint() It is used for 2D graphics in applet

java.applet.*;
java.awt.*;
public class program extends Applet
{
public void init()
{
}
public void start()
{
}
public void stop()
{
}
public void destroy()
{
}
public void paint(Graphics g)
{
}
}

4. Generation of Applet Code


Applet code can be generated using :
1) browser
2) AppletViewer (used only for testing)

5.To run JAVA applet on Browser


program.java → program.class

Browser → interprete → we need source code of html

→ for html we will use either frontpage or Dreamweaver

Frontpage → insert → advanced → plugins(for flash)→ java Applets


To make site we need following: →

1. For Server site → JSPEJB


2. Electronic mail → Java Mail
3. To make site attractive → flash/easy flash
4. Backend → Oracle/MS Access
5. Sites → Applet/Swings
6. For Client Side → Java Script

6. HTML code for Applet program class


<HTML>
<HEAD><TITLE>Applet Test</TITLE></HEAD>
<BODY>
<APPLET CODE="program.class" WIDTH="400" HEIGHT="400">
</APPLET>
</BODY>
</HTML>

7. Concept of 2D graphics in Java Applets


paint() function is used for this

S. No. Function Description


1 To draw Straight Line import java.awt.*;
drawLine(int x1,int y1,int x2,int y2) import java.applet.*;
x1,y1→ starting point public class program extends Applet
x2,y2→ ending point {
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
}
}
2 Color class
Color c = new Color(r,g,b);
c.getColor()
setColor(c)
3 To draw rectangle
a) drawRectangle(int x,int y, int width, import java.awt.*;
int height) import java.applet.*;
b) fillRectangle(int x,int y, int width, public class program extends Applet
int height) {
c) drawRoundRectangle(int x,int y, int public void paint(Graphics g)
width, int height, int diameter, int {
diameter) Color c = new Color(100,167,50);
d) fillRoundRectangle(int x,int y, int g.drawRect(10,10,50,50);
width, int height, int diameter, int g.setColor(c);
diameter) g.fillRect(60,60,50,50);
Color c1 = new Color(200,167,150);
g.drawRoundRect(110,110,50,50,20,20);
g.setColor(c1);
g.fillRoundRect(160,160,50,50,10,10);
}
}
4 To draw Ellipses and Circles import java.awt.*;
import java.applet.*;
drawOval(int x, int y,int height,int public class program extends Applet
width) {
public void paint(Graphics g)
fillOval(int x, int y,int height,int {
width) Color c = new Color(100,167,50);
g.drawOval(10,10,50,150);
if height=width then Circle else g.setColor(c);
Ellipse g.fillOval(60,60,50,20);
Color c1 = new Color(200,167,150);
g.drawOval(110,110,50,50);
g.setColor(c1);
g.fillOval(160,160,50,50);
}
}
5 To draw Arcs import java.awt.*;
import java.applet.*;
drawArc(int x,int y, int width, int public class program extends Applet
height,int startangle, int arcangle) {
public void paint(Graphics g)
fillArc(int x,int y, int width, int {
height,int startangle, int arcangle) Color c = new Color(100,167,50);
g.drawArc(10,10,30,50,50,80);
g.setColor(c);
g.fillArc(50,50,30,50,50,80);
}
}
6 To draw Polygon import java.awt.*;
import java.applet.*;
int x[] = {10,20,30,40,50}; public class program1 extends Applet
int y[] = {20,30,40,50,60}; {
public void paint(Graphics g)
drawPolygon(x[],y[],n) {
fillPolygon(x[],y[],n) Color c = new Color(200,167,150);
int x[] = {30, 200, 30, 200, 30};
if first point to be joined with last int y[] = {30, 30, 200, 200, 30};
point then n= limit of array int n= 5;
g.drawPolygon(x,y,n);
g.setColor(c);
int x1[] = {130, 200, 130, 200, 130};
int y1[] = {130, 130, 200, 200, 130};
g.fillPolygon(x1,y1,n);
}
}
7 Some important Points:
setBackground() To change background color
setForeground() To change foreground color
showStatus() For status bar string defination
drawString() For string to be displayed in Applet
Font f = new Font(); import java.awt.*;
import java.applet.*;
Font .type public class program extends Applet
Font.PLAIN/ITALIC/BOLD(not {
underline) public void paint(Graphics g)
Font.size {
Font f = new Font("Monotype
Corsiva",Font.ITALIC, 32);
g.setColor(Color.red);
g.setFont(f);
g.drawString("Hello World",50,100);
}
}

Component Programming

AWT (Abstract Window Toolkit): atleast one function need to be used add()

Components (button,labels etc)

Container (Applet)

Windows
All component should be initialized using function: public void init()

S.no Name & Function Program


1 Button import java.awt.*;
import java.applet.*;
Button b = new public class program extends Applet
Button( String ); {
public void init()
{
Button b = new Button("SAVE");
add(b);
}
}
2 Label import java.awt.*;
import java.applet.*;
Label lbl = new public class program extends Applet
Label(String, Label. {
LEFT /CENTER /RIGHT); public void init()
{
Label lbl = new Label("Hello World",
Label.LEFT);
add(lbl);
}
}
3 Text Field import java.awt.*;
import java.applet.*;
TextField txt1 = new public class program extends Applet
TextField() : single char {
public void init()
TextField txt1 = new {
TextField(20) : 20 char TextField txt1 = new TextField(20);
TextField txt2 = new TextField();
TextField txt1 = new TextField txt3 = new TextField("your name");
TextField(“Your Name”) : TextField txt4 = new TextField("password");
String will be displayed txt4.setEchoChar('*');
add(txt1);
txt1.echoChar(*) : String will add(txt2);
be dislayed as * add(txt3);
add(txt4);
}
}
4 TextArea : to display string import java.awt.*;
in multiple line. Scrollbar is import java.applet.*;
inbuilt public class program extends Applet
{
TextArea txt = new TextArea public void init()
(String, int x,int y) {
x = number of rows TextArea txt1 = new TextArea("Enter your
y = number of char per row comment here",5,45);
add(txt1);
}
}
5 Checkbox: It is of two types
a) Exclusive : RadioButton
b) Nonexclusive: Checkbox
a) Checkbox cb = new import java.awt.*;
Checkbox (“This is true”); import java.applet.*;
public class program extends Applet
Checkbox cb = new {
Checkbox (“A”,true); public void init()
{
true : A will be selected on Checkbox cb = new Checkbox ("A",true);
display Checkbox cb1 = new Checkbox ("B");
add(cb);
add(cb1);
}
}
b) CheckboxGroup cbg = new import java.awt.*;
CheckboxGroup (); import java.applet.*;
public class program extends Applet
Checkbox cb = new {
Checkbox ("A",cbg,true); public void init()
{
Checkbox cb1 = new CheckboxGroup cbg = new CheckboxGroup ();
Checkbox ("B",cbg,false); Checkbox cb = new Checkbox ("A",cbg,true);
Checkbox cb1 = new Checkbox ("B",cbg,false);
We can define more than one Checkbox cb2 = new Checkbox ("C",cbg,true);
true but button lastly define add(cb);
true will only be true add(cb1);
add(cb2);
}
}
6 Dropdown list : Two types
a) choice : single input
b) list : multiple input
a) Choice ch = new Choice(); import java.awt.*;
ch.add("A"); import java.applet.*;
ch.add("B"); public class program extends Applet
{
public void init()
{
Choice ch = new Choice();
ch.add("A");
ch.add("B");
ch.add("C");
ch.add("D");
ch.add("E");
add(ch);
}
}
b) List lt = new List(int, import java.awt.*;
Boolean); import java.applet.*;
public class program extends Applet
{
public void init()
{
List lt = new List(3,true);
lt.add("A");
lt.add("B");
lt.add("C");
lt.add("D");
lt.add("E");
add(lt);
}
}

Displaying Component at Specific position

Two method
→ using Panel
→ using LayoutManager

1) Panel → is object which hold other object. It also starts from center to right. To see panel we
need to change its background color , because by default its color is same as color of container.

import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
Panel p = new Panel();
Button b1= new Button("SAVE");
Button b2= new Button("CANCEL");
p.setBackground(Color.blue);
p.add(b1);
p.add(b2);
add(p);
}
}

To display panel at specific position we need layout manager

2) Layout Manager → function setLayout() is used

Layout Manger

Flow Layout Grid Layout Border Layout Card Layout Grid Bag Layout

Functions in Applet
Donot functions in
Applet

a) Flow Layout :→

FlowLayout flow = new


FlowLayout(FlowLayout.LEFT/ FlowLayout.CENTER/ FlowLayout.RIGHT)

import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
FlowLayout flow = new FlowLayout(FlowLayout.RIGHT);
setLayout(flow);
Button b1= new Button("SAVE");
Button b2= new Button("CANCEL");
Button b3= new Button("EXIT");
setBackground(Color.blue);
add(b1);
add(b2);
add(b3);
}
}
b) Grid Layout :→

GridLayout grid = new GridLayout (int a, int b, int c, int d);

Where a = rows, b= columns, c = cell spacing vertical, d = cell spacing horizontal

import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
GridLayout grid = new GridLayout (3,3,10,10);
setLayout(grid);
Button b1= new Button("1");
Button b2= new Button("2");
Button b3= new Button("3");
Button b4= new Button("4");
Button b5= new Button("5");
Button b6= new Button("6");
Button b7= new Button("7");
Button b8= new Button("8");
Button b9= new Button("9");
setBackground(Color.pink);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
}
}
Also try:
GridLayout grid = new GridLayout (2,3,10,10);
GridLayout grid = new GridLayout (1,3,10,10);
GridLayout grid = new GridLayout (3,3);

c) Border Layout :→ it has North, South, East, West, Center attributes.

BorderLayout border = new BorderLayout ([int a, int b]);


Where a = = cell spacing vertical, b = cell spacing horizontal
North

West

East
Center

South
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
BorderLayout border = new BorderLayout (10,10);
setLayout(border);
Button b1= new Button("1");
Button b2= new Button("2");
Button b3= new Button("3");
Button b4= new Button("4");
Button b5= new Button("5");
setBackground(Color.magenta);
add(b1,"North");
add(b2,"South");
add(b3,"East");
add(b4,"West");
add(b5,"Center");
}
}

d) Card Layout :→ it has container over container


Function show() is used to display cards.

import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
CardLayout card = new CardLayout (10,10);
setLayout(card);
Label lbl[] = new Label[2];
lbl[0]= new Label("A is label");
lbl[1]= new Label("B is label");
setBackground(Color.green);
for (int i=0;i<=1;i++)
{
add("Card" + i,lbl[i]);
card.show(this,"Card"+i);
}
}
}
Also try : for (int i=0;i<1;i++)

Frames
Frame is a child window. Minimum, maximum works but exit does not.

Functions:
S. No Function Name Description
1 setResizable(True/False) If it is true then we can change the size of the
By default: True frame, if not then we cannot.
2 setTitle(String) For giving title to frame
3 reshape(x,y,width,height) For changing size of frame
4 show() Used for displaying frame

import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
Frame f = new Frame();
f.setResizable(true);
f.setTitle("Frame Test");
f.reshape(10,10,250,250);
f.show();
}
}
Also try: f.setResizable(False);

Menus
There is only one menu bar inside a container or frame. It contains three things:
a) MenuBar
b) Menu
c) MenuItem
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
Frame f;
MenuBar mbar;
Menu m;
MenuItem mitem;
public void init()
{
f = new Frame();
mbar = new MenuBar();
m= new Menu("File",true);
mbar.add(m);
mitem= new MenuItem("Exit");
m.add(mitem);
f.setMenuBar(mbar);
f.reshape(10,10,250,250);
f.setBackground(Color.pink);
f.show();
}
}

Scroll Bar

ScrollBar sb = new Scrollbar(int a, int b, int c, int d, int e);

Where a = Scrollbar.HORIZONTAL / Scrollbar.VERTICAL


b = Starting value
c = Ending value
d = initial position of button inside bar
e = scroll parameter / scroll spacing
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
BorderLayout border = new BorderLayout (10,10);
setLayout(border);
Scrollbar sb= new Scrollbar();
add(sb,"West");
}
}
Passing parameter to an Applet
If we want some HTML parameters inside Applet then function getParameter() is used.

Java File:
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
String str;
public void init()
{
str=getParameter("message");
}
public void paint(Graphics g)
{
g.drawString(str,25,25);
}
}

HTML File:
<HTML>
<HEAD><TITLE>Applet Test</TITLE></HEAD>
<BODY>
<APPLET CODE="program.class" WIDTH="400" HEIGHT="400">
<PARAM NAME=message VALUE="Welcome to world of JAVA">
</APPLET>
</BODY>
</HTML>

JAVA Event Handling


Package java.awt.event is imported. All listeners are part of java.awt.event Package.
Concept of Listener
Interface
Listener

click Button
Predefined
Function

Event Handling

When we click Button, it calls its Listener (Interface) which calls its predefined function that handles its even

Types of Listeners

Java.awt.event

Action Event Adjustment Event Component Event Item Event Text Event
(Action Listener) (Adjustment Listener) (Component Listener) (Item Listener) (Text Listener)

Container Event Focus Event Input Window Event


(Container Listener) (Focus Listener) (Window Listener)

Key Event Mouse Event


(Key Listener) (Mouse Listener)
(Mouse Motion Listener)

Different Types Of Listener with their Event


(All Listeners are Interfaces)

Functions associated with Listeners


Functions:
S. No Listener Name Function Performed
1 Action Listener actionPerformed() {imp}
2 Adjustment Listener adjustmentValueChanged()
3 Component Listener componentHidden()
componentMoved()
componentResized()
componentShown()
4 Item Listener itemStateChanged() {imp}
5 Focus Listener focusGained()
focusLost()
6 Text Listener textValueChanged()
7 Container Listener componentAdded()
componentRemoved()
8 Window Listener windowActivated() {imp}
windowClosed()
windowClosing()
windowDeiconified()
windowDeactivated()
windowOpened()
windowIconified()
9 Key Listener keyPressed()
keyReleased()
keyTyped()
10 Mouse Event
a) Mouse Listener mouseClicked()
mouseEntered()
mousePressed()
mouseReleased()
mouseExited()
b) Mouse Motion Listener mouseDragged()
mouseMoved()

Components attached with Listeners

S. No Component Listener Name


1 Button Action Listener
2 Check Box Item Listener
3 Radio Button Item Listener
4 Choice Item Listener
5 List Item Listener /Action Listener
6 Component Component Listener /Focus Listener/ Key
Listener/ Mouse Listener
7 Container Container Listener
8 Menu Action Listener
9 Scroll Bar Adjustment Listener
10 Text Field/ Text Area Action Listener
11 Window Window Listener

Sample Programs

1) Program to change color of Applet using Button (Action Listener).

→ If we recognize button by string then function getActionCommand() is used.


→ If we define button using instance getSource() is used.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class program extends Applet implements ActionListener
{
Button b1,b2,b3;
String str;
public void init()
{
b1= new Button("RED");
b2= new Button("GREEN");
b3= new Button("BLUE");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent e)
{
str = e.getActionCommand();
if(str.equals("RED"))
{
setBackground(Color.red);
}
if(str.equals("GREEN"))
{
setBackground(Color.green);
}
if(str.equals("BLUE"))
{
setBackground(Color.blue);
}
repaint(); // it changes with reference to white
}
}
repaint (x,y,width,height) :→ for specific part of Applet.

Also try:
public void actionPerformed(ActionEvent e)
{
if(e.getSource() = = b1)
{
setBackground(Color.red);
}
if(e.getSource() = = b2)
{
setBackground(Color.green);
}
if(e.getSource() = = b3)
{
setBackground(Color.blue);
}
repaint();
}
}

this:→ is used when the function called is inside the class itself

2) Program to input data in one Text Field and send it to another Text Field
(Action Listener).

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class program extends Applet implements ActionListener
{
TextField t1,t2;
Button b1,b2;
String str;
public void init()
{
t1 = new TextField(20);
t2 = new TextField(20);
b1= new Button("Press Me");
b2= new Button("Clear");
t2.setEnabled(false);
t1.requestFocus();
b1.addActionListener(this);
b2.addActionListener(this);
add(t1);
add(t2);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
str= t1.getText();
t2.setText(str);
}
if(e.getSource()==b2)
{
t1.setText(" ");
t2.setText(" ");
}
}
}

3) Program to change color of Applet using Scrollbar (Adjustment


Listener).

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class program extends Applet implements AdjustmentListener
{
Scrollbar sb;
int val1; // Scrollbar returns int value
public void init()
{
setLayout (new BorderLayout());
sb = new Scrollbar();
//sb.addListener(this);
add(sb,"west");
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
val1 = e.getValue();
System.out.println(val1);
}
}

4) Program to display choice in Text Field using choice component (Item


Listener).

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class program extends Applet implements ItemListener
{
TextField t1;
Choice ch;
String str;
public void init()
{
ch = new Choice();
ch.add("Apple");
ch.add("Mango");
ch.add("Banana");
ch.add("Papaya");
ch.addItemListener(this);
t1 = new TextField(20);
add(ch);
add(t1);
}
public void itemStateChanged(ItemEvent e)
{
str= ch.getSelectedItem();
t1.setText(str + " is my favorite Fruite");
if(str.equals("Apple"))
{
t1.setBackground(Color.pink);
}
if(str.equals("Mango"))
{
t1.setBackground(Color.yellow);
}
if(str.equals("Banana"))
{
t1.setBackground(Color.red);
}
if(str.equals("Papaya"))
{
t1.setBackground(Color.green);
}
}
}

You might also like