Java Programming by K. Adisesha
Java Programming by K. Adisesha
Platform independent
Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into
platform specific machine, rather into platform independent byte code. This byte code is distributed over the web
and interpreted by virtual Machine (JVM) on whichever platform it is being run.
Reusability of Code
Emphasis on data rather than procedure
Data is hidden and cannot be accessed by external functions
Objects can communicate with each other through functions
New data and functions can be easily added Java has powerful features. The following are some of
them:Simple
Reusable
Portable (Platform Independent)
Distributed
Robust
Secure
High Performance
Dynamic
Threaded
Interpreted
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
Object Oriented Programming is a method of implementation in which programs are organized as cooperative
collection of objects, each of which represents an instance of a class, and whose classes are all members of a
hierarchy of classes united via inheritance relationships.
OOP Concepts
Four principles of Object Oriented Programming are
Abstraction
Encapsulation
Inheritance
Polymorphism
Abstraction
Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and
thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.
Encapsulation
Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and
behavior ; encapsulation serves to separate the contractual interface of an abstraction and its implementation.
Encapsulation
* Hides the implementation details of a class.
* Forces the user to use an interface to access data
* Makes the code more maintainable.
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
Polymorphism
Polymorphism is the existence of the classes or methods in different forms or single name denoting different
implementations.
Java is distributed
With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the
objects across net via URLs.
Java is Multithreaded
One of the powerful aspects of the Java language is that it allows multiple threads of execution to run
concurrently within the same program A single Java program can have many different threads executing
independently and continuously. Multiple Java applets can run on the browser at the same time sharing the CPU
time.
Java is Secure
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
Java was designed to allow secure execution of code across network. To make Java secure many of the features of
C and C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in
memory.
Garbage collection
Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of
memory. Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does
not use delete operator to free the memory as it is done in C++ to free the memory if the object is no longer
needed. It is done automatically with garbage collector.
Java Applications
Java has evolved from a simple language providing interactive dynamic content for web pages to a predominant
enterprise-enabled programming language suitable for developing significant and critical applications. Today, It
is used for many types of applications including Web based applications, Financial applications, Gaming
applications, embedded systems, Distributed enterprise applications, mobile applications, Image processors,
desktop applications and many more. This site outlines the building blocks of java by stating few java examples
along with some java tutorials.
Java Architecture
The Java environment is composed of a number of system components. You use these components at compile
time to create the Java program and at run time to execute the program. Java achieves its independence by
creating programs designed to run on the Java Virtual Machine rather than any specific computer system.
After you write a Java program, you use a compiler that reads the statements in the program and translates
them into a machine independent format called bytecode.
Bytecode files, which are very compact, are easily transported through a distributed system like the
Internet.
The compiled Java code (resulting byte code) will be executed at run time.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
Output
Hello World
ABOUT THE PROGRAM
I created a class named HelloWorld containing a simple main function within it. The keyword class specifies
that we are defining a class. The name of a public class is spelled exactly as the name of the file (Case Sensitive).
All java programs begin execution with the method named main(). main method that gets executed has the
following signature : public static void main(String args[]).Declaring this method as public means that it is
accessible from outside the class so that the JVM can find it when it looks for the program to start it. It is
necessary that the method is declared with return type void (i.e. no arguments are returned from the method). The
main method contains a String argument array that can contain the command line arguments. The brackets { and
} mark the beginning and ending of the class. The program contains a line System.out.println(Hello World);
that tells the computer to print out on one line of text namely Hello World. The semi-colon ; ends the line of
code. The double slashes // are used for comments that can be used to describe what a source code is doing.
Everything to the right of the slashes on the same line does not get compiled, as they are simply the comments in
a program.
Java Main method Declarations
class MainExample1 {public static void main(String[] args) {}}
class MainExample2 {public static void main(String []args) {}}
class MainExample3 {public static void main(String args[]) {}}
All the 3 valid main methods shown above accepts a single String array argument.
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
Javadoc
The javadoc tool provided by Sun is used to produce documentation for an application or program,
Jar Files
A jar file is used to group together related class files into a single file for more compact storage, distribution, and
transmission.
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
directory than, your program must get executed without any problems as, java tries to find your .class file is your
current directory. If your class files are present in some other directory other than that of the java files we must set
the CLASSPATH pointing to the directory that contain your compiled class files.CLASSPATH can be set as
follows on a Windows machine:
a. Click Start > Right Click My Computer and click on Properties
b. Click Advanced > Environment Variables.
Add the location of classes folder containing all your java classes in User Variables.
If there are already some entries in the CLASSPATH variable then you must add a semicolon and then add the
new value . The new class path takes effect in each new command prompt window you open after setting the
CLASSPATH variable.
Java 1.5
The Java 1.5 released in September 2004.
Goals
Less code complexity
Better readability
More compile-time type safety
Some new functionality (generics, scanner)
New Features
Enhanced for loop
Enumerated types
Autoboxing & unboxing
Generic types
Scanner
Variable number of arguments (varargs)
Static imports
Annotations
Keywords
There are certain words with a specific meaning in java which tell (help) the compiler what the program is
supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in
java are case sensitive, all characters being lower case.
Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site).
All the keywords are in lowercase.
abstract
boolean
break
byte
case
catch
char
class
const
continue
Prof. K. ADISESHA
default
do
double
else
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
www.adisesha.9f.com
this
throw
throws
transient
try
void
volatile
while
| email: adisesha1@rediffmail.com
Comments
Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores
comments and hence its only for documentation of the program.
Java supports three comment styles.
Block style comments begin with /* and terminate with */ that spans multiple lines.
Line style comments begin with // and terminate at the end of the line. (Shown in the above program)
Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally
created using the automatic documentation generation tool, such as javadoc. (Shown in the above program)
name of this compiled file is comprised of the name of the class with .class as an extension.
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
Note in the above example, a compilation error results in where the variable is tried to be accessed and not at the
place where its declared without any value.
The data type indicates the attributes of the variable, such as the range of values that can be stored and the
operators that can be used to manipulate the variable. Java has four main primitive data types built into the
language. You can also create your own composite data types.
Java has four main primitive data types built into the language. We can also create our own data types.
The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types.
Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the
below table. The size for each Java type can be obtained by a simple Google search.
Data Type
Default Value (for fields)
Range
byte
0
-127 to +128
short
0
-32768 to +32767
int
0
long
0L
float
0.0f
double
0.0d
char
\u0000
0 to 65535
String (object)
null
boolean
false
When we declare a variable we assign it an identifier and a data type.
For Example
String message = hello world
In the above statement, String is the data type for the identifier message. If you dont specify a value when the
variable is declared, it will be assigned the default value for its data type.
Identifier Naming Rules
Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character.
Must begin with a letter, dollar sign, or an underscore
Are case sensitive
Keywords cannot be used as identifiers
Within a given section of your program or scope, each user defined item must have a unique identifier
Can be of any length.
Classes
A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An
object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to
describe the behavior of an object. Methods are nothing but members of a class that provide a service for an
object or perform some business logic.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
Objects
An object is an instance of a class created using a new operator. The new operator returns a reference to a new
instance of a class. This reference can be assigned to a reference variable of the class. The process of creating
objects from a class is called instantiation. An object reference provides a handle to an object that is created and
stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Interface
An Interface is a contract in the form of collection of method and constant declarations. When a class implements
an interface, it promises to implement all of the methods declared in that interface.
Instance Members
Each object created will have its own copies of the fields defined in its class called instance variables which
represent an objects state. The methods of an object define its behaviour called instance methods. Instance
variables and instance methods, which belong to objects, are collectively called instance members. The dot .
notation with a object reference is used to access Instance Members.
Static Members
Static members are those that belong to a class as a whole and not to a particular instance (object). A static
variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and
static methods are collectively known as static members, and are declared with a keyword static. Static members
in the class can be accessed either by using the class name or by using the object reference, but instance members
can only be accessed via object references.
Below is a program showing the various parts of the basic language syntax that were discussed above.
/** Comment
* Displays "Hello World!" to the standard output.
*/
public class HelloWorld {
String output = "";
static HelloWorld helloObj; //Line 1
public HelloWorld(){
output = "Hello World";
}
public String printMessage(){
return output;
}
public static void main (String args[]) {
helloObj = new HelloWorld(); //Line 2
System.out.println(helloObj.printMessage());
}
}
Java Operators
They are used to manipulate primitive data types. Java operators can be classified as unary, binary, or ternary
meaning taking one, two, or three arguments, respectively. A unary operator may appear
before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its
arguments.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
=
>
&&
&
+=
<<=
?:
+
*
/
%
++
< >=
<= ==
!=
||
&
|
!
^
|
^
>>
>>>
-=
*=
/=
%=
>>= >>>=
--
Java has eight different operator types: assignment, arithmetic, relational, logical, bitwise, compound assignment,
conditional, and type.
Assignment operators
The java assignment operator statement has the following syntax:
<variable> = <expression>
If the value already exists in the variable it is overwritten by the assignment operator (=).
public class AssignmentOperatorsDemo {
public AssignmentOperatorsDemo() {
//
Assigning Primitive Values
int j, k;
j = 10; // j gets the value 10.
j = 5; // j gets the value 5. Previous value is overwritten.
k = j; // k gets the value 5.
System.out.println("j is : " + j);
System.out.println("k is : " + k);
//
Assigning References
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
System.out.println("i1 is : " + i1);
System.out.println("i2 is : " + i2);
i1 = i2;
System.out.println("i1 is : " + i1);
System.out.println("i2 is : " + i2);
//
Multiple Assignments
k = j = 10; // (k = (j = 10))
System.out.println("j is : " + j);
System.out.println("k is : " + k);
}
public static void main(String args[]) {
new AssignmentOperatorsDemo();
}
}
Arithmetic operators
Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (or
remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below
that demonstrates the different arithmetic operators in java.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
10
The binary operator + is overloaded in the sense that the operation performed is determined by the type of the
operands. When one of the operands is a String object, the other operand is implicitly converted to its string
representation and string concatenation is performed.
String message = 100 + Messages; //100 Messages
public class ArithmeticOperatorsDemo {
public ArithmeticOperatorsDemo() {
int x, y = 10, z = 5;
x = y + z;
System.out.println("+ operator resulted in " + x);
x = y - z;
System.out.println("- operator resulted in " + x);
x = y * z;
System.out.println("* operator resulted in " + x);
x = y / z;
System.out.println("/ operator resulted in " + x);
x = y % z;
System.out.println("% operator resulted in " + x);
x = y++;
System.out.println("Postfix ++ operator resulted in " + x);
x = ++z;
System.out.println("Prefix ++ operator resulted in " + x);
x = -y;
System.out.println("Unary operator resulted in " + x);
// Some examples of special Cases
int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is
// Integer.MIN_VALUE.
int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is
// Integer.MAX_VALUE.
System.out.println("tooBig becomes " + tooBig);
System.out.println("tooSmall becomes " + tooSmall);
System.out.println(4.0 / 0.0); // Prints: Infinity
System.out.println(-4.0 / 0.0); // Prints: -Infinity
System.out.println(0.0 / 0.0); // Prints: NaN
double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value
// 1.0.
double d2 = 12.0F / 8; // result: 1.5
System.out.println("d1 is " + d1);
System.out.println("d2 iss " + d2);
}
public static void main(String args[]) {
new ArithmeticOperatorsDemo();
}
}
ArithmeticOperatorsDemo Source code
Relational operators
Relational operators in Java are used to compare 2 or more objects. Java provides six relational operators:
greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and not equal (!=).
All relational operators are binary operators, and their operands are numeric expressions.
Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value.
Relational operators have precedence lower than arithmetic operators, but higher than that of the assignment
operators. An example program is shown below that demonstrates the different relational operators in java.
public class RelationalOperatorsDemo {
public RelationalOperatorsDemo( ) {
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
11
int x = 10, y = 5;
System.out.println("x > y : "+(x > y));
System.out.println("x < y : "+(x < y));
System.out.println("x >= y : "+(x >= y));
System.out.println("x <= y : "+(x <= y));
System.out.println("x == y : "+(x == y));
System.out.println("x != y : "+(x != y));
}
public static void main(String args[]){
new RelationalOperatorsDemo();
}
}
RelationalOperatorsDemo Source code
Logical operators
Logical operators return a true or false value based on the state of the Variables. There are six logical, or boolean,
operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a
logical operator must be a boolean data type, and the result is always a boolean data type. An example program is
shown below that demonstrates the different Logical operators in java.
public class LogicalOperatorsDemo {
public LogicalOperatorsDemo() {
boolean x = true;
boolean y = false;
System.out.println("x & y : " + (x & y));
System.out.println("x && y : " + (x && y));
System.out.println("x | y : " + (x | y));
System.out.println("x || y: " + (x || y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("!x : " + (!x));
}
public static void main(String args[]) {
new LogicalOperatorsDemo();
}
}
!x
x&y
x|y
x^y
true
true
false
false
true
false
true
false
false
false
true
true
x && y
true
false
false
false
x || y
true
true
true
false
false
true
true
false
Bitwise operators
Java provides Bit wise operators to manipulate the contents of variables at the bit level.
These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise
operators. They are AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned Rightshift. An example program is shown below that demonstrates the different Bit wise operators in java.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
12
Output
3,0,3
1
0
1
0
0
0
1
1
1
0
0
0
1
1
1
0
0
1
1
0
/*
* The below program demonstrates bitwise operators keeping in mind operator precedence
* Operator Precedence starting with the highest is -> |, ^, &
*/
public class BitwisePrecedenceEx {
public static void main(String[] args) {
int a = 1 | 2 ^ 3 & 5;
int b = ((1 | 2) ^ 3) & 5;
int c = 1 | (2 ^ (3 & 5));
System.out.print(a + "," + b + "," + c);
}
}
BitwiseOperatorsDemo2 Source code
Compound operators
The compound operators perform shortcuts in common programming operations. Java has eleven compound
assignment operators.
Syntax:
argument1 operator = argument2.
The above statement is the same as, argument1 = argument1 operator argument2. An example program is shown
below that demonstrates the different Compound operators in java.
public class CompoundOperatorsDemo {
public CompoundOperatorsDemo() {
int x = 0, y = 5;
x += 3;
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
13
Conditional operators
The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator
evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false,
then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement.
The conditional expression can be nested and the conditional operator associates from right to left:
(a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)
An example program is shown below that demonstrates the Ternary operator in java.
public class TernaryOperatorsDemo {
public TernaryOperatorsDemo() {
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : " + z);
}
public static void main(String args[]) {
new TernaryOperatorsDemo();
}
}
TernaryOperatorsDemo Source code
/*
* The following programs shows that when no explicit parenthesis is used then the
conditional operator
* evaluation is from right to left
*/
public class BooleanEx1 {
static String m1(boolean b) {
return b ? "T" : "F";
}
public static void main(String[] args) {
boolean t1 = false ? false : true ? false : true ? false : true;
boolean t2 = false ? false
: (true ? false : (true ? false : true));
boolean t3 = ((false ? false : true) ? false : true) ? false
: true;
System.out.println(m1(t1) + m1(t2) + m1(t3));
}
}
Output FFT
TernaryOperatorsDemo2 Source code
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
14
Type conversion allows a value to be changed from one primitive data type to another. Conversion can occur
explicitly, as specified in
the program, or implicitly, by Java itself. Java allows both type widening and type narrowing conversions.
In java Conversions can occur by the following ways:
Using a cast operator (explicit promotion)
Using an arithmetic operator is used with arguments of different data types (arithmetic promotion)
A value of one type is assigned to a variable of a different type (assignment promotion)
Operator Precedence
The order in which operators are applied is known as precedence. Operators with a higher precedence are applied
before operators with a lower precedence. The operator precedence order of Java is shown below. Operators at the
top of the table are applied before operators lower down in the table. If two operators have the same precedence,
they are applied in the order they appear in a statement.
That is, from left to right. You can use parentheses to override the default precedence.
postfix
unary
creation/caste
multiplicative
additive
shift
relational
equality
bitwise AND
bitwise exclusive OR
bitwise inclusive OR
logical AND
logical OR
ternary
assignment
[] . () expr++ expr
++expr expr +expr -expr ! ~
new (type)expr
*/%
+>> >>>
< <= > >= instanceof
== !=
&
^
|
&&
||
?:
= op=
Selection Statements
The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if
block is skipped and execution continues with the rest of the program. You can either have a single statement or a
block of code within an if statement. Note that the conditional expression must be a Boolean expression.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
15
Switch Case Statement The switch case statement, also called a case statement is a multi-way branch with
several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins
with a keyword, followed by an expression that equates to a no long integral value. Following the controlling
expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant
and each must be unique. When the switch statement executes, it compares the value of the controlling expression
to the values of each case label. The program will select the value of the case label that equals the value of the
controlling expression and branch down that path to the end of the code block. If none of the case label values
match, then none of the codes within the switch statement code block will be executed. Java includes a default
label to use in cases where there are no matches. We can have a nested switch within a case block of an outer
switch.
Its general form is as follows:
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
16
} // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in
the middle of the switch statement code block, you must insert a break statement, which causes the program to
continue executing after the current code block.
Below is a java example that demonstrates conditional execution based on nested if else statement condition to
find the greatest of 3 numbers.
public class SwitchCaseStatementDemo {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c) {
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
}
switch (status) {
case 1:
System.out.println("a is the greatest");
break;
case 2:
System.out.println("b is the greatest");
break;
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}
Output: c is the greatest
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
17
Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in
the Java program, whether these classes are in the same package or in another package.
private access modifier
The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used
for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled,
which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to
make all fields private and provide public getter methods for them.
protected access modifier
The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and
methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed
only by subclasses in other packages. Classes in the same package can also access protected fields, methods and
constructors as well, even if they are not a subclass of the protected members class.
Default access modifier
Java provides a default specifier which is used when no access modifier is present. Any class, field, method or
constructor that has no declared access modifier is accessible only by classes in the same package. The default
modifier is not used for fields and methods within an interface.
Below is a program to demonstrate the use of public, private, protected and default access modifiers while
accessing fields and methods. The output of each of these java files depict the Java access specifies.
The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file contains the
Base class and a subclass within the enclosing class that belongs to the same class as shown below.
package pckage1;
class BaseClass {
public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; //Implicit Default Access Modifier
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
private int getY() {
return y;
}
private void setY(int y) {
this.y = y;
}
protected int getZ() {
return z;
}
protected void setZ(int z) {
this.z = z;
}
int getA() {
return a;
}
void setA(int a) {
this.a = a;
}
}
public class SubclassInSamePackage extends BaseClass {
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
18
The second class is SubClassInDifferentPackage.java which is present in a different package then the first one.
This java class extends First class (SubclassInSamePackage.java).
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
19
import pckage1.*;
public class SubClassInDifferentPackage extends SubclassInSamePackage {
public int getZZZ() {
return z;
}
public static void main(String args[]) {
SubClassInDifferentPackage subClassDiffObj = new
SubClassInDifferentPackage();
SubclassInSamePackage subClassObj = new
SubclassInSamePackage();
//Access specifiers - Public
System.out.println("Value of x is : " + subClassObj.x);
subClassObj.setX(30);
System.out.println("Value of x is : " + subClassObj.x);
//Access specifiers - Private
//
if we remove the comments it would result in a compilaton
//
error as the fields and methods being accessed are private
/*
System.out.println("Value of y is : "+subClassObj.y);
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/
//Access specifiers - Protected
//
If we remove the comments it would result in a compilaton
//
error as the fields and methods being accessed are protected.
/*
System.out.println("Value of z is : "+subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : "+subClassObj.z);*/
System.out.println("Value of z is : " + subClassDiffObj.getZZZ());
//Access Modifiers - Default
//
If we remove the comments it would result in a compilaton
//
error as the fields and methods being accessed are default.
/*
System.out.println("Value of a is : "+subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of a is : "+subClassObj.a);*/
}
}
Output
Value of x is : 10
Value of x is : 30
Value of z is : 10
The third class is ClassInDifferentPackage.java which is present in a different package then the first one.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
20
import pckage1.*;
public class ClassInDifferentPackage {
public static void main(String args[]) {
SubclassInSamePackage subClassObj = new SubclassInSamePackage();
//Access Modifiers - Public
System.out.println("Value of x is : " + subClassObj.x);
subClassObj.setX(30);
System.out.println("Value of x is : " + subClassObj.x);
//Access Modifiers - Private
//
If we remove the comments it would result in a compilaton
//
error as the fields and methods being accessed are private
/*
System.out.println("Value of y is : "+subClassObj.y);
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/
//Access Modifiers - Protected
//
If we remove the comments it would result in a compilaton
//
error as the fields and methods being accessed are protected.
/*
System.out.println("Value of z is : "+subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : "+subClassObj.z);*/
//Access Modifiers - Default
//
If we remove the comments it would result in a compilaton
//
error as the fields and methods being accessed are default.
/*
System.out.println("Value of a is : "+subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of a is : "+subClassObj.a);*/
}
}
Output:
Value of x is : 10
Value of x is : 30
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
21
Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length,
breadth and height. Also the class contains a member function getVolume().
public class Cube {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
}
Instance Variables
Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object
has a state that is determined by the values stored in the object. An object is said to have changed its state when
one or more data values stored in the object have been modified. When an object responds to a message, it will
usually perform an action, change its state etc. An object that has the ability to store values is often said to have
persistence.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
22
Consider this simple Java program showing the use of static fields and static methods
// Class and Object initialization showing the Object Oriented concepts in Java
class Cube {
int length = 10;
int breadth = 10;
int height = 10;
public static int numOfCubes = 0; // static variable
public static int getNoOfCubes() { //static method
return numOfCubes;
}
public Cube() {
numOfCubes++; //
}
}
public class CubeStaticTest {
public static void main(String args[]) {
System.out.println("Number of Cube objects = " + Cube.numOfCubes);
System.out.println("Number of Cube objects = "
+ Cube.getNoOfCubes());
}
}
CubeStaticTest.java
Output
Number of Cube objects = 0
Number of Cube objects = 0
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
23
An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only
be manipulated via references, which can be stored in variables. Creating variables of your class type is similar to
creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of
instance variables comes into existence which defines the characteristics of that object. If you want to create an
object of the class and have the reference variable associated with this object, you must also allocate memory for
the object by using the new operator. This process is called instantiating an object or creating an object instance.
When you create a new object, you use the new operator to instantiate the object. The new operator returns the
location of the object which you assign o a reference type.
Method Overloading
Method overloading results when two or more methods in the same class have the same name but different
parameters. Methods with the same name must differ in their types or number of parameters. This allows the
compiler to match parameters and choose the correct method when a number of choices exist. Changing just the
return type is not enough to overload a method, and will be a compile-time error. They must have a different
signature. When no method matching the input parameters is found, the compiler attempts to convert the input
parameters to types of greater precision. A match may then be found without error. At compile time, the right
implementation is chosen based on the signature of the method call
Below is an example of a class demonstrating Method Overloading
public class MethodOverloadDemo {
void sumOfParams() { // First Version
System.out.println("No parameters");
}
void sumOfParams(int a) { // Second Version
System.out.println("One parameter: " + a);
}
int sumOfParams(int a, int b) { // Third Version
System.out.println("Two parameters: " + a + " , " + b);
return a + b;
}
double sumOfParams(double a, double b) { // Fourth Version
System.out.println("Two double parameters: " + a + " , " + b);
return a + b;
}
public static void main(String args[]) {
MethodOverloadDemo moDemo = new MethodOverloadDemo();
int intResult;
double doubleResult;
moDemo.sumOfParams();
System.out.println();
moDemo.sumOfParams(2);
System.out.println();
intResult = moDemo.sumOfParams(10, 20);
System.out.println("Sum is " + intResult);
System.out.println();
doubleResult = moDemo.sumOfParams(1.1, 2.2);
System.out.println("Sum is " + doubleResult);
System.out.println();
}
}
MethodOverloadDemo.java
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
24
Output: No parameters
One parameter: 2
Two parameters: 10 , 20
Sum is 30
Two double parameters: 1.1 , 2.2
Sum is 3.3000000000000003
Below is a code snippet to show whether a Class Object Represents a Class or Interface:
Class cls = java.lang.String.class;
boolean isClass = !cls.isInterface(); // true
cls = java.lang.Cloneable.class;
isClass = !cls.isInterface(); // false
Java Constructors
A java constructor has the same name as the name of the class to which it belongs. Constructors syntax does
not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new operator,
the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or initializations,
when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call.
Constructor arguments provide you with a way to provide parameters for the initialization of an object. Below is
an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
25
Cube1.java
Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects.
If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default
constructor will be a compile time error if an explicit default constructor is not provided in such a case.
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
26
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube2() {
this(10, 10);
System.out.println("Finished with Default Constructor");
}
Cube2(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having 2
params");
}
Cube2(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having 3
params");
}
public static void main(String[] args) {
Cube2 cubeObj1, cubeObj2;
cubeObj1 = new Cube2();
cubeObj2 = new Cube2(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
}
}
Output
Finished with Parameterized Constructor having 3 params
Finished with Parameterized Constructor having 2 params
Finished with Default Constructor
Finished with Parameterized Constructor having 3 params
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000
Constructor Chaining
Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor
which does not include either the this() function or an explicit super() call as its first statement. The super()
statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the
constructor.
The explicit super allows parameter values to be passed to the constructor of its superclass and must have
matching parameter types A super() call in the constructor of a subclass will result in the call of the relevant
constructor from the superclass, based on the signature of the call. This is called constructor chaining.
Below is an example of a class demonstrating constructor chaining using super() method.
class Cube {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
27
Cube() {
this(10, 10);
System.out.println("Finished with Default Constructor of Cube");
}
Cube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having
}
Cube(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having
}
}
public class SpecialCube extends Cube {
int weight;
SpecialCube() {
super();
weight = 10;
}
SpecialCube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having
}
SpecialCube(int l, int b, int h) {
super(l, b, h);
weight = 20;
System.out.println("Finished with Parameterized Constructor having
}
public static void main(String[] args) {
SpecialCube specialObj1 = new SpecialCube();
SpecialCube specialObj2 = new SpecialCube(10, 20);
System.out.println("Volume of SpecialCube1 is : "
+ specialObj1.getVolume());
System.out.println("Weight of SpecialCube1 is : "
+ specialObj1.weight);
System.out.println("Volume of SpecialCube2 is : "
+ specialObj2.getVolume());
System.out.println("Weight of SpecialCube2 is : "
+ specialObj2.weight);
}
}
Output: SpecialCube.java
Finished with Parameterized Constructor having 3 params of SpecialCube
Finished with Parameterized Constructor having 2 params of SpecialCube
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20
The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it can
only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same
constructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
28
Java Serialization
Introduction to Object Serialization
Java object serialization is used to persist Java objects to a file, database, network, process or any other system.
Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of bytes can then
be read at a later time, or in another environment, to recreate the original objects.
Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the state
from being written to the stream and from being restored during deserialization. Java provides classes to support
writing objects to streams and restoring objects from streams. Only objects that support the java.io.Serializable
interface or the java.io.Externalizable interface can be written to streams. public interface Serializable
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
29
GetPersonDetails is the class that is used to Deserialize object from the File (person.txt).
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
30
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
public class GetPersonDetails {
public static void main(String[] args) {
String filename = "person.txt";
List pDetails = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
pDetails = (ArrayList) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
// print out the size
System.out.println("Person Details Size: " + pDetails.size());
System.out.println();
}
}
PersonPersist is the class that is used to serialize object into the File (person.txt).
public class PersonPersist {
public static void main(String[] args) {
String filename = "person.txt";
PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
PersonDetails person2 = new PersonDetails("bob", 12, "Male");
PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
List list = new ArrayList();
list.add(person1);
list.add(person2);
list.add(person3);
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
System.out.println("Object Persisted");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Case 2: Below is an example that demonstrates object Serialization into the database
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
31
PersonPersist is the class that is used to serialize object into the into the Database Table SerialTest.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {
static String userid = "scott", password = "tiger";
static String url = "jdbc:odbc:bob";
static int count = 0;
static Connection con = null;
public static void main(String[] args) {
Connection con = getOracleJDBCConnection();
PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
PersonDetails person2 = new PersonDetails("bob", 12, "Male");
PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
PreparedStatement ps;
try {
ps = con.prepareStatement("INSERT INTO SerialTest VALUES (?, ?)");
write(person1, ps);
ps.execute();
write(person2, ps);
ps.execute();
write(person3, ps);
ps.execute();
ps.close();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM SerialTest");
while (rs.next()) {
Object obj = read(rs, "Name");
PersonDetails p = (PersonDetails) obj;
System.out.println(p.getName() + "\t" + p.getAge() + "\t"
+ p.getSex());
}
rs.close();
st.close();
} catch (Exception e) {
}
}
public static void write(Object obj, PreparedStatement ps)
throws SQLException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(baos);
oout.writeObject(obj);
oout.close();
ps.setBytes(1, baos.toByteArray());
ps.setInt(2, ++count);
}
public static Object read(ResultSet rs, String column)
throws SQLException, IOException, ClassNotFoundException {
byte[] buf = rs.getBytes(column);
if (buf != null) {
ObjectInputStream objectIn = new ObjectInputStream(
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
32
new ByteArrayInputStream(buf));
return objectIn.readObject();
}
return null;
}
public static Connection getOracleJDBCConnection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, userid, password);
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
return con;
}
}
Case 3: Below is an example that demonstrates object Serialization into the database using Base 64 Encoder
PersonDetails remains the same as shown above
GetPersonDetails remains the same as shown above
Create SerialTest Table
create table SerialTest(
name BLOB,
viewname VARCHAR2(30)
);
PersonPersist is the class that is used to serialize object into the Database Table SerialTest
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {
static String userid = "scott", password = "tiger";
static String url = "jdbc:odbc:bob";
static int count = 0;
static Connection con = null;
static String s;
public static void main(String[] args) {
Connection con = getOracleJDBCConnection();
PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
PersonDetails person2 = new PersonDetails("bob", 12, "Male");
PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
PreparedStatement ps;
try {
ps = con.prepareStatement("INSERT INTO SerialTest VALUES (?, ?)");
write(person1, ps);
ps.execute();
write(person2, ps);
ps.execute();
write(person3, ps);
ps.execute();
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
33
ps.close();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM SerialTest");
while (rs.next()) {
Object obj = read(rs, "Name");
PersonDetails p = (PersonDetails) obj;
System.out.println(p.getName() + "\t" + p.getAge() + "\t"+ .getSex());
}
rs.close();
st.close();
} catch (Exception e) {
}
}
public static void write(Object obj, PreparedStatement ps)
throws SQLException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(baos);
oout.writeObject(obj);
oout.close();
byte[] buf = baos.toByteArray();
s = new sun.misc.BASE64Encoder().encode(buf);
ps.setString(1, s);
// ps.setBytes(1, Base64.byteArrayToBase64(baos.toByteArray()));
ps.setBytes(1, baos.toByteArray());
ps.setInt(2, ++count);
}
public static Object read(ResultSet rs, String column)
throws SQLException, IOException, ClassNotFoundException {
byte[] buf = new sun.misc.BASE64Decoder().decodeBuffer(s);
// byte[] buf = Base64.base64ToByteArray(new
// String(rs.getBytes(column)));
if (buf != null) {
ObjectInputStream objectIn = new ObjectInputStream(
new ByteArrayInputStream(buf));
Object obj = objectIn.readObject(); // Contains the object
PersonDetails p = (PersonDetails) obj;
System.out.println(p.getName() + "\t" + p.getAge() + "\t"
+ p.getSex());
}
return null;
}
public static Connection getOracleJDBCConnection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, userid, password);
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
return con;
}
}
Below is a program that shows the serialization of a JButton object to a file and a Byte Array Stream. As before
theobject to be serialized must implement the Serializable interface.
PersonDetails is the bean class that implements the Serializable interface
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
34
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class ObjectSerializationExample {
public static void main(String args[]) {
try {
Object object = new javax.swing.JButton("Submit");
// Serialize to a file namely "filename.dat"
ObjectOutput out = new ObjectOutputStream(
new FileOutputStream("filename.dat"));
out.writeObject(object);
out.close();
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
out = new ObjectOutputStream(bos);
out.writeObject(object);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java Inheritance
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of
a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is
used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class
y, then a class z, which extends class x, will also inherit from class y.
For example a car class can inherit some properties from a General vehicle class. Here we find that the base class
is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to
derive from a super class which must be written in the header of the subclass definition. The subclass inherits
members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and
properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.
class Box {
double width;
double height;
double depth;
Box() {
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
void getVolume() {
System.out.println("Volume is : " + width * height * depth);
}
}
public class MatchBox extends Box {
double weight;
MatchBox() {
}
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
35
}}
Output: MatchBox.java
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
36
Output: VehicleDetails.java
Constructor of the Super class called
Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1
Output
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
37
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
38
Let c be a variable of type Car class and f be of class Ford and v be an vehicle interface reference. We can assign
the Ford reference to the Car variable:
I.e. we can do the following
Example 1
c = f; //Ok Compiles fine
Where c = new Car();
And, f = new Ford();
The compiler automatically handles the conversion (assignment) since the types are compatible (sub class - super
class relationship), i.e., the type Car can hold the type Ford since a Ford is a Car.
Example 2
v = c; //Ok Compiles fine
c = v; // illegal conversion from interface type to class type results in compilation error
Where c = new Car();
And v is a Vehicle interface reference (Vehicle v)
The compiler automatically handles the conversion (assignment) since the types are compatible (class interface
relationship), i.e., the type Car can be cast to Vehicle interface type since Car implements Vehicle Interface. (Car
is a Vehicle).
Casting Object References: Explicit Casting
Sometimes we do an explicit cast in java when implicit casts dont work or are not helpful for a particular
scenario. The explicit cast is nothing but the name of the new type inside a pair of matched parentheses. As
before, we consider the same Car and Ford Class
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
39
class Car {
void carMethod(){
}
}
class Ford extends Car {
void fordMethod () {
}
}
We also have a breakingSystem() function which takes Car reference (Superclass reference) as an input
parameter.
The method will invoke carMethod() regardless of the type of object (Car or Ford Reference) and if it is a Ford
object, it will also invoke fordMethod(). We use the instanceof operator to determine the type of object at run
time.
public void breakingSystem (Car obj) {
obj.carMethod();
if (obj instanceof Ford) ((Ford)obj).fordMethod ();
}
To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car object referenced by obj as
if it is a Ford object. Without the cast, the compiler will give an error message indicating that fordMethod()
cannot be found in the Car definition.
The following program shown illustrates the use of the cast operator with references.
Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes are subclasses of Class Car.
Both Car and HeavyVehicle Class extend Object Class. Any class that does not explicitly extend some other class
will automatically extends the Object by default. This code instantiates an object of the class Ford and assigns the
objects reference to a reference variable of type Car. This assignment is allowed as Car is a superclass of Ford. In
order to use a reference of a class type to invoke a method, the method must be defined at or above that class in
the class hierarchy. Hence an object of Class Car cannot invoke a method present in Class Ford, since the method
fordMethod is not present in Class Car or any of its superclasses. Hence this problem can be colved by a simple
downcast by casting the Car object reference to the Ford Class Object reference as done in the program. Also an
attempt to cast an object reference to its Sibling Object reference produces a ClassCastException at runtime,
although compilation happens without any error.
One common casting that is performed when dealing with collections is, you can cast an object reference into a
String.
import java.util.Vector;
public class StringCastDemo {
public static void main(String args[]) {
String username = "asdf";
String password = "qwer";
Vector v = new Vector();
v.add(username);
v.add(password);
//
String u = v.elementAt(0); Cannot convert from object to String
Object u = v.elementAt(0); //Cast not done
System.out.println("Username : " + u);
String uname = (String) v.elementAt(0); // cast allowed
String pass = (String) v.elementAt(1); // cast allowed
System.out.println();
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
40
instanceof Operator
The instanceof operator is called the type comparison operator, lets you determine if an object belongs to a
specific class, or implements a specific interface. It returns true if an object is an instance of the class or if the
object implements the interface, otherwise it returns false.
Below is an example showing the use of instanceof operator
class Vehicle {
String name;
Vehicle() {
name = "Vehicle";
}
}
class HeavyVehicle extends Vehicle {
HeavyVehicle() {
name = "HeavyVehicle";
}
}
class Truck extends HeavyVehicle {
Truck() {
name = "Truck";
}
}
class LightVehicle extends Vehicle {
LightVehicle() {
name = "LightVehicle";
}
}
public class InstanceOfExample {
static boolean result;
static HeavyVehicle hV = new HeavyVehicle();
static Truck T = new Truck();
static HeavyVehicle hv2 = null;
public static void main(String[] args) {
result = hV instanceof HeavyVehicle;
System.out.print("hV is an HeavyVehicle: " + result + "\n");
result = T instanceof HeavyVehicle;
System.out.print("T is an HeavyVehicle: " + result + "\n");
result = hV instanceof Truck;
System.out.print("hV is a Truck: " + result + "\n");
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
41
Note: hv2 does not yet reference an HeavyVehicle object, instanceof returns false. Also we cant use instanceof
operator with siblings
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
42
We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles
etc. All shapes have some common fields and methods, but each can, of course, add more fields and methods. The
abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract
because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles,
triangles etc.
public class Point extends Shape {
static int x, y;
public Point() {
x = 0;
y = 0;
}
public double area() {
return 0;
}
public double perimeter() {
return 0;
}
public static void print() {
System.out.println("point: " + x + "," + y);
}
public static void main(String args[]) {
Point p = new Point();
p.print();
}
}
Output: point: 0, 0
Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the abstract
methods of the Shape class must be implemented by the Point class.
The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass
itself will also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class.
A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class
extends an abstract class, it cant extend any other class.
Java Interface
In Java, this multiple inheritance problem is solved with a powerful construct called interfaces. Interface can be
used to define a generic template and then one or more abstract classes to define partial implementations of the
interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain
fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface
like that of an abstract class cannot be instantiated.
Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more
interfaces. Java does not support multiple inheritance, but it allows you to extend one class and implement many
interfaces.
If a class that implements an interface does not define all the methods of the interface, then it must be declared
abstract and the method definitions must be provided by the subclass that extends the abstract class.
Example 1: Below is an example of a Shape interface
interface Shape {
public double area();
public double volume();
}
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
43
Similarly, other shape objects can be created by interface programming by implementing generic Shape Interface.
Example 2: Below is a java interfaces program showing the power of interface programming in java
Listing below shows 2 interfaces and 4 classes one being an abstract class.
Note: The method toString in class A1 is an overridden version of the method defined in the class named Object.
The classes B1 and C1 satisfy the interface contract. But since the class D1 does not define all the methods of the
implemented interface I2, the class D1 is declared abstract.
Also,
i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super interfaces if
present. Hence a downcast of interface reference I1 solves the problem as shown in the program. The same
problem applies to i1.methodA1 (), which is again resolved by a downcast.
When we invoke the toString() method which is a method of an Object, there does not seem to be any problem as
every interface or class extends Object and any class can override the default toString() to suit your application
needs. ((C1)o1).methodI1() compiles successfully, but produces a ClassCastException at runtime. This is because
B1 does not have any relationship with C1 except they are siblings. You cant cast siblings into one another.
When a given interface method is invoked on a given reference, the behavior that results will be appropriate to the
class from which that particular object was instantiated. This is runtime polymorphism based on interfaces and
overridden methods.
interface I1 {
void methodI1(); // public static by default
}
interface I2 extends I1 {
void methodI2(); // public static by default
}
class A1 {
public String methodA1() {
String strA1 = "I am in methodC1 of class A1";
return strA1;
}
public String toString() {
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
44
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
45
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
46
System.out.println("SuperClassWithDifferentMethods.method7()");
}
private void method8(int x) {
System.out.println("SuperClassWithDifferentMethods.method8()");
}
public static void method9() {
System.out.println("SuperClassWithDifferentMethods.method9()");
}
}
class OverridingClass extends SuperClassWithDifferentMethods {
public int field1 = 30;
public static int field2 = 40;
public void method1() {
System.out.println("OverridingClass.method1()");
}
//We can't override a public final method
/*
public final void method2(){
System.out.println("OverridingClass.method2()");
}*/
private void method3() {
System.out.println("OverridingClass.method3()");
}
private final void method4() {
System.out.println("OverridingClass.method4()");
}
public static void method5() {
System.out.println("OverridingClass.method5()");
}
public void method6() throws CustomException {
System.out.println("OverridingClass.method6()");
}
public void method7() {
System.out.println("OverridingClass.method7()");
}
public void method8(final int x) {
System.out.println("OverridingClass.method8()");
}
//A static method cannot be overridden to be non-static instance method
/*public void method9() {
System.out.println("OverridingClass.method9()");
}*/
}
public class MethodOverridingDemo {
public static void main(String[] args) {
OverridingClass oc1 = new OverridingClass();
SuperClassWithDifferentMethods sc3 = new OverridingClass();
oc1.method1();
oc1.method2();
// Since its private, the below 2 methods are not visible
/*oc1.method3();
oc1.method4();*/
oc1.method5();
try {
oc1.method6();
} catch (CustomException e) {
e.printStackTrace();
}
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
47
oc1.method7();
oc1.method8(100);
System.out.println("oc1.field1 : " + oc1.field1);
System.out.println("oc1.field2 : " + oc1.field2);
System.out.println("sc3.field1 : " + sc3.field1);
System.out.println("sc3.field2 : " + sc3.field2);
sc3.method5();
OverridingClass overClass = new OverridingClass();
SuperClassWithDifferentMethods supClass = (SuperClassWithDifferentMethods) overClass;
supClass.method5();
supClass.method1();
}
}
Output : MethodOverridingDemo.java
OverridingClass.method1()
SuperClassWithDifferentMethods.method2()
OverridingClass.method5()
OverridingClass.method6()
OverridingClass.method7()
OverridingClass.method8()
oc1.field1 : 30
oc1.field2 : 40
sc3.field1 : 10
sc3.field2 : 20
SuperClassWithDifferentMethods.method5()
SuperClassWithDifferentMethods.method5()
OverridingClass.method1()
The new method definitions in the subclass OverridingClass have the same signature and the same return type as
the methods in the superclass SuperClassWithDifferentMethods. The new overridden method6 definition
specifies a subset of the exceptions (CustomException). The new overridden method7 definition also widens the
accessibility to public from private. The overriding method8 also declares the parameter to be final, which is not a
part of the method signature and Method Overriding holds good. A static method cannot be overridden to be nonstatic instance method as shown in the overridden method declaration of method9. A static method is classspecific and not part of any object, while overriding methods are invoked on behalf of objects of the subclass.
There are no such restrictions on the fields, as for fields only the field names matter. A final method cannot be
overridden, an attempt to which will result in a compile-time error. A private method is not accessible outside the
class in which it is defined; therefore, a subclass cannot override it.
A subclass must use the super keyword in order to invoke an overridden method in the superclass. A subclass
cannot override fields of the superclass, but it can hide them. Code in the subclass can use the keyword super to
access members, including hidden fields.
The following distinction between invoking instance methods on an object and accessing fields of an object must
be noted. When an instance method is invoked on an object using a reference, it is the class of the current object
denoted by the reference, not the type of the reference, that determines which method implementation will be
executed. When a field of an object is accessed using a reference, it is the type of the reference, not the class of
the current object denoted by the reference, that determines which field will actually be accessed. This is
demonstrated in the above program
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
48
class PointCoordinates {
private int x, y;
public PointCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public class ToStringDemo {
public static void main(String args[]) {
PointCoordinates point = new PointCoordinates(10, 10);
// using the Default Object.toString() Method
System.out.println("Object toString() method : " + point);
// implicitly call toString() on object as part of string concatenation
String s = point + " testing";
System.out.println(s);
}
}
ToStringDemo.java
When you run the ToStringDemo program, the output is:
Object toString() method : PointCoordinates@119c082
In the above example when we try printing PointCoordinates object, it internally calls the Objects toString()
method as we have not overridden the java toString() method. Since out example has no toString method, the
default one in Object is used. The format of the default toString method of the Object is as shown below.
Class Name, @, and the hex version of the objects hashcode concatenated into a string.
The default hashCode method in Object is typically implemented by converting the memory address of the object
into an integer.
Below is an example shown of the same program by Overriding the default Object toString() method. The
toString() method must be descriptive and should generally cover all the contents of the object.
class PointCoordinates {
private int x, y;
public PointCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
// Custom toString() Method.
public String toString() {
return "X=" + x + " " + "Y=" + y;
}
}
public class ToStringDemo2 {
public static void main(String args[]) {
PointCoordinates point = new PointCoordinates(10, 10);
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
49
System.out.println(point);
String s = point + " testing";
System.out.println(s);
}
}
ToStringDemo2.java
When you run the ToStringDemo2 program, the output is:
X=10 Y=10
X=10 Y=10 testing
Strings in java
Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same
reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs
from other classes, one difference being that the String objects can be used with the += and + operators for
concatenation.
Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing
whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a
String.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
50
}
Output: StringDemo1.java
byteStr :
charStr : abCD
buffStr : abcde
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
51
StringComparision2.java
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
52
StringBuffer Class
StringBuffer class is a mutable class unlike the String class which is immutable. Both the capacity and character
string of a StringBuffer Class. StringBuffer can be changed dynamically. String buffers are preferred when heavy
modification of character strings is involved (appending, inserting, deleting, modifying etc).
Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method
from the Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffer
manipulations
Creation of StringBuffers
StringBuffer Constructors
public class StringBufferDemo {
public static void main(String[] args) {
//
Examples of Creation of Strings
StringBuffer strBuf1 = new StringBuffer("Bob");
StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
System.out.println("strBuf1 : " + strBuf1);
System.out.println("strBuf2 capacity : " + strBuf2.capacity());
System.out.println("strBuf3 capacity : " + strBuf3.capacity());
}
}
Output: StringBufferDemo.java
strBuf1 : Bob
strBuf2 capacity : 100
strBuf3 capacity : 16
StringBuffer Functions
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
53
The following program explains the usage of the some of the basic StringBuffer methods like ;
1. capacity()
Returns the current capacity of the String buffer.
2. length()
Returns the length (character count) of this string buffer.
3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index
argument, is returned.
4. setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch
5. toString()
Converts to a string representing the data in this string buffer
6. insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded insert methods which can be used based on the
application need.
7. delete(int start, int end)
Removes the characters in a substring of this StringBuffer
8. replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in the specified String.
9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.
10. append(String str)
Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded append methods which can be used based on the
application need.
11. setLength(int newLength)
Sets the length of this String buffer.
public class StringBufferFunctionsDemo {
public static void main(String[] args) {
//
Examples of Creation of Strings
StringBuffer strBuf1 = new StringBuffer("Bobby");
StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
System.out.println("strBuf1 : " + strBuf1);
System.out.println("strBuf1 capacity : " + strBuf1.capacity());
System.out.println("strBuf2 capacity : " + strBuf2.capacity());
System.out.println("strBuf3 capacity : " + strBuf3.capacity());
System.out.println("strBuf1 length : " + strBuf1.length());
System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2));
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
54
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
55
Output: DivideException.java
An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal
operation. The Exit main() message is never reached in the main method
Computing Division.
java.lang.ArithmeticException: / by zero
Average : 25
Computing Division.
at DivideException.division(DivideException.java:11)
at DivideException.main(DivideException.java:5)
Exception in thread main
Exceptions in Java
Throwable Class
The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that
provides more information of the exception occurred. All classes of throwables define a one-parameter
constructor that takes a string as the detail message.
The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method
to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short
description of the exception. For more information on what is printed when the following messages are invoked,
please refer the java docs.
Syntax
String getMessage()
void printStackTrace()
String toString()
Class Exception
The class Exception represents exceptions that a program faces due to abnormal or special conditions during
execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).
Class RuntimeException
Runtime exceptions represent programming errors that manifest at runtime. For example
ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException
class, which is a subclass of the Exception class. These are basically business logic programming errors.
Class Error
Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are
direct subclass of Throwable class.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
56
try Block
The java code that you think may produce an exception is placed within a try block for a suitable catch block to
handle the error.
If no exception occurs the execution proceeds with the finally block else it will look for the matching catch block
to handle the error. Again if the matching catch handler is not found execution proceeds with the finally block and
the default exception handler throws an exception.. If an exception is generated within the try block, the
remaining statements in the try block are not executed.
catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a
catch block, normal execution continues and the finally block is executed (Though the catch block throws an
exception).
finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block
was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the
finally clock executes a control transfer statement such as a return or a break statement, then this control
statement determines how the execution will proceed regardless of any return or control statement present in the
try or catch.
The following program illustrates the scenario.
try {
<code>
} catch (<exception type1> <parameter1>) { // 0 or more
<statements>
}
} finally {
<statements>
}
// finally block
Output: DivideException2.java
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
57
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1
Java exception handling mechanism enables you to catch exceptions in java using try, catch, finally block. be An
exception consists of a block of code called a try block, a block of code called a catch block, and the finally block.
Lets examine each of these in detail.
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
58
Output: DivideException1.java
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
Main Program Terminating
As shown above when the divide by zero calculation is attempted, an ArithmeticException is thrown. and
program execution is transferred to the catch statement. Because the exception is thrown from the try block, the
remaining statements of the try block
are skipped. The finally block executes.
Defining new EXCEPTIONS!!
We can have our own custom Exception handler to deal with special exception conditions instead of using
existing exception classes. Custom exceptions usually extend the Exception class directly or any subclass of
Exception (making it checked).
The super() call can be used to set a detail message in the throwable. Below is an example that shows the use of
Custom exceptions along with how the throw and throws clause are used.
class BadTemperature extends Exception{
BadTemperature( String reason ){
super ( reason );
}
}
class TooHot extends BadTemperature{
TooHot(){
super ("Default messaeg : Hot");
}
TooHot(String message){
super (message);
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
59
}
}
class TooCold extends BadTemperature{
TooCold(){
super ("Default messaeg : Cold");
}
TooCold(String message){
super (message);
}
}
class TempertureObject{
int temperature;
TempertureObject( int temp ) {
temperature = temp;
}
void test() throws TooHot, TooCold {
if ( temperature < 70 ) throw new TooCold("Very Cold");
if ( temperature > 80 ) throw new TooHot("Very Hot");
}
}
public class ExceptionExample1{
private static void temperatureReport( TempertureObject batch ){
try{ batch.test();
System.out.println( "Perfect Temperature" );
}
catch ( BadTemperature bt ){
System.out.println( bt.getMessage( ) );
}
}
public static void main( String[] args ){
temperatureReport( new TempertureObject( 100 ) );
temperatureReport( new TempertureObject( 50 ) );
temperatureReport( new TempertureObject( 75 ) );
}
}
Output: ExceptionExample.java
Very Hot
Very Cold
Perfect Temperature
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
60
Output: DivideException3.java
Computing Division.
Finally Block Executes
Result : 10
Computing Division.
Finally Block Executes. Exception Occurred
Exception : Division attempt by 0
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
61
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
62
import java.io.DataInputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
public class ExceptionExample7{
static int numerator, denominator;
public ExceptionExample7( int t, int b ){
numerator = t;
denominator = b;
}
public int divide( ) throws ArithmeticException{
return numerator/denominator;
}
public static void main( String args[] ){
String num, denom;
num = JOptionPane.showInputDialog(null, "Enter the Numerator");
denom = JOptionPane.showInputDialog(null, "Enter the Denominator");
try{
numerator = Integer.parseInt( num );
denominator = Integer.parseInt( denom );
}
catch ( NumberFormatException nfe ){
System.out.println( "One of the inputs is not an integer" );
return;
}
catch ( Exception e ){
System.out.println( "Exception: " + e.getMessage( ) );
return;
}
ExceptionExample7 d = new ExceptionExample7( numerator, denominator );
try{
double result = d.divide( );
JOptionPane.showMessageDialog(null, "Result : " + result);
}
catch ( ArithmeticException ae ){
System.out.println( "You can't divide by zero" );
}
finally{
System.out.println( "Finally Block is always Executed" );
}
}
}
Java Threads
Introduction to Threads
Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an
independent path of execution within a program. Many threads can run concurrently within a program. Every
thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads,
and these threads can run concurrently, either asynchronously or synchronously.
Multithreading has several advantages over Multiprocessing such as;
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
63
Context switching between threads is usually less expensive than between processes
Cost of thread intercommunication is relatively low that that of process intercommunication
Threads allow different tasks to be performed concurrently.
The following figure shows the methods that are members of the Object and Thread Class.
Thread Creation
There are two ways to create thread in java;
Implement the Runnable interface (java.lang.Runnable)
By Extending the Thread class (java.lang.Thread)
Implementing the Runnable Interface
public interface Runnable {
void run();
}
One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the
class. We need to override the run() method into our class which is the only method that needs to be implemented.
The run() method contains the logic of the thread.
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An
object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The
Thread object now has a Runnable object that implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start() method returns
immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught
exception.
Below is a program that illustrates instantiation and running of threads using the runnable interface instead of
extending the Thread class. To start the thread you need to invoke the start() method on your object.
class RunnableThread implements Runnable {
Thread runner;
public RunnableThread() {
}
public RunnableThread(String threadName) {
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}
public class RunnableExample {
public static void main(String[] args) {
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
64
Output
thread3
Thread[thread1,5,main]
Thread[thread2,5,main]
Thread[thread3,5,main]
Thread[main,5,main]private
Runnable Thread Program Example
This approach of creating a thread by implementing the Runnable Interface must be used whenever the class
being used to instantiate the thread object is required to extend some other class.
Extending Thread Class
The procedure for creating threads based on extending the Thread is as follows:
1. A class extending the Thread class overrides the run() method from the Thread class to define the code
executed by the thread.
2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the
super() call.
3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread
eligible for running.
Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of
implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.
class XThread extends Thread {
XThread() {
}
XThread(String threadName) {
super(threadName); // Initialize thread.
System.out.println(this);
start();
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
65
Thread[thread5,5,main]
thread1
thread5
thread2
Thread-3
Thread-2
Thread[main,5,main]
When creating threads, there are two reasons why implementing the Runnable interface may be preferable to
extending the Thread class:
Extending the Thread class means that the subclass cannot extend any other class, whereas a class
implementing the Runnable interface
has this option.
A class might only be interested in being runnable, and therefore, inheriting the full overhead of the
Thread class would be excessive.
An example of an anonymous class below shows how to create a thread and start it:
( new Thread() {
public void run() {
for(;;) System.out.println(Stop the world!);
}
}
).start();
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
66
Lab Programs
//Program-1
//To find the factorial of a Number
class fact
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
{
int fact =1;
for(int j=1;j<=Integer.parseInt(args[i]);j++)
fact=fact*j;
System.out.println("factorial of "+args[i]+" is "+fact);
}
}
}
//Program-2
//To find the to find Prime Number Series
class prime
{
public static void main(String args[])
{
if(args.length==1)
{
int i,j;
System.out.println("prime no.s");
for(i=2;i<=Integer.parseInt(args[0]);i++)
{
int count=0;
for(j=1;j<i;j++)
if(i%j==0)
count++;
if(count==1)
System.out.println(i);
}
}
else
System.out.println("argssfdsfds");
}
}
//Program-3
//To Sort a Number series in Ascending order
class sorting
{
public static void main(String args[])
{
int num[]={55,40,80,65,71,45,55,22,33};
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
67
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
68
if(s1.equals(s2))
System.out.println("strings are equal");
else
System.out.println("strings are not equal");
System.out.println(s2.charAt(3));
System.out.println("compare s1 to s2\n"+s1.compareTo(s2));
String s3;
s3=s1.concat(s2);
System.out.println(s3);
System.out.println(s2.substring(2));
System.out.println(s2.substring(2,4));
System.out.println(s2.indexOf('p'));
}
}
//Program-5
// Program to perform Geometrical shapes.
import java.lang.*;
class shapes
{
public void square(int s)
{
double area=s*s;
System.out.println("area of square is\t"+area);
}
public void rectangle(int l,int b)
{
double area=l*b;
System.out.println("area of rectangle is\t"+area);
}
public void circle(int r)
{
double area=3.14*r*r;
System.out.println("area of circle is\t"+area);
}
public void triangle(int a,int b,int c)
{
int s=(a+b+c)/2;
double area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("area of triangle is\t"+area);
}
}
class geometrical
{
public static void main(String args[])
{
shapes s=new shapes();
s.square(5);
s.rectangle(5,5);
s.circle(5);
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
69
s.triangle(5,5,5);
}
}
//Program-6
//Program to perform bitwise functions.
class bitwise
{
public static void main(String args[])
{
int a=10,b=13,c=0;
System.out.println("the a&b\n"+(a&b));
System.out.println("the a|b\n"+(a|b));
System.out.println("the a^b\n"+(a^b));
System.out.println("the ~a\n"+(~a));
System.out.println("the a<<2\n"+(a<<2));
System.out.println("the a>>2\n"+(a>>2));
System.out.println("the a>>>2\n"+(a>>>2));
}
}
//Program-7
//Program to implement constructor overloading by passing different number of parameter of different
types
// constructor overloading
Class Triangles
{
int x,y;
float z;
Triangles(int i)
{
x=y=i;
Z=i;
}
Triangles(int i, int j)
{
x=i;
y=i;
Z=j;
}
Triangles(int i, int j, float k)
{
x=i;
y=i;
Z=k;
}
float peri()
{
return(x+y+z);
}
}
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
70
Class Overloading
{
Public static void main (String args[])
(
float val;
Triangles a=new Triangles(5);
Triangles b=new Triangles(5,3);
Triangles c=new Triangles(2,3,5.5f);
System.out.println(================================ \n);
val=a.peri();
System.out.println(Perimeter of equilateral triangle= +val+ Sq.units \n);
Val=b.peri();
System.out.println(Perimeter of isoceles triangle= +val+ Sq.units \n);
Val=c.peri();
System.out.println(Perimeter of scalene triangle= +val+ Sq.units \n );
System.out.println(================================ \n);
}
}
//Program-8
//Program to create a student report by reading the inputs using textboxes and display the output using
buttons
// Applet program
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=StudReport width=300 height=450>
</applet>
*/
public class StudReport extends Applet implements ActionListener
{
TextField tRegNo, tName, tCourse, tResult;
Label lTitle, lRegNo,lName,lCourse,lResult;
Button CReport;
String rno=,course=,nam=,res=;
public void init()
{
lTitle=new Lable(Enter Student Details);
lRegNo=new Lable(Regsiter Number,Label.Right);
lName= new Lable(Student Name,Label.Right);
lCourse=new Lable(Course,Label.Right);
lResult=new TextField(20);
tRegNo= new TextField(20);
tName= new TextField(20);
tCourse= new TextField(20);
tResult= new TextField(20);
CReport= new Button (Report);
add(lTitle);
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
71
add(lRegNo);
add(tRegNo);
add(lName);
add(tName);
add(lcourse);
add(tcourse);
add(lResult);
add(tResult);
add(CResult)
tRegNo.addActionListener(this);
tName. addActionListener(this);
tCourse. addActionListener(this);
tResult. addActionListener(this);
CReport. addActionListener(this);
}
Public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==CReport)
{
Rno=tRegNo.getText();
Course=tCourse.getText();
nam-tName.getText();
rno=Register Number :+rno;
nam=Name :+nam;
course=Course :+course;
res=Result :+res;
repaint();
}
}
Public void paint(Graphics g)
{
g.drawString(rno,30,180);
g.drawString(nam,30,200);
g.drawString(course,30,220);
g.drawString(res,30,240);
}
}
//Program-9
//Program to calculate bonus for different departments using method overriding.
class SuperCalass
{
float basic,da,it;
Cuperclass(float b, float d, float i)
{
basic=b;
da=d;
it=i;
}
double vonus()
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
72
{
System.out.print("Research dept:");
return(basic*0.2);
}
}
class SubClass extends SuperClass
{
float har,pt;
SubClass(float b, float d, float i, float p,float h)
{
super(b,d,i); //passing values to super class
hra=h;
pt=p;
}
double bonus() //overriding method
{
Sysem.out.print("Administration dept:");
return(basic*0.4);
}
}
class findSal
{
public static void nain(String args[])
{
SubClass sc=new SubClass(20000, 12000, 6000, 1000, 500);
System.out.print("______________________________________/n");
System.out.print("bonus is Rs."+sc.bonus+"\n");
System.out.print("______________________________________/n");
}
}
//Program-10
//Program to implement thread priorities
class clicker implements Runnable
{
int click=0;
Thread t;
private volatile boolean running=true;
public clicker(int p)
{
t=new Thread(this);
t.setPririty(P);
}
Public void run()
{
while(running)
{
click++;
}
}
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
73
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
74
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
75
//do nothing
}
}
public void update(Graphics g)
{
if(dbImage==null)
{
dbIMage=createImage(this.getSize().width,this,getSize().height);
dbg=dbImage.getGraphics();
}
dbg.setColor(getBackground());
dbg.fillrect(0,0,this.getSize.width, this.getSize().height);
dbg.setColorgetForeground());
paint(dbg);
g.drawImage(dbImage,0,0,this);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(x_pos-radius,y_pos-radius,2*radius,2*radius)
}
}
Prof. K. ADISESHA
www.adisesha.9f.com
| email: adisesha1@rediffmail.com
76