Core-JAVA notes
Core-JAVA notes
General Syntax:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
1
.
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;
2
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 - -;
3
}
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
4
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);
}
}}
5
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~~~~~”; }
}
II. 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.
6
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.
7
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.
8
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
10
2
OOPS
Unit Structure
Objectives
Introduction
Class
Object
Static Keywords
Constructors
this Key Word
Inheritance
super Keyword
Polymorphism (overloading and overriding)
Abstraction
Encapsulation
Abstract Classes
Interfaces
Summary
Textbook
Additional References
Questions
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:
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.
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.
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 ();
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.
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
Java Constructor Java Method
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
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);
System.out.println(n1+n2);
}
public void add (Complex n1, Complex n2)
{
28
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.
29
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.
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.
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
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three access modifiers, private, public, and protected, provide a
variety of ways to produce the many levels of access required by these
categories.
ABSTRACT CLASSES
A class which is declared “abstract” is called as an abstract class. It can
have abstract methods as well as concrete methods. A normal class cannot
have abstract methods. Abstract classes help to describe generic types of
behaviors and object-oriented programming class hierarchy. It also
30
Core JAVA describes subclasses to offer implementation details of the abstract class.
Abstract class cannot be instantiated and is only used through inheritance.
A “final” keyword cannot be used with abstract class.
Abstract Method: A method without a body is known as an Abstract
Method. It must be declared in an abstract class. The abstract method will
never be final because the abstract class must implement all the abstract
methods. Abstract methods do not have an implementation; it only has
method signature
If a class is using an abstract method they must be declared abstract. The
opposite cannot be true. This means that an abstract class does not
necessarily have an abstract method. If a regular class extends an abstract
class, then that class must implement all the abstract methods of the
abstract parent otherwise this class will also become abstract. Abstract
methods are mostly declared where two or more subclasses are also doing
the same thing in different ways through different implementations.
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.
31
interface<interface_name> [extends [Interface_name]]{
OOPS
// fields
// Methods
}
Example:
Interface MyMath{
public static final double
PI=3.14; public int add(int a, int
b);
public int sub(int a, int b);
public int mul(int a, int b);
public int div(int a, int b);
}
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.
32
Core JAVA
2.15 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 &SaurabhChoudhary,
Oxford Press
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.
33
3
STRING MANIPULATIONS AND
INTRODUCTION TO PACKAGES
Unit Structure
Objectives
String Manipulations
Packages
Summary.
Textbook
Additional Reference(s)
Questions:
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.
STRING MANIPULATIONS:
String is a group of characters. String is defined as array of characters
without a null char to terminate the array. Any string declared represents
an object of java.lang.String class. This sting is an immutable string object
stored in memory. Each time altered version of an existing string, a new
String object is created that contains the modifications keeping the
original string unchanged. This approach is used because fixed, immutable
strings can be implemented more efficiently than changeable ones. For
those cases in which a modifiable string is desired, Java provides two
options: java.lang. String Buffer and java.lang.String Builder. Both hold
strings that can be modified after they are created.
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.
34
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.
35
copyValueOf(char[] data, int offset, int count) String Manipulations and Introduction to Packages
static
String Returns a String that represents the character sequence in the
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.
36
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”
37
String Buffer
String Manipulations and
StringBuffer class represents a mutable string that is growable and Introduction to Packages
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
StringBuf append (StringBuffer sb)
fer Appends the specified StringBuffer to this sequence.
capacity ()
int
Returns the current capacity.
charAt(int index)
char
Returns the char value in this sequence at the specified index.
StringBuf delete (int start, int end)
fer Removes the characters in a substring of this sequence.
StringBuf delete Char At (int index)
fer Removes the char at the specified position in this sequence.
ensure Capacity (int minimumCapacity)
void Ensures that the capacity is at least equal to the specified
minimum.
index Of (String str)
int Returns the index within this string of the first occurrence of the
specified substring.
38
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.
StringBuf insert(int offset, String str)
fer Inserts the string into this character sequence.
lastIndexOf(String str)
int Returns the index within this string of the rightmost occurrence of
the specified substring.
lastIndex Of(String str, int fromIndex)
int Returns the index within this string of the last occurrence of the
specified substring.
length()
int
Returns the length (character count).
replace(int start, int end, String str)
StringBuf
fer Replaces the characters in a substring of this sequence with
characters in the specified String.
reverse()
StringBuf
fer Causes this character sequence to be replaced by the reverse of the
sequence.
setCharAt(int index, char ch)
void
The character at the specified index is set to ch.
setLength(int newLength)
void
Sets the length of the character sequence.
substring(int start)
String Returns a new String that contains a subsequence of characters
currently contained in this character sequence.
substring(int start, int end)
String Returns a new String that contains a subsequence of characters
currently contained in this sequence.
toString()
String
Returns a string representing the data in this sequence.
trimToSize()
void
Attempts to reduce storage used for the character sequence.
39
String Tokenizer
String Manipulations and
The String Tokenizer class from java.util package provides the first step Introduction to Packages
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.
40
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,”
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.
41
The Float class wraps a value of String Manipulations and
Float Introduction to
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.
42
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).
43
String Manipulations and Introduction to Packages
Class Description
The root class from which all event state objects shall
EventObject
be derived.
44
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.
45
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.
46
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.
47
Class Description String Manipulations and
Introduction to Packages
JComponent Super class of all component classes in swing.
48
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.
Access specifiers
Encapsulationis the mechanism of binding together code and the data it
manipulates, and keeps both safe from outside interference and misuse.
Java achieves this using class and four different access levels. Public,
private, no-specifier (default) and protected. A public Class, method and
field can be accessed from any other class in the Java program, whether
they are in the same package or in another package. Private Fields and
methods can be accessed within the same class to which they belong.
Using private specifier we can also achieve encapsulation which is used
for hiding data. Protected fields and methods can only be accessed by
subclasses in another package or any class within the package of protected
members class. Default i. e. if not declared any specifier, it will follow the
default accessibility level and can access class, method, or field which
belongs to the same package, but not from outside this package.
CHAPTER SUMMARY:
The chapter help 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 introduced the concept of
Package and access specifiers.
TEXT BOOK(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
49
2) Programming in JAVA, 2nd Ed, Sachin Malhotra &SaurabhChoudhary,
String Manipulations and
Oxford Press Introduction to Packages
3) Core Java – SYBSC CS – Sheth Publication – Prof. Ahtesham Shaikh,
Prof.Beena Kapadia
3) The Java Tutorials: http://docs.oracle.com/javase/tutorial/
QUESTIONS:
50
Unit II
4
EXCEPTION HANDLING
Unit Structure
Introduction
Types of errors
Exceptions
Syntax of Exception Handling Code
Multiple catch Statements
Using finally Statement
Throw and throws keyword
4.9 Using Exception for debugging
Summary
Textbook
Additional References
Questions
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.
TYPES OF ERRORS
Errors may be classified into two categories:
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
}
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.
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
{
……………
…………..
}
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
USING EXCEPTION FOR DEBUGGING Exception Handling
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
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
QUESTIONS:
65
5
MULTITHREADING
Unit Structure
Introduction
Creating threads
Extending the thread Class
Stopping and Blocking a thread
5.6 Life Cycle of A thread
Using thread Methods
Synchronization in Java
Summary
Textbook
Additional Reference(s)
Questions
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.
CREATING THREADS
Creating threads in Java is simple. Threads are implemented in the form of
objects that contain a method called run(). The run() method is the heart
and soul of any thread. It makes up the entire body of a thread and is the
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.
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:
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.
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.
SYNCHRONIZATION IN JAVA
So far, we have seen threads that use their own data and methods provided
inside their run()methods. What happens when they try to use data and
methods outside themselves? In such situations, they may compete for the
same resources and may lead to serious problems.
For example, one thread may try to read a record from a file while another
is still writing to the same file. Depending on the situation, we may get
strange results.
Java provides a way to overcome this problem using a technique known as
synchronization.
In case of Java, the keyword synchronized helps to solve such problems
by keeping a watch on such locations. For example, the method that will
read information from a file and the method that will update the same file
may be declared as synchronized.
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 ()
{
……………………
……………………
}
}
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.
TEXTBOOK
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
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
Introduction
Types of Streams
Byte Stream
Character Stream
Java Input Stream Class
Java FileInput Stream Class
Java Byte Array Input Stream Class
Java Output Stream Class
Java File Output Stream Class
Java Byte Array Output Stream Class
Java Reader and Writer
Summary
Textbooks
Questions
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.
TYPES OF STREAMS
Depending upon the data a stream holds, it can be classified into following
types:
Byte Stream
Character Stream
BYTE STREAM
Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called
InputStream and OutputStream.
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.
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.
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.
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.
// creates a ByteArrayInputStream that reads a portion of array
ByteArrayInputStream input = new ByteArrayInputStream(byte[]
arr, int start, int length);
Here the input stream reads the number of bytes equal to length from the
array starting from the start position.
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.
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
// Creating a ByteArrayOutputStream with specified size
ByteArrayOutputStream out = new ByteArrayOutputStream(int
size);
Here, the size specifies the length of the array.
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
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] array = data.getBytes();
// Writes data to the output stream
out.write(array);
97
Core JAVA // Retrieves data from the output stream in string format
String streamData = out.toString();
System.out.println("Output stream: " + streamData);
out.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
Output:
JAVA READER
Java Reader is an abstract class for reading character streams. The only
methods that a subclass must implement are read(char[], int, int) and
close().
Some of the
implementation class are BufferedReader, CharArrayReader, FilterReader,
InputStreamReader,
PipedReader, StringReader
Program 6.6
import java.io.*;
98
class ReaderExample
I/O Streams
{
public static void main(String[] args)
{
try
{
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1)
{
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
SUMMARY I/O Streams
TEXTBOOKS
Herbert Schildt, Java The Complete Reference, Ninth Edition, McGraw-
Hill Education, 2014
QUESTIONS
1) What is stream? Explain the types of stream.
2) Explain the difference between input & output stream class?
10
1
7
NETWORKING
Unit Structure
Introduction
Java networking terminology
Java networking classes
Java networking interfaces
Java socket programming
Socket class
ServerSocket class
Summary
Reference
Questions
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.
SOCKET CLASS
The Socket class is used to create socket objects that help the users in
implementing all basic socket operations. The users can implement
various networking actions such as sending data, reading data, and
closing connections.
Each Socket object created using java.net.Socket class has been
associated specifically with 1 remote host. If a user wants to connect to
another host, then he must create a new socket object.
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.
SERVERSOCKET CLASS
The ServerSocket class is used for providing 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.
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);
Socket s=ss.accept(); //establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e)
{
System.out.println(e);
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.
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:
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.
REFERENCE
1) E. Balagurusamy, Programming with Java, Tata McGraw-Hill
Education India, 2014
2) Programming in JAVA, 2nd Ed, Sachin Malhotra &SaurabhChoudhary,
Oxford Press
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
Objective
Introduction
Types of Wrapper classes
Summary
Exercise
Reference
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
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
WRAPPER CLASSES
Boolean
Methods Description
Boolean(boolean b) Creates the Boolean object which holds the
same Boolean value as that of b
Ex: boolean b=True;
Boolean b1= Boolean(b)
Boolean(String b) Creates the Boolean object which holds the
same Boolean value as that of String variable b
ex: String b=”True”;
Boolean b1= Boolean(b)
booleanbooleanValue() Returns primitive boolean equivalent value of
Boolean object
boolean b=b1.booleanValue();
118
Following program 8.1, demonstrate the use of boolean wrapper class
Wrapper Classes
Program 8.1: Use of Boolean wrapper class
public class booeandemo{
public static void main(String []args)
{
boolean b=true;
Boolean b1=new Boolean(b);
System.out.println("Boolean object --> "+b1);
String s="False";
b1=new Boolean(s);
System.out.println("Boolean object --> "+b1);
System.out.println("Boolean object to primitive value -->
"+b1.booleanValue());
}
}
Output:
Boolean object --> true
Boolean object --> false
Boolean object to primitive value --> false
Table 8.2 shows the listing of other wrapper classes and their methods
Table 8.2: Wrapper classes and their methods
Wrapper Method Description
class
Integer Integer(int intval) Creates an Integer objects from
int value
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)
121
Core JAVA ArrayList<Integer> a1 = new ArrayList<Integer>(); a1.add(n1);
a1.add(n2[0]);
a1.add(n2[1]);
System.out.println("Elements in arraylist are--> "+a1); if(n1<10) //unboxing
System.out.println(n1+" is smaller than 10 "); else
System.out.println(n1+" is larger than 10");
}
}
Output:
Elements in arraylist are--> [12, 20, 30]
12 is larger than 10
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.
EXERCISE:
1. What is wrapper class?
2. Create a list of integer values 10,20,30,40,50.
3. What is autoboxing and unboxing?
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
Objective
Introduction to Collections Framework
Util package
List
Set
Map
List interface & its classes
ArrayList
LinkedList
Set interface & its classes
HashSet
TreeSet
Map interface & its classes
HashMap
TreeMap
Iterator
Summary
Exercise
Reference & Bibliography
OBJECTIVE
INTRODUCTION TO COLLECTIONS
FRAMEWORK:
Collection means group of things. For example, collection of coins called
a bunch, collection of tickets. Similarly,in computing collection of data in
a one unit which helps to store, manipulate the data easily.
123
Core JAVA Collection framework is a framework which is use to represent the data
and helps in manipulating the data in easy way. Each collection
framework provides the methods to represent the data (Interface),
manipulate the data (Implementations) and algorithms to search, sort the
data efficiently.
Collection framework provides high performance by allowing the
programmer to implement the defined data structures and algorithms. Low
level complexities for defining the data structure and the algorithms are
eliminated. Instead, use of appropriate Collection framework for defining
and manipulating the group of data is required.
UTIL PACKAGE
Utility classes such as Collection framework, event, date and time,
internationalization, currency, StringTokenizer are present in the java.util
package. Lets see Collection framework in detail.
Collection framework provides different Interfaces for representing the
data. Figure 9.1 shows the collection framework hierarchy.
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.
LIST INTERFACE:
List is the interface derived from Collection interface. List allows the
duplicates and stores the elements in order. List maintains the position-
oriented collection of objects. Table 9.2 shows the methods of list
interface.
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).
MAP INTERFACE:
Map is not inherited from Collection interface. Map interface allows the
collection of elements in the form of key-value pair. With the help of the
key, value can be searched. Keys duplication is not allowed but value may
be duplicated. Table 9.3 listed the methods of Map interface.
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
LIST INTERFACE & ITS CLASSES: Collection Framework
ArrayList class
ArrayList class extends AbstractList class and implements List interface.
ArrayList is a resizable. Arrays in java are fixed in size but arrayList
allows you to create a collection of object which can be accessible like
array and can grow or shrink during execution. Table 9.5 shows the
constructor and methods of ArrayList class
Methods Description
ArrayList( ) Creates an empty ArrayList object
ArrayList(Collection c) Creates an ArrayList object using existing collection
ArrayList(int capacity) Creates an ArrayList object with some initial capacity
object[ ] toArray( ) Converts ArrayList object to an array of object.
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
LinkedList class
The LinkedList class extends AbstractSequentialList class and implements
the List, Deque, and Queue interfaces. Table 9.6 shows the constructors
and the methods of LinkedList class.
Methods Description
LinkedList( ) Creates an empty Linkedlist object.
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
HashSet( ) HashSet is used to create a HashSet
which has default initial capacity of
16 elements and fil-ration of 0.75
HashSet(Collection c) Create a HashSet with existing
Collection object.
HashSet(int capacity) Creates a HashSet object with initial
capacity
HashSet(int capacity, float Capacity is the numeric value which
fillRatio) tells how many elements in hashSet
Fillratio is the number that tells at
what size, the capacity of HashSet
should be increase automatically.
130
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
TreeSet( ) Creates an empty TreeSet object
TreeSet(Collection c) Create TreeSet object from existing
collection object
TreeSet(Comparator Create TreeSet object in order define by the
comp) comparator object.
TreeSet(SortedSet ss) Create TreeSet object from existing
SortedSet object
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.
HashMap class:
133
Core JAVA
TreeMap class
Methods Description
TreeMap( ) Constructor used to create an empty
tree map and keys will be sorted in
natural order
TreeMap(Comparator Constructor creates an empty tree-
comp) based map and keys will be sorted
using the Comparator object.
TreeMap(Map m) constructor creates a tree map using
existing map elements and keys will
be sorted in natural order.
TreeMap(SortedMap sm) Constructor creates a tree map using
existing SortedMap, and keys will be
sorted in the same order as in
SortedMap sm.
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
136
Core JAVA Following code demonstrate the use of Iterator class.
SUMMARY
137
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.
EXERCISE
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/
138
10
INNER CLASSES
Unit Structure
Objective
Introduction
Inner class/nested class
Method Local inner class
Static inner class
Anonymous inner class
Summary
Exercise
References
OBJECTIVE:
Objective of this chapter is
Learn the use of inner classes
Learn the different type of inner classes
Learn implementation of classes with the help of anonymous class.
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
}
}
Output:
in disp 20
This type of the class is written inside the method of outer class. The
inner class can access the methods and data members defined in outer
class but class’s own member functions and data is not accessible
outside. The program 10.2 demonstrates the method local inner class.
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
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
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.
EXERCISE:
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
Objective
Introduction,
Components,
Containers
Event-Delegation-Model and Listeners,
Button
Label
CheckBox, and CheckboxGroup
TextComponents: Text Field and Text Area
List
Choice
Menu
Layout Managers
FlowLayout
BorderLayout
CardLayout
GridLayout
GridBagLayout
11.12 Summary
Exercise
References
OBJECTIVE
146
INTRODUCTION AWT
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
public void setSize(int Set the size of the componen with
width,int specific width and height t
height)
147
Core JAVA
CONTAINER
Methods Description
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.
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
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:
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.
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
Panel() Creates the panel object with default
layout manager
Panel(LayoutManager lm) Creates a panel with specific layout
manager
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
EventObject(Object source) Constructs the Event object for the
source object
Object getSource( ) Returns the source object which
regenerates the event
String toString() Returns the string representation of the
event
152
How to write the code for event handling?
AWT
Step1: Import java.awt.event.*
Step2: Implement an appropriate listener for the event
Implements the Listener for the event
Ex: public class abc extends Frame implements ActionListener {
Step3: Register the source for the event listener
this.addActionListener(this)
Step4: Implement the even handlers
public void actionPerformed(ActionEvent ae)
{
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
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
Button() Creates the button object with no
label on it
Button(String lbl) Creates the button object with given
label on it
void setLabel(String str) Set the new label for the button
String getLabel( ) Returns the label of the button on
which this method is called
Void Register the button object for
addActionListener(ActionEvent ae) ActionListener
Void Remove the ActionListener for the
removeActionListener(ActionEvent button object.
ae)
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
Label() Constructs the label with no caption
Label(String text) Constructs the label with caption
Label(String text, int Constructs the label with caption and
alignement) aligned it to the left, right or centre as
specified
Ex: Label(“Name”,Label.CENTER)
155
Core JAVA void setText(String text) Sets the caption/label to the label
String getText() Returns the caption/label of the label
int getAlignment() Returns the alignment value of the label
Methods Description
Checkbox() Constructs the checkbox with no
label/string
Checkbox(String label) Constructs the checkbox with
label/string
Checkbox(String label, Boolean Constructs the checkbox with
state) label/string and given state
Checkbox(String label, boolean Constructs the checkbox with
state, CheckboxGroup chk) label/string, its initial state and its
specified checkbox group
Void addItemListener It registers the checkbox for item
(IntemListener al) listener.
Boolean getState() Returns the state of the checkbox.
True if it is selected otherwise false.
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
TEXT COMPONENT:
It is a superclass for a TextField and TextArea Class that allows the user to
enter the text.
Text Field and Text Area:
TextField creates a single line where as TextArea for multiline text. Table
11.11 and table 11.12 shows some of the methods of TextField and
TextArea class
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);
r2=new Checkbox("9th",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:
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
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
Choice() Constructs the empty choice list
void add(String item) Adds the specified item in the
choice
String getItem(int index) Returns the string/item present in
the given index position
int getItemCount() Returns the number of items in
the choice.
String getSelectedItem() Returns the selected string/item.
int getSelectedIndex() Returns the index value of the
selected string/item.
void insert(String item, int index) Insert the specific item at the
specific given index position.
void remove(int position) Removes the item from the given
index position
void remove(String item) Removes the specified item from
the choice
void removeAll() Remove all items from the
choice.
void addItemListener(ItemListener l) Register the choice component
for the ItemListener
void Remove the registration of choice
removeItemListener(ItemListener l) component for the ItemListener
163
Core JAVA Program 11.6 demonstrates the use of Choice component.
164
new ChoiceDemo(); AWT
}
}
Output:
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
Menu() Construct a new menu with no label
Menu(String label) Construct a new menu with label
MenuItem add(MenuItem mi) Add the menu item to the menu
void add(String label) Add the item with given label
void addSeparator() Add separator between menu
int countItems() Returns the items in the menu
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(){
setTitle("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Close");
MenuItem i1=new MenuItem("New");
MenuItem i2=new MenuItem("Open");
MenuItem i3=new MenuItem("Save");
MenuItem i4=new MenuItem("Save As");
MenuItem i5=new MenuItem("Exit");
menu.add(i1);
menu.add(i2);
menu.add(i3);
menu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
setMenuBar(mb);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
166
{ AWT
new MenuDemo();
}
}
Output:
LAYOUT MANAGER:
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() Creates a default FlowLayout which place
the components starting from centre of first
line. By default, the space between two
components is 5 pixel.
FlowLayout(int alignment) Creates a FlowLayout with 5 pixel space
between each components and places the
component as per the alignment specified
FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER
FlowLayout.LEADING
FlowLayout.TRAILING
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
BorderLayout() Creates a default BorderLayout which
place the components at centre.
BorderLayout (int hgap, int Creates a BorderLayout with specific
vgap) space/gaps between components.
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:
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
CardLayout() Creates a default CardLayout
172
//add two panel on main frame
AWT
// set the cardlayout for first panel
cardp=new Panel();
crd=new CardLayout();
cardp.setLayout(crd);
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
b5 = new Button("5");
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
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
GridLayout() Creates the grid layout of single column
GridLayout(int r, int c) Creates the grid layout of given rows and
columns
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
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 Table
177
Core JAVA public GridBagLayoutDemo()
{
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gb);
setTitle("GridBag Layout Example");
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;
this.add(new Button("4"), gbc);
//contraints for button 2
gbc.gridx = 2;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = 1;
gbc.gridheight=2;
this.add(new Button("+"), gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = 1;
gbc.gridheight=1;
this.add(new Button("="), gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
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();
}
}
SUMMARY
180
EXERCISE: AWT
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