JAVA-Notes
JAVA-Notes
4. Exception Handling 50
5. Multithreading 66
6. I/O Streams 86
7. Networking 102
❖❖❖❖
Course: TOPICS (Credits : 02 Lectures/Week:03)
USCS302 Core Java
Objectives:
The objective of this course is to teach the learner how to use Object Oriented paradigm to develop
code and understand the concepts of Core Java and to cover-up with the pre-requisites of Core java.
Expected Learning Outcomes:
1. Object oriented programming concepts using Java.
2. Knowledge of input, its processing and getting suitable output.
3. Understand, design, implement and evaluate classes and applets.
4. Knowledge and implementation of AWT package.
The Java Language: Features of Java, Java programming format, Java Tokens,
Java Statements, Java Data Types, Typecasting, Arrays
OOPS: Introduction, Class, Object, Static Keywords, Constructors, this Key
Word, Inheritance, super Key Word, Polymorphism (overloading and
15L
overriding), Abstraction, Encapsulation, Abstract Classes, Interfaces
String Manipulations: String, String Buffer, String Tokenizer
Packages: Introduction to predefined packages (java.lang, java.util, java.io,
java.sql, java.swing), User Defined Packages, Access specifiers
Exception Handling: Introduction, Pre-Defined Exceptions, Try-Catch-Finally,
Throws, throw, User Defined Exception examples
Multithreading: Thread Creations, Thread Life Cycle, Life Cycle Methods,
Synchronization, Wait() notify() notify all() methods
15L
I/O Streams: Introduction, Byte-oriented streams, Character- oriented streams,
File, Random access File, Serialization
Networking: Introduction, Socket, Server socket, Client –Server
Communication
Wrapper Classes: Introduction, Byte, Short, Integer, Long, Float, Double,
Character, Boolean classes
Collection Framework: Introduction, util Package interfaces, List, Set, Map,
List interface & its classes, Set interface & its classes, Map interface & its classes
Inner Classes: Introduction, Member inner class, Static inner class, Local inner
class, Anonymous inner class
AWT: Introduction, Components, Event-Delegation-Model, Listeners, Layouts, 15L
Individual components Label, Button, CheckBox, Radio Button, Choice, List,
Menu, Text Field, Text Area
Textbook(s):
1) Herbert Schildt, Java The Complete Reference, Ninth Edition, McGraw-Hill Education, 2014
Additional Reference(s):
1) E. Balagurusamy, Programming with Java, Tata McGraw-Hill Education India, 2014
2) Programming in JAVA, 2nd Ed, Sachin Malhotra & Saurabh Choudhary, Oxford Press
3) The Java Tutorials: http://docs.oracle.com/javase/tutorial/
1
THE JAVA LANGUAGE
Unit Structure
1.0 Objectives
1.1 Features of Java
1.2 Java programming format
1.3 Summary
1.4 Textbook
1.5 Additional References
1.6 Questions
1.0 OBJECTIVES:
The objective of this chapter is to learn the basic building blocks of java
and understand the concepts of Core Java and to cover-up with the pre-
requisites of Core java, Advanced Java, J2EE and J2ME.
Topics:
Features of Java, Java programming format, Java Tokens, Java
Statements, Java Data Types, Typecasting, Arrays
➢ Secure, Portable and Robust: Java programs are safe and secure to
download from internet. At the core of the problem is the fact that
malicious code can cause its damage due to unauthorized access gained to
system resources. Java achieved this protection by confining a program to
the Java execution environment and not allowing it access to other parts of
the computer. The same code must work on all computers. Therefore,
some means of generating portable executable code was needed. The
multi-platform environment of the Web places extraordinary demands on
a program, because the program must execute reliably in a variety of
1
Core JAVA systems. Thus, the ability to create robust programs was given a high
priority in the design of Java. To gain reliability, Java restricts a few key
areas and forces to find your mistakes early in program development. At
the same time, Java frees a programmer from having to worry about many
of the most common causes of programming errors.
2
1.2 JAVA PROGRAMMING FORMAT The Java Language
Example:
// ----- 1 Package Section -------
Package mypack;
// -------- 2 Import Section -------
import java.util.Date; // This line will import only one class from the util
package
import java.awt.*; // This line will import all classes available in awt
package
// ----------- 3 Class / Interface Section ----------
class A {
// Class Body
}
interface B {
// Interface Body
}
// ----------- 4 Main Method Section ----------
public class Test{
public static void main(String[] args){
// body of main method
}
}
3
Core JAVA 2 Java Tokens
Tokens are the basic building blocks of the java programming language
that are used in constructing expressions, statements and blocks. The
different types of tokens in java are:
• All variable names must begin with a letter of the alphabet. The
dollar sign and the underscore are used in special case.
• After the first initial letter, variable names may also contain letters
and the digits 0 to 9. No spaces or special characters are allowed.
4
• Java keyword (reserved word) cannot be used for a variable name. The Java Language
[] Brackets Used to declare array types. Also used when dereferencing array
values.
3 Java Statements
A statement specifies an action in a Java program. Statements in Java can
be broadly classified into three categories:
5
Core JAVA
1. Declaration
A declaration statement is used to declare a variable, method or class.
For example: int num;
double PI = 3.14;
String name=”University of Mumbai;
int showResult(int a, int b);
2. Expression
An expression is a construct made up of variables, operators, and method
invocations, which are constructed according to the syntax of the
language, that evaluates to a single value.
Arithmetic Expression: ( A + B ) * C - ( D % E ) * ( - F + G )
Logical Expression: ~(m > n && x < y) != (m <= n || x >= y)
3. Flow Control
By default, all the statements in a java program are executed in the order
they appear in the program code. However sometime a set of statements
need to be executed and a part to be skipped, also some part need to be
repeated as long as a condition is true or till some fix number of iteration.
Java programming language uses flow control statements to cause the flow
of execution to advance and branch based on changes to the state of a
program. Java’s program control statements can be put into the following
categories: Branching / selection, Looping / iteration, and jump control.
Selection statements allow your program to choose different paths of
execution based upon the outcome of an expression or the state of a
variable. Iteration statements enable program execution to repeat one or
more statements (that is, iteration statements form loops). Jump statements
allow your program to execute in a nonlinear fashion.
6
I. Selection / Branching: The Java Language
Java supports two selection statements: if and switch. These statements
allow you to control the flow of your program’s execution based upon
conditions known only during run time.
➢ if
The if statement is Java’s conditional branch statement. It can be used to
route program execution through two different paths.
General Syntax:
if (condition)
statement1 / { if Block };
else
statement2 / { else Block};
Here, each statement may be a single statement or a compound statement
enclosed in curly braces (that is, a block). The condition is any expression
that returns a boolean value. The else clause is optional.
Example:
class ifelsetest{
public static void main(String[] args){
int num=10;
if(num%2 == 0){
System.out.println(“Number is EVEN”);
}
else {
System.out.println(“Number is ODD”);
}
}
}
➢ switch
The switch statement is Java’s multiway branch statement. It provides an
easy way to dispatch execution to different parts of your code based on the
value of an expression. As such, it often provides a better alternative than
a large series of if-else-if statements.
General Syntax:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
8
. The Java Language
casevalueN :
//statement sequence break;
default:
// default statement sequence
}
For versions of Java prior to JDK 7, expression must be of type byte,
short, int, char, or an enumeration. JDK 7 onwards the switch expression
can also be of type String.
Example:
class switchcasetest{
public static void main(String[] args){
int num=10;
switch(num){
case 1:
System.out.println(“Monday”);
break;
case 2:
System.out.println(“Tuesday”);
break;
case 3:
System.out.println(“Wednesday”);
break;
case 4:
System.out.println(“Thursday”);
break;
case 5:
System.out.println(“Friday”);
break;
case 6:
System.out.println(“Saturday”);
break;
case 7:
System.out.println(“Sunday”);
break;
9
Core JAVA default:
System.out.println(“~~~ Invalid Week day No ~~~~”);
break;
}
}
}
➢ while
The while loop is Java’s most fundamental loop statement. It repeats a
statement or block while its controlling expression is true.
General Syntax:
while(condition)
{
// body of loop
}
The condition in java must be strictly a Boolean expression. The body of
the loop will be executed as long as the conditional expression is true.
When condition becomes false, control passes to the next line of code
immediately following the loop. The curly braces are unnecessary if only a
single statement is being repeated.
Examples:
public class WhileDemo
{
public static void main(String args[])
{ int n = 10;
while(n > 0)
{
System.out.println("Count Doun Value" + n);
n - -;
10
} The Java Language
}
}
➢ do-while
Sometimes it is desirable to execute the body of a loop at least once, even
if the conditional expression is false to begin with. In other words, there
are times when you would like to test the termination expression at the end
of the loop rather than at the beginning. Java provides a loop that does just
that: the do-while. The do-while loop always executes its body at least
once, because its conditional expression is at the bottom of the loop.
General Syntax:
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and
then evaluates the conditional expression. If this expression is true, the
loop will repeat. Otherwise, the loop terminates. As with all of Java’s
loops, condition must be a Boolean expression.
Examples:
public class DoWhileDemo
{
public static void main(String args[])
{ int n = 10;
do{
System.out.println("Loop Executed Once even if condition is False" );
n - -;
} while(n > 10) ;
}
}
➢ For
The for loop operates as follows. When the loop first starts, the
initialization portion of the loop is executed. Generally, this is an
expression that sets the value of the loop control variable, which acts as a
counter that controls the loop. It is important to understand that the
11
Core JAVA initialization expression is executed only once. Next, condition is
evaluated. This must be a Boolean expression. It usually tests the loop
control variable against a target value. If this expression is true, then the
body of the loop is executed. If it is false, the loop terminates. Next, the
iteration portion of the loop is executed. This is usually an expression that
increments or decrements the loop control variable. The loop then iterates,
first evaluating the conditional expression, then executing the body of the
loop, and then executing the iteration expression with each pass. This
process repeats until the controlling expression is false.
General Syntax:
for(initialization; condition; increment / decrement expression)
{
// loop body
}
Examples:
public class ForDemo
{
public static void main(String args[])
{
for(int x = 1 ; x <=10 ; x++)
{
System.out.println("Loop Variable Value is : " + x);
}
}
}
There will be times when you will want to include more than one
statement in the initialization and iteration portions of the for loop.
Example:
public class TwoVarFor
{
public static void main(String args[]) {
int a, b ;
for(a=1, b=4; a<= b; a++, b--){
System.out.println(“value of A is : “+a+” Value of B is : “+b);
}
}}
12
➢ The For-Each Loop The Java Language
A for-each loop by using the keyword for-each, Java adds the for-each
capability by enhancing the for statement. The advantage of this approach
is that no new keyword is required, and no pre-existing code is broken.
The for-each style of for is also referred to as the enhanced for loop.
General Syntax
for( type itr-var : collection)
{
// statement-block;
}
Example:
public class ForEachDemo {
public static void main(String args[])
{ String names[] = {“Mumbai”, “Pune”, “Nagpur”, “Aurangabad”,
“Thane”, “Nasik” };
for (String x : names)
{ System.out.println("Name of the City in Maharashtra is: " + x);
}
System.out.println("~~~~Printing on City Names Done~~~~~”; }
}
III. Jump Control Statement
Java supports three jump statements: break, continue, and return. These
statements transfer control to another part of a java program.
In Java, the break statement has three uses. First, as you have seen, it
terminates a statement sequence in a switch statement. Second, it can be
used to exit a loop. Third, it can be used as a form of goto statement in
C/C++.
Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the remainder
of the code in its body for this particular iteration. This is, in effect, a goto
just past the body of the loop, to the loop’s end. The continue statement
performs such an action. In while and do-while loops, a continue
statement causes control to be transferred directly to the conditional
expression that controls the loop. In a for loop, control goes first to the
iteration portion of the for statement and then to the conditional
expression. For all three loops, any intermediate code is bypassed.
The last control statement is return. The return statement is used to
explicitly return from a method. That is, it causes program control to
transfer back to the caller of the method.
13
Core JAVA 4 Java Data Types
The Primitive Types: Java defines eight primitive types of data: byte,
short, int, long, char, float, double, and boolean. The primitive types are
also commonly referred to as simple types.
The smallest integer type is byte. Variables of type byte are especially
useful when you’re working with a stream of data from a network or file.
They are also useful when you’re working with raw binary data that may
not be directly compatible with Java’s other built-in types. The most
commonly used integer type is int. long is a signed 64-bit type and is
useful for those occasions where an inttype is not large enough to hold the
desired value.
14
3. Characters This group includes char, which represents symbols in The Java Language
a character set, like letters and numbers. C++ char is 8 bit i.e. 256 symbols
while java char uses 16 bit i.e. 65536 symbols to represent Unicode
characters. Unicode defines a fully international character set that can
represent all of the characters found in all human languages and is a
unification of character sets, such as Latin, Greek, Arabic, Cyrillic
Hebrew, Katakana, Hangul, and many more. There is no signed char in
java. char can also be used as an integer type on which you can perform
arithmetic operations.
Example: if char ans =’A’ then ans = ans + 5 will result ‘F’.
5 Typecasting
As a part of Java’s safety and robustness Java is a strongly typed language.
Every variable has a type, every expression has a type, all assignments,
whether explicit or via parameter passing in method calls is checked for
type compatibility and every type is strictly defined. There are no
automatic coercions or conversions of conflicting types. If the two types
are compatible and the target type is equal to or larger than the source type
JVM performs automatic type conversion. This type of conversion is also
called implicit conversion or automatic type casting or widening
conversion.
byte→ short →int→ long or int→ float → double
If the two types are incompatible and the target type is smaller than the
source type then typecasting is required conversion. This type of
conversion is also called explicit conversion or manual type casting or
narrowing conversion.
15
Core JAVA
6 Arrays
An array is a collection of similar data type, identified by a common name
and stored in consecutive memory location. Array elements can be
conveniently accessed using index number. Java arrays are reference type.
A one-dimensional array is a list of like typed variables. The general form
of a one-dimensional array declaration is
1.3 SUMMARY:
The chapter helps to learn the features of java language, the format of java
program, basic building blocks of java and understand the concepts of
Core Java and to cover-up with the pre-requisites of Core java, Advanced
Java, J2EE and J2ME.
1.4 TEXTBOOKS:
1) Herbert Schildt, Java The Complete Reference, Ninth Edition,McGraw-
Hill Education, 2014
1.5 ADDITIONAL REFERENCES:
1) E. Balagurusamy, Programming with Java, Tata McGraw-Hill
Education India, 2014
2) Programming in JAVA, 2nd Ed, Sachin Malhotra &SaurabhChoudhary,
Oxford Press
1.6 QUESTIONS:
1. Explain the feature of Java
2. Explain the For-Each Loop with example?
❖❖❖❖
17
OOPS
Unit Structure
2.0 Objectives
2.1 Introduction
2.2 Class
2.3 Object
2.4 Static Keywords
2.5 Constructors
2.6 this Key Word
2.7 Inheritance
2.8 super Keyword
2.9 Polymorphism (overloading and overriding)
2.10 Abstraction
2.11 Encapsulation
2.12 Abstract Classes
2.13 Interfaces
2.14 Summary
2.15 Textbook
2.16 Additional References
2.17 Questions
2.0 OBJECTIVES
The objective of this chapter is to learn the basic concepts of Object
Oriented Programming and its implementation in java to develop the code
to cover-up with the pre-requisites of Core java, Advanced Java, J2EE and
J2ME.
Topics:
2.1 INTRODUCTION
Object oriented programming implements object oriented model in
software development.OOP is based on three principles i.e. Encapsulation,
Inheritance and polymorphism.OOP allows decomposing a large system
into small object.
18
Encapsulationis the mechanism of binding together code and the data it OOPS
manipulates, and keeps both safe from outside interference and misuse. It
is like a protective wrapper that prevents the code and data from being
arbitrarily accessed by other code defined outside the wrapper. Access to
the code and data inside the wrapper is tightly controlled through a well-
defined interface.
Inheritance is the process by which one object acquires the properties of
another object. It is a way of making new classes using existing one and
redefining them.
Polymorphism (Greek meaning “many forms”) is a feature that allows one
interface to be used for a general class of actions. More generally, the
concept of polymorphism is often expressed by the phrase “one interface,
multiple methods.” This means that it is possible to design a generic
interface to a group of related activities. This helps reduce complexity by
allowing the same interface to be used to specify a general class of action.
2.2 CLASS
A class is a blue print for creating objects. A class is a group of objects
which have common properties.A classdefines the data and code that can
be shared by a set of objects. Each object of a given class contains the
structure and behavior defined by the class, as if it were stamped out by a
mold in the shape of the class.
19
Core JAVA The data, or variables, defined within a class are called instance variables.
The code is contained within methods. The methods, constants and
variables etc. defined within a class are called members of the class.
2.3 OBJECT
An entity that has state and behavior is known as an object. An object has
three characteristics:
• State: represents the data or value of an object.
• Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
• Identity: An object identity is a unique ID.
An object represents a class during program execution. Thus, a class is a
template for an object, and an object is an instance of a class. Because an
object is an instance of a class, you will often see the two words object and
instance used interchangeably.
There are five different ways to create objects in java:
Using new keyword:
Complex com = new Complex(10, 20);
1. Using Class.forName():
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
2. Using clone():
Complex com1 = com.clone();
3. Using Object Deserialization
ObjectInputStreamois =new objectInputStream(some data);
MyObject object=(MyObject) instream.readObject();
Using newIntance() method
Object obj =
DemoClass.class.getClassLoader().loadClass("DemoClass").new
Instance ();
2.4 STATIC KEYWORDS
Static is a non-access modifier in Java, it is used with variables, methods,
blocks and nested class. It is a keyword that are used for share the same
variable or method of a given class. This is used for a constant variable or
a method that is the same for every object of a class. The main method of
a class is generally labeled static. The static keyword is used in java
mainly for memory management. No object needs to be created to use
static variable or call static methods, just put the class name before the
static variable or method to use them. Static method cannot call non-static
method. The static variable allocate memory only once in class area at the
time of class loading. It is use to make our program memory efficient.
20
When a variable is declared as static, then a single copy of variable is OOPS
created and shared among all objects at class level. Static variables are,
essentially, global variables. All instances of the class share the same
static variable and can be created at class-level only.
When a method is declared with static keyword, it is known as static
method. The most common example of a static method is main( ) method.
Any static member can be accessed before any objects of its class are
created, and without reference to any object. Methods declared as static
can only directly call other static methods and can only directly access
static data. They cannot refer to this or super.
2.5 CONSTRUCTORS
A constructor initializes an object at the time of creation. It has the same
name as the class in which it resides. The constructor is automatically
called when the object is created, before the newoperator completes.
Constructors have no return type, not even void. This is because the
implicit return type of a class’ constructor is the class type itself. It is the
constructor’s job to initialize the internal state of an object so that the code
creating an instance will have a fully initialized, usable object
immediately.
There are three rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Default constructor: If not implemented any constructor by the
programmer in a class, Java compiler inserts a default constructor with
empty body into the code, this constructor is known as default constructor.
If user defines any parameterized constructor, then compiler will not
create default constructor and vice versa if user don’t define any
constructor, the compiler creates the default constructor by default during
compilation
Eg:
Program code Compile time
class complex{ class complex{
} complex(){
}
}
}
Parameterized constructor: Constructor with arguments is known as no-arg
constructor. The signature is same as default constructor; however body
can have any code unlike default constructor where the body of the
constructor is empty.
class complex {
inta,b,c;
public complex (int r, inti){
real=r;
img=i;
}
}
Copy Constructor: Values from one object to another object can be
copied using constructor or by clone() method of Object class.
A copy constructor is a parameterized constructor but the parameter is the
reference of containing class.
class complex {
inta,b,c;
public complex (complex c){
real=c.real; img=c.img;
}
22
Difference between constructor and method in Java OOPS
The constructor name must be The method name may or may not be
same as the class name. same as class name.
23
Core JAVA
2.6 THIS KEY WORD
“this” is a reference to object itself. ‘this’ keyword can be used to refer
current class instance variables, to invoke current class constructor,
to return the current class instance, as method parameter, to invoke
current class method and as an argument in the constructor call.
“this” keyword when used in a constructor can only be the first statement
in Constructor and constructor can have either this or super keyword but
not both.
class A{
int a=10;
public void show(){
double a=100.200;
System.out.println(“Value of A is : “+a);
}
}
The above program code will display “Value of A is : 100.200”, because
the preference will always go to local variable or the variable with
immediate scope.
System.out.println(“Value of A is : “+this.a);
The above statement will display “Value of A is: 10”, because the
reference “this” will point to current instance variable “a” of the class.
class A{
A(){
this(111);
System.out.println(“ Default Constructor Called …..”);
}
A(int a){
System.out.println(“ Parameterized Constructor Called”);
}
}
The call A obj = new A() will create an object of “A” using default
constructor and will also call the parameterized constructor by passing
value 111 using “this”.
24
2.7 INHERITANCE OOPS
25
Core JAVA Java supports multiple inheritance using Interfaces:
“super” is the reference to the parent class. Super keyword can be used to
access parent class variable, method and to invoke parent class
constructor.
26
class A{ OOPS
String var=”ANAAS”; }
class B extends A{
String var=”AARISH”;}
public void show(){
String var=”NASHRAH”;
System.out.println(“Variable value is :”+var):
System.out.println(“Variable value is :”+this.var):
System.out.println(“Variable value is :”+super.var):
}}
In the above example var refer to the local context, this refer to the class
variable and super will refer to super class member.
• super keyword can only be the first statement in Constructor.
• A constructor can have either this or super keyword but not both.
class A{
A(){System.out.println(“Hello at A”);}
A(String name){System.out.println(name+ “ Hello at A”);}}
class B extends B{
B(String name){System.out.println(name+ “ Hello at B”);}}
}
27
Core JAVA
2.9 POLYMORPHISM (OVERLOADING AND
OVERRIDING)
Method Overloading is a mechanism in which a class allows more than
one method with same name but with different prototype. Multiple
methods can be created by changing the no. of parameters, type of
parameters, order of parameters or combination of any. The method
binding is done by the compiler at compile time and fix the calling method
based on the actual parameter matching or by using implicit type
conversion. This is also called as static binding, early binding or compile
time polymorphism.
Class MyMath{
public void add(){System.out.println(“Addition of 10 and 20 is
“+(10+20));}
public void add (int n1, int n2){ System.out.println(n1+n2); }
public void add (double n1, double n2){ System.out.println(n1+n2); }
public void add (int n1, double n2){ System.out.println(n1+n2); }
public void add (double n1, int n2){ System.out.println(n1+n2); }
public void add (Complex n1, Complex n2){ System.out.println(n1+n2);
}}
Method Overriding is a mechanism in which a method in a child class that
is already defined in the parent class with the same method signature —
same name, arguments, and return type. Method overriding is used to
provide the specific implementation of a method which is already
provided by its superclass. The method binding is done by the java
interpreter at run time and fix the calling method based on the latest
implementation in class hierarchy. This is also called as dynamic binding,
late binding or run time polymorphism.
class MyClass1{
public void add(int a, int b){ return a+b;}
}
class MyClass2 extends MyClass1{
@override
public void add(int a, int b){ return 5*a+50*b; }
}
@override annotation tells the compiler that the method is meant to
override a method declared in a superclass.
28
Overloading Overriding OOPS
1 More than one method with same More than one method with same
name but different signature in name and same signature in
same scope. different scope.
2 Parameters are different Parameters are same
3 Binding at compile time Binding at run time.
4 Method return type may or may Method return type should be
not be same same.
5 Allowed for static method Not allowed for static method
6 Cannot be prevented Can be prevented by declaring a
method as static or final.
7 Occurs in same class. Occurs in sub class.
2.10 ABSTRACTION
Abstraction is a process of hiding the implementation details and showing
only functionality to the user. Abstraction is selecting data from a larger
pool to show only the relevant details to the object. It helps to reduce
programming complexity and effort. In Java, abstraction is accomplished
using Abstract classes and interfaces. Abstraction can be achieved using
Abstract Class and Abstract Method in Java.
2.11 ENCAPSULATION
Classes and packages are both means of encapsulating and containing the
name space and scope of variables and methods. Packages act as
containers for classes and other subordinate packages. Classes act as
containers for data and code. The class is Java’s smallest unit of
abstraction. Because of the interplay between classes and packages, Java
addresses four categories of visibility for class members:
• Subclasses in the same package
2.13 INTERFACES
An interface is like a class but, it has static constants and abstract methods
only. An interface in java is a blueprint of a class. The interface in Java is
a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body.
An interface is declared using interface keyword. It is used to provide
total abstraction. That means all the methods in interface are declared with
empty body and are public and all fields are public, static and final by
default. A class that implement interface must implement all the methods
declared in the interface. To implement interface use implements
keyword.
Interface can extend another interface. Java allows multiple inheritance
using interface.
30
interface<interface_name> [extends [Interface_name]]{ OOPS
// fields
// Methods
}
Example:
Interface MyMath{
2.14 SUMMARY:
The chapter helps to learn the concept of OOPS, like Classes, Inheritance,
the keywords associated with OOP, implementation of polymorphism and
Abstraction in java.
31
Core JAVA
2.15 TEXTBOOK(S):
1) Herbert Schildt, Java The Complete Reference, Ninth Edition,
McGraw-Hill Education, 2014
2.17 QUESTIONS:
1. What is interface? Explain with example?
2. Write a short note on abstarct class?
3. Explain the difference between Overloading & Overiding.
4. Exaplain the Difference between constructor and method in Java.
❖❖❖❖
32
3
STRING MANIPULATIONS AND
INTRODUCTION TO PACKAGES
Unit Structure
3.0 Objectives
3.1 String Manipulations
3.2 Packages
3.3 Summary.
3.4 Textbook
3.5 Additional Reference(s)
3.6 Questions:
3.0 OBJECTIVES:
The objective of this chapter is to learn the classes used in string
manipulation. The different methods associated with string manipulation.
String is a commonly used in many desktop and web application and has a
wide range of applications. The chapter further introduces the concept of
Package and access specifiers.
3.1.2 String
Any string variable decalred represents and object of Java.lang.String
class. A string can be declared using a sequence of characters enclosed in
double quotes or can be initialized using different constructors of String
class.
33
Core JAVA Constructors:
String()
Create a string object without any content.
String(char chars[ ])
Creates an string object using array of characters.
String(char chars[ ], intstartIndex, intnumChars)
Creates a string object using selected range of characters from array.
String(byte chrs[ ])
Creates a string object using array of bytes.
String(byte chrs[ ], intstartIndex, intnumChars)
Creates a string object using selected range of byte from array.
String(String strObj)
Creates a string object using another string.
Methods:
String S1 = “Monu, Saru, Yes Mama, Eating Sugar, No Mama!!”
String S2=”Yellow Color Yellow Color Where are you? Here I am ..”
Modifier
and Method and Description
Type
charAt(int index)
char Returns the char value at the specified index.
s1.charAt(2) will return ‘n’
compareTo(String anotherString)
Compares two strings lexicographically.
int “ABCD”.compareTo(“ABXY”) will math A, B then calculate
the difference between first unmatched character X – C ie 88-67
= 22 is the result.
compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case
int
differences.
Same as above but comparison will ignore case differences.
concat(String str)
Concatenates the specified string to the end of this string.
String
“Abcd”.concat(“Xyz”) will result “AbcdXyz”, can also be
done using “+” operator.
copyValueOf(char[] data)
static
String Returns a String that represents the character sequence in the
array specified.
34
copyValueOf(char[] data, int offset, int count) String Manipulations and
static Introduction to Packages
Returns a String that represents the character sequence in the
String
array specified.
endsWith(String suffix)
Tests if this string ends with the specified suffix.
boolean
S1.endsWith(“Mama”) will return true. And
S2.endsWith(“Mama”) will return false.
equals(Object anObject)
boolean Compares this string to the specified object.
S1.equals(“mypassword”) will return false.
equalsIgnoreCase(String anotherString)
boolean Compares this String to another String, ignoring case
considerations.
getBytes()
byte[] Encodes this String into a sequence of bytes using the platform's
default charset, storing the result into a new byte array.
getBytes(String charsetName)
byte[] Encodes this String into a sequence of bytes using the named
charset, storing the result into a new byte array.
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
void Copies characters from this string into the destination character
array.
indexOf(int ch)
Returns the index within this string of the first occurrence of the
int
specified character.
S1.indexOf(‘M’); will return 0
indexOf(String str)
Returns the index within this string of the first occurrence of the
int
specified substring.
S1.indexOf(“Mama”); will return 15
indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the
int
specified character, starting the search at the specified index.
S1.indexOf(‘M’,5); will return 15
isEmpty()
boolean
Returns true if, and only if, length() is 0.
lastIndexOf(int ch)
int Returns the index within this string of the last occurrence of the
specified character.
35
Core JAVA S1.lastIndexOf(‘M’) will return 40
lastIndexOf(String str)
Returns the index within this string of the last occurrence of the
int
specified substring.
S1.lastIndexOf(“Mama”) will return 40
length()
int Returns the length of this string.
S1.length(‘Mama’) will return 45
replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of
String
oldChar in this string with newChar.
“a for apple”.replace(‘a’,’@’) will return @ for @pple
startsWith(String prefix)
boolean
Tests if this string starts with the specified prefix.
startsWith(String prefix, int toffset)
boolean Tests if the substring of this string beginning at the specified
index starts with the specified prefix.
substring(int beginIndex)
String Returns a new string that is a substring of this string.
S1.substring(25) will return “ting Sugar, No Mama!!”
substring(int beginIndex, int endIndex)
String Returns a new string that is a substring of this string.
S1.substring(25, 33) will return “ting Sugar”
toCharArray()
char[]
Converts this string to a new character array.
toLowerCase()
Converts all of the characters in this String to lower case using
String the rules of the default locale.
S1.to LowerCase() will return “monu, saru, yes mama, eating
sugar, no mama!!”
toUpperCase()
Converts all of the characters in this String to upper case using
String the rules of the default locale.
S1.to UpperCase() will return “MONU, SARU, YES MAMA,
EATING SUGAR, NO MAMA!!”
trim()
Returns a copy of the string, with leading and trailing
String
whitespace omitted.
“ AnuAruNash “.trim() will return “AnuAruNash”
36
3.1.3 String Buffer String Manipulations and
Introduction to Packages
StringBuffer class represents a mutable string that is growable and
writable character sequences. StringBuffermay have characters and
substrings inserted in the middle or appended to the end. StringBuffer will
automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow room for growth.
Constructors
StringBuffer defines these four constructors:
StringBuffer( )
Creates a StringBuffer object with empty contents and has an initial
capacity of 16 characters.
StringBuffer(intcapacity)
Creates a StringBuffer object with empty contents with specified capacity.
StringBuffer(String str)
Creates a StringBuffer object with specified contents and has an initial
capacity of 16 characters.
Modifier
Method and Description
and Type
37
Core JAVA
index Of(String str, int fromIndex)
int Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.
insert(int offset, char c)
StringBuf
fer Inserts the string representation of the char argument into this
sequence.
38
3.1.4 String Tokenizer String Manipulations and
Introduction to Packages
The String Tokenizer class from java.util package provides the first step
in parsing process, called the lexer, lexical analyzer or scanner. Parsing is
the division of text into a set of discrete parts or tokens. String
tokenization is a process where a string is broken into several parts. Each
part is called a token. For example, if "Anu, Aru, Nash, Yes Mama" is a
string, the discrete parts—such as, "Anu,""Aru," “Nash” “Yes” and "
Mama" aretokens.
Constructors:
StringTokenizer(String str)
Creates an object using String to be tokenized and space as delimiter
excluding space from token.
StringTokenizer(String str, String delimiters)
Creates an object using String to be tokenized and second argument as
delimiter excluding space from token.
StringTokenizer(String str, String delimiters, booleandelimAsToken)
Creates an object using String to be tokenized and second argument as
delimiter excluding space from token as specified by true/false.
String S1 = “Anu, Aru, Nash, Yes Mama, Eating Sugar, No Mama!!”
Stk = StringTokenizer(S1)
Method Description
int countTokens()
Calculates the number of times that this tokenizer'snextToken
method can be called before it generates an exception.
stk.countTokens() will return 8
boolean hasMoreElements()
Returns the same value as the hasMoreTokens method.
boolean hasMoreTokens()
Tests if there are more tokens available from this tokenizer's
string.
Object nextElement()
Returns the same value as the nextToken method, except that its
declared return value is an Object rather than a String.
39
Core JAVA
String nextToken()
Returns the next token from this string's tokenizer.
stk.nextToken() will return “Anu,”
stk.nextToken() will return “Aru, “
String nextToken(String delim)
Returns the next token in this string's tokenizer's string.
stk.nextToken(“u,”) will return “An”
stk.nextToken(“Mama”) will return “ Aru, Nash, Yes,”
3.2 PACKAGES:
Class Description
The Boolean class wraps a value of
Boolean the primitive type boolean in an
object.
The Byte class wraps a value of
Byte
primitive type byte in an object.
The Character class wraps a value of
Character
the primitive type char in an object.
Instances of the class Class represent
Class<T> classes and interfaces in a running
Java application.
A class loader is an object that is
ClassLoader
responsible for loading classes.
The Compiler class is provided to
Compiler support Java-to-native-code
compilers and related services.
The Double class wraps a value of the
Double
primitive type double in an object.
This is the common base class of all
Enum<E extends Enum<E>>
Java language enumeration types.
40
The Float class wraps a value of String Manipulations and
Float Introduction to Packages
primitive type float in an object.
The Integer class wraps a value of the
Integer
primitive type int in an object.
The Long class wraps a value of the
Long
primitive type long in an object.
The class Math contains methods for
performing basic numeric operations
Math such as the elementary exponential,
logarithm, square root, and
trigonometric functions.
The abstract class Number is the
superclass of classes BigDecimal,
Number
BigInteger, Byte, Double, Float,
Integer, Long, and Short.
Class Object is the root of the class
Object
hierarchy.
Package objects contain version
Package information about the implementation
and specification of a Java package.
Every Java application has a single
instance of class Runtime that allows
Runtime the application to interface with the
environment in which the application
is running.
The security manager is a class that
SecurityManager allows applications to implement a
security policy.
The Short class wraps a value of
Short
primitive type short in an object.
The String class represents character
String
strings.
A thread-safe, mutable sequence of
StringBuffer
characters.
StringBuilder A mutable sequence of characters.
The System class contains several
System
useful class fields and methods.
A thread is a thread of execution in a
Thread
program.
41
Core JAVA
A thread group represents a set of
ThreadGroup
threads.
This class provides thread-local
ThreadLocal<T>
variables.
The Throwable class is the superclass
Throwable of all errors and exceptions in the
Java language.
The Void class is anuninstantiable
placeholder class to hold a reference
Void
to the Class object representing the
Java keyword void.
Thrown when an exceptional
ArithmeticException
arithmetic condition has occurred.
Thrown to indicate that an array has
ArrayIndexOutOfBoundsException
been accessed with an illegal index.
Thrown when an application tries to
load in a class through its string name
ClassNotFoundException
using: The forName method in class
Class.
The class Exception and its
subclasses are a form of Throwable
Exception that indicates conditions that a
reasonable application might want to
catch.
Thrown when an application attempts
NullPointerException to use null in a case where an object
is required.
Thrown to indicate that the
application has attempted to convert a
NumberFormatException string to one of the numeric types, but
that the string does not have the
appropriate format.
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).
42
String Manipulations and
Introduction to Packages
Class Description
The root class from which all event state objects shall
EventObject
be derived.
43
Core JAVA
The Stack class represents a last-in-first-out (LIFO)
Stack<E>
stack of objects.
java.io
Provides for system input and output through data streams, serialization
and the file system.
Class Description
A BufferedInputStream adds functionality to
another input stream-namely, the ability to buffer
BufferedInputStream
the input and to support the mark and reset
methods.
BufferedOutputStream The class implements a buffered output stream.
Reads text from a character-input stream,
BufferedReader buffering characters so as to provide for the
efficient reading of characters, arrays, and lines.
Writes text to a character-output stream,
buffering characters so as to provide for the
BufferedWriter
efficient writing of single characters, arrays, and
strings.
A data input stream lets an application read
DataInputStream primitive Java data types from an underlying
input stream in a machine-independent way.
A data output stream lets an application write
DataOutputStream primitive Java data types to an output stream in a
portable way.
An abstract representation of file and directory
File
pathnames.
44
Instances of the file descriptor class serve as an String Manipulations and
opaque handle to the underlying machine- Introduction to Packages
FileDescriptor
specific structure representing an open file, an
open socket, or another source or sink of bytes.
A FileInputStream obtains input bytes from a file
FileInputStream
in a file system.
A file output stream is an output stream for
FileOutputStream
writing data to a File or to a FileDescriptor.
FilePermission This class represents access to a file or directory.
FileReader Convenience class for reading character files.
FileWriter Convenience class for writing character files.
This abstract class is the superclass of all classes
InputStream
representing an input stream of bytes.
An InputStreamReader is a bridge from byte
streams to character streams: It reads bytes and
InputStreamReader
decodes them into characters using a specified
charset.
An ObjectInputStreamdeserializes primitive data
ObjectInputStream and objects previously written using an
ObjectOutputStream.
This abstract class is the superclass of all classes
OutputStream
representing an output stream of bytes.
An OutputStreamWriter is a bridge from
character streams to byte streams: Characters
OutputStreamWriter
written to it are encoded into bytes using a
specified charset.
Prints formatted representations of objects to a
PrintWriter
text-output stream.
Writer Abstract class for writing to character streams.
Signals that an I/O exception of some sort has
IOException
occurred.
Signals that an attempt to open the file denoted
FileNotFoundException
by a specified pathname has failed.
java.sql
Provides the API for accessing and processing data stored in a relational
database using the Java programming language.
45
Core JAVA
Class Description
javax.swing
The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
46
Class Description String Manipulations and
Introduction to Packages
JComponent Super class of all component classes in swing.
47
Core JAVA The java run time system by default uses the current working directory as
its starting point. After the current working directory the runtime system
searches the –CLASSPATH environmental variable and uses the directory
to locate class files. Then the run time system searches the –CLASSPATH
location used with javac or java command.
48
2) Programming in JAVA, 2nd Ed, Sachin Malhotra &SaurabhChoudhary, String Manipulations and
Oxford Press Introduction to Packages
3.6 QUESTIONS:
❖❖❖❖
49
Unit II
4
EXCEPTION HANDLING
Unit Structure
4.1 Introduction
4.2 Types of errors
4.3 Exceptions
4.4 Syntax of Exception Handling Code
4.5 Multiple catch Statements
4.6 Using finally Statement
4.7 Throw and throws keyword
4.9 Using Exception for debugging
4.9 Summary
4.10 Textbook
4.11 Additional References
4.12 Questions
4.1 INTRODUCTION
Rarely does a program run successfully at its very first attempt. It is very
common to make mistakes while developing as well as typing a program.
A mistake might lead to an error causing the program to produce
unexpected results. Errors can make a program go wrong.
An error may terminate the execution of the program or may produce an
incorrect output or even may cause the system to crash. It is important to
detect and manage properly all the possible error condition in the program
so that the program will not terminate/crash during execution.
• Compile-time errors
• Run-time errors
50
Compile-Time Errors Exception Handling
All syntax errors are detected and displayed by the Java compiler and
hence these errors are known as compile-time errors. Whenever the
compiler displays an error, it will not create the .class file. Therefore, it is
necessary that we fix all the errors before we can successfully compile and
run the program.
We can now go to the appropriate line, correct an error and recompile the
program. Sometimes, a single error may be the source of multiple errors
later in the compilation. For example, use of an undeclared variable in
several places will cause a series of errors of type “undefined variable”.
In such case, we should consider the earliest errors as the major source of
problem. Once we fix an error, we should recompile the program and look
for other errors.
Most of the compile-time errors are due to typing mistakes. Typographical
errors are hard to find, and we may have to check code word by word. The
most common problems are:
• Missing semicolons
• Missing (or mismatch of) brackets in classes and methods
• Misspelling of keywords and identifiers
• Missing double quotes in strings
• Using undeclared variables
• Use of = in place of == operator and so on.
51
Core JAVA Other errors may occur because of directory paths. An error such as
Run-Time Errors
Sometimes, a program may compile successfully creating.class file but it
may not run properly. Such programs may produce incorrect output due to
wrong logic or may terminate due to errors such as stack overflow. Most
common run-time errors are:
}
52
Program 4.2 is syntactically correct and therefore does not cause any Exception Handling
problem during compilation. However, during execution, it displays the
following message and stops without executing remaining statements.
4.3 EXCEPTIONS
An exception is a condition caused by a run-time error in the program.
When the Java interpreter encounters an error such as dividing an integer
by zero, it creates and throws an exception object (i.e., informs us that an
error has occurred). If the exception object is not caught and handled
properly, the interpreter will display an error message as shown in the
output of Program 4.2 and will terminate the program.
If we want our program to continue with the execution of the remaining
code, then we should try to catch the exception object thrown by the error
condition and then display an appropriate message for taking corrective
actions. This task is known as exception handling.
The purpose of exception handling is to detect and report an “exceptional
circumstance” so that appropriate action can be taken. Error handling code
performs the following tasks:
1. Find the problem (Hit the exception).
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
Error handling code consists of two segments, one to detect errors and to
throw exceptions and the other to catch exceptions and take appropriate
actions.
While writing programs, we must check for places in the program where
an exception could be generated. Some common exceptionsare listed in
Table 4.1
53
Core JAVA Table 4.1 Common java Exceptions
try
{
statement ; //generates an exception
}
catch (Exception- type e)
{
statement ; //processes the exception
}
………………………..
………………………..
The try block can have one or more statements that could generate an
exception. If any one statement generates an exception, the remaining
statements in the try block are skipped and execution jumps to the catch
block that is placed immediately next to the try block.
The catch block can have one or more statements that are necessary to
process the exception. Every try statement should be followed by at least
one catch statement; otherwise compilation error will occur.
The catch statement works like a method definition. A single parameter,
which is reference to the exception object is thrown (by the try block). If
the catch parameter matches with the type of exception object, then the
exception is caught and statements in the catch block will be executed.
Otherwise, the exception is not caught, and the default exception handler
will cause the execution to terminate.
Program 4.3 illustrates the use of try and catch blocks to handle an
arithmetic exception. Note that program 4.3 is a modified version of
Program 4.2.
55
Core JAVA Program 4.3 Using try and catch for exception handling
class Error3
{
public static void main(String[] args)
{
int x = 10;
int y = 5;
int z = 5;
try
{
inta = x/(y-z); //Exception here
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
int b = x/(y+z);
System.out.println("b=" +y);
}
Program 4.3 displays the following output:
Note that the program did not stop when an exception is caused inside try
block. Exception is caught by catch block and it prints the error message,
and then continues the execution, as if nothing has happened. Compare
with the output of Program 4.2 which did not give the value of y.
Program 4.4 shows another example of using exception handling
mechanism.
56
Program 4.4 Example of ArrayIndexOutOfBoundsException Exception Handling
class TryCatchExample
{
}
Output:
In this program we have array which contains 4 elements i.e arr[0], arr[1],
arr[2], arr[3]. We are printing arr[4] which doesn’t exist in the array list.
Hence ArrayIndexOutOfBoundsException is caused by try block and
caught by catch block.
57
Core JAVA catch (Exception- Type-1 e)
{
statement; // processes exception type 1
}
catch (Exception- Type-2 e)
{
statement; // processes exception type 2
}
catch (Exception- Type-3e)
{
statement; // processes exception type N
}
………………………………
………………………………
When an exception in a try block is generated, the Java treats the multiple
catch statements like cases in a switch statement. The first statement
whose parameter matches with the exception object will be executed, and
the remaining statements will get skipped.
Note that Java does not require any processing of the exception at all. We
can simply have a catch statement with an empty block to avoid program
abortion.
Example:
Note that the array element a [10] does not exist because array a is defined
to have only five elements, a[0], a[1], a[2], a[3], a[4]. Therefore, the index
10 is outside the array boundary thus causing the block
catch (ArrayIndexOutofBoundsException e)
to catch and handle the error. Remaining catch blocks are skipped.
59
Core JAVA finally catch(……)
{ {
…………… ……………
………….. …………….
} }
catch (……)
{
……………
…………….
}
.
.
.
finally
{
……………
…………..
}
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
finally
{
System.out.println("rest of the code");
}
}
}
This will produce the same output.
throw newThrowable_subclass;
Examples:
throw new ArithmeticException( );
throw new NumberFormatException( );
61
Core JAVA In Program 4.6, we have created validate method that takes integer value
as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
63
Core JAVA class OwnException
{
public static void main (String args[])
{
int x = 5, y = 1000;
try
{
float z = (float) x / (float) y;
if(z < 0.01)
{
throw new MyException("Number is too small");
}
}
catch(MyException e)
{
System.out.println("Caught my exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here");
}
}
}
Output:
The object e which contains the error message “Number is too small” is
caught by the catch block which then display’s the message using the
getMessage() method.
Note that Program 4.8 also illustrates the use of finally block. The last
line of output is produced by the finally block.
64
4.8 USING EXCEPTION FOR DEBUGGING Exception Handling
4.9 SUMMARY
A good program does not produce unexpected results. We should
incorporate features that could check for potential problem spots in
programs and guard against program failures. Exceptions in Java must be
handled carefully to avoid any program failures.
In this chapter we have discussed the following:
✓ What exceptions are
✓ try,catch and finally block
✓ How to catch and handle different types of exceptions.
✓ How to throw system exceptions
4.10 TEXTBOOK(S):
1) Herbert Schildt, Java The Complete Reference, Ninth Edition,McGraw-
Hill Education, 2014
4.12 QUESTIONS:
❖❖❖❖
65
5
MULTITHREADING
Unit Structure
5.1 Introduction
5.2 Creating threads
5.3 Extending the thread Class
5.4 Stopping and Blocking a thread
5.6 Life Cycle of A thread
5.6 Using thread Methods
5.7 Synchronization in Java
5.8 Summary
5.9 Textbook
5.10 Additional Reference(s)
5.11 Questions
5.1 INTRODUCTION
Those who are familiar with the modern operating systems (Windows 10)
may recognize that they can execute several programs simultaneously.
This ability is known as multitasking. In system's terminology, it is called
multithreading.
Multithreading is a conceptual programming paradigm where a program
(process) is divided into two or more subprograms (processes), which can
be implemented in parallel. This is similar to dividing one task into
subtasks and assigning them to different people for execution
independently and simultaneously. For example, one subprogram can
display an animation on the screen while another may build the next
animation to be displayed.
In most computers, there is only a single processor and therefore, in
reality, the processor does only one thing at a time. However, the
processor switches between the processes so fast that it appears to human
beings that all of them are being executed simultaneously. Java programs
that we have seen and discussed so far contain only a single sequential
flow of control. This is what happens when we execute a normal program.
The program begins, runs through a sequence of executions, and finally
ends. At any given point of time, there is only one statement under
execution.
70
A thread is similar to a program that has a single flow of control. It has a Multithreading
beginning, a body, and an end, and executes commands sequentially. All
main programs in our earlier (previous chapters) examples can be called
single-threaded programs. Every program will have at least one thread as
shown in Fig. 5.1
71
Core JAVA
Once initiated by the main thread, the threads A, B run concurrently and
share the resources jointly. It is like people living in joint families and
sharing certain resources among all of them. Since threads in Java are
subprograms of a main application program and share the same memory
space, they are known as lightweight threads or lightweight processes.
It is important to remember that 'threads running in parallel' does not
really mean that they are running at the same time. Since all the threads
are running on a single processor, the flow of execution is shared between
the threads. The Java interpreter handles the switching of control between
the threads in such a way that it appears they are running concurrently.
Multithreading is a powerful programming tool that makes Java distinctly
different from its fellow programming languages. Multithreading enables
programmers to do multiple things at same time. They can divide a long
program (containing operations that are conceptually concurrent) into
threads and execute them in parallel. For example, we can send print
command into the background and continue to perform some other task in
the foreground. This approach would considerably improve the speed of
our programs.
Any application we are working on that requires two or more things to be
done at the same time is probably a best one for use of threads.
72
only method in which the thread's behaviour can be implemented. A Multithreading
typical run() method would appear as follows:
public void run( )
{
……………………..
……………………..
(statements for implementing thread)
……………………….
……………………….
}
The run( ) method should be invoked by an object of the concerned
thread. This can be achieved by creating the thread and initiating it with
the help of another thread method called start().
A new thread can be created in two ways.
1. By creating a thread class:
Define a class that extends Thread class and override its run( ) method
with the code required by the thread.
73
Core JAVA ❖ Declaring the Class
74
❖ An Example of Using the Thread Class Multithreading
Program 5.1 illustrates the use of Thread class for creating and running
threads in an application. In program we have created two threads A and B
for undertaking two different tasks. The main method in the ThreadTest1
class also constitutes another thread which we may call the "main thread".
The main thread dies at the end of its main method. However, before it
dies. it creates and starts other two threads A, B.
We can start a thread as follows:
A t1 = new A();
t1.start();
Immediately after the thread A is started, there will be two threads running
in the program: the main thread and the thread A.
The start() method returns back to the main thread immediately after
invoking the run( ) method, thus the allowing the main thread to start the
thread B.
75
Core JAVA System.out.println("Exit from B");
}
}
class Threadtest1
{
public static void main(String args[])
{
A t1 = new A();
B t2 = new B();
t1.start(); //start first thread
t2.start(); //start second thread
}
}
Output:
First run
Second run
76
Third run Multithreading
By the time the main thread has reached the end of its main method, there
are a total of three separate threads running in parallel.
We have simply initiated two new threads and started them. We did not
hold on to them further. They are running concurrently on their own. Note
that the outputs from the threads are not sequential. They do not follow
any specific order.
They are running independently of one another and each executes
whenever it has a chance. Remember, once the threads started. We cannot
decide with certainty the order in which they may execute statements.
Note a second run and third run has a different output sequence.
aThread.stop( );
This statement causes the thread to move to the dead state. A thread will
also move to the dead state automatically when it reaches the end of its
method. The stop( ) method may be used when the premature death of a
thread is desired.
Blocking a Thread
A thread can also be suspended temporarily or blocked from entering
into the runnable and subsequently running state by using either of the
following thread methods:
Newborn State
When we create a thread object, the thread is born and is said to be in
newborn state. The thread is not yet scheduled for running. At this state,
we can do only one of the following things with it:
✓ We can schedule it for running using start() method.
✓ We can kill it using stop() method.
If scheduled, it moves to the runnable state (Fig. 5.4). If we attempt to use
any other method at this stage, an exception will be thrown.
78
Multithreading
79
Core JAVA
80
Blocked State Multithreading
A thread is said to be in blocked state when it is prevented from entering
the runnable state and subsequently the running state.
It happens when the thread is suspended, sleeping or waiting in order to
satisfy certain requirements.
A blocked thread is considered “not runnable” but it is not dead and
therefore fully qualified to run again.
Dead State
Every thread has a life cycle. A running thread ends its life when it
completes executing its run () method. It is a natural death.
However, we can kill it by sending the stop message to it at any state thus
causing a premature death. A thread can be killed as soon as it is born, or
while it is running, or even when it is in “not runnable” (blocked)
condition.
Program 5.2 illustrates the use of yield(), sleep(), and stop() methods.
t2.start();
82
System.out.println("End of main thread"); Multithreading
}
}
Output:
Program 5.2 uses the yield() method in thread A at the iteration i=1.
Therefore, the thread A, although started first, has relinquished its control
to the thread B.
The thread B started sleeping after executing for loop only once.
When it woke up (after 2000 milliseconds), the other thread has already
completed its runs and therefore was running alone.
The main thread died much earlier than the other two threads.
83
Core JAVA Example:
synchronized void update()
{
………………….
…………………. //code here is synchronized
……………………
}
When we declare a method synchronized, Java creates a “monitor” and
hands it over to the thread that calls the method first time. As long as the
thread is holding the monitor, no other thread can enter the synchronized
section of the code. A monitor is like a key and the thread that holds the
key can only open the lock.
It is also possible to mark a block of code as synchronized as shown
below:
synchronized (lock-object)
{
…………………… //code here is synchronized
……………………
}
Whenever a thread completes its work of using synchronized method (or
block of code), it will hand over the monitor to the next thread that is
ready to use the same resource.
A deadlock situation may occur when two or more threads are waiting to
gain control of a resource. Due to some reason, the condition on which the
waiting threads rely on to gain control does not happen.
For example, assume that the thread X must access Method1 before it can
release Method2, but the thread Y cannot release Method1 until it gets
hold of Method2. Because these are mutually exclusive conditions, a
deadlock occurs. The code below illustrates this:
Thread X
synchronized method2 ()
{
synchronized method1()
{
……………………
84
…………………… Multithreading
}
}
Thread Y
synchronized method1 ()
{
synchronized method2 ()
{
……………………
……………………
}
}
5.8 SUMMARY
A thread is a single line of execution within a program. Multiple threads
can run concurrently in any single program.
A thread is created either by sub classing the Thread class or
implementing the Runnable interface. Careful application of
multithreading will considerably improve the execution speed of Java
programs.
5.9 TEXTBOOK
Herbert Schildt, Java The Complete Reference, Ninth Edition, McGraw-
Hill Education, 2014
5.11 QUESTIONS
1. What is thread? Explain the life cycle of thread.
2. Explain the synchronization of thread.
3. Write a java program to implement the concept of thread.
❖❖❖❖
85
6
I/O STREAMS
Unit Structure
6.1 Introduction
6.2 Types of Streams
6.2.1 Byte Stream
6.2.2 Character Stream
6.3 Java Input Stream Class
6.3.1 Java FileInput Stream Class
6.3.2 Java Byte Array Input Stream Class
6.4 Java Output Stream Class
6.4.1 Java File Output Stream Class
6.4.2 Java Byte Array Output Stream Class
6.5 Java Reader and Writer
6.6 Summary
6.7 Textbooks
6.8 Questions
6.1 INTRODUCTION
Java I/O (Input and Output) is used to process the input and produce the
output.
Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
CONCEPT OF STREAMS
A stream is a sequence of data. In Java, a stream is composed of bytes.
It's called a stream because it is like a stream of water that continues to
flow.
In Java, streams are the sequence of data that are read from the source and
written to the destination.An input stream is used to read data from the
source and, an output stream is used to write data to the destination.
86
Program 6.1 I/O Streams
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
For example, in above HelloWorld program, we have used System.out to
print a string. Here, the System.out is a type of output stream.
Similarly, there are input streams to take input.
87
Core JAVA 6.2.2 CHARACTER STREAM
Character stream is used to read and write a single character of data.
All the character stream classes are derived from base abstract
classes Reader and Writer.
❖ SUBCLASSES OF INPUTSTREAM
In order to use the functionality of InputStream, we can use its following
subclasses.
✓ FileInputStream
✓ ByteArrayInputStream
✓ ObjectInputStream
✓ BufferedInputStream
❖ CREATE AN INPUTSTREAM
In order to create an InputStream, we must import the
java.io.InputStream package first.
Once we import the package, here is how we can create the input stream.
// Creates an InputStream
InputStream object1 = new FileInputStream();
Here, we have created an input stream using FileInputStream. It is
because InputStream is an abstract class. Hence, we cannot create an
object of InputStream.
❖ METHODS OF INPUTSTREAM
The InputStreamclass provides different methods that are implemented by
its subclasses.
Some of the commonly used methods are:
✓ read()-
It reads one byte of data from the input stream.
✓ read(byte[] array) –
It reads bytes from the stream and stores in the specified array.
✓ available() –
It returns the number of bytes available in the input stream.
✓ mark() –
88
It marks the position in the input stream up to which data has been read. I/O Streams
✓ reset() –
It returns the control to the point in the stream where the mark was set.
✓ markSupported() –
It checks if the mark() and reset() method is supported in the stream.
✓ skips() –
It skips and discards the specified number of bytes from the input stream.
✓ close() –
It closes the input stream.
❖ CREATE A FileInputStream
In order to create a FileInputStream, we must import
the java.io.FileInputStream package first. Once we import the package,
here is how we can create a file input stream in Java.
❖ METHODS OF FileInputStream
The FileInputStream class provides implementations for different
methods present in the InputStream class.
read() Method
✓ read() - It reads a single byte from the file.
✓ read(byte[] array) –It reads the bytes from the file and stores in the
specified array.
✓ read(byte[] array, int start, int length) –It reads the number of
bytes equal to length from the file and stores in the specified array starting
from the position start.
89
Core JAVA Suppose we have a file named test.txt with the following content.
Program 6.2
import java.io.FileInputStream;
import java.io.InputStream;
class Program
{
public static void main(String args[])
{
byte[] array = new byte[100];
try
{
e.getStackTrace();
}
}
}
Output:
❖ CREATE A BYTEARRAYINPUTSTREAM
In order to create a byte array input stream, we must import the
java.io.ByteArrayInputStream package first.
Once we import the package, we can create an input stream as follows:
// Creates a ByteArrayInputStream that reads entire array
ByteArrayInputStream input = new ByteArrayInputStream(byte[]
arr);
Here, we have created an input stream that reads entire data from
the arr array.
91
Core JAVA However, we can also create the input stream that reads only some data
from the array.
❖ METHODS OF BYTEARRAYINPUTSTREAM
The ByteArrayInputStream class provides implementations for different
methods present in the InputStream class.
read() Method
✓ read() –
It reads the single byte from the array present in the input stream.
✓ read(byte[] array) –
It reads bytes from the input stream and stores in the specified array.
class Program3
{
public static void main(String[] args)
{
try
{
ByteArrayInputStream input = new ByteArrayInputStream(array);
catch(Exception e)
{
e.getStackTrace();
}
}
}
Output:
❖ CREATE AN OUTPUTSTREAM
In order to create an OutputStream, we must import the
java.io.OutputStream package first. Once we import the package, here is
how we can create the output stream.
93
Core JAVA // Creates an OutputStream
OutputStream object = new FileOutputStream();
Here, we have created an object of output stream using File Output
Stream. It is because OutputStream is an abstract class, so we cannot
create an object of OutputStream.
❖ METHODS OF OUTPUTSTREAM
The OutputStream class provides different methods that are implemented
by its subclasses. Some of the methods are as follows:
✓ write() -
It writes the specified byte to the output stream.
✓ write(byte[] array) –
It writes the bytes from the specified array to the output stream.
✓ flush() –
It forces to write all data present in output stream to the destination.
✓ close() –
It closes the output stream.
❖ CREATE A FILEOUTPUTSTREAM
In order to create a file output stream, we must import
the java.io.FileOutputStream package first.
Once we import the package, we can create a file output stream in Java as
follows.
1. Using the path to file
// Including the boolean parameter
94
Also, value is an optional boolean parameter. If it is set to true, the new I/O Streams
data will be appended to the end of the existing data in the file. Otherwise,
the new data overwrites the existing data in the file.
2. Using an object of the file
95
Core JAVA }
}
}
When we run the program, the output.txt file is filled with the following
content.
❖ CREATE a ByteArrayOutputStream
In order to create a byte array output stream, we must import
the java.io.ByteArrayOutputStream package first.
Once we import the package, here is how we can create an output stream.
// Creates a ByteArrayOutputStream with default size
96
I/O Streams
❖ METHODS OF ByteArrayOutputStream
The ByteArrayOutputStream class provides the implementation of the
different methods present in the OutputStream class.
write() Method
✓ write(int byte) –
It writes the specified byte to the output stream.
✓ write(byte[] array) –
It writes the bytes from the specified array to the output stream.
✓ write(byte[] arr, int start, int length) –
It writes the number of bytes equal to length to the output stream from an
array starting from the position start.
✓ writeTo(ByteArrayOutputStream out1) –
It writes the entire data of the current output stream to the specified output
stream.
EXAMPLE: ByteArrayOutputStreamTO WRITE DATA
Program 6.5
import java.io.ByteArrayOutputStream;
class Program4
{
public static void main(String[] args)
{
String data = "Hello all";
try
{
// Creates an output stream
out.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
Output:
98
class ReaderExample I/O Streams
{
public static void main(String[] args)
{
try
{
{
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
It is file.txthaving content “I love my India.”
Output:
99
Core JAVA Java Writer
It is an abstract class for writing to character streams. The methods that a
subclass must implement are write(char[], int, int), flush(), and close().
Program 6.7
import java.io.*;
public class WriterExample
{
public static void main(String[] args)
{
try
{
Writer w = new FileWriter("output1.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Success");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Output:
100
6.6 SUMMARY I/O Streams
6.7 TEXTBOOKS
Herbert Schildt, Java The Complete Reference, Ninth Edition, McGraw-
Hill Education, 2014
6.8 QUESTIONS
1) What is stream? Explain the types of stream.
2) Explain the difference between input & output stream class?
❖❖❖❖
101
7
NETWORKING
Unit Structure
7.1 Introduction
7.2 Java networking terminology
7.3 Java networking classes
7.4 Java networking interfaces
7.5 Java socket programming
7.5.1 Socket class
7.5.2 ServerSocket class
7.6 Summary
7.7 Reference
7.8 Questions
7.1 INTRODUCTION
Networking is a concept of connecting two or more computing devices
together so that we can share resources. Java socket programming
provides facility to share data between different computing devices.
The java.net package supports two protocols:
1. TCP:
TCP stands for Transmission Control Protocol. It provides reliable
communication between the sender and receiver.
It is used along with the Internet Protocol referred as TCP/IP. TCP is a
connection-oriented protocol which means that once a connection is
established, data can be transmitted in two directions. This protocol is
typically used over the Internet Protocol. Therefore, TCP is also referred
to as TCP/IP.
TCP has built-in methods to examine for errors and ensure the delivery
of data in the order it was sent, making it a complete protocol for
transporting information like still images, data files, and web pages.
2. UDP:
UDP stands for User Datagram Protocol. It provides a connection-less
protocol service by allowing packet of data to be transferred along two or
102
more nodes. It allows data packets to be transmitted between different Networking
applications.
UDP is a simple Internet protocol in which error-checking and recovery
services are not required. In UDP, there is no overhead for opening a
connection, maintaining a connection, or terminating a connection. In
UDP, the data is continuously sent to the recipient, whether they receive
it or not.
1. IP Address
An IP address is a unique address assigned to a device that distinguishes
a device on the internet or a local network.
IP stands for “Internet Protocol.” It comprises a set of rules governing
the format of data sent via the internet or local network. It is composed
of octets. The range of each octet varies from 0 to 255.
• Range of the IP Address – 0.0.0.0 to 255.255.255.255
• IP address Example – 192.168.0.1
2. Protocol
A network protocol is an organized set of commands that define how
data is transmitted between different devices in the same network.
Network protocols are the reason through which a user can easily
communicate with people all over the world and thus play a critical role
in modern digital communications.
For Example – Transmission control protocol(TCP), File Transfer
Protocol (FTP), Post Office Protocol(POP), etc.
3. MAC Address
MAC address stands for Media Access Control address. It is a
identifier that is allocated to a NIC (Network Interface Controller/ Card).
It contains a 48 bit or 64-bit address, which is combined with the
network adapter. MAC address can be in hexadecimal composition. In
simple words, a MAC address is a unique number that is used to track a
device in a network.
4. Socket
A socket is an endpoint of a two-way communication connection
between the two applications running on the network. The socket
mechanism presents a method of inter-process communication (IPC) by
setting named contact points between which the communication occurs.
A socket is bound to a specific port number so that the TCP layer can
identify the application to which the data is intended to be sent to.
103
Core JAVA 5. Connection-oriented and Connection-less protocol
In a connection-oriented service, the user must establish a connection
before starting the communication. When the connection is established,
the user can send the message or the information, and after this, they can
release the connection.
In connectionless protocol, the data is transported in one route from
source to destination without verifying that the destination is still there
or not or if it is ready to receive the message. Authentication is not
needed in the connectionless protocol.
6. Port Number
A port number is a way to recognize a process connecting internet or
other network information when it reaches a server. The port number is
used to identify different applications uniquely and behaves as a
communication endpoint among applications. The port number is
associated with an IP addressfor transmission and communication among
two applications. There are 65,535 port numbers, but not all are used
every day.
1. CacheRequest
This class is used in java whenever there is a need to store resources in
ResponseCache. The objects of this class provide an edge for the
OutputStream object to store resource data into the cache.
2. CookieHandler
This class is used in Java to implement a callback mechanism to hook up
an HTTP state management policy implementation inside the HTTP
protocol handler. The HTTP state management mechanism specifies the
mechanism of how to make HTTP requests and responses.
3. CookieManager
This class is used to provide a precise implementation of CookieHandler.
This class separates the storage of cookies from the policy surrounding
104
accepting and rejecting cookies. A CookieManager comprises a Networking
CookieStore and a CookiePolicy.
4. DatagramPacket
This class is used for the connectionless transfer of messages from one
system to another. This class provides tools to produce datagram packets
for connectionless transmission by applying the datagram socket class.
5. InetAddress
This class is used to provide methods to get the IP address of any
hostname. An IP address is represented by a 32-bit or 128-bit unsigned
number. InetAddress can handle both IPv4 and IPv6 addresses.
6. ServerSocket
This class is used for implementing system-independent implementation
of the server-side of a client/server Socket Connection. The constructor
for ServerSocket class throws an exception if it can’t listen on the
specified port.
For example –
It will throw an exception if the port is already in use.
7. Socket
This class is used to create socket objects that help users in
implementing all fundamental socket operations. The users can
implement various networking actions such as sending, reading data, and
closing connections.
Each Socket object is built using java.net.Socket class that has been
connected exactly with 1 remote host; for connecting to another host, a
user must create a new socket object.
8. DatagramSocket
This class is a network socket that provides a connection-less point for
sending and receiving packets. Datagram Sockets is Java’s mechanism
for providing network communication via UDP instead of TCP. Every
packet sent from a datagram socket is individually routed and delivered.
It can further be practiced for transmitting and accepting broadcast
information.
9. Proxy
A proxy is a kind of tool or program or system, which serves to preserve
the data of its users and computers. It behaves like a wall between
computers and internet users. A Proxy Object represents the Proxy
settings to be applied with a connection.
105
Core JAVA 10. URL
The URL class in Java is the entry point to any available sources on the
internet. A Class URL describes a Uniform Resource Locator, which is
a signal to a “resource” on the World Wide Web.
A source can be a simple file or directory, or it can indicate a more
difficult object, such as a query to a database or a search engine.
1. CookiePolicy
The CookiePolicy interface in the java.net package provides the classes
for implementing various networking applications. It decides which
cookies should be accepted and which should be rejected.
In CookiePolicy, there are three pre-defined policy implementations,
namely ACCEPT_ALL, ACCEPT_NONE, and
ACCEPT_ORIGINAL_SERVER.
2. CookieStore
A CookieStore is an interface that describes a storage space for cookies.
CookieManager combines the cookies to the CookieStore for each HTTP
response and recovers cookies from the CookieStore for each HTTP
request.
3. FileNameMap
The FileNameMap interface is an uncomplicated interface that
implements a tool to outline a file name and a MIME type string.
FileNameMap charges a filename map (known as a mimetable) from a
data file.
4. SocketOption
The SocketOption interface helps the users to control the behavior of
sockets. Often, it is essential to develop necessary features in Sockets.
SocketOptions allows the user to set various standard options.
5. SocketImplFactory
The SocketImplFactory interface defines a factory for SocketImpl
instances. It is used by the socket class to create socket implementations
that implement various policies.
106
6. ProtocolFamily Networking
This interface represents a family of communication protocols.
The ProtocolFamily interface contains a method known as name(), which
returns the name of the protocol family.
107
Core JAVA An endpoint is a combination of an IP address and a port number. The
package in the Java platform provides a class, Socket which implements
one side of a two-way connection between your Java program and another
program on the network.
The class sits on top of a platform-dependent implementation, hiding the
details of any system from your Java program. By using the class instead
of relying on native code, your Java programs can communicate over the
network in a platform-independent fashion.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
The client in socket programming must know these two things:
1. IP Address of Server, and
2. Port number
A client application generates a socket on its end of the communication
and strives to combine this socket with a server. When the connection is
established, the server generates an object of socket class on its
communication end. The client and the server can now communicate by
writing to and reading from the socket.
The java.net.Socket class describes a socket, and the java.net.Server
Socket class implements a tool for the server program to host clients and
build connections with them.
108
Sr Networking
No. Method Description
public Inet Address get It is used to return the location of the other
3 Inet Address() computer to which the socket is connected.
109
Core JAVA Methods of Server Socket Class:
Methods of the Server Socket class are as follows:
Sr
No. Method Description
110
The accept() method waits for the client. If clients connect with the given Networking
port number, it returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s= ss.accept();//establishes connection and waits for the client
Creating Client:
To create the client application, we need to create the instance of Socket
class.
Here, we need to pass the IP address or hostname of the Server and a port
number. Here, we are using "localhost" because our server is running on
same system.
Socket s=new Socket("localhost",6666);
Let's see a simple example of Java socket programming where client sends
a text message, server receivesand prints it.
Filename: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(6666);
111
Core JAVA }
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient
{
public static void main(String[] args)
{
try
{
Socket s= new Socket("localhost",6666);
DataOutputStreamdout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
112
1. First run the Server application (MyServer.java). It will show: Networking
and the server accepts the client and a message will be displayed on the
server console.
{
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
File: MyClient1.java
import java.net.*;
import java.io.*;
class MyClient1
{
114
public static void main(String args[])throws Exception Networking
{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStreamdout=new DataOutputStream(s.getOutputStream());
BufferedReaderbr=new BufferedReader(new
InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}
}
First run the Server application. It will show:
115
Core JAVA Then run the Client application on another terminal. It will show:
7.6 SUMMARY
Networking is a concept of connecting two or more computing devices
together so that we can share resources. Java socket programming
provides facility to share data between different computing devices.
7.7 REFERENCE
1) E. Balagurusamy, Programming with Java, Tata McGraw-Hill
Education India, 2014
2) Programming in JAVA, 2nd Ed, Sachin Malhotra &SaurabhChoudhary,
Oxford Press
7.8 QUESTIONS
1) Write a short note on java.net package.
2) What is socket? Explain the Socket Class with example.
❖❖❖❖
116
Unit III
8
WRAPPER CLASSES
Unit Structure
8.0 Objective
8.1 Introduction
8.2 Types of Wrapper classes
8.3 Summary
8.4 Exercise
8.5 Reference
8.0 OBJECTIVE
Objective of this chapter is to learn
1. Need of objects and primitive data types
2. How to convert primitive data types to objects and vies-a-versa
3. Autoboxing and unboxing feature of Java5
8.1 INTRODUCTION:
As you know Java supports primitive data types and non-primitive data
types. In programming, many cases, there is need of object representation.
In such standard representation primitive data types are not suitable. For
example,
1. Data structures implemented by java uses collection of objects.
117
Core JAVA Table 8.1 Primitive types and their Wrappers
boolean Boolean
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
Methods Description
118
Following program 8.1, demonstrate the use of boolean wrapper class Wrapper Classes
Table 8.2 shows the listing of other wrapper classes and their methods
Table 8.2: Wrapper classes and their methods
119
Core JAVA
Byte Byte(byte b) Creates Byte objects from byte
Byte(String b) throws value
NumberFormatException
Creates Byte objects from String
coded byte value.
Byte byteValue() Return the byte value present in
Byte Object.
Short Short(short sh) Creates Short objects from short
Short(String sh) throws value
NumberFormatException Creates Short objects from
String coded short value.
Short shortValue() Return the short value present in
Short Object.
Long Long(long l) Creates Long objects from long
Long(String l) throws value
NumberFormatException Creates Long objects from
String coded long value.
long longValue() Return the long value present in
Long Object.
Float Float(float f) Creates Float objects from float
Float(String f) throws value
NumberFormatException Creates Float objects from
String coded float value.
Float floatValue() Return the float value present in
Float Object.
Double Double(double d) Creates Double objects from
double value
Creates Double objects from
Double(String d) throws
String coded double value.
NumberFormatException
Double doubleValue() Return the double value present
in Double Object.
Character Character(char ch) Creates Character objects from
char value
120
Program 8.2: Demonstrate use of Integer Wrapper class and Wrapper Classes
NumberFormatException
public class wrapperdemo
{
public static void main(String []args)
{
String s="10";
Integer n1=new Integer(s);
System.out.println("Integer object --> "+n1);
String s1="Ten";
Integer n2=new Integer(s1);
System.out.println("Integer value --> "+n2);
}
}
Integer object --> 10
Exception in thread "main" java.lang.NumberFormatException: For input
string: "Ten"
At
java.lang.NumberFormatException.forInputString(NumberFormatExceptio
n.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.<init>(Integer.java:867)
at booeandemo.main(booeandemo.java:8)
8.4 SUMMARY:
1. For handling the collection of objects required primitive data in
object form
2. Wrapper classes wrapped the primitive data and present them in
object form
3. There are Long, Short, Byte, Integer, Float, Double, Character,
Boolean wrapper classes in java
4. xxxValue() method used to convert xxx type object into primitive
data form.
8.5 EXERCISE:
1. What is wrapper class?
2. Create a list of integer values 10,20,30,40,50.
3. What is autoboxing and unboxing?
8.6 REFERENCES:
1. H. Schildt, Java Complete Reference, vol. 1, no. 1. 2014.
2. E. Balagurusamy, Programming with Java, Tata McGraw-Hill
Education India, 2014
3. Sachin Malhotra & Saurabh Choudhary, Programming in JAVA, 2nd
Ed, Oxford Press
4. The Java Tutorials: http://docs.oracle.com/javase/tutorial/
❖❖❖❖
122
9
COLLECTION FRAMEWORK
Unit Structure
9.0 Objective
9.1 Introduction to Collections Framework
9.2 Util package
9.3 List
9.4 Set
9.5 Map
9.6 List interface & its classes
9.6.1 ArrayList
9.6.2 LinkedList
9.7 Set interface & its classes
9.7.1 HashSet
9.7.2 TreeSet
9.8 Map interface & its classes
9.8.1 HashMap
9.8.2 TreeMap
9.8.3 Iterator
9.9 Summary
9.10 Exercise
9.11 Reference & Bibliography
9.0 OBJECTIVE
Method Description
Boolean add (Object Add single element into collection
element)
Boolean remove (Object Remove single element from the collection
element)
int size() Return the size of collection
boolean isEmpty() Returns true if collection is empty otherwise
false
boolean contains (Object Returns if element is present in the collection
element) otherwise false
124
Collection Framework
Boolean contains All Returns true if collection is a subset of
(Collection collection) current collection otherwise false
boolean add All Returns true if all elements of collection are
(Collection collection) added to current collection
void remove All Returns true if all elements of collection are
(Collection collection) removed from current collection
void retain All (Collection It retains all the elements of current
collection) collectionwhich are present in the collection
and removes the elements that are not in
collection (similar to intersection)
void clear() Removes all elements from the collection
Iterator iterator() start to finish traversal in collection is
possible using Iterator interface object. This
method gives reference to the Iterator
Interface hence its methods can be used.
Method Description
void add(int index, Object Insert an elements at specific index
element) location
boolean addAll(int index, Insert all elements of collection at
Collection collection) specific index location.
Object get(int index) Returns the element present at
specified index position
int indexOf(Object element) Returns an index value of specified
element
int lastIndexOf(Object element) Returns the last index of elements
specified. If the element is not present
in the list then it returns -1
Object remove(int index) Returns an element which is present at
specified index position.
Object set(int index, Object It replaces the element present at the
element) specified index position with new
element.
List subList(int fromIndex, int Returns the sub-list from- to index
toIndex) position
125
Core JAVA
9.4 THE SET INTERFACE:
Set is the derived from Collection interface and does not allow the
duplication of elements.If we try to add duplicate element using add
method, it returns false. Set does not have any additional method. All
methods are inherited from Collection interface (please refer Table 9.1).
Method Description
Object put (Object key, Object Insert an object in a MAp
value)
Object remove (Object key) Removes an object having specified
key from Map
void putAll(Map mapping) Put all the elements specified in the
Map.
void clear () All map entries are cleared
Object get(Object key) Returns an element whose key is
mention
boolean containsKey(Object key) Returns true if key is in Map
otherwise false
boolean containsValue(Object Returns true if the value is present in
value) map otherwise false
boolean isEmpty() Returns true if Map is empty
otherwise false
int size() Returns the size or number of
elements present in the map
public Set keyset () Returns Set of keys present in map
public Collection values() Returns all values in Collection form
public Set entrySet() Returns Set of all elements in key and
value pair form
126
9.6 LIST INTERFACE & ITS CLASSES: Collection Framework
List ArrayList
LinkedList
Set HashSet
TreeSet
Map HashMap
TreeMap
Methods Description
127
Core JAVA al.add(1);
al.add(2);
al.add(3);
al.add(4);
System.out.println("Contents of ArrayList : " + al);
// Get the array.
Integer ia[] = new Integer[al.size()];
ia = al.toArray(ia);
int sum = 0;
// Sum the array.
for(int i=0;i<ia.length;i++)
sum += ia[i];
System.out.println ("Sum of elements of an Array is: " + sum);
}
}
Output:
Contents of ArrayList : [1, 2, 3, 4]
Sum of elements of an Array is: 10
Methods Description
128
Collection Framework
129
Core JAVA System.out.println("List after modification: " + ll);
}
}
Output:
Original elements of list: [Amita, Aarti, Seeta, Babita, Deepak, Keshav,
Zareena]
list elements after deletion: [Amita, Seeta, Babita, Keshav, Zareena]
List elements after deleting first and last: [Seeta, Babita, Keshav]
List after modification: [Seeta, Babita_FY, Keshav]
Methods Description
130
9.7.2 TreeSet class Collection Framework
Objects in TreeSet are stored in ascending order. Object retrieval time is
fast. Figure 9.2 shows the class hierarchy and Table 9.8 shows the
constructors of TreeSet class.
Constructors Description
Program 9.3 demonstrates how to create an object an object and use the
methods of TreeSet class and HashSet class.
Figure 9.3 shows the hierarchy of the classes implementing Map interface.
Lets see in detail the implementation and use of these classes.
132
Table 9.9 Constructors of HashMap class Collection Framework
Methods Description
133
Core JAVA
9.8.2 TreeMap class
Methods Description
134
System.out.println(tm); Collection Framework
9.8.3 Iterator:
This Iterator Interface is used for any collection to traverse through
collection. It is a cursor which is iterated through the collection to access
or to remove the element from the collection. Table 9.11 shoes the
methods of Iterator Interface.
Methods Description
135
Core JAVA Following code demonstrate the use of Iterator class.
9.9 SUMMARY
136
• Set collects unique elements. Treeset uses the concept of tree to store Collection Framework
the data elements whereas Hashset uses hashing techniques.
• HashSet stores the elements in hashTable.
• Map interface allows the mapping between key and value. Map is
implemented using HashMap and TreeMap classes.
• HashMap allows storing null elements but the keys for those
elements must be different.
9.10 EXERCISE
9.11 REFERENCES
1. H. Schildt, Java Complete Reference, vol. 1, no. 1. 2014.
2. E. Balagurusamy, Programming with Java, Tata McGraw-Hill
Education India, 2014
3. Sachin Malhotra & Saurabh Choudhary, Programming in JAVA, 2nd
Ed, Oxford Press
4. The Java Tutorials: http://docs.oracle.com/javase/tutorial/
❖❖❖❖
137
10
INNER CLASSES
Unit Structure
10.0 Objective
10.1 Introduction
10.2 Inner class/nested class
10.3 Method Local inner class
10.4 Static inner class
10.5 Anonymous inner class
10.6 Summary
10.7 Exercise
10.8 References
10.0 OBJECTIVE:
Objective of this chapter is
10.1 INTRODUCTION
Inner class is the class which is a member of other class. Inner Class could
not be accessed from outside world. They are accessible to only class
inclosing it. When the developer does not want the outside world to access
some classes then the concept of inner class is useful.
There are four types of inner classes as shown in the table 10.1.
Table 10.1: Types of Inner classes
class Outer
{
class Inner
{
}
Outer class scope }
Inner class
Here Inner class can access the methods and data members of outer class
but not a vise a versa. Following code demonstrate the same.
Program 10.1:
public class Outer
{
int a=10;
class Inner
{
int p=20;
void show(String a1)
{
System.out.println(a);
}
}
public void disp()
{
System.out.println("in disp "+new Inner().p);
}
139
Core JAVA {
Outer o1=new Outer();
o1.disp();
}
}
Output:
in disp 20
int outp=7;
void outerClassMethod()
System.out.println("inside outerMethod");
int p=9;
class Inner
int inp=10;
void innerClassMethod()
140
System.out.println("inside innerMethod-->"+p); Inner Classes
System.out.println("inside innerMethod-->"+outp);
y.innerClassMethod();
System.out.println("outside class-->"+y.inp);
x.outerClassMethod();
Output:
inside outerMethod
inside innerMethod-->9
inside innerMethod-->7
outside class-->10
141
Core JAVA
Program 10.3: Demonstration of anonymous class.
//abstract class defination
abstract class Greet {
abstract void greetSomeone();
}
//extending abstract class to define its method
class Hello extends Greet {
void greetSomeone() {
System.out.println("DO greetings --from extended class ");
}
}
public class HelloTest {
void anonymousMethod()
{
//here use the anonymous class to define the abstract method.
Greet g1= new Greet(){ void greetSomeone(){
System.out.println("Anonymous greeting --from anonymous class");}};
//invoke the abstract method
g1.greetSomeone();
System.out.println("Anonymous class name "+g1);
}
public static void main(String []ar) {
HelloTest h1 =new HelloTest();
System.out.println("Demo class name "+h1);
Hello h=new Hello();
System.out.println("Extended class name "+h);
h.greetSomeone();
h1.anonymousMethod();
}
}
142
Output: Inner Classes
Demo class name HelloTest@6d06d69c
Extended class name Hello@7852e922
DO greeting --from extended class
Anonymous greeting --from anonymous class
Anonymous class name HelloTest$1@4e25154f
Output shows that compiler had created the anonymous class with name
HelloTest$1
143
Core JAVA int p=10;
static class Inner
{
int stat_p=20;
void show()
{
System.out.println("accessing static data in static class "+ data);
System.out.println("accessing non-static data in static class "+ new
Outer().p);
}
}
void disp()
{
System.out.println("--accessing static class data in non-static class method
--> "+ new Inner().stat_p );
}
public static void main(String args[])
{
Outer.Innerobj=new Outer.Inner();
obj.show();
new Outer().disp();
}
}
Output:
accessing static data in static class 30
accessing non-static data in static class 10
--accessing static class data in non-static class method --> 20
10.6 SUMMARY
The chapter gives the brief introduction about the inner class. Inner classes
restrict the use of data members and member function to the outside
world. Anonymous classes ease the job of implementing the interface and
144
extending abstract class. One can use abstract class or interface without Inner Classes
defining their implementation classes with the help of anonymous class.
10.7 EXERCISE:
10.8 REFERENCES:
1. H. Schildt, Java Complete Reference, vol. 1, no. 1. 2014.
2. E. Balagurusamy, Programming with Java, Tata McGraw-Hill
Education India, 2014
3. Sachin Malhotra & Saurabh Choudhary, Programming in JAVA, 2nd
Ed, Oxford Press
4. The Java Tutorials: http://docs.oracle.com/javase/tutorial/
❖❖❖❖
145
11
AWT
Unit Structure
11.0 Objective
11.1 Introduction,
11.2 Components,
11.3 Containers
11.4 Event-Delegation-Model and Listeners,
11.5 Button
11.6 Label
11.7 CheckBox, and CheckboxGroup
11.8 TextComponents: Text Field and Text Area
11.9 List
11.10 Choice
11.11 Menu
11.12 Layout Managers
11.12.1 FlowLayout
11.12.2 BorderLayout
11.12.3 CardLayout
11.12.4 GridLayout
11.12.5 GridBagLayout
11.12 Summary
11.14 Exercise
11.15 References
11.0 OBJECTIVE
146
11.1 INTRODUCTION AWT
11.2 COMPONENTS
Component is anabstract superclass for all visual components in AWT (as
shown in figure 11.1). Component is responsible for the remembering the
background, foreground colour and the font. Table 11.1 shows some of the
methods of Component class
Table 11.1 Methods of Component class
Methods Description
147
Core JAVA
11.3 CONTAINER
Methods Description
11.3.1 Window:
Window is a top-level container which provides the display surface. It is
not contained within any object. It has no border, title bar, menu bar. We
can’t create window’s object directly. Instead, we use its subclasses Frame
or Dialog.
11.3.2 Frame:
Frame is a subclass of a window and has border, menu bar, and title bar.
Table 11.3 shows the methods and the constructors of Frame class.
Table 11.3 Methods of Frame class
148
Methods Description AWT
Void setSize(int w, int h) Set the width and height for a frame
window
Void setVisible(boolean v) Set the visibility for frame window. If v
is true frame is visible otherwise not.
149
Core JAVA Program 11.2. Frame using Inheritance
import java.awt.*;
public class framedemo extends Frame{
framedemo() {
setTitle("Frame using inheritance ");
setSize(600,200);
setVisible(true);
}
public static void main(String args[]) throws Exception
{ framedemo f=new framedemo(); }
}
Output:
11.3.3 Dialog:
Dialog is a container which required a parent container. This is used for
accepting inputs from user or to display the information to user. It will get
close if parent window will close. Program 11.3 is the demonstration of
how to use Dialog class.
11.3.4 Panel:
Panel does not have borders. It is a simple container use for grouping the
controls. Table 11.4. shows the constructors of Panel class.
Table 11.4: Constructors of Panel class
Methods Description
Example:
Panel p=new Panel();
p.add(new Button());
the above code creates the Panel as a window and contains component
Button. Panel is not a main container. Now let’s see how events are
designed in AWT.
151
Core JAVA Here the source of the action is Button and its state change means button
gets presses. This change in state causes some activity happen like form
get submitted etc. This whole mechanism is called as Event Handling.
Java uses the event delegation model as shown in figure 11.2.
Method Description
152
How to write the code for event handling? AWT
Table 11.6 shows the list event and respective event listeners for the
various components.
Table 11.6: List of controls, Listeners and respective event class
153
Core JAVA Dialog, Window- void Window window is
Frame Listener windowClosing Event activated,
(Window Event deactivated,
we) window is
void window closed or
Opened closing
(Window Event
we)
void window
Deiconified
(Window Event
we)
void window
Closed
(Window Event
we)
void window
Activated
(Window Event
we)
void window
Deactivated
(Window Event
we)
Canvas, Mouse void mouse Mouse Event mouse is
Dialog, Motion- Dragged dragged or
Frame, Listener (Mouse Event moved
Panel, me)
Window void mouse
Moved (Mouse
Event me)
Component Key Listener void key Key Event key is pressed,
Pressed (Key released and
Event ke) typed
void key
Released (Key
Event ke)
void key Typed
(Key Event ke)
Text- TextListener void text TextEvent Text is
Component Changed (Text typed/entered in
Event te) the textbox
Now let’s see the various controls in AWT with the event they support.
154
11.5 BUTTON: AWT
This is push button when pressed action is triggered. Used for creating
navigational buttons, for submitting the form. Constructors and methods
are shown in table 11.7
Table 11.7: Methods of Button class
Methods Description
11.6 LABEL:
It’s a simple component used to display a string. Constructors and
methods are shown in table 11.8. Static fields defined in label class are
1. static int LEFT: the label is placed to left
2. static int RIGHT: the label is placed to right.
3. static int CENTER: the label is placed to centre.
Table 11.8: Methods of Label class
Methods Description
155
Core JAVA void setText(String text) Sets the caption/label to the label
Methods Description
156
Table 11.10: Methods of Check box Group class AWT
Methods Description
CheckboxGroup() Create the instance of checkbox group
Checkbox Returns the selected checkbox from
getSelectedCheckbox() the group
Program 11.4 demonstrate the use of Checkbox components
Methods Description
TextField() Creates TextField component with no text
TextField(String text) Creates TextField component with initial
text
TextField(int n) Creates TextField component with n number
of columns
TextField(String text,int n) Creates TextField component with initial
text and with n columns.
void setText(String t) Set the text t for the textfield
Methods Description
TextArea() Creates TextArea component with no text
TextArea (String text) Creates TextArea component with initial
text
TextArea (int row, int Creates TextArea component with rows and
column) columns
TextArea (String text, int Creates TextArea component with initial
row, int column) text and with rows and columns.
TextArea (String text, int Creates TextArea component with initial
row, int column, int text and with rows and columns with
scrollbars) visibility
void setText(String t) Set the text t for the TextArea
157
Core JAVA Program 11.4 demonstrates the use of TextField class.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class chkdemo implements ItemListener,ActionListener
{
Label lbl1,lbl2,lbl3;
Checkbox checkbox1,checkbox2,r1,r2,r3;
TextField txtname,t2;
Button submit;
CheckboxGroup cbg;
chkdemo()
{
Frame f = new Frame("Checkbox Example");
f.setLayout(new GridLayout(5,2));
checkbox1 = new Checkbox("C++");
lbl1=new Label("Enter your Name");
lbl2=new Label();
lbl3=new Label();
txtname=new TextField();
submit=new Button("save");
checkbox2 = new Checkbox("Java", true);
cbg=new CheckboxGroup();
r1=new Checkbox("8th",false, cbg);
158
r3=new Checkbox("10th",false, cbg); AWT
f.add(lbl1);
f.add(txtname);
f.add(checkbox1);
checkbox1.addItemListener(this);
checkbox2.addItemListener(this);
submit.addActionListener(this);
f.add(checkbox2);
f.add(r1);f.add(r2);f.add(r3);
f.add(lbl2);
f.add(submit);
f.add(lbl3);
f.setSize(400,400);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==checkbox1)
lbl2.setText("C++: " +
(e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkbox2)
lbl2.setText("Java : " +
(e.getStateChange()==1?"checked":"unchecked"));
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
lbl3.setText("Dear "+txtname.getText()+ " Your data is saved ");
}
159
Core JAVA }
public static void main (String args[])
{
new chkdemo();
}
}
Output:
11.9 LIST:
This component displays the list of text items. Here user can select one or
multiple items from the list. Table 11.13 lists the methods of the List class.
Table 11.13: Methods of List class
Methods Description
List() Constructs the empty list
List(int num) Constructs the list with number of
lines specified visible.
List(int num, Boolean mode) Constructs the list with number of
lines visible and mode of selection. If
true then list is with multiselects
option otherwise false for single item
select.
void add(String item) Add the given item in the list
160
void add(String item, int index) Add the given item at the given AWT
position in the list
void deselect(int index) Deselects the given item in the list
String getItem(int index) Returns the item present at specified
index position
int getItemCount() Returns the total item present in the
list
String[] getItems() Returns the names of the items
present in the list
int getRows() Returns the count of visible lines in
the list
int getSelectedIndex() Returns the index value of the
selected item in the list
VoidsetMultipleMode(boolean Set the multiple selection mode for
mode) the list if value is true otherwise set
single selects
void remove(String item) Removes the specified item from the
list
void select(int index) Selects the item in the given index
position
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ListDemo implements ActionListener{
Label lbl;
Button btnadd;
List l1,l2;
ListDemo() {
Frame f = new Frame();
l1 = new List(5);
l2 = new List(5);
btnadd=new Button("Add");
161
Core JAVA l1.add("Java Programming");
l1.add("C Programming");
l1.add("Python Programming");
l1.add("C++ Programming");
l1.add("C#");
btnadd.addActionListener(this);
f.add(l1);
f.add(l2);
f.add(btnadd);
f.setSize(400, 400);
f.setLayout(new FlowLayout());
f.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==btnadd)
l2.add(l1.getSelectedItem());
}
public static void main(String args[]) {
new ListDemo();
}
}
Output:
162
11.10 CHOICE: AWT
Choice is a drop-down list component. User can select any one item from
the list. Every item in the choice has index value. Table 11.14 shows the
methods of Choice class.
Methods Description
163
Core JAVA Program 11.6 demonstrates the use of Choice component.
164
new ChoiceDemo(); AWT
}
}
Output:
11.11 MENU:
Menu is the list of pop up items associated with top level windows. AWT
provides three classes MenuBar, Menu, and MenuItem. MenuBar has
multiple Menus and each menu can have sub-menus in drop-down list
form. Here MenuItem is the superclass of Menu. CheckboxMenuItem will
create the checkable menu item. Table 11.15 shows the methods of Menu
class.
Methods Description
165
Core JAVA Following program 11.7, demonstrate the use of MenuBar, MenuItem and
Menu class
import java.awt.*;
public class MenuDemo extends Frame
{
MenuDemo(){
166
{ AWT
new MenuDemo();
}
}
Output:
When the GUI is designed, the components are placed at some defined
location using setBounds(int x, int y, int w, int h)or by using setSize(int w,
int h) and setLocation(int x, int y) method. If numbers of components are
more, it becomes difficult to define the position and size of each
component. AWT supports predefined layout manager classes which helps
to place the components on the define container. AWT supports following
Layout Managers namely:
• FlowLayout
• BorderLayout
• CardLayout
• GridLayout
• GridBagLayout
167
Core JAVA Table 11.16: Methods of FlowLayout class
Constructors/Methods Description
FlowLayout.TRAILING
f.add(b2);
168
f.add(b3); AWT
f.add(b4);
f.add(b5);
f.add(b6);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String argvs[])
{
new FlowLayoutDemo();
}
}
Output:
11.12.2 BorderLayout:
BorderLayout arrange the components in five different regions, namely
centre, east, west, north, and south. Each region holds only one
component.
Following constants represents the region,
• BorderLayout.NORTH
• BorderLayout.SOUTH
• BorderLayout.EAST
• BorderLayout.WEST
• BorderLayout.CENTRE
169
Core JAVA A component is explicitly added to the one of the above said region using
method,
Add(Component c, Object region)
Ex: to add a button in south region use
add (new Button(b1), BorderLayout.SOUTH)
Table 11.17 shows the constructors and methods of BorderLayout and
program 11.9 shows how to use borderLayout.
Table 11.17: Methods of BorderLayout class
Constructors/Methods Description
setLayout(new BorderLayout(10,10));
setSize(500, 500);
setTitle("BorderLayout Demo");
Button b1 = new Button("1");
170
add(b1,BorderLayout.EAST); AWT
add(b2,BorderLayout.NORTH);
add(b3,BorderLayout.WEST);
add(b4,BorderLayout.SOUTH);
add(b5,BorderLayout.CENTER);
setVisible(true);
}
public static void main(String argvs[])
{
new BorderLayoutDemo();
}
}
Output:
11.12.3 CardLayout:
CardLayout keeps the components like the cards i. e. components are
stack and only one component is visible at a time. Table 11.18 shows the
constructors and methods of CardLayout.
171
Core JAVA Table 11.18: Methods of CardLayout class
Constructors/Methods Description
void next(Container deck) Shows the next card (in sequence) on the
container
void previous(Container deck) Shows the previous card (in sequence)
on the container
import java.awt.BorderLayout;
Import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CardLayoutDemo extends Frame implements ActionListener{
CardLayout crd;
Panel cardp,nevigate;
Button b1,b2,b3,b4,b5,first, last, next,previous,show;
CardLayoutDemo() {
//Set Layout for Main frame
setLayout(new BorderLayout());
setSize(500, 500);
setTitle("CardLayout Demo");
172
//add two panel on main frame AWT
cardp.add("Button1",b1);
cardp.add("Button2",b2);
cardp.add("Button3", b3);
cardp.add("Button4",b4);
cardp.add("Button5",b5);
add(cardp,BorderLayout.CENTER);
// create a second panel; add navigation button ; set the flowlayout
Panel nevigate=new Panel();
nevigate.setLayout(new FlowLayout());
first = new Button("first");
last = new Button("last");
next = new Button("next");
previous = new Button("previous");
show = new Button("show");
//register the navigation buttons for ActionListener
first.addActionListener(this);
last.addActionListener(this);
next.addActionListener(this);
previous.addActionListener(this);
173
Core JAVA show.addActionListener(this);
nevigate.add(first);
nevigate.add(next);
nevigate.add(last);
nevigate.add(previous);
nevigate.add(show);
add(nevigate,BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
// on click of respective navigation button, card is displayed
if(ae.getSource()==last)
crd.last(cardp);
if(ae.getSource()==first)
crd.first(cardp);
if(ae.getSource()==next)
crd.next(cardp);
if(ae.getSource()==previous)
crd.previous(cardp);
if(ae.getSource()==show)
crd.show(cardp,"Button3");
}
public static void main(String argvs[])
{
new CardLayoutDemo();
}
}
174
Output: AWT
11.12.4 GridLayout:
This layout arranges the components in grid format i. e. in 2 X 2 matrixes.
Table 11.x shows the constructors of GridLayout class. Table 11.19 shows
the constructors and methods of GridLayout.
Constructor Description
GridLayoutIint r,int c,int Creates the grid layout of given rows and
h_gap, int v_gap) columns and with specified gaps.
175
Core JAVA setTitle("GridLayout Demo");
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
b5 = new Button("5");
b6 = new Button("6");
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
setVisible(true);
}
public static void main(String argvs[])
{
new GridLayoutDemo();
}
}
Output:
176
11.12.5 Grid Bag Layout: AWT
Grid Layout places the components in a grid in a sequence of adding those
on window. All those components have same/equal fixed dimensions.
Components’ size can not be resized.
Table 11.21 describes the grid Bag Constraints’ field and their purpose
import java.awt.*;
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
public class GridBagLayoutDemo extends Frame
{
177
Core JAVA public GridBagLayoutDemo()
{
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gb);
setTitle("GridBag Layout Example");
//GridBagLayout layout = new GridBagLayout();
//this.setLayout(layout);
//contraints for textfield
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight=1;
gbc.gridwidth=3;
this.add(new TextField("Enter Number"), gbc);
//contraints for button 1
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight=1;
gbc.gridwidth=1;
this.add(new Button("1"), gbc);
//contraints for button 2
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridheight=1;
gbc.gridwidth=1;
this.add(new Button("2"), gbc);
//contraints for button 3
178
gbc.fill = GridBagConstraints.BOTH; AWT
//gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridheight=1;
gbc.gridwidth=1;
this.add(new Button("3"), gbc);
//contraints for button 4
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridheight=1;
gbc.gridwidth=1;
179
Core JAVA gbc.gridwidth = 2;
gbc.gridheight=1;
this.add(new Button("-"), gbc);
setSize(600, 600);
setPreferredSize(getSize());
setVisible(true);
}
public static void main(String[] args)
{
GridBagLayoutDemo a = new GridBagLayoutDemo();
}
}
11.13 SUMMARY
180
11.14 EXERCISE: AWT
11.15 REFERENCES
1. H. Schildt, Java Complete Reference, vol. 1, no. 1. 2014.
2. E. Balagurusamy, Programming with Java, Tata McGraw-Hill
Education India, 2014
3. Sachin Malhotra & Saurabh Choudhary, Programming in JAVA, 2nd
Ed, Oxford Press
4. The Java Tutorials: http://docs.oracle.com/javase/tutorial/
❖❖❖❖
181