Java Notes PDF
Java Notes PDF
1
CCIT
Index
Topic Page
Java Basic :
History, Features, JRE, JVM, ByteCode, JDK, Errors, JavaProgram, DataTypes, 2
Operators, Identifiers , Literals, Type Casting, Variables types/Scope
Control Structures
If statement ,Nested if , Ladder, Ternary Operator, while , for , do-while, switch , 14
Nested Loops
Program Input
49
Naming Conventions, Reading Input
Functions
Functions basic, types of functions, method signature, method prototype, 57
Recursion
OOPS
Oops basic, classes, objects,data members , methods, method overloading, 61
access specifiers,
Constructors
Default constructor, Constructor with Args, Constructor Overloading, Initilization 81
blocks, private constructors.
Static Members
87
Static data members, static member functions , static initialization blocks,
Wrapper Classes
91
Basics, class Integer, class Character
Arrays
Single Dimensional arrays, MultiDimensional Arrays, Array of Objects, class 96
Arrays , Command Line Arguments, Variable Arguments
Inheritance
Basics, Method Overriding, super keyword, this keyword, types of inheritance, 108
abstract keyword, Aggeration, final keyword, strictfp keyword,
2
CCIT
Polymorphism
124
Basics, compiletime vs runtime polymorphism, instance of operator
Interfaces
Basics, classes vs Interfaces, Abstract classes vs Interfaces, Interface Need, 128
Default methods,
Inner Classes
135
Basics , Anonymous classes, static nested classes
Packages
142
Basics, Advantages, import statement, static import
Library Classes
String, Math, String buffer , Vector, ArrayList, Set, HashSet, TreeSet, Map, 146
Hashmap, Date, Calender,
Applets
Baiscs, Applications Vs Applets, Life Cycle of Applet, Applet Tag, Applet 180
Execution, Applet Parameters, Class Applet
AWT
Graphics, Event Delegation Model, Button, TextField, TextArea, Checkbox,
Label, List, Choice, Layout Managers, Font, Color, ScrollBar, Panel, Frame, 188
Menu, Dialog, Mouse Events, Window Events, FileDialog, MediaTracker,
Adapaters
Exceptions
Basics, Uncaught Exceptions, Checked and Unchecked Exception, Exception
229
Hierarchy, Exception Methods, try,catch, throw, throws, finally, Exception
classes, User defined Exceptions, Nested try blocks, Exception Propogation
Input-Output / Streams
Basics, File , InputStream, OutputStream, FileInputStream, FileOutputStream,
246
Reader, FileReader, Writer, FileWriter, PrintStream, DataInputStream,
DataOutputStream, Serialization, Deserialization
Multi-Threading
Basics, Life Cycle of Thread, class Thread, Thread Priorities, Thread 260
Synchronization, Thread Deadlock
3
CCIT
Java
Java is a simple object-oriented, distributed, interpreted, robust,
secure, architecture neutral, portable, high-performance, multi threaded and
dynamic language, use to built internal application.
History of Java
James Gosling, the father of Java, was
intent on building a low-cost, hardware-
independent software platform using
C++. James Gosling initiated the Java
language project in June 1991 for use in
one of his many set-top box projects.
4
CCIT
Features
Simple. Java's developers deliberately left out many of
the unnecessary features of other high-level
programming languages. For example, Java does not
support pointer math, implicit type casting, structures
or unions, operator overloading, templates, header files,
or multiple inheritance.
Object-oriented. Java uses classes to organize code
into logical modules. At runtime, a program creates
objects from the classes.
Statically typed. All objects used in a program must
be declared before they are used. This enables the Java
compiler to locate and report type conflicts.
Compiled. Before you can run a program written in the
Java language, the program must be compiled by the
Java compiler. The compilation results in a "byte-code"
file that, while similar to a machine-code file, can be
executed under any operating system that has a Java
interpreter. This interpreter reads in the byte-code file
and translates the byte-code commands into machine-
language commands that can be directly executed by
the machine that's running the Java program. You could
say, then, that Java is both a compiled and interpreted
language.
Multi-threaded. Java programs can contain multiple
threads of execution, which enables programs to handle
several tasks concurrently. For example, a multi-
threaded program can render an image on the screen in
one thread while continuing to accept keyboard input
from the user in the main thread.
5
CCIT
6
CCIT
Java bytecode
Java Byte Code is the language to which Java source is
compiled and the Java Virtual Machine understands. Unlike
compiled languages that have to be specifically compiled for
each different type of computers, a Java program only needs
to be converted to byte code once, after which it can run on
any platform for which a Java Virtual Machine exists.
JRE
JRE is an acronym for Java Runtime Environment.It is used to
provide runtime environment.It is the implementation of JVM. It
physically exists. It contains set of libraries + other files that JVM
uses at runtime.
Implementation of JVMs are also actively released by other
companies besides Sun Micro Systems/Oracle .
7
CCIT
J2EE uses many components of J2SE, as well as, has many new
features of it’s own like Servlets, JavaBeans,
8
CCIT
9
CCIT
Errors
The three kinds of errors you can encounter:
Compile Errors
Compile errors result from incorrectly constructed code. If
you incorrectly type a keyword, omit some necessary
punctuation, or use a do statement without a corresponding
while statement at design time, Java detects these errors
when you compile the application.
Run-Time Errors
Run-time errors occur while the application is running when a
statement attempts an operation that is impossible to carry
out. An example of this is division by zero. Suppose you have
this statement:
Speed = Miles / Hours
If the variable Hours contains zero, the division is an invalid
operation, even though the statement itself is syntactically
correct. The application must run before it can detect this
error.
Logic Errors
Logic errors occur when an application doesn't perform the
way it was intended. An application can have syntactically
valid code, run without performing any invalid operations, and
yet produce incorrect results. Only by testing the application
and analyzing results can you verify that the application is
performing correctly.
10
CCIT
import statements
global declaration
class name
{
public static void main (String arg [])
{
statements
-------------
}
}
1) Import Statement: -
Java provide us different library classes. These
classes are different packages, so, if we want to use them we
have to import them by using import statement.
Eg: - import java.awt. *;
import java.awt.button;
2) Global declaration: -
In this section we can define classes & interface
(user define data type) we can not define global variable &
function like C & C++.
3) Function main:-
This is the entry point of our program execution
of the program being with function main.
Java is complete object – oriented language. So
even function main must be defined with in class.
11
CCIT
Output statements: -
For eg:
class test
{
public static void main (string arg [ ])
{
System.out.println (“Welcome to JAVA”);
}
}
12
CCIT
13
CCIT
EDIT-COMPILE-RUN-CYCLE
EDIT:
COMPILE:
It will create class files for all the classes that are
present in the program.
14
CCIT
Data types
1. int 4 bytes
2. long 8 bytes whole nos.
3. short 2 bytes
Operators
15
CCIT
Operator Associvity
the associativity (or fixity) of an operator is a property that
determines how operators of the same precedence are grouped
in the absence of parentheses.
Type Promotion
If an expression contains mixed type of value then result will be
calculated according to higher datatype of value present in
expression.
1. double
2. float
3. long
4. int
5. char or short
6. byte
16
CCIT
17
CCIT
18
CCIT
19
CCIT
Java Identifiers:
All Java components require names. Names used for classes,
variables and methods are called identifiers.
20
CCIT
Java Literals
Java literals are fixed or constant values in a program's source
code.
21
CCIT
Type Casting
Assigning a value of one type to a variable of another type is
known as Type Casting. Java data type casting comes with 3
flavors.
Implicit casting :
A data type of lower size (occupying less memory) is
assigned to a data type of higher size. This is done
implicitly by the JVM. The lower size is widened to higher
size. This is also named as automatic type conversion.
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0
Explicit casting (narrowing conversion)
A data type of higher size (occupying more memory)
cannot be assigned to a data type of lower size. This is not
done implicitly by the JVM and requires explicit casting; a
casting operation to be performed by the programmer. The
higher size is narrowed to lower size.
float a=3.2;
int b=(int )a; //Explicit casting by using cast operator
3. Boolean casting
A boolean value cannot be assigned to any other data
type. Except boolean, all the remaining 7 data types can be
assigned to one another either implicitly or explicitly; but
boolean cannot. We say, boolean is incompatible for
conversion. Maximum we can assign a boolean value to
another boolean.
22
CCIT
Instance variables
Class/static variables
Local variables:
Local variables are declared in methods, constructors, or
blocks.
23
CCIT
Instance variables:
Instance variables are declared in a class, but outside a
method, constructor or any block.
24
CCIT
Class/static variables:
Class variables also known as static variables are declared
with the static keyword in a class, but outside a method,
constructor or a block.
25
CCIT
If Statement
It is used to conditionally execute a block of code.
Syntax:-
if(condition)
{
statements
}
else
{
Statements
optional
}
next statement
26
CCIT
WAP to print total marks of a student from given marks of 5 subject, also
print percentage if student if pass. (Passing marks 40 per sub.)
class marks
{public static void main (String arg [ ])
{
int a = 57 , b = 48, c = 93, d = 80, e = 84, total;
double per;
total = a + b + c + d + e;
System.out.println (“Total marks = ” + total);
if (a >= 40 && b >= 40 && c >= 40 && d >= 40 && e >= 40 )
{
per = total / 5.0;
System.out.println (“Student is pass”);
System.out.println (“Percentage is ” + per);
}
else
System.out.println (“Student is fail”);
}
}
27
CCIT
Nested if
class marks
{ public static void main (String arg [ ])
{
int a = 57 , b = 48, c = 93, d = 80, e = 84, total;
double per;
total = a + b + c + d + e;
per = total / 5.0;
System.out.println (“Total marks = ” + total);
if (a >= 40 && b >= 40 && c >= 40 && d >= 40 && e >= 40 )
{
if (per >= 60)
System.out.println (“Student get Ist class”);
}
}
}
28
CCIT
Ladder Structure
If a if statement is used within an if statement then such a
control structure is called ladder structure.
Syntax: - if (condition)
---------------
else if (condition)
---------------
else if (condition)
---------------
29
CCIT
30
CCIT
31
CCIT
Loops
Loops are used to repeatedly executes a block of codes. Java provide
us & different looping structures.
while loop
Statements within this loop are
repeatedly executed while condition
is true. Program control is
transferred to next statement only
when the condition becomes false.
Syntax: -
while (condition )
{
Block of
statements;
}
Next statements;
32
CCIT
33
CCIT
34
CCIT
for loop
- Statement within this loop are repeatedly executed while condition is true.
Syntax: -
for(initialization, condition, evaluation)
{
Statement
--------------
}
next statements
--------------
35
CCIT
WAP to print all no. from 1 to n. Which divides the no. n perfectly.
class test
{ public static void main (String args [ ])
{ int I=1,n=27;
for(int I=1;I<=n;I++)
{ if(n %I == 0 )
System.out.println (I);
}
}
}
36
CCIT
For-each loop
Advantage:
It makes the code more readable.
It elimnates the possibility of programming errors.
Syntax
for(data_type variable : array | collection)
{
Statements….
………………
}
For eg:
class ForEachExample1
{
public static void main(String args[])
{
int arr[]={12,13,14,44};
for(int i:arr)
{
System.out.println(i);
}
}
}
37
CCIT
Nested Loops
If a loop is used within a loop then such a control structure is called as Nested
Loop. Nested loops are used to repeatedly execute a block of code which is it
self repeating a block of code.
38
CCIT
do-while loop
Statements within
this loop are repeatedly
executed while condition
is true specially of this
loop is that, it is executed
at least once even if
condition at least once
even if condition is false.
Syntax:-
do
{ Statements;
……………….
}
while (condition);
Next statements
WAP to read a no while the no. entered is not equals to 0 and find sum of
all nos. entered.
class sum
{public static void main (String args [ ])
{int Sum=0;
do { String s=JoptionPane.showInputDialog (null, “Enter a no.”);
int N=Integer.parseInt(s);
Sum=Sum + N;
}
while(N!=0);
System.out.println( “Sum is =”+ Sum);
}
}
}
39
CCIT
Jump Statements
Java provides us different jump statements which are
used to control flow of execution of program
Eg:- class pc
{ public static void main (String args[])
{ int I =1;
while (I <=10)
{
System.out.println(i);
if ( I ==5 )
break;
I ++;
}
}
}
class pc
{ public static void main( String arg [] )
{ int I = 0;
while (I <10)
{I ++;
if ( I %2 ==0 )
continue;
System.out.println (I);
}
}
}
40
CCIT
class pc
{
public static void main( String args [] )
{
-------------------
-------------------
A : while (--------)
{
B : while (--------)
{
-------------------
-------------------
break A;
}
-------------------
-------------------
}
-------------------
-------------------
}
}
41
CCIT
switch Statement
Syntax:-
switch( variable )
{
case value: -------------
-------------
case value: -------------
-------------
….
default: -------------
-------------
}
42
CCIT
43
CCIT
WAP to read a single digit no & print all the no. from that no. to 9 & on
word.
class digit
{
public static void main (String arg[] )
{
String s = JOptionPane.showInputDialog (null, “Enter a single digit no”);
int N = Integer.parseInt (s);
switch( N )
{
case 0: System.out.println (“Zero”);
case 1: System.out.println (“One”);
case 2: System.out.println (“Two”);
case 3:System.out.println (“Three”);
case 4: System.out.println (“Four”);
case 5: System.out.println (“Five”);
case 6: System.out.println (“Six”);
case 7: System.out.println (“Seven”);
case 8: System.out.println (“Eight”);
case 9: System.out.println (“Nine”);
default: System.out.println (“Not a single digit no.”);
}
}
}
Final Variables
You can declare a variable in any scope to be final . The value of a
final variable cannot change after it has been initialized. Such variables
are similar to constants in other programming languages. To declare a
final variable, use the final keyword in the variable declaration before the
type:
final int aFinalVar = 0;
The previous statement declares a final variable and initializes it,
all at once. Subsequent attempts to assign a value to aFinalVar
result in a compiler error. You may, if necessary, defer initialization
of a final local variable. Simply declare the local variable and
initialize it later, like this:
final int blankfinal;
. . .
blankfinal = 0;
44
CCIT
Naming Conventions
Java provides us different library classes for naming
these classes & their method they have followed some
conventions.
Name Convention
class name should start with uppercase letter and be a noun e.g.
String, Color, Button, System, Thread etc.
45
CCIT
Reading data
If a program requires some user input then such input
can be provided in different ways.
WAP to read a no & print all no. from 1to that no.
class test
{public static void main (String args [ ])
{
String s=JoptionPane.showInputDialog (null, “Enter a no.”);
int N=Integer.parseInt(s);
for(int i=1; i<=N; i++)
System.out.println(i);
}
}
46
CCIT
class fact
{
public static void main (String args [ ])
{
int f=1;
int N=Integer.parseInt(args [0]);
for (int i=1; i<=N; i++)
f=f *i;
System.out.println ( “Factorial is =”+ f);
}
}
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
47
CCIT
import java.io.*;
class fact
{
public static void main (String args [ ])
{
int f=1;
try {
DataInputStream din=new
DataInputStream(System.in);
System.out.print(“Enter a No “);
String s=din.readLine();
int N=Integer.parseInt(s);
for (int i=1; i<=N; i++)
{
f=f +i;
}
System.out.println ( “Factorial is =”+ f);
}
catch(Exception er)
{
System.out.println(er);
}
}
}
48
CCIT
Bitwiase Operators
Java's bitwise operators operate on individual bits of integer values. If an
operand is shorter than an int, it is promoted to int before doing the operations.
It helps to know how integers are represented in binary. For example the
decimal number 3 is represented as 11 in binary and the decimal number 5 is
represented as 101 in binary. Negative integers are store in two's complement
form. For example, -4 is 1111 1111 1111 1111 1111 1111 1111 1100.
49
CCIT
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
50
CCIT
Enum
Enum in java is a data type that contains fixed set of constants.
class EnumExample
{
public enum Season { WINTER, SPRING, SUMMER, FALL }
}
}
values() method
The java compiler internally adds the values() method when it creates
an enum. The values() method returns an array containing all the
values of the enum.
51
CCIT
int x = 5, y;
x++;
System.out.println("x : " + x); //will print x : 9
52
CCIT
Functions
Return type:-
It indicates the datatype of the value which function is
going to return. It can be any datatype such as int, long, float,
double, byte, boolean, char , an object etc.
if function is not returning any value then return type must
be void.
53
CCIT
class pc
{ public static void main ( String arg [] )
{
repeat (‘#’,20);
repeat (‘*’,30);
repeat (‘&’,10);
}
static void repeat(chat a, int n)
{for (int i=1; i<= n; i++)
System.out.println( a );
}
}
54
CCIT
class pc
{public static void main ( String arg [] )
{ int z =100 + fact (5);
System.out.println ( “Result is ”+ z);
}
static int fact (int n)
{
int f =1;
for (int i=1; i<= n; i++)
f = f * i;
return f;
}
}
Method Signature
A method signature is part of the method declaration. It is the
combination of the method name and the parameter list.
The reason for the emphasis on just the method name and
parameter list is because of overloading. It's the ability to
write methods that have the same name but accept different
parameters. The Java compiler is able to discern the
difference between the methods through their method
signatures.
Method Prototpe
It is the combination of the return type ,method name and
the parameter list as well as function modifiers.
55
CCIT
Recursion
Recursion is the process of repeating items in a self-similar
way. In programming languages, if a program allows you to
call a function inside the same function, then it is called a
recursive call of the function.
class fabo
{
private static int index = 0;
private static int stoppingPoint = 40;
fibonacciSequence(n2, n1+n2);
}
}
56
CCIT
OOPS
Java is an object oriented language. It provides us a program
environment where we can create object & perform operations on
them.
Polymorphism Classes
Inheritance Objects
Encapsulation Instance
Abstraction Method
57
CCIT
Data Hiding POP does not have OOP provides Data Hiding
any proper way for so provides more
hiding data so it security.
is less secure.
58
CCIT
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data
(variables) and code acting on the data (methods) together
as as single unit. In encapsulation the variables of a class will
be hidden from other classes, and can be accessed only
through the methods of their current class, therefore it is
also known as data hiding.
Polymorphism
Polymorphism is the ability of an object to take on many
forms. The most common use of polymorphism in OOP occurs
when a parent class reference is used to refer to a child class
object.
Inheritance
Inheritance is the ability, offered by many OOP languages, to
derive a new class (the derived or inherited class) from another
class (the base class). The derived class automatically inherits the
properties and methods of the base class.
59
CCIT
Message
A message is a request to an object to invoke one of its methods.
A message therefore contains
the name of the method and
the arguments of the method.
This interacting between objects is based on messages which are
sent from one object to another asking the recipient to apply a
method on itself. we could create new objects and invoke methods
on them. For example,
Object
An entity that has state and behavior is known as an object e.g.
chair, bike, marker, pen, table, car etc. Object is an instance
of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.
60
CCIT
Class
syntax
class name
{
Data members
----------------
----------------
----------------
Member functions
----------------
----------------
----------------
}
61
CCIT
Data members
They indicate information about an object current state of the
object.
Syntax:-
[Access modifiers] datatype membername [= value] ;
Member function
Eg:-
class rectangle
{
int length, breath;
void area()
{
int a = length * breath;
System.out.println( “ Area is = ”+ a);
}
void perimeter()
{
int p = 2 * (length * breath);
}
}
62
CCIT
Creating objects :
Syntax:- reference = new classname ();
It will create an object and will return id of an
object, which we can stored in a reference variable.
Whenever an object is created the space is reserved for its
data members..
Note:
reference variable.
variable.
63
CCIT
Using clone():
64
CCIT
Objects Vs Classes
Object Class
65
CCIT
Accessing Members:-
Members of an object can be access by using
syntax.
recferecneName.memberName
Access specifiers
They indicate accessibility of member of a class. It
can be private, public, protected or default (not specified).
66
CCIT
class rectangle
{
int length, breath;
void area()
{ int a = length * breath;
System.out.println( “ Area is = ”+ a);
}
void perimeter()
{ int p = 2 * (length * breath);
}
}
class pc
{public static void main ( String arg [] )
{ Rectangle a, b;
a=new Rectangle ();
b=new Rectangle ();
a.length = 3;
a.breadth = 4;
b.length = 5;
b.breadth = 4;
b.perimeter ();
a.area ();
b.area ();
}
}
67
CCIT
Setter functions
These functions are used to set values of private data
members. Generally their name starts with the name ‘set’.
Eg:-
class Rectangle
{ private int length, breadth;
public void area ()
{int a = length * breadth;
System.out.println (“ Area is = ” + a);
}
public void perimeter ()
{int p = 2 * ( length + breadth );
System.out.println (“Perimeter is =” + p);
}
public void setdimension (int l, int b)
{length = l;
breadth = b;
}
}
class pc
{public static void main ( String args [] )
{ Rectangle a, b;
a = new Rectangle ();
b = new Rectangle ();
a.setdimention (3,7);
b.setdimention (4,4);
a.area ();
b.perimeter ()
b.area ();
}
}
68
CCIT
class Box
{ private int l, b, h;
public void setdimension (int x, int y, int z)
{ l = x;
b = y;
h = z;
}
public void volume ()
{ int v = l * b * h;
System.out.println (“Volume is =” + v);
}
}
class pc
{
public static void main ( String args [] )
{
Box a, b;
a = new Box ();
b = new Box ();
a.setdimention (3, 7, 9);
b.setdimention (4, 4, 4);
a.volume ();
b.volume ()
}
}
69
CCIT
Design a class worker containing data member wages & wdays &
member function setdata & payment.
class Worker
{
private int wages, wdays;
public void setdata (int x, int y)
{
wages = x;
wdays = y;
}
public void payment ()
{
int p = wages * wdays;
System.out.println (“Payment is =” + p);
}
}
class pc
{
public static void main (String args [])
{
Worker a, b;
a = new Worker ();
b = new Worker ();
a.setdata (250, 23);
b.setdata (210, 44);
a.payment ();
b.payment ();
}
}
70
CCIT
Method overloading
Defining multiple methods in a class having same
name is called as method overloading. Only precaution to be
take is that no. of arguments & type of arguments must be
different. Compiler decides which method is called defending
on no. of arguments & type or type of argument that are pass
while calling the method. By defining multiple methods we
can call that method in multiple ways.
71
CCIT
class box
{ private int l, b, h;
public void setdimension (int x, int y, int z)
{l = x; b = y; h = z;
}
public void setdimension (int x )
{l = b = h = x;
}
public void volume ()
{ int v = l * b * h;
System.out.println (“Volume is”+ v);
}
}
class pc
{public static void main (String args [ ])
{ box a, b;
a = new box ();
b = new box ();
a.setdimention (4, 5, 6);
b.setdimention (5);
a.volume ();
b.volume ();
}
}
72
CCIT
class pc
{public static void main (String args [ ])
{worker a, b;
a = new worker ();
b = new worker ();
a.setdata (250, 23);
b.setdata (210, 20);
int n = a.payment () + b.payment ();
System.out.println (“Payment is = ”+ n);
}
}
73
CCIT
Constructors
Are special member functions of a class which
gets automatically invoke when ever an object of its class is
created. They are use for initialization of Object.
Rules/Properties/Characteristics of a constructor:
2. Constructor should not return any value even void also (if we
write the return type for the constructor then that
constructor will be treated as ordinary method).
74
CCIT
Default Constructor
Ex.
class circle
{ private int r;
public void setradius (int n)
{r = n;
}
public void area ()
{double a = 3.14 * r * r;
System.out.println (“area is ” + a);
}
public circle () //constructor
{r = 1;
}
}
class pc
{public static void main (String args [])
{Circle a, b;
a = new circle ();
b = new circle ();
a.setradius (7);
b.setradius (2);
a.area ();
b.area ();
}
}
75
CCIT
class circle
{
private int r;
public void area ()
{
double a = 3.14 * r * r;
System.out.println (“area is ” + a);
}
public circle (int n) // constructor with args.
{
r = n;
}
}
class pc
{ public static void main (String args [])
{ circle a, b;
a = new circle (7);
b = new circle (2);
a.area ();
b.area ();
}
}
76
CCIT
Constructor overloading
Defining multiple constructors in a class is called
as constructor overloading. Only precaution is to be taken is
that no. of args & type of args must be different.
Compiler decides which constructor to call
depending on the no. of arguments & type of arguments
which are pass while creating objects.
Eg:-
class circle
{ private int r;
public void area ()
{
double a = 3.14 * r * r;
System.out.println (“area is ” + a);
}
public circle (int n)
{ r = n;
}
public circle ()
{ r = 1;
}
}
class pc
{public static void main (String args [])
{circle a, b, c;
a = new circle (7);
b = new circle (2);
c = new circle ();
a.area ();
b.area ();
c.area ();
}
}
77
CCIT
Constructor Vs Methods
private constructors
Making the constructor private makes the class effectively
final because a the sub-class can't access it's constructor.
78
CCIT
Note: The java compiler copies the code of instance initializer block
in every constructor.
79
CCIT
class circle
{ private int r; // object member or instance
private static double pi = 3.14; // class member
public void area ()
{ double a = pi * r * r;
System.out.println (“area is ” + a);
}
public circle (int n)
{
r = n;
}
}
class pc
{
public static void main (String args [])
{
circle a, b, c;
a = new circle (7);
b = new circle (2);
c = new circle (5);
a.area ();
b.area ();
c.area ();
}
}
80
CCIT
81
CCIT
Static Initializers
If initialization requires some logic (for example, error
handling or a for loop to fill a complex array), simple
assignment is inadequate. Instance variables can be
initialized in constructors, where error handling or other logic
can be used. To provide the same capability for class
variables, the Java programming language includes static
initialization blocks.
Syntax :
static
{
//CODE
}
82
CCIT
A class can have any number of static initialization blocks, and they
can appear anywhere in the class body. The runtime system
guarantees that static initialization blocks are called in the order
that they appear in the source code.
Example :
class Test
{ static int stNumber;
int number;
Test()
{ number = 10;
}
static
{ stNumber=30;
}
…… // other methods here
}
83
CCIT
All of the numeric wrapper classes are subclasses of the abstract class Number:
Primitive Wrapper
Type class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
84
CCIT
class Integer
It is an wrapper class which wraps a value of type int in it.
Constructor:-
1) Integer (int n):-
Will create an integer object from int value.
Eg:- Integer b;
int a =5;
b = new Integer (a);
85
CCIT
* WAP to print all nos from 1 to 25 along with its Hex & Oct.
class sum
{ public static void main(String arg[])
{
for(int I=1;I<=25;I++)
{
String s1=Integer.toHexString(I);
String s2=Integer.toOctalString(I);
System.out.println(I+” “+s1+” “+s2);
}
}
}
86
CCIT
Class Character
It is wrapper class which wraps value of char in it. It provides
us different static method to perform operations on char type of data.
Method :-
1) public static boolean isDigit (char ch):-
Returns true if a given character represents a digits.
Eg:- boolean b= Character.isDigit (7);
2) public static boolean isLetter (char ch):-
Returns true if a given character represents alphabet or not.
Eg:- boolean b= Character.isLetter (‘7’);
3) public static boolean isSpace (char ch):-
Returns true if a given character represents a ‘ ‘ , ‘\t’, ‘\n’, ‘\r’
4) public static boolean isUpperCase (char ch):-
Returns true if a given character is in upper case.
5) public static boolean isLowerCase (char ch):-
Returns true if a given character is in lower case.
6) public static char toUpperCase (char ch):-
Converts given character into upper case.
7) public static char toLowerCase (char ch):-
Converts given character into lower case.
87
CCIT
88
CCIT
Arrays
An array is a group of elements of same type sharing
same name. In java arrays are treated like an object. They
can be dynamically created by using a keyword new.
Array Reference:
It is a variable in which we can store ID of an Array.
Creating Array:
An array can be dynamically created by using keyword
new, specifying datatype & no. of elements.
Array Size:
Size of array can be find out by using its special public
member length
yntax : arrayname.length
89
CCIT
Eg. class pc
{
public static void main (String arg [])
{int a[ ]; // declare a array reference
a=new int[5]; // create an array
a[0]=244; // initialize it.
a[1]=4;
a[2]=76;
a[3]=6544;
a[4]=42;
// print the array
for(int i=0;i< a.length;i++)
System.out.println(a[i]);
}
}
Array Initilization
An array can be initialized while createing it.
Eg. int a[ ]={544, 322, 86, 332, 667, 21, 366, 22};
int s=0;
for(int i=0;i< a.length;i++)
s=s+a[i];
System.out.println(“Sum is “+s);
}
}
90
CCIT
* WAP to find Average temp if temp values are given for a week in an
array.
class pc
{public static void main (String arg [])
{
double a[ ]={35.44, 32.2, 28.6, 33.2, 26.67, 21.9, 36.6};
double s=0;
for(int i=0;i< a.length;i++)
s=s+a[i];
double m=s/a.length;
System.out.println(“Average temp is “+m);
}
}
class pc
{
public static void main (String arg [])
{
int a[ ]={544, 322, 86, 332, 667, 21, 366, 22};
int g=a[0];
for(int i=1;i< a.length;i++)
if(a[i]>g)
g=a[i];
System.out.println(“Greatest no is “+g);
}
}
91
CCIT
Multidimensional Array
In java a multidimensional array is actually an
array of an array. It creates multiple single dimensional array.
These array may be of same size or of different size.
Eg.
int a[ ][ ];
a=new int[2][4]; // it will create two single dimensional array of size 4
Eg.
int a[ ][ ];
a=new int [2][ ];
a[0]=new int [5]; // it will create two single dimensional array of size5.
a[1]=new int [3]; // it will create two single dimensional array of size3.
this array will have 2 rows. First row of size 5 & second row of size 3.
92
CCIT
Array Initilization
An array can be initialized while createing it.
Syntax :datatype arrayname[ ][] ={{ list of values……},{ list of values……},..};
class pc
{public static void main (String arg [])
{int a[ ]={ {54, 4, 32 ,2, 8, 6, 3, 32},
{ 6, 67, 21, 366},
{ 2, 6, 5, 5, 2, 3}};
for(int i=0;i< a.length;i++)
{
int s=0;
for(int j=0;j< a[i].length;j++)
s=s+a[i][j];
System.out.println(“Sum of row “ + i + ” is “+s);
}
}
93
CCIT
Array of Objects
Whenever an array of object is created space is created
by references of Objects & not Objects
class circle
{private int r;
public void area ()
{double a = 3.14 * r * r;
System.out.println (“area is ” + a);
}
public circle (int n)
{r = n;
}
}
class pc
{ public static void main (String args [])
{ circle a [ ]; // defining a array reference
a = new circle [5]; // creating 5 references for array object
a[0] = new circle (2); // creating 5 objects
a[1] = new circle (7);
a[2] = new circle (5);
a[3] = new circle (12);
a[4] = new circle (8);
for(int i=0;i< a.length;i++) // calling fn area for all objects
a[i].area ();
}
}
94
CCIT
Class Arrays
The java.util.Arrays class contains various static methods for
sorting and searching arrays, comparing arrays, and filling
array elements. These methods are overloaded for all
primitive types.
95
CCIT
import java.util.*;
class demo
{
public static void main(String args[ ])
{
int arr[]={23,5,12,111,15,6,2};
Arrays.sort(arr);
display(arr);
int pos=Arrays.binarySearch(arr,7);
if(pos<0)
System.out.println("Not Found");
else
System.out.println("Found at pos :"+pos);
}
public static void display(int arr[])
{
for(int n:arr)
System.out.println(n);
}
}
96
CCIT
*WAP to display all arguments which are passed from command prompt.
class Test
{public static void main (String args [ ])
{System.out.println(“Total arguments are “+ args.length);
*WAP to sum of all nos which are passed from command prompt.
class sum
{public static void main (String args [ ])
{
int s=0;
System.out.println(“Sum is “+s);
}
}
97
CCIT
Variable Arguments(var-args):
Java enables you to pass a variable number of arguments of
the same type to a method. The parameter in the method is
declared as follows:
typeName... parameterName
98
CCIT
Pass by Value
When the argument is of primitive type , pass-by-value
means that the method cannot change its value. When
the argument is of reference type, pass-by-value means
that the method cannot change the object reference,
but can invoke the object's methods and modify the
accessible variables within the object.
class CCIT
{
public static void change(int a)
{
a++;
}
}
class pc
{
public static void main(String arg[])
{
int a=5;
CCIT.change(a);
System.out.println(a);
} // Result of this program will be 5 and not 6
as while calling
} //method change value of a is passed as argument.
99
CCIT
Pass by Reference
For a method to modify an argument, it must be of a
reference type such as an object or array. Objects and arrays
are passed by reference. So the effect is that arguments of
reference types are passed in by reference. Hence the name.
A reference to an object is the address of the object in
memory. Now, the argument in the method is referring to
the same memory location as the caller.
class pc
{public static void main(String arg[])
{ Circle a;
a=new Circle();
a.setRadius(5);
CCIT.change(a);
System.out.println(a.getRadius());
} // Result of this program will be 2 and not 5 as while calling
} //method change reference of object ‘a’ is passed as argument.
// so the changes made by the method are actually done on the //original object
100
CCIT
Inheritance
Inheritance is the ability, offered by many OOP
languages, to derive a new class (the derived or inherited class)
from another class (the base class). The derived class automatically
inherits the properties and methods of the base class. For example,
you could define a generic Shape class with properties such as
Color and Position and then use it as a base for more specific
classes (for example, Rectangle, Circle, and so on) that inherit all
those generic properties. You could then add specific members,
such as Width and Height for the Rectangle class and Radius for the
Circle class. It's interesting to note that, while polymorphism tends
to reduce the amount of code necessary to use the class,
inheritance reduces the code inside the class itself and therefore
simplifies the job of the class creator.
101
CCIT
class pc
{ public static void main (String arg [])
{ Account a = new Account();
a.open (4117, 5000);
a.withdraw (2000);
a.showBalance ();
SAccount b = new Saccount ();
b.open (3210, 8000);
b.deposit (7000);
b.addIntrest (10.25, 3);
b.showBalance ();
}
}
102
CCIT
Method overriding
Redefining a base class method in derived class is
called as method overriding.
The overriding method must have same name,
same no. & type of arguments similar to a base class method.
So when the method is called for the derived class objects
this overrided method is executed instead of inherited base
class method.
103
CCIT
Design a class box containing data member’s length, breadth & height &
member function setdimension, value & surface_area then derived a new
class openbox from class box.
class box
{ protected int l, b, h;
public void setdimension (int x, int y, int z)
{ l = x;
b = y;
h = z;
}
public void volume ()
{ int v = l * b * h;
System.out.println(“Volume is ”+ v);
}
public void surface_area ()
{ int a = 2 * l * h + 2 * h * b + 2 * b * l;
System.out.println (“Surface area is ”+ a);
}
}
class pc
{ public static void main (String arg [])
{ openbox a = new openbox ();
a.setdimension (4, 7, 5);
a.volume ();
a.surfacearea ();
}
}
104
CCIT
Design a class a/c containing data member’s accno & balance and
member function open, deposit, withdraw & showbalance. Then derived
a new class current a/c from a class a/c having the transaction.
class Account
{ protected int accno, balance;
public void open (int an, int b)
{ accno = an;
balance = b;
}
public void deposit (int amt)
{balance = balance + amt;
}
public void withdraw (int amt)
{balance = balance – amt;
}
public void showBalance ()
{System.out.println(“Balance is = ”+ balance);
}
}
class CAccount extends Account
{public void deposit (int amt)
{balance = (balance + amt)- 1;
}
public void withdraw (int amt)
{
balance = (balance - amt)- 1;
}
}
105
CCIT
class pc
{public static void main (String arg [])
{ Account a = new Account();
a.open (4117, 5000);
a.withdraw (2000);
a.deposit (7000);
a.showBalance ();
106
CCIT
107
CCIT
108
CCIT
Type of Inheritance
3) Hierarchical inheritance:-
If a multiple classes are derived from
single class then such type of inheritance is
called as hierarchical inheritance.
4) Multiple inheritance:-
If a single class is derived from multiple
classes then such type of inheritance is called as
multiple inheritance.
NOTE: Java does not support multiple
inheritance for classes but it can be achive
through Interfaces.
109
CCIT
Design class person containing data member name address and member
function containing setdata and showdata then derived a new class
employee from person containing additional data member job and salary
class person
{protected String Name, Add;
public void setdata(String n, String a)
{Name=a;
Add=a;
}
public void showdata()
{System.out.println (“Name=”+Name);
System.out.println (“Add=”+Add);
}
}
class pc
{ public static void main(String arg[])
{
employee b;
b=new employee(“Amit Jain”,23,”Manager”,34500);
b.showdata();
}
}
110
CCIT
Abstraction in Java
Abstraction is a process of hiding the implementation details
and showing only functionality to the user.
Abstract Class
A class which contains the abstract keyword in its declaration is
known as abstract class.
111
CCIT
Eg.
abstract class Circle
{ protected int R;
public void setRadius(int n)
{ R=n;
}
public void area()
{double a=3.14.*R*R;
System.out.println(“Area is “+a);
}
abstract public void circumference( ); // this is an abstract method
} // it is declared but not defined.
112
CCIT
Aggregation
If a class have an entity reference, it is known as Aggregation.
Aggregation represents HAS-A relationship.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
113
CCIT
void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.countr
y);
}
e.display();
e2.display();
}
}
114
CCIT
Final Keyword
The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized final
variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block
only. We will have detailed learning of these. Let's first learn the basics
of final keyword.
If you make any variable as final, you cannot change the value of final
variable(It will be constant).
115
CCIT
Strictfp Keyword
Java strictfp keyword ensures that you will get the same result on
every platform if you perform operations in the floating-point
variable. The precision may differ from platform to platform that is
why java programming language have provided the strictfp
keyword, so that you get same result on every platform. So, now
you have better control over the floating-point arithmetic.
class A{
strictfp void m(){}//strictfp applied on method
}
116
CCIT
Polymorphism
117
CCIT
class Circle
{
private int R;
public Circle(int n)
{
R=n;
}
118
CCIT
class Rect
{ private int L,B;
public Rect(int m,int n)
{L=m;
B=n;
}
public void area( )
{ int a=L*B;
System.out.pritln(“Area is “+a);
}
}
class Test
{public static void main(String args[ ])
{Shape p[ ]=new Shape[5]; //create 5 references of type shape.
p[0]=new Circle(4); // a shape reference can point to a Circle object
p[1]=new Rect(3, 8); // as well as a Rect object
p[2]=new Rect(7, 4);
p[3]=new Circle(11);
p[4]=new Rect(5, 5);
for(int i=0;i< p.length;i++)
p[i].area(); // method area of Circle or Rect will be called
} // depending on type of the object.
}
instanceof Operator
This operator is used to datatype of a Object pointed by a reference.
if ( p instanceof Circle)
…………..
if(p instanceof Rect)
…………….
119
CCIT
120
CCIT
Interface
Definition: An interface is a named collection of method
definitions (without implementations). An interface can also
declare constants.
An interface defines a protocol of behavior that can be
implemented by any class anywhere in the class hierarchy.
An interface defines a set of methods but does not
implement them. A class that implements the interface
agrees to implement all the methods defined in the
interface, thereby agreeing to certain behavior. Because
an interface is simply a list of unimplemented, and
therefore abstract, methods, you might wonder how an
interface differs from an abstract class. The differences are
significant.
121
CCIT
Class Vs Interfaces
Property Class Interface
Variables All the variables are All the variables are static
instance by default final by default, and a value
unless otherwise needs to be assigned at the
specified time of definition
Methods All the methods should All the methods are abstract
be having a definition by default and they will not
unless decorated with an have a definition.
abstract keyword
122
CCIT
7) Example: Example:
public abstract class Shape public interface Drawable
{ {
public abstract void draw(); void draw();
} }
123
CCIT
Defining an Interface
An interface definition has two components: the interface
declaration and the interface body. The interface declaration
declares various attributes about the interface, such as its
name and whether it extends other interfaces. The interface
body contains the constant and the method declarations for
that interface.
Syntax :
interface Name
{ // final Data Members
// abstract Member Functions
}
124
CCIT
Implementing an Interface
An interface defines a protocol of behavior. A class that
implements an interface adheres to the protocol defined by
that interface. To declare a class that implements an
interface, include an implements clause in the class declaration.
Your class can implement more than one interface (the Java
platform supports multiple inheritance for interfaces), so the
implements keyword is followed by a comma-separated list of
the interfaces implemented by the class.
By Convention: The implements clause follows the extends clause, if it
exists.
class Sphere implements Solid
{
….. //in this class we have to override volume() and surfaceArea () method
//otherwise this class will become an abstract class
}
When a class implements an interface, it is essentially signing
a contract. Either the class must implement all the methods
declared in the interface and its superinterfaces, or the class
must be declared abstract. The method signature--the name
and the number and type of arguments in the class--must
match the method signature as it appears in the interface
125
CCIT
Interface Features:
Variable of an interface are explicitly declared final and static
(as constant) meaning that the implementing the class
cannot change them they must be initialize with a
constant value all the variable are implicitly public of the
interface, itself, is declared as a public .
Method declaration contains only a list of methods without
anybody statement and ends with a semicolon the
method are, essentially, abstract methods there can be
default implementation of any method specified within an
interface each class that include an interface must
implement all of the method.
Need:
To achieve multiple Inheritance.
126
CCIT
// default method
default void show()
{ System.out.println("Default Method Executed");
}
}
127
CCIT
Inner Class
Creating an inner class is quite simple. You just need to write
a class within a class. Unlike a class, an inner class can be
private and once you declare an inner class private, it cannot
be accessed from an object outside the class. Given below is
the program to create an inner class and access it. In the
given example, we make the inner class private and access
the class through a method.
class Outer_Demo{
int num;
//inner class
private class Inner_Demo{
public void print(){
System.out.println("This is an inner class");
}
}
//Accessing he inner class from the method within
void display_Inner(){
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class{
public static void main(String args[]){
//Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
//Accessing the display_Inner() method.
outer.display_Inner();
}
}
128
CCIT
129
CCIT
If you compile and execute the above program, you will get
the following result.
130
CCIT
But in all the three cases, you can pass an anonymous inner
class to the method. Here is the syntax of passing an
anonymous inner class as a method argument:
obj.my_Method(new My_Class(){
public void Do(){
.....
.....
}
});
//interface
interface Message{
String greet();
}
131
CCIT
132
CCIT
133
CCIT
134
CCIT
Packages
To make classes easier to find and to use, to avoid
naming conflicts, and to control access, programmers
bundle groups of related classes and interfaces into
packages.
Definition: A package is a collection of related classes and
interfaces providing access protection and namespace
management.
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
135
CCIT
There are three ways to access the package from outside the
package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
136
CCIT
137
CCIT
static import
Example
import static java.lang.Math.sqrt; //importing static method
sqrt of Math class
Example
import static java.lang.Math.*; //importing all static
member of Math class
138
CCIT
java.util
Contains the collections framework, legacy collection classes,
event model, date and time facilities, internationalization,
and miscellaneous utility classes (a string tokenizer, a
random-number generator, and a bit array).
java.awt
Contains all of the classes for creating user interfaces and for
painting graphics and images.
java.io
Java.io package provides classes for system input and output
through data streams, serialization and the file system.
java.net
contains clasess for Communication and Netwroking.
139
CCIT
class String
An object of this type is used to store a strings.
Data stored in a string object can not be modified.
Constructors :-
1) String (char a []):-
Creates a string object from a character array.
Eg:- char a[] = {‘C’, ‘C’, ‘I’, ‘T’};
String s= new String(a);
System.out.println (s); O/p :- “CCIT”
140
CCIT
NOTE: String object are automatically created when ever java founds strings
in double codes.
Eg:- String s;
s = “Amravati”;
System.out.println (s); O/p: - “Amravati”
Methods:-
1) int length ():-
It returns length of the string.
Eg:-
String s;
s = “Amravati”;
int n = s.length();
System.out.println (“Length is ” + n);
141
CCIT
142
CCIT
143
CCIT
144
CCIT
145
CCIT
146
CCIT
WAP to read a sentence & check if the ‘CCIT’ is present in that sentence
or not.
class pc
{ public static void main (String arg [])
{String s = JOptionPane.showInputDialog (Null, “Enter a sentence”);
int n = s.indexOf (“CCIT”);
if(n == -1)
System.out.println (“not found”);
else
System.out.println (“found at position”+n);
}
}
WAP to read a filename & check if it is an valid .html file or not.
class pc
{ public static void main (String arg [])
{ String s = JOptionPane.showInputDialog (Null, “Enter a sentence”);
boolean b = s.endsWith(“.html”);
boolean a = s.endsWith(“.htm”);
if(b == true || a == true)
System.out.println(“web page”);
Else
System.out.println(“not a web page”);
}
}
WAP to separate date, month, & year from a date string .
class pc
{public static void main (String arg [ ])
{ String s = “27-11-2005”
String p = s.subString (0, 2);
System.out.println(“Date is ”+p);
String x = s.subString (3, 5);
System.out.println(“Month is ”+x);
String z = s.subString (6);
System.out.println(“Year is ”+z);
}
}
147
CCIT
class Math
This class provide us different mathematical function.
All member of this class are static.
Data member
1) public static final double PI = 3.14
Eg:- a = Math.pi * r * r ;
Method
1) public static int abs (int n)
It returns absolute value
Eg. Z = Math.abs (5) + Math.abs (-5)
2) public static long abs (long n)
3) public static float abs (float n)
4) public static double abs (double n)
5) public static int max (int a, int b)
Maximum of two numbers.
Eg:- z = max (4117)
6) public static int min (int a, int b)
Will return lowest of two value
Eg:- z = min (4117, 308);
Similar method for long, float & double.
7) public static double sqrt (double n)
It returns square root of given numbers.
Eg:- double z = Math.sqrt (10);
8) public static double pow (double a, double b)
It return a to the power b.
9) public static double sign (double n)
Sing of given value.
10) public static double tan (double n)
11) public static double cos (double n)
12) public static double ceil (double n)
It returns lowest whole no which is greater than or equal to given no.
13) public static double floor (double n)
It returns grestest whole no which is less than or equal to given no.
148
CCIT
WAP to print all no. from 1 to 10 along with their square, cube & square
root.
class pc
{
public static void main (String args [])
{
for (int I =1;I <= 10;I ++)
{
System.out.println (“The no. is ”+ I );
double s = Math.pow (I ,2);
double p = Math.pow (I ,3);
double q = Math.sqrt (I);
}
System.out.println (“Square is =” + s);
System.out.println (“Cube is =” + p);
System.out.println (“Square root is =” + q);
}
}
149
CCIT
StringBuffer Class
The java.lang.StringBuffer class is a growable buffer for
Characters. We can create a StringBuffer object and its append( )
method:
Constructors
1. StringBuffer(): creates an empty string buffer with the initial
capacity of 16.
2. StringBuffer(String str): creates a string buffer with the
specified string.
3. StringBuffer(int capacity): creates an empty string buffer
with the specified capacity as length.
methods
1. public synchronized StringBuffer append(String s): is
used to append the specified string with this string. The
append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double)
etc.
2. public synchronized StringBuffer insert(int offset, String
s): is used to insert the specified string with this string at the
specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex,
int endIndex, String str): is used to replace the string from
specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex,
int endIndex): is used to delete the string from specified
startIndex and endIndex.
150
CCIT
String Vs StringBuffer
String StringBuffer
String class is immutable.
StringBuffer class is mutable.
151
CCIT
class Vector
Vector implements a dynamic array. Vector proves to be very
useful if you don't know the size of the array in advance or
you just need one that can change sizes over the lifetime of
a program.
Vector( )
This constructor creates a default vector, which has an
initial size of 10
Vector(int size)
This constructor accepts an argument that equals to the
required size, and creates a vector whose initial capacity is
specified by size:
Vector(Collection c)
creates a vector that contains the elements of collection c
152
CCIT
Methods
void add(int index, Object element)
Inserts the specified element at the specified position in this
Vector.
boolean add(Object o)
Appends the specified element to the end of this Vector.
boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the
end of this Vector, in the order that they are returned by the
specified Collection's Iterator.
int capacity()
Returns the current capacity of this vector.
void clear()
Removes all of the elements from this Vector.
Object firstElement()
Returns the first component (the item at index 0) of this
vector.
153
CCIT
boolean isEmpty()
Tests if this vector has no components.
Object lastElement()
Returns the last component of the vector.
boolean remove(Object o)
Removes the first occurrence of the specified element in this
Vector If the Vector does not contain the element, it is
unchanged.
154
CCIT
boolean removeAll(Collection c)
Removes from this Vector all of its elements that are contained
in the specified Collection.
void removeAllElements()
Removes all components from this vector and sets its size to
zero.
int size()
Returns the number of components in this vector.
void trimToSize()
Trims the capacity of this vector to be the vector's current size.
155
CCIT
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
// create an empty Vector vec with an initial capacity of 4
Vector vec = new Vector(4);
// use add() method to add elements in the vector
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(3);
// let us get the index of 3
System.out.println("Index of 3 is :"+vec.indexOf(3));
}
}
- Arrays provide efficient access to any element and can not modify
or increase the size of the array.
- Vector is efficient in insertion, deletion and to increase the size.
- Arrays size is fixed where as Vector size can increase.
- Elements in the array can not be deleted, where as a Vector can.
156
CCIT
ArrayList Class
ArrayList supports dynamic arrays that can grow as needed. Array
lists are created with an initial size. When this size is exceeded, the
collection is automatically enlarged. When objects are removed, the
array may be shrunk.
ArrayList( )
This constructor builds an empty array list.
ArrayList(Collection c)
This constructor builds an array list that is initialized with the
elements of the collection c.
ArrayList(int capacity)
This constructor builds an array list that has the specified initial
capacity.
boolean add(Object o)
Appends the specified element to the end of this list
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the
end of this list.
157
CCIT
void clear()
Removes all of the elements from this list.
boolean contains(Object o)
Returns true if this list contains the specified element.
int indexOf(Object o)
Returns the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this
element.
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this
element.
int size()
Returns the number of elements in this list.
Object[] toArray()
Returns an array containing all of the elements in this list in
the correct order. Throws NullPointerException if the specified
array is null.
158
CCIT
import java.util.*;
class demo
{public static void main(String args[ ])
{
ArrayList arr=new ArrayList();
arr.add("Ram");
arr.add("Ramesh");
arr.add("Rajesh");
System.out.println(arr);
}
}
ArrayList Vs Vector
ArrayList Vector
1) ArrayList is not Vector is synchronized.
synchronized.
159
CCIT
Set Interface
A Set is a Collection that cannot contain duplicate elements.
It models the mathematical set abstraction.
add( )
Adds an object to the collection
clear( )
Removes all objects from the collection
contains( )
Returns true if a specified object is an element within the
collection
isEmpty( )
Returns true if the collection has no elements
remove( )
Removes a specified object from the collection
size( )
Returns the number of elements in the collection
Set have its implementation in various classes like HashSet,
TreeSet, LinkedHashSet
160
CCIT
import java.util.*;
public class SetDemo {
public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);
161
CCIT
HashSet Class
HashSet extends AbstractSet and implements the Set
interface. It creates a collection that uses a hash table for
storage.
A hash table stores information by using a mechanism called
hashing. In hashing, the informational content of a key is
used to determine a unique value, called its hash code.
The hash code is then used as the index at which the data
associated with the key is stored. The transformation of the
key into its hash code is performed automatically.
HashSet( )
This constructor constructs a default HashSet.
HashSet(Collection c)
This constructor initializes the hash set by using the elements
of the collection c.
HashSet(int capacity)
This constructor initializes the capacity of the hash set to the
given integer value capacity. The capacity grows automatically
as elements are added to the HashSet.
162
CCIT
boolean add(Object o)
Adds the specified element to this set if it is not already
present.
void clear()
Removes all of the elements from this set.
Object clone()
Returns a shallow copy of this HashSet instance: the elements
themselves are not cloned.
boolean contains(Object o)
Returns true if this set contains the specified element
boolean isEmpty()
Returns true if this set contains no elements.
Iterator iterator()
Returns an iterator over the elements in this set.
boolean remove(Object o)
Removes the specified element from this set if it is present.
int size()
Returns the number of elements in this set (its cardinality).
163
CCIT
TreeSet Class
TreeSet provides an implementation of the Set interface that
uses a tree for storage. Objects are stored in sorted,
ascending order.
TreeSet( )
This constructor constructs an empty tree set that will be
sorted in ascending order according to the natural order of its
elements.
TreeSet(Collection c)
This constructor builds a tree set that contains the elements of
the collection c.
TreeSet(Comparator comp)
This constructor constructs an empty tree set that will be
sorted according to the given comparator.
TreeSet(SortedSet ss)
This constructor builds a TreeSet that contains the elements of
the given SortedSet
164
CCIT
void add(Object o)
Adds the specified element to this set if it is not already
present.
boolean addAll(Collection c)
Adds all of the elements in the specified collection to this set.
void clear()
Removes all of the elements from this set.
boolean contains(Object o)
Returns true if this set contains the specified element.
Object first()
Returns the first (lowest) element currently in this sorted set.
boolean isEmpty()
Returns true if this set contains no elements.
Iterator iterator()
Returns an iterator over the elements in this set.
Object last()
Returns the last (highest) element currently in this sorted set.
boolean remove(Object o)
Removes the specified element from this set if it is present.
165
CCIT
Map Interface
The Map interface maps unique keys to values. A key is an
object that you use to retrieve a value at a later date.
Given a key and a value, you can store the value in a Map object.
After the value is stored, you can retrieve it by using its key.
166
CCIT
HashMap Class
The HashMap class uses a hashtable to implement the Map
interface. This allows the execution time of basic operations,
such as get( ) and put( ), to remain constant even for large
sets.
Constructors and Description
HashMap( )
This constructor constructs a default HashMap.
HashMap(Map m)
This constructor initializes the hash map by using the elements
of the given Map object m
HashMap(int capacity)
This constructor initializes the capacity of the hash map to the
given integer value, capacity.
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}}
167
CCIT
Clas Date
Constructor
Methods
long getTime()
This method returns the number of milliseconds since January 1,
1970, 00:00:00 GMT represented by this Date object.
String toString()
This method converts this Date object to a String of the form.
Int getDate()
returns date from date object
168
CCIT
Class Calender
The java.util.calendar class provides methods for converting
between a specific instant in time and a set of calendar fields such
as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for
manipulating the calendar fields, such as getting the date of the
next week.
Method
Date getTime()
This method returns a Date object representing this
Calendar's time value (millisecond offset from the Epoch").
169
CCIT
String toString()
This method return a string representation of this calendar.
import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args) {
// create a calendar
Calendar cal = Calendar.getInstance()
// print current date
System.out.println("The current date is : " + cal.getTime());
// add 20 days to the calendar
cal.add(Calendar.DATE, 20);
System.out.println("20 days later: " + cal.getTime());
// subtract 2 months from the calendar
cal.add(Calendar.MONTH, -2);
System.out.println("2 months ago: " + cal.getTime());
// subtract 5 year from the calendar
cal.add(Calendar.YEAR, -5);
System.out.println("5 years ago: " + cal.getTime());
}
}
170
CCIT
Scanner class
The Java Scanner class breaks the input into tokens using a delimiter
that is whitespace bydefault. It provides many methods to read and
parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive
types using regular expression.
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and
returns the value as a string.
171
CCIT
Java Modifiers
Used
Modifier Meaning
on
172
CCIT
173
CCIT
Applications Vs Applets
Applets Applications
Applet does not use main() Application use main() method
method for initiating execution for initiating execution of code
of code
Applet cannot run any program Application can run any program
from local computer. from local computer.
174
CCIT
Applets
An applet is a Java program that runs in a Web browser. An
applet can be a fully functional Java application because it
has the entire Java API at its disposal.
There are some important differences between an applet and
a standalone Java application, including the following:
An applet is a Java class that extends the java.applet.Applet
class.
A main() method is not invoked on an applet, and an applet
class will not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet,
the code for the applet is downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a
plug-in of the Web browser or a separate runtime
environment.
The JVM on the user's machine creates an instance of the
applet class and invokes various methods during the
applet's lifetime.
Applets have strict security rules that are enforced by the
Web browser. The security of an applet is often referred to
as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a
single Java Archive (JAR) file.
175
CCIT
176
CCIT
These are the different stages involved in the life cycle of an applet:
Initialization State : This state is the first state of the applet life
cycle. An applet is created by the method init(). This method
initializes the created applet. It is Called exactly once in an applet's
life when applet is first loaded, which is after object creation, e.g.
when the browser visits the web page for the first time.Used to
read applet parameters, start downloading any other images or
media files, etc. Init() method should be overrided in our applet.
Running State : This state is the second stage of the applet life
cycle. This state comes when start() method is called. Called at
least once.Called when an applet is started or restarted, i.e.,
whenever the browser visits the web page.
Idle or Stopped State : This state is the third stage of the applet
life cycle. This state comes when stop() method is called implicitly
or explicitly.stop() method is called implicitly. It is called at least
once when the browser leaves the web page when we move from
one page to another. This method is called only in the running state
and can be called any number of times.
It should be overrided in our applet.
Dead State : This state is the fourth stage of the applet life cycle.
This state comes when destroy() method is called. In this state the
applet is completely removed from the memory. It called exactly
once when the browser unloads the applet.Used to perform any
final clean-up. It occurs only once in the life cycle. It should be
overrided in our applet.
Display State : This state is the fifth stage of the applet life cycle.
This state comes when use s the applet displays something on the
screen. This is achieved by calling paint() method.Paint() method
can be called any number of times.This can be called only in the
running state.This method is a must in all applets. It should be
overrided in our applet.
177
CCIT
codebase
The codebase attribute should specify a URL that identifies
the directory used to find the .class files needed for the
applet
code
The code attribute specifies the name of the class that
implements the applet.
alt
The alt attribute specifies the text that should be displayed
by Web browsers that understand the <applet> tag but
cannot run Java applets.
width
The width attribute specifies the width of the applet in pixels.
height
The height attribute specifies the height of the applet in
pixels.
178
CCIT
Applet Executation
179
CCIT
Applet Parameters
Many times when you're developing a Java applet, you want to
pass parameters from an HTML page to the applet you're invoking.
For instance, you may want to tell the applet what background
color it should use, or what font to use etc.
A great benefit of passing applet parameters from HTML pages to
the applets they call is portability. If you pass parameters into your
Java applets, they can be portable from one web page to another,
and from one web site to another.
We can get any information from the HTML file as a parameter. For
this purpose, Applet class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
for eg:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
180
CCIT
Class Applet
This is a base class from which all applet classes are derived.This
class provides us different features required to build an applet.
Browser called its different method on different event .
Methods–
public void paint(Graphics g) -
This method is called by the browser whenever it wants to show
applet. We can override this method if we want to perform some
drawing and painting operation.
public void init() -
This is the first method which is called by the browser after
creating the applet object. We can override this method, if we
want to perform some initialization.
public void start() -
This method called by the browser when applets scroll into view.
public void stop() -
This method is called by browser whenever an applet scroll out of
the view.
public void destroy() -
This method called by the browser before removing the applet.
public void showStatus(String msg) -
We can call this method to show some message into browser
statusbar.
public URL getDocumentBase() -
It returns the URL of the document /site from where the document
is received.
public URL getCodeBase() -
It returns the URL of site from where the code is received.
public String getParameter(String parname) -
It returns the parameter value of given parameter name.
public Image getImage(String filename) -
It returns a image object from specified resource.
181
CCIT
Class Graphics
This class provide us different method for drawing and
painting.
Method Description
void drawRect(int x,int y,int w ,int h) Will draw a rectangle.
void fillRect(int x, int y, int w, int h) Will draw a fillrectangle.
182
CCIT
AWT components
A component is an object having a graphical representation
that can be displayed on the screen and that can interact with the
user. Examples of components are the buttons, checkboxes, and
scrollbars of a typical graphical user interface.
AWT Container
A container is an object in which we can add awt
compontents . The job of the container is to arrange the
components which are added into the container . To arrange the
components it has a LayoutManager object .AWT provides us
different container by calling its method
void add(Component c)
AppletViewer
AppletViewer is a standalone command-line program
from Sun to run Java applets.Appletviewer is generally used
by developers for testing their applets before deploying them
to a website. As a Java developer, it is a preferred option for
running Javaapplets that do not involve the use of a web
browser.
183
CCIT
Class Component
The Component class defines a number of methods that
can be used on any of the classes that are derived from
it.Methods listed below can be used on all User Interface(UI)
components as well as containers.
Method Description
void setSize(int width , int Resizes the corresponding
height) component so that it has width and
height.
void setFont(Font f) Sets the font of the corresponding
component.
void setEnabled(boolean b) Enables or disables the
corresponding component
,depending on the value of the
parameter b.
void setVisible (boolean b) Shows or hides the corresponding
component depending on the value
of parameter b.
void setForeground(Color c) Sets the foreground color of the
corresponding component.
void setBackground(Color Sets the background color of the
c) corresponding component.
void setBounds(int x,int resizes the component.
y,int w,int h)
Gets the background color of the
Color getBackground() corresponding component.
Color getForeground() Gets the foreground color of the
corresponding component.
Dimention getBounds() Gets the bounds of the
corresponding component .
Dimention getSize() Returns the size of the component
in the form of a Dimension object.
Font getFont() Gets the font of the corresponding
component.
184
CCIT
185
CCIT
class Button
Buttons are components that can contain a label. Button is
similar to a push button in any other GUI. Pushing a button causes
the run time system to generate an event. This event is sent to the
program. The program in turn can detect the event and respond to
the event. Clicking the button generate the ActionEvent.
Constructor Description
Button() Constructs a button with no label.
Button(String label) Constructs a button with the label specified.
class ActionEvent
An object of this type contain the information about the source
which has generated the event .
String Returns the label of the button which
getActionCommand() has generated the event .
Object getSource() It returns the reference of the button
which has generated the event .
186
CCIT
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MyApplet extends Applet implements ActionListener
{
Button b1,b2;
public void init()
{
b1= new Button("ok");
b2= new Button("exit");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Button bs=(Button)e.getSource();
if(bs==b1)
{
showStatus("ok button clicked");
}
if(bs==b2)
{
showStatus("exit button clicked");
}
}
}
187
CCIT
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MyApplet extends Applet implements ActionListener
{
Button b1,b2;
public void init()
{
b1= new Button("ok");
b2= new Button("exit");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s1=e.getActionCommand();
if(s1.equals("ok"))
{
showStatus("ok button clicked");
}
if(s1.equals("exit"))
{
showStatus("exit button clicked");
}
}
}
188
CCIT
Class Label
Lables do not generate any event .
This component can be used for displaying a single line of
text in a container.
Constructor Description
Label() Constructs an empty Label.
Label(String text) Constructs a string with
corresponding text.
Label(String text , int Constructs a string with the text, with
alignment) the specified alignment .The
alignment can be
CENTER,LEFT,RIGHT.
Methods –
String getText() Gets the text of the
corresponding label.
void setText(String text) Sets the text for the
corresponding label to the
specified text.
189
CCIT
Class Font
This class is used to create Font object and we can set Fonts
using method
setFont(Font f) of class Component.
Constructor Description
Font (String fontname,int Create Font object with given
style,int size) fontname,style and size.
Fontname :
TimesRoman,MonoSpaced,Dialog,DialogInput,ScanScript,Courier
etc.
Styles :
public static final int BOLD;
public static final int ITALIC;
public static final int PLAIN;
String getFamily()
Returns the family name of this Font.
String getFontName()
Returns the font face name of this Font.
int getSize()
Returns the point size of this Font, rounded to an integer.
boolean isBold()
Indicates whether or not this Font object's style is BOLD.
boolean isItalic()
Indicates whether or not this Font object's style is ITALIC.
190
CCIT
Class List
List components present the user with a scrolling list of text
items.
The differences between a list and a choice menu are:
Unlike Choice, which displays only the single selected item, the list
can be made to show any number of
choices in the visible window.
Constructor Description
List() Creates a new scrolling list of items.
List(int visibleitems) Creates a new scrolling list of items
with the specified number of visible
items.
List(int visibleitems, Creates a new scrolling list of items to
boolean multimode) display the specified number of
visibleitems.
Method Description
void add(String item) Add the specified item to the end of
the scrolling list
void add(String item,int Adds the specified item at the
index) position
String getItem(int index) Gets the item at the specified index.
int getItemCount() Gets the no. of items in the list.
String [] getItems() Gets the items in the list.
int getSelectedIndex() Gets the index of the selected item
in the list
String getSelectedItem() Gets the selected item in the
corresponding list
void Sets the flag that allows multiple
setMultipleMode(boolean b) selection
191
CCIT
import java.applet.Applet;
import java.awt.List;
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
list.add("Five");
list.add("Six");
list.add("Seven");
//add list
add(list);
}
}
192
CCIT
Class Choice
The Choice class implements a pop up menu that allows the
user to select an item from that menu .This UI component displays
the currently selected item with an arrow to its right. On clicking
the arrow, the menu opens and displays options for a user to
select.
Constructor Description
Choice() Creates a new choice menu.
Methods Description
void add(String item) Adds an item to the corresponding
choice menu.
void addItem(String Adds an item to the corresponding
item) choice .
String getItem(int Gets the string at the specified index of
index) the corresponding choice menu.
int getItemCount() Returns the no. of items in the
corresponding choice menu.
int getSelectedIndex() Returns the index of the currently
selected item.
String Gets a representation of the current
getSelectedItem() choice as a string.
insert(String item,int Inserts the item into the corresponding
index) choice at the specified position.
void remove(int Removes the first occurance of item
position) from the corresponding Choice menu.
void removeAll() Removes all the items from the
corresponding Choice menu.
select(int position) Sets the selected item in the
corresponding
Choice menu to be the item at specified
position.
select(String str) Sets the selected item in the
corresponding
Choice menu to be the item whose name
is equal to the specified string.
193
CCIT
Interface ItemListener
This interface is used to listen action of the List ,Choice,
Checkboxes, Radiobuttons.
Method –
public void itemStateChanged(ItemEvent e)-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class pcListApplet extends Applet
implements ItemListener
{ Choice ch;
public void init()
{ ch=new Choice();
add(ch);
ch.addItemListener(this);
ch.addItem("Circle");
ch.addItem("Rect");
ch.addItem("Pie");
}
public void itemStateChanged(ItemEvent e)
{ Graphics g=this.getGraphics();
String item=ch.getSelectedItem();
g.clearRect(50,50,100,100);
if(item.equals("Circle"))
g.fillOval(50,50,100,100);
if(item.equals("Rect"))
g.fillRect(50,50,100,100);
if(item.equals("Pie"))
g.fillArc(50,50,100,100,0,90);
}
}
194
CCIT
Class TextField
TextFields are UI components that accept text input from the user.
TextFields only have single line text .
Constructor Description
TextField() Constructs a new text field
TextField(int columns) Creates a new text field with the
specified number of columns.
TextField(String text) Constructs a new text field initialized
with the specified text.
TextField(String text,int Constructs a new text field initialized
columns) with the specified text with the
specified number of columns.
Methods Description
int getColumns() Gets the no. of columns in the
corresponding text field.
char getEchoChar() Gets the character that is to be used for
echoing.
void setColumns(int Sets the no. of columns in the text field.
columns)
void setEchoChar(char c) Sets the echo character for the text field.
void setText(String str) Sets the text
class TextComponent
TextComponent is a base class for class TextField & TextArea.
Methods Description
void setText(String str) sets the given string into the
textbox
String getText() Gets the text from textbox.
void select(int start, int end) Selects the text in specified range
String getSelectedText() Gets the selected text from textbox
int getSelectionStart() Gets starting position of selected
Text.
int getSelectionEnd() Gets ending position of selected
Text.
195
CCIT
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ExgApplet extends Applet implements ActionListener
{TextField t1,t2;
Button b;
public void init()
{ t1=new TextField(10);
add(t1);
b=new Button("Exchange");
add(b);
b.addActionListener(this);
t2=new TextField(10);
add(t2);
}
public void actionPerformed(ActionEvent e)
{ String temp=t1.getText();
t1.setText(t2.getText());
t2.setText(temp);
}
}
196
CCIT
class TextArea
TextAreas behave like TextFields except that they have more
functionality to handle large amounts of text .
TextArea can contain multiple rows of text.
TextArea have scrolls that permit handling of large amounts
of data.
Constructors Description
TextArea() Constructs new text area.
TextArea(int rows,int columns) Constructs new text area with
specified no. of rows and
columns.
TextArea(String text) Constructs new text area with
the specified text.
TextArea(String text, int rows,int Constructs new text area with
columns) specified text and specified no.
of rows and columns.
TextArea(String text, int rows,int Constructs new text area with
columns,int scrollbar) specified text and specified no.
of rows and columns
and visibility of the scrollbar.
Methods Description
void append(String str) Appends the given string to the
text area’s content.
int getColumns() Gets the no. of columns in the
text area.
int getRows() Gets the no. of rows in the text
area.
void insert(String str,int pos) Inserts the specified string at
the specified position.
void setColumns(int columns) Sets the no. of columns for the
text area
void setRows(int rows) Sets the no. of rows for the text
area
197
CCIT
Class Color
An object of this type represent Color.
This provide us different readymade Color object which we can
use.
public static final Color red;
public static final Color blue;
public static final Color green;
public static final Color white;
public static final Color black;
public static final Color yellow;
public static final Color orange;
public static final Color pink;
public static final Color magenta;
public static final Color cyan;
public static final Color lightGray;
public static final Color darkGray;
Constructor -
Color (int redcolor,int greencolor,int bluecolor)-
It create color object by intensity of red, green, blue . Intensity
must be in range 0 to 255.
or
198
CCIT
Class Checkbox
This class is used to create checkbox type object.
Constructor Description
Checkbox() It is used to create Checkbox
without label.
Checkbox(String label) It is used to create Checkbox
with specified label.
Checkbox(String label, boolean It is used to create Checkbox
state) with specified label and
state.(state can be true or
false).
Checkbox((String label, Both the constructor is used
CheckboxGroup g,boolean state) to create radiobuttons.
Checkbox((String label, boolean
state, CheckboxGroup g)
Methods Description
void setLabel(String label) It is used to set label on Checkbox.
String getLabel() It returns the label of the Checkbox.
boolean getState() It returns the state of the Checkbox.
setState(boolean b) It is used to set state of Checkbox.
public void This method tells the Checkbox to call
addItemListener(ItemListe a method “itemStateChanged when
ner l) checkbox state is changed.
Class CheckboxGroup
This class is used to group radiobutton and user can select
only one radiobutton in group.
Constructor Description
CheckboxGroup() It is used to create Checkbox
object.
Methods Description
Checkbox Returns the reference of the
getSelectedCheckbox()- checkbox object.
199
CCIT
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class pcBonusApplet extends
Applet implements ItemListener
{Label l1,l2;
TextField t1,t2;
Checkbox cb1,cb2,cb3;
Button b;
public void init()
{
l1=new Label("Enter Basic Salary"); add(l1);
t1=new TextField(10); add(t1);
cb1=new Checkbox("Add Bonus Rs 2000"); add(cb1);
cb2=new Checkbox("Add HRA Rs 1000"); add(cb2);
cb3=new Checkbox("Deduct ITax Rs 5000"); add(cb3);
b=new Button("Net Salary");
add(b); b.addActionListener(this);
t2=new TextField(10); add(t2);
}
public void actionPerformed(ActionEvent e)
{
int bs=Integer.parseInt(t1.getText());
if(cb1.getState())
bs=bs+2000;
if(cb2.getState())
bs=bs+1000;
if(cb3.getState())
bs=bs-5000;
t2.setText(String.valueOf(bs));
}
}
200
CCIT
201
CCIT
Class Scrollbar
Scrollbar are used to select a value between a specified
minimum and maximum.
The arrows at either end allow incrementing or decrementing the
value represented by the scrollbar.
The thumb’s position represents the value of the scrollbar.
The various constructors that can be used to create Scrollbar are :
Constructor Description
Scrollbar() Constructs a vertical scrollbar.
Scrollbar(int orientation) Constructs a new scrollbar with
the specified orientation
Scrollbar(int orientation,int Constructs a new scrollbar with
maxvalue,int visible,int the specified orientation ,initial
minimum,int maximum) value, page size,minimum and
maximum values.
Methods Description
int getValue() Gets the current value of scrollbar.
void Sets the block increment scroll bar.
setBlockIncrement(int v)
setMaximum(int n) Sets the maximum value scrollbar.
setMinimum(int n) Sets the minimum scrollbar.
setValue(int n) Sets the value of the scrollbar
public void This method tells the scrollbar to call the
addAdjustmentListener( special method
AdjustmentListener L) adjustmentValueChanged(AdjustmentEve
nt e) whe n the scrolling event occurs.
Interface AdjustmentListener
Methods of this interface is implemented to listen scrolling
events.
Methods -
public void adjustmentValueChanged(AdjustementEvent e) –
This method is called when scrolling event occurs.
202
CCIT
Class AdjustementEvent
Object of this contain information about that object which
has generated the scrolling events.
Methods –
Methods Description
int getValue() Returns the current thumb position.
Object getSource() Returns the reference of the object which has
generated the event.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class xscroll extends
Applet implements AdjustmentListener
{ Scrollbar s1,s2,s3;
public void init()
{s1= new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,255);add(s1);
s2= new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,255);add(s2);
s3= new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,255);add(s3);
s1.addAdjustmentListener(this);
s2.addAdjustmentListener(this);
s3.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{ int r=s1.getValue();
int g=s2.getValue();
int b= s3.getValue();
Color c= new Color (r,g,b);
setBackground (c);
showStatus(String.valueOf(r)+" , "+String.valueOf(g)+",
"+String.valueOf(b));
}
}
203
CCIT
LayoutManagers
Every container has a LayoutManager attached with it . Job
of the LayoutManager is to arrange the components which are
added in the container .Different LayoutManager are derived from
base class LayoutManager.
class FlowLayout
This LayoutManager arranges the component like words on a
page .i.e. from left to right and top to bottom. This is the default
LayoutManager of the container Applet.
Constructor Description
FlowLayout() LayoutManager with default Layout
center.
FlowLayout(int alignment) Will create a LayoutManager with
specified alignment.
FlowLayout(int alignment,int LayoutManager with specified
hgap,int vgap) alignment with specified hgap and
vgap between two components.
Alignment can be. LEFT , RIGHT, CENTER;
// applet containg a
button at top right
position
import java.awt.*;
import java.applet.*;
public class pcFLayout
extends Applet
{ Button b;
public void init()
{ FlowLayout f= new FlowLayout(FlowLayout.RIGHT);
setLayout(f);
b=new Button("OK");
add(b);
}
}
204
CCIT
class GridLayout
This LayoutManager arranges the components in a grid
fashion. i.e. in rows and columns.
Constructor Description
GridLayout(int rows, int Creates a grid of no. of rows and
columns) columns specified.
GridLayout(int rows, int with specified hgap and vgap
columns, int hgap,int vgap)
// applet containg 9 buttons arranged in 3 X 3
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class pcLMGrid extends Applet
implements ActionListener
{ Button b[];
public void init()
{ setLayout(new GridLayout(3,3,5,5));
b=new Button[9];
for(int i=0;i<b.length;i++)
{
b[i]=new Button(String.valueOf(i+1));
add(b[i]);
b[i].addActionListener(this);
}
}
public void actionPerformed(ActionEvent e)
{ String cmd=e.getActionCommand();
showStatus(cmd);
}
}
205
CCIT
class BorderLayout
This LayoutManager arranges the components along the
border and at the center of the container. While adding the
component we have to specify the constraint where we want to add
by calling method
add(Component c, Object constraint) –
constraint can be any of the
“North”,”South”,”West”,”East’,”Center”.
Constructor Description
BorderLayout() Arranges component along the
borders
BorderLayout(int hgap,int vgap) with specified hgap and vgap
//applet containg 2 buttons at
Top & Botttom
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class pcLMBorder extends
Applet implements ActionListener
{Button b1,b2;
public void init()
{ setLayout(new BorderLayout());
b1=new Button("OK");
add(b1,"North");
b1.addActionListener(this);
b2=new Button("Cancel");
add(b2,"South");
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ String cmd=e.getActionCommand();
showStatus(cmd);
}
}
206
CCIT
class CardLayout
This LayoutManager arranges the components like a dake of cards.
It creates each component like as large as container so only one
component is visible at a time.
Constructor Description
CardLayout()
CardLayout(int hgap,int vgap)
Methods Description
void next(Container parent) It will show next component from
container
void previous(Container will show previous component
parent)
void first(Container parent) It will show first component in
container
void last(Container parent) It will show last component in
container
import java.awt.*; //Example of LayoutManager CardLayout
import java.awt.event.*;
import java.applet.*;
public class pcLMCard extends Applet implements ActionListener
{Button b[];
String s[]={"SUN","MON","TUE","WED","THR","FRI","SAT"};
CardLayout cl;
public void init()
{ cl=new CardLayout();
setLayout(cl);
b=new Button[7];
for(int i=0;i<b.length;i++)
{ b[i]=new Button(s[i]);
add(b[i],"Center");
b[i].addActionListener(this); }
}
public void actionPerformed(ActionEvent e)
{ cl.next(this);
}}
207
CCIT
class Panel
Panel is a container in which we can add multiple
components.This class is derived from the class Component. So we
can add Panel into another container like component.
Constructor – Description
Panel() Create blank Panel object .
Panel(LayoutManager Create Panel object with given layout.
lm).
//Example of Panel
public class pcPanelApplet extends
Applet implements ActionListener
{ Button b[ ];
Label lbl;
Panel p;
Color co[ ]={Color.red, Color.orange, Color.yellow, Color.green,
Color.blue };
public void init()
{ setLayout(new BorderLayout());
lbl=new Label("CCIT",Label.CENTER);
add(lbl,"Center");
lbl.setFont(new Font("TimesRoman",Font.BOLD,100));
p=new Panel(new GridLayout(1,5,10,10));
add(p,"South");
b=new Button[5];
for(int i=0;i<b.length;i++)
{ b[i]=new Button(); p.add(b[i]);
b[i].addActionListener(this);
b[i].setBackground(co[i]);
}
}
public void actionPerformed(ActionEvent e)
{ Button bs=(Button)e.getSource();
Color cs=bs.getBackground();
lbl.setForeground(cs);
}}
208
CCIT
Windows application
We can built GUI application and for this we required
different window classes .Java provides us classes like
Frame,Dialog.
To create standard window we can use class Frame.
Class Frame –
This is used to create standard application window.
Default LayoutManager of the frame object is BorderLayout.
To close Frame without using WindowListener we can use a special
method of class System. System.exit(0);
Constructor Description
Frame() Create a blank Frame object without title.
Frame(String title) Create a Frame object with specified title.
Methods Description
void setTitle(String title) It is used to set title of Frame
object.
String getTitle() It returns the title of the Frame.
setMenuBar(MenuBar mb) It is used to attach MenuBar object.
void setResizable(Boolean b) It creates resizable or fixed window.
void setSize(int w,int h) Sets the size of the window.
void setVisible() It shows or hides the window.
209
CCIT
import java.awt.*;
import java.awt.event.*;
class pc
{
public static void main(String args[])
{
myFrame f=new myFrame();
f.setSize(400,200);
f.setVisible(true);
}
}
210
CCIT
Class MenuBar
This class is used to create MenuBar object.
Constructor Description
MenuBar() It will create a MenuBar object.
Methods Description
void add(Menu m) It will add specified menu in MenuBar object.
void remove(int n) It will remove menu from specified position.
int getMenuCount() Return total no. of menu in MenuBar.
Class Menu
This class is used to create pull down menu pane.
Constructor Description
Menu(String label) It will create Menu object with specified
label.
Methods Description
add(MenuItem mi) It will add MenuItem in menu.
int getItemCount() Returns total no. of MenuItems in menu.
void remove(int It remove menu at specified index.
index)
addSeperator() It is used to separate menus.
Class MenuItem
This class is used to create MenuItems which can be added
into MenuPane.
Constructor Description
MenuItem(String label) Create menu item with given label.
Methods Description
void addActionListener(Listener L) This method tells MenuItem to
call a special method
actionPerformed when
MentItem is selected.
void setLabel(String label) It is used to set label on
MenuItem.
211
CCIT
Class CheckboxMenuItem
This class is used to create MenuItem with check mark.
Constructor Description
CheckboxMenuItem(String Create checkbox menu item with
label) given label.
Methods Description
public void This method tells the menu item to
addItemListener(ItemListener call a special method
L) itemStateChanged when item is
selected.
Boolean getState() Returns the state of the menu item.
import java.io.*; //* WAP to create simple Menu with Open Option to
import javax.swing.*; // Open a File
import java.awt.*;
import java.awt.event.*;
class pcFrame extends Frame implements ActionListener
{MenuBar mb;
Menu mu1,mu2;
MenuItem mi;
TextArea ta;
public pcFrame()
{mb=new MenuBar();
this.setMenuBar(mb);
mu1=new Menu("File"); mb.add(mu1);
mi=new MenuItem("New");
mu1.add(mi);mi.addActionListener(this);
mi=new MenuItem("Open");
mu1.add(mi);mi.addActionListener(this);
mi=new MenuItem("Save");
mu1.add(mi);mi.addActionListener(this);
mi=new MenuItem("Exit");
mu1.add(mi);mi.addActionListener(this);
212
CCIT
mu2=new Menu("Edit");mb.add(mu2);
mi=new MenuItem("Copy");
mu2.add(mi);mi.addActionListener(this);
mi=new MenuItem("Cut");
mu2.add(mi);mi.addActionListener(this);
mi=new MenuItem("Paste");
mu2.add(mi);mi.addActionListener(this);
ta=new TextArea();
add(ta,"Center");
}
public void actionPerformed(ActionEvent e)
{
String cmd=e.getActionCommand();
if(cmd.equals("Exit"))
System.exit(0);
if(cmd.equals("Open"))
{
String fname=JOptionPane.showInputDialog(this,"Enter FileName");
try{
FileInputStream fin;
fin=new FileInputStream(fname);
int n=fin.available();
byte b[]=new byte[n];
fin.read(b);
fin.close();
String s=new String(b);
ta.setText(s);
}
catch(Exception er)
{ JOptionPane.showMessageDialog(this,er); }
}
}
}
213
CCIT
Interface WindowListener
Methods Description
public void This method is called when
windowOpened(WindowEvent e) first time window is called.
public void This method is called when
windowClosing(WindowEvent e) window is closed through
system menu.
public void This method is called when
windowClosed(WindowEvent e) window is closed by call to
hide.
214
CCIT
MouseListeners
To listen the events of mouse awt provides us two listeners .
1] MouseListener
2] MouseMotionListener
Interface MouseListener
Methods of this interface are implemented to listen mouse events
.
Methods Description
public void It is called when mouse button is
mousePressed(MouseEvent e) pressed.
public void when pressed mouse button is
mouseReleased(MouseEvent e) released
public void when mouse pointer entered in
mouseEntered(MouseEvent e) component.
public void when mouse button is clicked.
mouseClicked(MouseEvent e)
Interface MouseMotionListener
Methods of this interface is used to listen mouse motions.
Methods Description
public void This method is called when
mouseDragged(MouseEvent e) mouse is moved with button
pressed.
public void This method is called when
mouseMoved(MouseEvent e) mouse is moved.
215
CCIT
216
CCIT
class Dialog
This is the base class from which all dialog classes is derived.
import java.awt.*;
import java.awt.event.*;
class pcFrame extends Frame implements ActionListener
{ Button b1,b2; Label l;
public pcFrame()
{ b1= new Button("select Color");
add(b1,"North");
b2= new Button("exit");
add(b2,"South");
l= new Label("CCIT",Label.CENTER);
add(l,"Center");
217
CCIT
218
CCIT
Class FileDialog
The FileDialog class displays a dialog window from which the
user can select a file. Being a modal dialog , it blocks the rest of
the application until the user has choosen a file.
Constructor Description
FileDialog(Frame parent) Creates a file dialog for loading
a file.
FileDialog(Frame parent,String Creates a file dialog window
title) with the specified title for
loading a file.
FileDialog(Frame parent,String Creates a file dialog window
title,int mode) with the specified title for
loading a file or saving a file.
Methods Description
getDirectory() Gets the directory of the
corresponding file dialog.
getFile() Gets the file of the
corresponding file dialog.
getMode() Indicates whether the file dialog
is in the save mode or open
mode.
void setDirectory(String str) Sets the directory of the file
dialog window to the one
specified.
void setFile(String file) Sets the selected file for the
corresponding file dialog window
to the one specified.
void setMode(int mode) Sets the mode of the file dialog.
219
CCIT
Class MediaTracker
The MediaTracker class is a utility class to track the status of a
number of media objects. Media objects could include audio clips as
well as images, though currently only images are supported.
return image;
}
220
CCIT
221
CCIT
Adapter classes
An adapter class provides the default implementation of all
methods in an event listener interface. Adapter classes are very
useful when you want to process only few of the events that are
handled by a particular event listener interface.
An adapter class provides an empty implementation of all
methods in an event listener interface i.e this class itself write
definition for methods which are present in particular event listener
interface. However these definitions does not affect program flow
or meaning at all.
Adapter classes are useful when you want to receive and
process only some of the events that are handled by a particular
event listener interface. You can define a new class to act as an
event listener by extending one of the adapter classes and
implementing only those events in which you are interested.
E.g. Suppose you want to use MouseClicked Event or method
from MouseListener, if you do not use adapter class then
unnecessarily you have to define all other methods from
MouseListener such as MouseReleased, MousePressed etc.
But If you use adapter class then you can only define
MouseClicked method and don’t worry about other method
definition because class provides an empty implementation of all
methods in an event listener interface.
For eg:
1. WindowListener = > WindowAdapter
2. MouseListener => MouseAdapter
3. MouseMotionListener => MouseMotionAdapter
4. KeyListener => KeyAdapter
5. FocusListener => FocusAdapter
222
CCIT
Exception Handling
223
CCIT
Uncaught Exception
Before you learn how to handle exception in your
program, it is useful to see what happens when you
don’t handle them. This simple program includes an
expression that intentionally causes a divide by zero
error.
class ex
{
public static void mian(String args[])
{
int a=4/0;
}
}
224
CCIT
Checked Exception
225
CCIT
Unchecked Exception
NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException
226
CCIT
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception
class. The exception class is a subclass of the Throwable
class. Other than the exception class there is another
subclass called Error which is derived from the Throwable
class.
227
CCIT
Exceptions Methods:
Following is the list of important medthods available in the
Throwable class.
228
CCIT
try {
// block of code to moniter for errors.
}
catch(ExceptionType1 exob)
{
// exception handler for ExceptionType1
}
catch(ExceptionType2 exob)
{
// exception handler for ExceptionType2
}
//…
finally
{ //block of code to be executed before try block ends.
}
229
CCIT
Keyword throw –
It is used to throw an exception object manually (i.e. ourself).
Syntax – throw ExceptionObject
It throw program control into catch block of the method.(if corresponding
catch block is not found then it searches in its inner block this process
continue.)
Keyword finally –
The code which we want to compulsory execute is to be placed in a
finally block. The code present in this block is always executed regardless
of exception thrown or not. A finally block is defined after a try block.
Keyword throws –
If a method is decleared with this keyword then such a method has
to be called in try block.
(when we want to handle error at compile time then this keyword is
used.)
Exception Classes
JVM (java virtual machine) throws different type of exception object for
different type of errors.
ArrayIndexOutOfBoundException –
It is thrown when we try to access elements of an array outside its
bounds.
e.g. int a[]= new int[10];
for(i=0;i<=a.length ;i++) //error there is no element at position 10.
ClassNotFoundException-
An Exception object is thrown when class is not found.
230
CCIT
class err1
{
public static void main(String args[])
{
System.out.println(" before call" );
test(4,0);
System.out.println(" after call" );
System.out.println(" program end" );
}
231
CCIT
232
CCIT
233
CCIT
User-defined Exceptions:
You can create your own exceptions in Java. Keep the
following points in mind when writing your own exception
classes:
All exceptions must be a child of Throwable.
If you want to write a checked exception that is
automatically enforced by the Handle or Declare Rule, you
need to extend the Exception class.
If you want to write a runtime exception, you need to extend
the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception{
}
Common Exceptions
In Java, it is possible to define two catergories of Exceptions
and Errors.
234
CCIT
235
CCIT
The try block within a try block is known as nested try block in java.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e){System.out.println(
e);}
System.out.println("other statement);
}
catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
236
CCIT
Exception propagation
An exception is first thrown from the top of the stack and if it is
not caught, it drops down the call stack to the previous
method,If not caught there, the exception again drops down to
the previous method, and so on until they are caught or until
they reach the very bottom of the call stack.This is called
exception propagation.
For eg:
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
237
CCIT
throw vs throws
throw throws
Java throw keyword is used to Java throws keyword is used
explicitly throw an exception. to declare an exception.
238
CCIT
239
CCIT
I/O Streams
An I/O Stream represents an input source or an output destination.
A stream can represent many different kinds of sources and
destinations, including disk files, devices, other programs, and
memory arrays.
A stream is a sequence of
data.
InputStream: A program
uses an input stream to read
data from a source, one item
at a time:
OutputStream: A program
uses an output stream to write
data to a destination, one item
at time:
240
CCIT
Class File -
An object of this type represents a file or directory.
Constructors -
File(String path) -
File(String directorypath,String filename) -
File(String directorypath) -
File(File dir,String filename) -
Methods–
241
CCIT
class InputStream
Methods -
int read() - it reads a single byte from an InputStream and return
int value.
class FileInputStream
This class is derived from class InputStreeam .It provides
features to read data from an FileStream.
Constructors -
FileInputStream(String filename) -
FileInputStream (File f) -
242
CCIT
import java.io.*;
class file1
{public static void main(String args[]) throws Exception
{
int ch;
FileInputStream fin;
fin = new FileInputStream ("e://jdk1.3/bin/xscroll.java");
while((ch=fin.read())!=-1) //read a single byte
{ System.out.print((char) ch); // print char which is read as byte.
}
fin.close(); //close the file.
}
}
import java.io.*;
class file2
{
public static void main(String args[])throws Exception
{
FileInputStream fin;
fin = new FileInputStream ("e://jdk1.3/bin/xscroll.java");
int n=fin.available(); // get file size.
byte b[] = new byte[n]; //create a buffer of file size
fin.read(b); //read a buffer.
243
CCIT
Class OutputStream
It is an abstract class . Different OutputStream classes are
derived from this class.It provides us methods to write data into a
stream.
Methods -
void write(int b) - it writes a byte(i.e. a single byte) into a
OutputStream .
void write(byte b[]) - it will write all the bytes from byte[] into
OutputStream.
void write (byte b[],int offset,int n) - it writes n bytes starting
from specified offset from byte[] into OutputStream.
class FileOutputStream
This class is derived from class OutputStream .It provides
features to write data into FileStream.We can use all the methods
OutputStream class.
Constructors -
FileOutputStream(String filename) -
FileOutputStream (File f) -
244
CCIT
Class Reader
Abstract class for reading character streams. The only methods that
a subclass must implement are read(char[], int, int) and close().
Most subclasses, however, will override some of the methods
defined here in order to provide higher efficiency, additional
functionality, or both.
Methods
abstract close()
void Closes the stream and releases any system resources
associated with it.
int read()
Reads a single character.
int read(char[] cbuf)
Reads characters into an array.
abstract read(char[] cbuf, int off, int len)
int Reads characters into a portion of an array.
int read(CharBuffer target)
Attempts to read characters into the specified character buffer.
boolean ready()
Tells whether this stream is ready to be read.
void reset()
Resets the stream.
long skip(long n)
Skips characters.
245
CCIT
Class Writer
Abstract class for writing to character streams. The only
methods that a subclass must implement are write(char[], int, int),
flush(), and close(). Most subclasses, however, will override some
of the methods defined here in order to provide higher efficiency,
additional functionality, or both.
Methods
Writer append(char c)
Appends the specified character to this writer.
void close()
Closes the stream, flushing it first.
void flush()
Flushes the stream.
void write(int c)
Writes a single character.
246
CCIT
Class FileReader
This class inherits from the Reader class. FileReader is used
for reading streams of characters.
Constructors
FileReader(File file)
This constructor creates a new FileReader, given the File to
read from.
FileReader(String fileName)
This constructor creates a new FileReader, given the name
of the file to read from.
Class FileWriter
This class inherits from the Writer class. The class is used for
writing streams of characters.
Constructors
FileWriter(String fileName)
This constructor creates a FileWriter object, given a file
name.
247
CCIT
import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
248
CCIT
class PrintStream
A PrintStream provides a wrapper for an OutputStream. This
class provides us simple methods to write different types of values
in a OutputStream object.
Constructor –
PrintStream (OutputStream out) –
It creates a PrintStream object by wrapping a OutputStream object
in it.
Methods –
void print(String s) – Will print the String.
void print(int n) – Will print the integer value.
void println(String s) – Will print the String with line feed.
void println(int n) – Will print the integer value with line feed.
Similar methods for different datatypes……………
import java.io.*; //program to print int values int file mynos.txt
class Test
{ public static void main(String args[])throws Exception
{int a[]={5454,4534,1234,2345};
FileOutputStream fout= new FileOutputStream("c:/mynos.txt");
PrintStream ps= new PrintStream(fout);
for(int i=0;i<a.length;i++)
ps.println(a[i]);
ps.close();
fout.close();
}
}
249
CCIT
Class DataOutputStream
It provides us an wrapper to write different types of primitive
values into an OutputStream.
Constructor –
DataOutputStream(OutputStream out) –
Will create a DataOutputStream object by wrapping OutputStream
object in it.
Methods –
import java.io.*; // program to store int values in binary format into file
class Test
{public static void main(String args[])
{int a[]={5454,4534,1234,2345};
FileOutputStream fout= new FileOutputStream("c:/x1.txt");
DataOutputStream ds= new DataOutputStream (fout);
for(int i=0;i<a.length;i++)
ds.writeInt(a[i]);
ds.close();
fout.close();
}
}
250
CCIT
Class DataInputStream
It provides us an wrapper to read different types of primitive
values into an InputStream.
Constructor –
DataInputStream(InputStream in) –
Will create a DataInputStream object by wrapping InputStream
object in it.
Methods –
import java.io.*;
class Test
{public static void main(String args[])
{try{
File f= new File("c:/x1.txt");
int count = (int)f.length()/4; //total no. of elements.
FileInputStream fin= new FileInputStream(f);
DataInputStream din= new DataInputStream (fin);
for(int i=0;i<count;i++)
{int n=din.readInt(); //method of DataInputStream
System.out.println(n);
}
din.close();
fin.close();
}
catch(Exception er)
{ System.out.println("Error : "+er);
}
}
}
251
CCIT
Object Serialization
Serialization in java is a mechanism of writing the state of an
object into a byte stream.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types
and Java objects to an OutputStream. Only objects that support the
java.io.Serializable interface can be written to streams.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi");
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
252
CCIT
Deserialization
ObjectInputStream class
For eg:
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{
in.close();
}
}
253
CCIT
Multi Threading
254
CCIT
New: A new thread begins its life cycle in the new state. It
remains in this state until the program starts the thread. It
is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread
becomes runnable. A thread in this state is considered to be
executing its task.
Waiting: Sometimes, a thread transitions to the waiting
state while the thread waits for another thread to perform a
task.A thread transitions back to the runnable state only
when another thread signals the waiting thread to continue
executing.
Timed waiting: A runnable thread can enter the timed
waiting state for a specified interval of time. A thread in this
state transitions back to the runnable state when that time
interval expires or when the event it is waiting for occurs.
Terminated ( Dead ): A runnable thread enters the
terminated state when it completes its task or otherwise
terminates.
255
CCIT
Class Thread
Constructors
Thread() : Allocates a new Thread object.
Thread(Runnable) : Allocates a new Thread object.
Thread(Runnable, String) : Allocates a new Thread object.
Thread(String) : Allocates a new Thread object.
Methods
activeCount() : Returns the current number of active threads in
this thread group.
getPriority() : Returns this thread's priority.
isAlive() : Tests if this thread is alive.
isDaemon() : Tests if this thread is a daemon thread.
join() : Waits for this thread to die.
join(long) : Waits at most millis milliseconds for this thread to die.
join(long, int) : Waits at most millis milliseconds plus nanos
nanoseconds for this thread to die.
resume() : Resumes a suspended thread.
run() : If this thread was constructed using a separate Runnable
run object, then that Runnable object's run method is called;
otherwise, this method does nothing and returns.
setDaemon(boolean) : Marks this thread as either a daemon
thread or a user thread.
setName(String) : Changes the name of this thread to be equal to
the argument name.
setPriority(int) : Changes the priority of this thread.
sleep(long) : Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of
milliseconds.
start() : Causes this thread to begin execution; the Java Virtual
Machine calls the run method of this thread.
stop() : Forces the thread to stop executing.
stop(Throwable) : Forces the thread to stop executing.
suspend() : Suspends this thread.
yield() : Causes the currently executing thread object to
temporarily pause and allow other threads to execute.
256
CCIT
class demo{
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Thread Priorities:
Every Java thread has a priority that helps the operating
system determine the order in which threads are scheduled.
Java thread priorities are in the range between
MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a
constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a
program and should be allocated processor time before
lower-priority threads. However, thread priorities cannot
guarantee the order in which threads execute and very much
platform dependent.
257
CCIT
2. Now override the “public void run()” method and write your logic
there (This is the method which will be executed when this thread
is started).
That’s it, now you can start this thread as given below
class demo{
public static void main(String args[]){
MyRunnableTask t1=new MyRunnableTask ();
t1.start();
}
}
258
CCIT
Thread Synchronization
When using multiple threads, you must be very careful if you
allow more than one thread to access the same data structure.
Conside a Non Shareable object such as printer is being used by
multiple threads to print. Preventing this problem is called thread
synchronization. The basic technique for preventing two threads
from accessing the same object at the same time is to require a
thread to obtain a lock on the object before the thread can modify
it. While any one thread holds the lock, another thread that
requests the lock has to wait until the first thread is done and
releases the lock. Every Java object has the fundamental ability to
provide such a locking capability. The easiest way to keep objects
thread-safe is to declare all sensitive methods synchronized.
Thread Deadlock
Deadlock describes a situation where two or more threads are
blocked forever, waiting for each other. Deadlock occurs when
multiple threads need the same locks but obtain them in
different order. A Java multithreaded program may suffer
from the deadlock. Deadlock occurs when multiple threads
need the same locks but obtain them in different order.
259
CCIT
A process has separate virtual Threads are entities within a process. All
address space. Two processes threads of a process share its virtual
running on the same system at address space and system resources but
the same time do not overlap they have their own stack created.
each other.
Every process has its own data All threads created by the process share the
segment same data segment.
Child process creation within Threads can be created quite easily and no
from a parent process requires duplication of resources is required.
duplication of the resources of
parent process
260
CCIT
261
CCIT
262
CCIT
263
CCIT
264