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

PROGRAMMING IN JAVA

UNIT - I
PROGRAMMING IN JAVA
Java Essentials:

Java is a platform independent, Object - oriented programming language. Java


encompasses the following features:

 A High Level Language java is a high level language that looks very
similar to C and C++ but offers unique features of its own.
 Java BytecodeBytecode in java is and intermediate code generated by the
compiler, such as Sun's javac, that is executed by the JVM.
 Java virtual Machine (JVM) JVM acts as an interpreter for the byte code,
which takes bytecodes as input and executes it as if it was a physical
process executing machine code.

Java is designed to be architecturally neutral so that it can run on


multiple platforms. The same runtime code can run on any platform that
supports Java. To achieve its cross-architecture capabilities, the java
compiler generates architecturally neutral byte code instructions. These
instructions are designed to be both easily interpreted on any machine
and easily translated into native machine code on the fly.

Source code resembles C++ but is simpler to


develop and understand

Same bytecode runs on any JVM

All major platforms have a JVM

JAVA Runtime Environment (JRE) includes JVM, class libraries, and other
supporting files.

Tools such as javac(compiler), java (interpreter) and other are provided in a


bundle, popular known as Java Development Kit (JDK).

JVM:

All language compilers translate source code into machine code for specific
computer. Java compiler also does the same thing. Java compiler produces an
intermediate code known as byte code for a machine that does not exist. This
machine is called the Java Virtual Machine and it exists only inside the

Smt. T. LalithaKumari Page 1


PROGRAMMING IN JAVA

computer memory. The process of compiling a java program into bytecode which
is also referred to as virtual machine code.

Source Code Byte code

Process of Compilation

The Virtual machine code is not machine specific. The machine specific code is
generated by the java interpreter by acting as an intermediary between the
virtual machine and the real machine.

Real Machine

Process of converting bytecode into Machine Code

Java Features:
 Compiled and Interpreted
 Platform- Independent and portable
 Object Oriented
 Robust and Secure
 Distributed
 Familiar, Simple and Small
 Multithreaded and Interactive
 High performance
 Dynamic and Extensible
 Compiled and Interpreted: Usually a computer languages is either
compiled or Interpreted. Java combines both these approaches. First, java
compiler translates source code into byte code instructions. Byte code are
not machine instructions and therefore second stage, Java interpreter
generates machine code that can be directly executed by the machine.
Java is both a compiled and an interpreted language.
 Platform Independent and Portal : The most significant contribution of
java over other languages is its portability. Java programs can be moved
from one computer to another, anywhere and anytime. Changes and
upgrades in operating systems, processors and system resources will not
force any change in java programs. If a program yields the same result on
every machine, then the programs is called portability.
 Object Oriented: Java is a true Object -oriented language. Almost
everything in java is an object. All programs code and data reside within
objects and classes. The object model in java is simple and easy to extend.

Smt. T. LalithaKumari Page 2


PROGRAMMING IN JAVA

 Robust and Secure: Robust means string. Java programs are strong and
they don't crash easily like a C or C++ program. There are 2 reasons.
Firstly, Java has got excellent inbuilt exception handling features.
Secondly java is robust lies in its memory management features. User
need not to be allocate and deallocate memory in java, everything will be
taken care of by JVM.
 Distributed: JAVA is designed as a distributed language for creating
applications on networks. It can ability to share both data and programs.
Java applications can open and access remote objects on Internet easily as
they can do in a local system.
 Simple, Small and Familiar: Java is small and simple language. For
example Java does not use pointers, preprocessor header files, goto
statement and many others. Java uses many constructs of C and C++ and
therefore, Java code "looks like a C++ code. In fact, java is a simplified
version of C++.
 Multithreaded and interactive: Multithreaded means handling multiple
tasks simultaneously. Java supports multithreaded programs. Example:
we can listen to an audio clip while scrolling a page and at the same time
download an applet from a instant computer.
 High Performance: The problem with interpreter inside the JVM is that it
is slow. Because of this, Java programs used to run slow. To overcome this
problem, along with the interpreter, java soft people have introduced
JIT(Just in time) compiler, which enhances the speed of execution.
 Dynamic and extensible: Java is a dynamic language. java is capable of
dynamic linking new class libraries, methods and objects.

JAVA Tokens:
 Reserved words
 identifiers
 literals
 operators
 Separators.
Character set: Basic character set which include letters, punctuation marks,
digits, in normal English language.
Letters: A..Z, a..z
Numbers: 0..9
Special Characters: +, - . *, / ,%, @, #, $, ^, &, *, ( , ), {, } , [ , ], : , ; , ", ', ?,<, > , back space etc.
Keywords: keywords are the essential part of language definition. Java
language has50 keywords. It has some specific meaning in java, we cannot use
them as names for variables, classes, methods and so on. All keywords are to be
written in lower case letters.

Smt. T. LalithaKumari Page 3


PROGRAMMING IN JAVA

Abstract Continue For New switch

Assert Default Goto Package synchronized

Boolean Do If Private this

Break Double Implements protected throw

Byte Else Import Public throws

Case Enum instance of Return transient

Catch Extends Int Short try

Char Final Interface Static void

Class Finally Long Strictfp volatile

Const Float Native Super while

Identifiers: Identifiers are programmed design tokens. They are used for
naming classes, methods, variables, objects, labels, packages and identifiers in
a program.
JAVA identifier follow the following rules:-
1. They can have alphabets, digits and the underscore and dollar sign
characters.
2. They must not begin with a digit.
3. Upper case and lower case are distinct.
4. They can be any of length.

Examples:
 names of all public methods and instance of variables starts with lower
case letters.
Ex: average
sum
 When more than one words are used in a name second subsequent word
are marked with the upper case letter.
Ex: dayTemp
firstDayOfMonth
totalMaks
 All classes and interfaces starts with a upper case letters.
Ex: Student
Helloworld
Motorcycle
 Variables represents uppercase, lowercase and underscore between the
words.

Smt. T. LalithaKumari Page 4










Ex:Total_Marks
F_Max
Principle_Amount.

 Integer Literals.
PROGRAMMING IN JAVA

Arithmetic Operators (+, -, *, / , %)


Relational Operators (< ,>, <=, >=, ==, !=)
Logical Operators ( AND, OR, NOT)
Assignment Operators( =, +=, -=, *=, /=, %=)
Increment and decrement operators( ++, --)
Conditional Operators( ?,:)
Bitwise Operators (Bitwise AND, Bitwise OR, XOR, >>, <<)
Special Operators (sizeof, typedef, , , ->, * )

Separators: Separators or symbols used to indicate where groups of code are


divided and arranging.

S
l
e
R
a
t
s
o
C
g
n
i
r
Literals: Literals in java are a sequence of characters. [ Digits, letters and other
characters] . That represents constant values to be stored in variables.

 Floating Point Literals.


 Character Literals.
 String Literals.
 Boolean Literals.

Operators: An Operator is a symbol that takes one or more arguments and


operators on them to produce a result. Java operators are classified as:

Constants: Constants in java refers to fixed values that do not change during
the execution of the program. Java supports several types of constants.

Integer Constant: An integer constant refers to a sequence of digits. It does not


allow fractional part. There are3 types of integer constants namely decimal,
Octal, Hexadecimal.

Decimal Constant: decimal integers consist of set of digits 0 .. 9

Ex: 256, 189

Smt. T. LalithaKumari Page 5


PROGRAMMING IN JAVA

Octal Constant: An Octal constant consists of combination of digits from the


set 0 to 7, with leading 0.
Ex: 067, 0435
Hexa Decimal Constant: Hexa decimal integer constant consists of any
combination of digits 0..9 letter A..F. The sequence of digits preceeded by 0x,
0X.
Ex: 0x9F, 0XBCD8,0x189
Real Constants: A number containing the fractional part is called real
constants.
Ex: 0.008, -0.45, 435.78
Real number may also be expressed in exponential notation.
Syntax: mantissa e exponent
Ex: 0.65 e-45, 7.5 e43
A floating point constant may comprise 4 parts.
1. A whole number
2. A decimal number
3. A fractional Part
4. An Exponent.
Single character constant: It contains single character enclosed with pair of
single code.
Ex: 'A', '15'.
String Constant:
Sequence of characters are enclosed with in double codes is called string
constant.
Ex: "Welcome", "computer"
Variables:
A variable is an identifier that denotes a storage locations used to store a data
value. During the execution of the program, values can be stored in a variable
and the value can be changed. In java programming it is necessary to declare
variable before being used.
Rules for declaring a variable:
 A variable name may consists of alphabets, digits and underscore.
 They must not begin with digit.
 Upper case and lower case are different.
 It should not a keyword.
 White space is not allowed.
 Variable names can be of any length.
Syntax:
datatype variable1, variable2, variable3,.........;
Example:
int count;
floatavg;

Smt. T. LalithaKumari Page 6


PROGRAMMING IN JAVA

double p1;
Giving values to a variable:
1. By using assignment statement.
2. By using Read Keyword.
Syntax:
variablename=value;
Ex:
initialvalue=0;
finalvalue=10;
a=90;
Syntax:
datatypevariablename=value;
Ex:
intinitialvalue=0;
intfinalvalue=10;

write a program to read and display one integer,floating point number


using read statement.

class Example
{
public static void main(String args[])
{
int i;
float x;
System.out.println("Enter any integer number ");
i=Integer.parseInt(in.readLine( ));
System.out.println("Enter any floating point number");
x= Float.valueOf(in.readLine()).floatValue( );
System.out.println("Integer i=" +i);
System.out.println("Float x=" +x);
}
}

Scope of variables:
1. Instance variables.
2. class/static variables.
3. Local variables.
Instance variables:Anon static variable that is declared with in the class but
not in the method is called instance variable. Instance variables are related to a
specific object; they can access class variables.
Class / Static variables: A variable that is declared with static keyword is a
class but not in the method is called static or class variable.

Smt. T. LalithaKumari Page 7


PROGRAMMING IN JAVA

Local variable: A variable that is declared within the method that is called
local variables. It is defined in method or other statements, such as defined and
used within the cache block and outside the block or method, the variable
cannot be used.
Ex:
class A
{
int amount=100; // instance variable
static int pin=2315; // static variable
public static void main(String args[])
{
int age=35; // local variable
}
}

Java Data Types


The main purpose of Data Types in java is to determine what kind of value we
can stored in to the variable.
Integer data types: These data types represent integer numbers, i.e.
numbers without any fractional parts or decimal points. Integer datatypes
are again sub divided into byte, short, int and long types.
Ex: int x;
long x=15L;
Floating point types: Integer types can hold only whole numbers and
therefore we use another type known as floating point type to hold
numbers containing fractional part such as 27.59 and -1.345. There are
two types of floating point. The float type values are single precision
numbers while the double types represents double precision numbers. In
a single precision mode, we must append f or F to the number.
Ex: float pi=3.142f;
If f is not written at the end, then JVM would have allotted 8 bytes
assuming the value to be double.
CharacterType: In order to store character constants in memory, java
provides a character data type is called Char. Char type assumes a size of
2 bytes. but, basically, it can hold a single character.
Ex:- char ch='x';
Boolean Type: Boolean type is used to test a particular condition during
the execution of program. There are 2 values that a Boolean type can take
: True or false.
Ex:-boolean response=true;

Smt. T. LalithaKumari Page 8


PROGRAMMING IN JAVA

Data Memory Minimum and Maximum Values


Types Size
Byte 1 byte
-128 to +127

Short 2 bytes
-32768 to + 32767

Int 4 bytes
-2147483648 to + 2147483647

Long 8 bytes
-9223372036854775808to
+9223372036854775807

Float 4 bytes
-3.4e-38 to +3.4e+038.

Double 8 bytes
-1.7e-308 to 1.7e+308.

Char 2 bytes
0 to 65535

Boolean
true or false

Symbolic Constants: We often use certain unique constants in a program.


Constants may appear repeatedly in a number of places in a program. Symbolic
names take the same form as variable name. But they are written in "capitals".
They can NOT be declared inside a method. They should be used only as class
data members in the beginning of the class.
Syntax:
final type symbolic_name=value;
Ex:
final int STRENGTH=100;

Smt. T. LalithaKumari Page 9


PROGRAMMING IN JAVA

finalint PASS_MARK=50;

Automatic Type Conversion:

Java permits mixing of constants and variable of different types in an


expression. If a value of narrower (lower size) data type converted to a value of a
broader (higher size) data type without loss of information, is called Widening
conversion. This is done implicitly by the JVM and also known as implicit
casting. For example an integer data type is directly converted to a double.

int a = 100;
double b = a;
System.out.println(b);

In above example integer (4 Byte) converted into double (8 Byte)

Widening conversion is allowed in the following cases:

 byte can be converted to short, int, long, float, or double


 Short can be converted to int, long, float, or double
 char can be converted toint, long, float, or double
 int can be converted to long, float, or double
 long can be converted to double
 float can be converted to double

Narrowing Conversion

If a value of broader (higher size) data type converted to a value of a narrower


(lower size) data type which can result in loss of information, is called Narrowing
conversion. This is not done implicitly by the JVM and requires explicit casting.
For example double data type explicitly converted into integer

Smt. T. LalithaKumari Page 10


PROGRAMMING IN JAVA

double a = 100.7;
int b = (int) a;
System.out.println(b);

In above example the double 'a' is explicitly converted to int 'b'.

 float into int causes truncation of fractional part.


 double to float causes rounding of digits.
 long to int causes dropping of excess higher order bits.

Narrowing conversion is allowed in these cases:

 short can be converted to byte or char


 char can be converted to byte or short
 int can be converted to byte, short, or char
 long can be converted to byte, short, or char
 float can be converted to byte, short, char, int, or long
 double can be converted to byte, short, char, int, long, or float

Type Casting:

We often encounter situations where there is a need to store a value of one type
into a variable of another type. The process of converting one data type to
another data type is called casting.
type variable1=(type) variable2;
there are instances when we want to force a type conversion in a way that is
different from the automatic conversion.
Ex:-ratio=female_no/male_no;
Since female_no&male_no are declared as integer, the decimal part of the result
of the division would be lost and ratio would not represent a correct result. This
can be solved by converting locally one of the variables to floating point.
Ex:- ratio=(float)female_no/male_no;

The process of such local conversion is known as casting value.


(type_name) expression;

Examples:

Examples Action
X=(int) 7.5 7.5 is converted to
integer by truncation
A=(int)21.3/(int)4.5 Evaluated as 21/4 and
the result would be 5
B=(double) sum/n Division is done in

Smt. T. LalithaKumari Page 11


PROGRAMMING IN JAVA

floating point mode.


Y=(int) (a+b) The result of a+b is
converted to integer
Z= (int) a+b A is converted to integer
and then added to b

Conditional statements:
1. If statement.
2. If...else statement
3. Nested if statement.
4. If...else..if statement.
5. Switch statement
1. If Statement:
This is a control statement to execute a single statement or a block of
statements, when the given condition is true and if it is false then it
skips if block and rest code of program is executed .

  Syntax:

  if(test expression)
{
  <statements>;
  ...;
  ...;
}
Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates
to 0 so if block is executed. Hence "This is even number" is printed on the
screen.
Class Simpleif
{
public static void main(String args[])
{
    int n = 10;
if(n%2 = = 0)
{
   System.out.println("This is even number");
}
}
}
2. If-else Statement:

The "if-else" statementis an extension of if statement that provides another


option when 'if' statement evaluates  to "false" i.e. else block is executed
if "if" statement is false.  

Smt. T. LalithaKumari Page 12


PROGRAMMING IN JAVA

  Syntax:
   if( test expression)

{
 <statements>;
  ...;
  ...;
 }
   else

{
 <statements>;
  ....;
  ....;
   } 

Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2
evaluates to 1 that is not equal to 0 so else block is executed. So "This is not
even number" is printed on the screen.

class Ifelse
{
public static void main(String args[])
{
      int n = 11;
if(n%2 = = 0)
{
   System.out.println("Even number");
}
else{
   System.out.println("Odd number");
}
}
}

3. Nesting of If...Else Statements: Nested if statements means an if statement


inside an if statement. IF the condition-1 is false, the statment-3 will be
executed; if the condition1 is true it performs the second test. If the condition2
is true, the statement-1 will be executed; otherwise statement-2 will be executed
and then control is transferred to the next statement of the nested if statement.
Syntax:
if(test condition1)
{
if( test condition2)
{

Smt. T. LalithaKumari Page 13


PROGRAMMING IN JAVA

statement -1;
}
else
{
statement-2;
}
else
{
statement-3;
}

 4. If ...Else if ladder:


The general form is

if( condition 1)
statement 1;
else if( condition 2)
statement 2;
else if( condition 3)
statement 3;
:
:
else
statement n;

Smt. T. LalithaKumari Page 14


PROGRAMMING IN JAVA

(OR)

if(condition 1)
block1;
else if(condition 2)
block 2;
else if(condition 3)
block 3;
:
:
else
block n;

In this form if the condition 1 is true block 1 is executed. If the condition 2 is


true block 2 is executed and on when all the conditions are false default is
executed. A block may contain single or group of statements are executed
with in the braces.

5. Switch Statement:
General form is:

switch (expression)
{
case constant 1: statement;
break;
case constant2: statement;
break;
:
:
:
case constant n: statement;
break;

Smt. T. LalithaKumari Page 15


PROGRAMMING IN JAVA

default: statement;
}
The switch statements is multi way conditional statement .where expression
is an integer expression or character type expression and constant1,
constant2….constant n are the constants or constant expression called case
labels.
If the switch statement is executed , the value of the expression is
successively compared against the values of constant1,constant2,…constant
n. If a case is found whose value matches with the constant of the expression
the block of statement that follows the ‘case ‘ are executed.
The break statement at the end of a particular case causes an exit
from the switch statement. The absence of break statement at each block
causes the sequential execution of all statements from the block to the end of
the switch structure.
The default statement is executed if no matches are found. The
default is optional and if not present, no actual takes place of all matches fail.
When a match is found, the statement associated with that case is executed
until the break statement is reached.

Example: Here expression "day" in switch statement evaluates to 5 which


matches with a case labeled "5" so code in case 5 is executed that results to
output "Friday" on the screen.
int day = 5;
switch (day) {
   case 1:
  System.out.println("Monday");
  break;
   case 2:
   System.out.println("Tuesday");
   break;
  case 3:
  System.out.println("Wednesday");
  break;
  case 4:
  System.out.println("Thrusday");
  break;
  case 5:
   System.out.println("Friday");
   break;
  case 6:
   System.out.println("Saturday");
   break;
  case 7:
  System.out.println("Sunday");
  break;
  default:
   System.out.println("Invalid entry");

Smt. T. LalithaKumari Page 16


PROGRAMMING IN JAVA

   break;
}

Decision making and looping ( OR)Repetition Statements:

In looping a sequence of statements are executing repeatedly until some


condition is satisfied depending upon position of the condition.
There are three types of loops.
1. while statement
2. do .. while statement
3. for statement

1.while statement:- The general form of the while loop is

While(condition)
{
Statement 1;
: body of the loop
:
Statement n;
}

While is an entry control looping statement. Here first the condition is tested,
if it is true the body of the loop will be executed as long as the condition is
true. When if the condition is false the control comes out of the loop.

Example: Here expression i<=10 is the condition which is checked before


entering into the loop statements. When i is greater than value 10 control comes
out of loop and next statement is executed. So here i contains value "1" which is
less than number "10" so control goes inside of the loop and prints current value
of i and increments value of i. Now again control comes back to the loop and

Smt. T. LalithaKumari Page 17


PROGRAMMING IN JAVA

condition is checked. This procedure continues until i becomes greater than


value "10". So this loop prints values 1 to 10 on the screen.

int i = 1;
//print 1 to 10
while (i <= 10){
  System.out.println("Num " + i);
  i++;
}
2.do-while loop statements:

The general form is


do
{
Statement 1;
: body of the loop
:
Statement n;
} while(condition);

Do ..while statement is an exit control loop statement. Here first the body of
the loop is executed and then condition is tested. If the condition is true again
the body of the loop is executed. If the condition is false the statements of the
loop will be terminated. i.e. control transfers to the statement following do ..
while statement.

Example: Here first do block of code is executed and current value "1" is printed
then the condition i<=10 is checked. Here "1" is less than number "10" so the
control comes back to do block. This process continues till value of i becomes
greater than 10.

      int i = 1;
do{
  System.out.println("Num: " + i);
   i++;
}while(i <= 10);
3. for loop statements:
For loop is another entry control loop . The general form of for statement is

Syntax:
    for (initialization; condition; increment or decrement){
  <statement>;
  ...;
  ...;

Smt. T. LalithaKumari Page 18


PROGRAMMING IN JAVA

 }
initialization: The loop is started  with the value specified.
condition: It evaluates to either 'true' or 'false'. If it is false then the loop is
terminated. 
increment or decrement: After each iteration, value increments or decrements. 

The execution of for statements the initialization of control value is done first.
The value of control variable is tested by using test condition. If the condition is
true then the body of the loop will be executed then the value of control variable
is incremented. This new value again tested using the test condition if it is true
again the body of loop is executed. If the condition is false control comes out of
the loop.

Example: Here num is initialized to value "1", condition is checked whether


num<=10. If it is so then control goes into the loop and current value of num is
printed. Now num is incremented and checked again whether num<=10.If it is so
then again it enters into the loop. This process continues till num>10. It prints
values 1 to10 on the screen.
            for (intnum = 1; num<= 10; num++){
            System.out.println("Num: " + num);
            }
 Branching Mechanism Statements:
1. Break statements: 
The break statement is a branching statement that contains two forms: labeled
and unlabeled. The break statement is used for breaking the execution of a loop
(while, do-while and for) . It also terminates the switch statements. 

Syntax:
  break;  // breaks the innermost loop or switch statement.
  break label;   // breaks the outermost loop in a series of nested loops.

Continue statements:
This is a branching statement that are used in the looping statements (while, do-
while and for) to skip the  current iteration of the loop and  resume the next
iteration . 
Syntax:
  continue;
Return statements:

It is a special branching statement that  transfers the control to the caller of


the method. This statement is used to return a value to the caller method and
terminates execution of method. This has two forms: one that returns a value
and the other that cannot return. the returned value type must match the
return type of  method. 

Syntax:
  return;

Smt. T. LalithaKumari Page 19


PROGRAMMING IN JAVA

  return values;

return;   //This returns nothing. So this can be used when method is declared with
void return type.
return expression;   //It returns the value evaluated from theexpression.
Chapter -2
Classes and Objects
Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical entity. A
class in java can contain:
 Fields
 methods
 Constructors
 blocks
 nested class and interface.
Syntax of Class:
class <class_name>
{
field declaration;
method declaration;
}
A class definition starts with the keyword class followed by the class name.
Where class name is a valid identifier for the class. The body of the declaration
can contains members, that can be either fields or method declarations. The
class members are classified into 3 categories: Private, Public and Protected.
These are called member access specifiers.
1. Private members: Private members of a class are accessible only from
within .members of the same class. You cannot access it outside the class.
2. Protected members: Protected members of their same class and also from
members of their derived classes.
3. Public Members: Public members are accessible from anywhere the object is
visible.
Note: By default all members of the class declared with the class keyword have
private access for all its members.

Method Declaration: Methods that are necessary for manipulating the data
contained in the class. Methods are declared inside the body of the class. But
immediately after the declaration of instance variables.
General Form:
type methodname(parameterlist)

Smt. T. LalithaKumari Page 20


PROGRAMMING IN JAVA

{
method body;
}
Method declaration have 4 basic parts:
I. The name of the method (methodname)
II. The type of value the method returns ( datatype)
III. A list of parameters (parameter_list)
IV. The body of the method.
 The type specify the type of value the method would return. This could be a
simple datatype such as int as well as any class type. It could even be void
type, if the method does not return any value.
 The method name is the valid identifier.
 The parameter list is always enclosed in a parenthesis. The list of variables
can be separated by commas. In the case, where no input data are required
the declaration must return the empty parenthesis.
Creating Objects: An object in java is a block of memory that contains space to
store all the instance variables. Creating an object is also referred to as
"initiating" an object.
Objects in java are created using the new operator. The new operator
creates an object of the specified class and returns a reference to that object.

Syntax:classname objectname= new classname( );


Ex: Rectangle rect1= new Rectangle( );
Accessing class members:-
Now we have created objects, each containing its own set of variables, we
should assign these values to these variables in order to use them in our
program. All variables must assign values before they are used. Since we are
outside the class, we cannot access the instance variables and the methods
directly. To do the this we must use the concerned object and the dot operator.
Syntax:
objectname.variablename=value;
objectname.methodname(parameter_list);
Ex: rect1.length=15; rect1.breadth=10; rect1.getdata(15,10);
Example Program:
class Rectangle
{
Private: int length, breadth;
Public: int getdata(int x, int y)
{
length=x;

Smt. T. LalithaKumari Page 21


PROGRAMMING IN JAVA

breadth=y;
}
int rectarea( )
{
int area=length*breadth;
return(area);
}
}
class Rectarea
{
public static void main(String args[])
{
int area1, area2;
Rectangle rect1=new Rectangle( );
Rectangle rect2= new Rectangle( );
rect1.length=15;
rect1.breadth=10;
area1= rect1.length* rect1.breadth;
rect2.getdata(20,10);
area2= rect2.rectarea( );
System.out.println("Area1=" +area1);
System.out.println("Area2=" +area2);
}
}
Method Overloading:
In Java, it is possible to create methods that have the same name, but different
parameter lists and different definitions. This is called method overloading.
Method overloading is used when objects are required to perform similar tasks
but using different input parameters. When we call a method in an object. Java
matches up the method name first and then the number and type of parameters
to decide which one of the definitions to execute. This process is known as
"Polymorphism".
To create an overloaded method, all we have to do is to provide several
different method definitions in the class, all with the same name, but with
different parameter lists. The difference may either be in the number or type of
arguments. That is each parameter list should be unique.

Example Program:
class Room
{
float length;

Smt. T. LalithaKumari Page 22


PROGRAMMING IN JAVA

float breadth;
Room(float x, float y)
{
length=x;
breadth=y;
}
Room(float x)
{
length=breadth=x;
}
float area( )
{
return(length*breadth);
}
public static void main(String args[])
{
Room r1=new Room(10);
Room r2= new Room(10,20);
System.out.println("Area=" +r1.area( ) );
System.out.println("Area=" +r2.area( ) );
}
}

UNIT - 2
CONSTRUCTORS
Constructors & Types of constructors?

Smt. T. LalithaKumari Page 23


PROGRAMMING IN JAVA

 It is a special type of method.


 It is used to initialize an instance variable.
 Name must be same as class name.
 It cannot contain return type ; not even void.
 An interface cannot have the constructor.
 Constructor cannot be private.
 A constructor can be overloaded.
 It will execute during object creation time.
 It will execute one time for every object created.
 It can contain any number of parameters.
1. Zero Parameters 2. Parameterized
 A class can contain any number of constructors.
Zero Parameter or Default Constructor:
Default constructor is the constructor which does not take any arguments.
It has no parameters.
Ex:
class Student
{
int rollno;
public static void main( String args[ ])
{
Student s1= new Student( );
}
Student( )
{
rollno=101;
System.out.println("Rollno" +rollno);
}
}
In this case, as soon as object is created the constructor is called which initializes its data
members.
OUTPUT:Rollno=101

A default constructor is so important for initialization of object members, that


even if we do not define a constructor explicitly, the compiler will provide a
default constructor implicitly.
Ex:
class Student
{
int rollno;
public static void main( String args[ ])
{
Student s1= new Student( );
}
Student( )
{
System.out.println("Rollno" +rollno);
}
}
OUTPUT:Rollno=0
Parameterized Constructor:

Smt. T. LalithaKumari Page 24


PROGRAMMING IN JAVA

There are the constructor with parameter. Using this constructor you can
provide different values to data members of different objects. by passing the
appropriate values as argument.

Example Program:
class Rectangle
{
{
intlength;
int breadth;
Rectangle(int x, int y)
{
length=x;
breadth=y;
}
public static void main(String args[])
{
Rectangle r1=new Rectangle(10,20);
System.out.println("Length of the rectangle" +r1.length);
System.out.println("Breadth of the rectangle" r1.breadth);
}
}

Constructor Overloading:
Just like other member functions, constructor can also be overloaded. In fact
when you have both default and parameterized constructors defined in your
class you are having overloaded constructors, one with no parameters and other
with parameters.

Example Program:
class Student
{
introllno;
String name;
public static void main(String args[])
{
Student s1=new Student( );
Student s2=new Student( 102, "Spandhan");
}
Student( )
{
rollno=101;
name="Preetham";
System.out.println(rollno + " " + name);
}
Student(int x, String n)
{
rollno=x;
name=n;
System.out.println(rollno + " " + name);
}
}
Static Variables and Methods:
 The static keyword in java is used for memory management. It makes
your program memory efficient[i.e. it saves memory].
 It can apply for

Smt. T. LalithaKumari Page 25


PROGRAMMING IN JAVA

 variables
 methods
 blocks.
 The static variable can be used to refer the common property of all
objects.
 Static variables gets memory only once in class area at the time of class
loading.
 The members that are declared static are called static members.
 Class basically contains two sections. One declares variables and other
declares methods. These variables and methods are called instance
variables and instance methods. Every time class is initiated, a new
copy of each of them is created. They are accessed using the objects
( with dot operator).
 we want to define member that is common to all objects and accessed
without using particular object. That is, the member belongs to the
class as a whole rather than the objects created from a class.
 Example: static int x;
static int max(int x, int y);
with the help of static method we can change (or) assign value to the
static variable.

class Student
{
int rollno;
String name;
static String college="GDCBCM";
Student(int x, String n)
{
rollno=x;
name=n;
}
static void change( )
{
college="Govt. Degree & PG College";
}
void display( )
{
System.out.println(rollno + " " +name + " " + college);
}
public static void main( String args[])
{
Student s1=new Student (101,"Preetham");
Student s2=new Student(102,"Spandhan");
change( );
s1.display( );
s2.display( );
}
}

this Keyword:
 this Keyword refers to current instance of a class.
 Using this keyword we can access instance members [ variables&
members].

Smt. T. LalithaKumari Page 26


PROGRAMMING IN JAVA

 this is a reference variable that refers to the current class object.


 this( ) can be used to invoke current class constructor.
 this keyword invoke current class method.
 specifying this keyword is sometime optional and sometimes mandatory.

Optional:
If there is no confusion between instance variable and local variable this
keyword is optional. In such case we don't specify this keyword automatically
and access local variable.
Mandatory:
If there is a confusion between instance variable and local variable then
specifying the this keyword is mandatory. In such case we don't specify this
keyword the compiler will also not specify this keyword and instead access local
variable. If we want to access instance variable then the programmer has to
specify the this keyword.

Example for this Optional:


class Student
{
int x=15; //instance variable
void display( )
{
int y=20; // local variable
System.out.println(y);
}
public static void main(String args[ ] )
{
Student s=new Student( );
s.display( );
}
}

Example for this Mandatory:


class Student
{
int x=15; //instance variable
void display( )
{
int x=20; // local variable
System.out.println(this.x);
}
public static void main(String args[ ] )
{
Student s=new Student( );
s.display( );
}
}
OUTPUT: 15
without using the this keyword OUTPUT is 20.

Using the constructor this keyword:


class Student
{
int x;

Smt. T. LalithaKumari Page 27


PROGRAMMING IN JAVA

Student(int x )
{
this.x=x;
{
void display( )
{
System.out.println(x);
}
public static void main(String args[ ] )
{
Student s=new Student( 50);
s.display( );
}
}

Defining the Array:


An array is a variable which can store multiple values of same datatype at a time
collection of similar type of data items stored in continuous memory locations
with single name. The array variable starts from 0th location in the memory. The
array each cell can be created by separate address value. each array element is
referred by specifying the array name followed by one or more subscripts. With
each subscript enclosed in square brackets. The number of subscripts
determines the number of dimensionality of the array.
Arrays are 3 types:
1. One dimensional.
2. Two dimensional
3. Multi-dimensional.
1.One dimensional Array:
A list of items can be given one variable name using only one subscript such a
variable is called a single dimensional array.

Syntax: Datatype arrayname= new datatype[size];


Ex: int arr=new int[5];

Here arr is one dimensional array is of integer type, array containing 5 elements
those are arr[0], arr[1], arr[2],arr[3], arr[4].

Storing the values into the array:


1.Initialization of Array.
2.Assigning values.
3. Inputting the values.

1.Initialization of one dimensional Array:we can initialize the elements of


arrays in the same way of ordinary variables when they are declared.
General Form:
Data type arrayname[size]={list of values};

Exint arr[ ]={35,40,20,37,19};


2. Assigning the Values:
int arr[ ]= new int[5];
arr[0]=5;

Smt. T. LalithaKumari Page 28


PROGRAMMING IN JAVA

arr[1]=10;
arr[2]=15;
arr[3]=20;
arr[4]=25;

Array Length: All arrays store the allocated size in a variable named length. we
can obtain the length of array a using a.length.
Arraylength=Upper+lower +1
Ex:

class Arraydemo
{
public static void main(String args[ ])
intarr[ ]= new int[5];
arr[0]=5;
arr[1]=10;
arr[2]=15;
arr[3]=20;
arr[4]=25;
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
3. Inputting the values: We can inputting or read the values to an array by
using for loop.
Ex:
int a[]= new int[20];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the size of the array");
int n= Integer.parseInt(br.readLine( ));
System.out.println("enter the elementsinto the array");
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine( ));
}

Practical Program: /* Java program Find the smallest Element in Array */

importjava.util.Scanner;
public class Javaprogram
{
public static void main(String args[ ])
{
intsmall,size,i;
intarr[ ]= new int[20];
Scanner scan= new Scanner(System.in);
System.out.println("Enter the array size ");
size=scan.nextInt( );
System.out.println("Enter the elementsinto the array ");
for(i=0;i<size;i++)
{
arr[i]=scan.nextInt( );
}
System.out.println("Searching for the smallest element \n \n");
small=arr[0];

Smt. T. LalithaKumari Page 29


PROGRAMMING IN JAVA

for(i=1;i<size;i++)
{
if(small>arr[i])
{
small=arr[i];
}
}
System.out.println("smallest Element " +small);
}
}
2. Two Dimensional Array: A list of items can be given one variable name
using two subscripts such a variable is called a two dimensional array.
Syntax: datatype arrayname[ ][ ]= new datatype[size][size];
Ex: int arr[ ] [ ]= new int[3][3];

1.Initialization of two dimensional Array:when they are declared.


General Form: Data type arrayname[size][size]={list of values};
Ex intarr[ ][ ]={{1,2,3},{4,5,6},{7,8,9}};
2. Assigning the Values:
intarr[ ][ ]= new int[2][2];
arr[0][0]=5;
arr[0][1]=10;
arr[1][0]=15;
arr[1][1]=20;
Practical Program: Find the Matrix Multiplication:
importjava.util.Scanner;
classMatrixmultiplication
{
public static void main(String args[])
{
int m1[ ][ ]= new int[3][3];
int m2[ ][ ]= new int[3][3];
int m3[ ][ ]= new int[3][3];
inti,j,k;
System.out.println("Enter the first matrix \n");
Scanner input = new Scanner(System.in);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
m1[i][j]=input.nextInt( );
}
System.out.println("Enter the Second matrix \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
m2[i][j]=input.nextInt( );
}
System.out.println("Matrix Multiplication \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m3[i][j]=0;
for(k=0;k<3;k++)
{
m3[i][j]+=m1[i][k]*m2[k][j];

Smt. T. LalithaKumari Page 30


PROGRAMMING IN JAVA

}
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(m3[i][j]+ "\t");
}
System.out.println("\n");
}
}
}

Command Line Arguments: Command line arguments (parameters) that are


supplied to the application program at the time of invoking it for execution.
We can write java programs that can receive and use the arguments
provided in the command line. recall the signature of the main( ) method.
public static void main( String args[ ])
As pointed earlier, args[ ] is declared as an array of strings (Known as string
objects). Any arguments provided in the command Line (at the time of
execution) are passed to the array args as its elements.

Example program on command Line argument:


classCommline
{
public static void main(String args[])
{
int count,i=0;
String str;
count=args.length;
System.out.println("No. of args=" +count);
while(i<count)
{
str=args[i];
i=i+1;
System.out.println("i+ ":+ "Java is" +str);
}
}
}
Compile & Run Program:
java Commline Java is a Object Oriented Program
Output:
No. of args=6
1:Java is Java
2: Java is is
3:Java is a
4:Java is Object
5:Java is Oriented
6:Java is Program

Inner Class in Java (or) Nested Class:


A class defined within another class is known as Nested class. The class that
holds the inner class is called outer class.

Smt. T. LalithaKumari Page 31


Syntax:
class Outer
{
-------;
-------;
class Inner
{
--------;
--------;
}
}
Ex: Class Outer
{
int n;
class Inner
{
-------;
-------;
}
}
PROGRAMMING IN JAVA

Nested classes are divided into 2 types:

n
o
y
u
a
ti
e
t
d
l
s
M
h
i
A
m
I
r
S
N
c
C
 Non static Nested class (These are the non static members of the class).
 Static Nested class ( These are the static members of a class).

Inner Class: Creating inner class is quite simple. You just need to write
class within a class. Unlike a class, an inner class can be private and
once you declare an inner class private , it cannot be accessed from an
object outside the class.
Ex:

class Outer
{
class Inner
{

Smt. T. LalithaKumari Page 32


PROGRAMMING IN JAVA

void innermethod( )
{
System.out.println("This is an inner class method ");
}
}
void outermethod( )
{
System.out.println("this is Outer method");
Inner i=new Inner( );
i.innermethod( );
}
public static void main(String args[])
{
Outer outr= new Outer( );
outr.outermethod( );
}
}
OUTPUT:
This is Outer method
This is inner class method
Method Local Inner Class:
In Java we can write a class within a method and this will be a local type.
Like local variable, the scope of the inner class is restricted within the method.
A method local inner class can be instantiated only within the method where the
inner class is defined.

Ex:
class Outer
{
void outermethod( )
{

class MethodInner
{
void innermethod( )
{
System.out.println("inner class method");
}
}
MethodInner inn= new MethodInner( );
inn.innermethod( );
}
public static void main(String args[])
{
Outer outr=new Outer( );
outr.outermethod( );
}
}
Output: inner class method.

Anonymous Inner Class: An inner class declared without a classname is known


as anonymous inner class. In case of anonymous inner class, we declare and
instantiate then at the same time. Generally, they are used whenever you need
to override a method of class (or) an interface.
Syntax:
AnonymousInneraninn=new AnonymousInner( )

Smt. T. LalithaKumari Page 33


PROGRAMMING IN JAVA

{
public void mymethod( )
{
------------;
------------;
}
};

Program on anonymous Inner class:


class AnonymousInner
{
void mymethod();
{
System.out.println("Hello");
}
}
classOuterclass
{
public static void main(String args[ ])
{
AnonymousInner a= new AnonymousInner( );
a.mymethod();
AnonymousInner b= new AnonymousInner( )
{
void mymethod()
{
System.out.println("This is an example of Anonymous Inner class");
}
};
b.mymethod( );
}
}
output:
Hello
This is an example of Anonymous Inner Class.

Static Nested Classes:


Static nested classes are not technically an inner class. They are like a static
member of outer class.
Example Program

class Outer
{
static class Inner
{
void innermethod()
{
System.out.println("static inner class method");
}
}

public static void main(String args[ ] )


{
Inner i= new Inner();
i.innermethod( );
}

Smt. T. LalithaKumari Page 34


PROGRAMMING IN JAVA

}
output:
static inner class method

Inheritance
 A Process of acquiring the members ( Properties and methods) of one class
to another class is called inheritance.
 Inheritance is a mechanism wherein a new class is derived from existing
class.
 Using inheritance we can achieve reusability and thereby reduce the code
size and development time of the application.
 Inheritance represents the is-a relationship, also known as parent -child
relationship.
Uses of Inheritance in java:
 for method overloading ( so runtime polymorphism can achieved)
 for code reusability.

Terms Used in Inheritance:


 Class: A Class is a group of objects which have common properties. It is a
blue print from which objects are created.
 Sub Class/Child Class: Sub class is a class which inherits the other class.
It is also called as derived class, Extended class (or) child class.
 Super Class/ Parent Class: Super class is the class from where a sub
class inherits the features. It is also called a base class (or) a parent class.
 Reusability: As the name specifies, reusability is mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class.
Syntax of JAVA Inheritance:

class subclass-name extends superclass


{
//methods & fields
}

The extends keyword indicates that you making a new class that derives
from an existing class. The meaning of extends is to increase the functionality.

Smt. T. LalithaKumari Page 35


PROGRAMMING IN JAVA

Program:
class Employee{  
 float salary=40000;  
}  
class Programmer extends Employee{  
 int bonus=10000;  
 public static void main(String args[]){  
   Programmer p=new Programmer();  
   System.out.println("Programmer salary is:"+p.salary);  
   System.out.println("Bonus of Programmer is:"+p.bonus);  
}  
}  

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through


interface only. We will learn about interfaces later.

Single Inheritance: In this type of inheritance one derived class extends from
only one base class. It is the most simplest form of inheritance.

Multilevel Inheritance: In this type of inheritance the derived class extends


from a class. Which in turn inherits from some other
class. The super class for one , is subclass class for the
other.

Smt. T. LalithaKumari Page 36


PROGRAMMING IN JAVA

Hierarchical Inheritance: In this type of inheritance multiple derived classes


can extends from a single base class.

“Multiple Inheritance” & “Hybrid


Inheritance” is not supported in Java
through class.

Multiple Inheritance: In this type of inheritance a single derived class may


extends from two or more than two base classes.

Hybrid Inheritance: Hybrid inheritance is a combination of Hierarchical and


multiple inheritance.

Multilevel Example:

class Add
{
int a=15,b=10;
void Add()
{
System.out.println(a+b);
}
}
Class Sub extends Add

Smt. T. LalithaKumari Page 37


PROGRAMMING IN JAVA

{
void Sub()
{
System.out.println(a-b);
}
Class Mul extends Sub
{
void Mul()
{
System.out.println(a*b);
}
Class Div extends Mul
{
void Div()
{
System.out.println(a/b);
}
}
Class Multilevel
{
Public static void main( String args[])
{
Div d=new Div();
d.add();
d.Sub();
d.Mul();
d.Div();
}
}

Hierarchical Example:

class Animal
{  
void eat()
{
System.out.println("eating...");
}  
}  
class Dog extends Animal{  
void bark()
{
System.out.println("barking...");
}  
}  
class Cat extends Animal
{  
void meow()
{

Smt. T. LalithaKumari Page 38


PROGRAMMING IN JAVA

System.out.println("meowing...");
}  
}  
class Hierarchical
{  
public static void main(String args[])
{  
Cat c=new Cat();  
c.meow();  
c.eat();  
//c.bark();//C.T.Error  
Dog d=new Dog();
d.bark();
d.eat();
}
}  

Method Overriding In JAVA:


If subclass (child class) has the same method as declared in the parent
class it is known as Method Overriding In Java.
In other words, if subclass provides the specific implementation of the
method that has been provided by one of its parent class, it is known as
overriding.
Usage of Java Method overriding:
 Method overriding is used to provide specific implementation of a method
that is already provided by its super class.
 Method overriding is used for runtime polymorphism.
Rules for Java Overriding:
1. Method must have same name as in the parent class.
2. Method must have same parameter as in the parent class.
3. Must be Is-A relationship (inheritance).
Example:
class Vehicle
{  
void run()
{
System.out.println("Vehicle is running");
}  
}  
class Bike extends Vehicle
{  
Void run()
{
System.out.println(“Bike Is running safely”);
}
}
Class Overridetest
{
  public static void main(String args[])

Smt. T. LalithaKumari Page 39


PROGRAMMING IN JAVA

{  
 Bike obj = new Bike();  
   obj.run();  
  }  
}  
OUTPUT:
Bike is running safely.

Example:
class Super1
{
int x;
Super1(int x)
{
this.x=x;
}
void display()
{
System.out.println(“Super x=” +x);
}
}
class Sub1 extends Super1
{
int y;
Sub1(int x, int y)
{
Super1(x);
this.y=y;
}
void display()
{
System.out.println(“Super x=” +x);
System.out.println(“Super y=” +y);
}
}
class Overridetest
{
Sub1 s1=new Sub(100,200);
s1.display();
}
}

Super Keyword in Java:


The super keyword in java is a reference variable that is used to refer parent
class objects.  The keyword “super” came into the picture with the concept of
Inheritance.

Smt. T. LalithaKumari Page 40


PROGRAMMING IN JAVA

1. Use of super with variables: This scenario occurs when a derived class and
base class has same data members. In that case there is a possibility of
ambiguity for the JVM. We can understand it more clearly using this code

/* Base class vehicle */

Class Vehicle
{
    int maxSpeed = 120;
}
  
Class Car extends Vehicle
{
    int maxSpeed = 180;
  
    Void display()
    {
                System.out.println("Maximum Speed: "+ super.maxSpeed);
    }
}
  
Class Test
{
    publicstaticvoidmain(String[] args)
    {
        Car c= newCar();
        c.display();
    }
}
Output:
Maximum Speed: 120

 2. Use of super with methods: This is used when we want to call parent class
method. So whenever a parent and child class have same named methods then
to resolve ambiguity we use super keyword. This code snippet helps to
understand the said usage of super keyword.

classPerson
{
    Void message()
    {
        System.out.println("This is person class");
    }
}
  
Class Student extends Person
{
    Void message()

Smt. T. LalithaKumari Page 41


PROGRAMMING IN JAVA

    {
        System.out.println("This is student class");
    }
  
    Void display()
    {
                message();
                  super.message();
    }
}
  
classTest
{
    Public static void main(String args[])
    {
        Student s = newStudent();
        s.display();
    }
}
Output:
This is student class
This is person class
 
3. Use of super with constructors: super keyword can also be used to access
the parent class constructor.
Class Person
{
    Person()
    {
        System.out.println("Person class Constructor");
    }
}
  
Class Student extends Person
{
    Student()
    {
                super();
          System.out.println("Student class Constructor");
    }
}
  
classTest
{
    Public static void main(String[] args)
    {
        Student s = new Student();
    }

Smt. T. LalithaKumari Page 42


PROGRAMMING IN JAVA

}
Output:
Person class Constructor
Student class Constructor

Final Keyword:

Final keyword can be used along with variables, methods and classes.
1. Final variable -> to create the constant variable.
2. Final method -> prevent the overriding.
3. Final class -> prevent the inheritance.

1.Final Variable: If you make any variable final, you cannot change the value.
A final variable that have no value it is called blank final variable(or)
uninitialized final variable. It can be initialized constructor only. The blank
final variable can be static also which will be initialized in static block only.
Example:

class Bike
{
final int speedlimit=90;
void run( )
{
speedlimit=120;
}
public static void main(String args[])
{
Bike b=new Bike( );
b.run();
}
}
Output: compile time error.

Final Method : If you make any method as final you cannot be override it.

Example:
class Bike
{
final void run( )
{
System.out.println(“Running”);
}
}
class Honda extends Bike
{
void run( )
{

Smt. T. LalithaKumari Page 43


PROGRAMMING IN JAVA

System.out.println(“ Running safely 100 kmph”);


}
Public static void main(String args[])
{
Honda honda=new Honda( );
honda.run();
}
}
Output: Compile Time Error.

Final class: If you make class as final, you cannot extend it.

Example:

final class Bike


{
void run( )
{
System.out.println(“Running”);
}
}
class Honda extends Bike
{
void run( )
{
System.out.println(“Running safely 100 kmph”);
}
public static void main( String args[])
{
Honda Honda=new Honda( );
honda.run();
}
}
Output:Compile time error

Abstract class: A class is called as an abstract that means compulsory we


declare abstract keyword before the class.
 An abstract class may or may not contain abstract methods (or) may or
may not contain concrete methods.
 In java object creation is not possible for abstract class.
 But, if a class has at least one abstract methods, then the class must be
declared abstract.
 To use the abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all
the abstract methods in it.
Abstract method: If you want a class to contain particular method but you want
the actual implementation of the method to be determined by child classes, you
can declare the method in the parent class as are abstract.

Smt. T. LalithaKumari Page 44


PROGRAMMING IN JAVA

 Abstract keyword is used to declare the method as abstract.


 You have to place the abstract keyword before the method name in method
declaration.
 An abstract method contains a method signature but no method body.
 Instead of curly braces, an abstract method will have semicolon(;) at the
end.

Example:- abstract class myclass


{
Public void disp1()
{
System.out.println(“concreated method of parent class”);
}
abstract public void disp2();
}
Class Demo Extends myclass
{
/*must over ride this method while extending Myclass*/
Public void disp2()
{
System.out.println(“overriding abstract method”);
}
Public static void main(string args[ ])
{
Demo obj=new Demo();
Obj.disp2();
}
}

Interfaces (or) multiple Inheritance:-


 Java does not support multiple inheritance. That is, classes in JAVA
cannot have more than one super class.
 Java provides alternate approach known as interfaces to support the
concept of multiple inheritance. Although, a java class cannot be a
subclass of more than one super class, it can implement more than one
interface.
 An interface is basically a kind of class. Like classes, interfaces contains
methods &variables, but the major difference is interfaces define only
abstract methods & final fields.
 This means that interfaces do not simplify any code to implement this
methods and data fields contain only constants. And interface is implicitly
abstract, we need not declare abstract keyword before interface.

Syntax:-interface interfacename
{
Variable declaration;
Method declaration;
}

Smt. T. LalithaKumari Page 45


PROGRAMMING IN JAVA

Here interface is the keyword and interface name is any valid java variable.

Variables are declared has follows:-


Static final type variablename= value;
Each method in interface is also implicitly public & abstract .So abstract
keyword is not needed.

Methods are declared as follows ;-


Returntype methodname (parameter-list);

Ex;- interface Item


{
Static final int i=100;
Abstract public void display();
}
Extending Interface;-
Like classes, interfaces can also be extended. An interface can be sub
interfaced from other interfaces. The new sub interface will inherit all the
members of the super interface in the manner similar to subclass.
Syntax:-interface name2 extends name1
{
\\ body of the name2;
}

Note:- When on interface extends two or more interfaces, they are separated by
commas.

Implementing the interface:-


 The responsibility of the class that implements an interface to define code
for implementation of these methods.
 Interfaces are used as “super class” whose properties are inherited by
classes.

Syntax:-
Class classname implements interfacename
{
\\ body of the class
}
Here class classname“ implements” the interface.

A class can extends another class while implementing interfaces.


Syntax:
Class classname extends superclass implements interface1,interface2,…..
{
\\ body of the class name
}

Smt. T. LalithaKumari Page 46


PROGRAMMING IN JAVA

Example: multiple Inheritance


Interface father
{
Float HT= 6.2f;
Void height ( );
}
Interface mother
{
Float HT=5.8f;
Void height( );
}
Class child implements father, mother
{
Public void height ( )
{
Float ht=(father. HT+ mother.HT)/2;
System.out.println (‘child’s height=” +ht );
}
Class multi
{
Public static void main (string args [ ])
{
Child ch=new child ( );
Ch. Height ( );
}
}

Output;- child’s height 6.0

*Abstract class Vs Interface

Abstract class Interface


An abstract class can extended only one An interface can be extended any
class or one abstract class at a time. number of interface at time.
An abstract class can extended An interface can only extended
another concrete or abstract class another interface.
An abstract class can have both An Interface can have only
abstract & concrete methods abstract methods
In abstract class keywords
“abstract” is mandatory to In interface keyword
declare a method as an “abstract” is optional
abstract
An abstract class can have
interface can only have public
static, final (or) static final
static final variable
variable with access specifiers
An interface connect contain
An abstract class can contain
instance variables, It contain
instance variables also
only constants.

Smt. T. LalithaKumari Page 47


PROGRAMMING IN JAVA

Abstract class is declared by Interface is declared using the


using the keyword abstract keyword interface.

*Packages *
Package:- A package represents a directory that contains related group of
classes and interfaces. In fact, packages acts as “containers” for classes.
By organizing our classes into packages we achieve following benefits;
 The classes contained in the packages of other programs can be
easily reused.
 In packages, classes can be unique. That is two classes in two
different packages can have the same name
 Packages provide a away to “hide" classes preventing other
programs or packages from accessing classes that are meant for
internal use only.

Java packages are of 2 types;


1. JAVA API packages ( application program interface)
2. User defined packages.

JAVA API Packages:-


JAVA API provides a large number of classes grouped into different
packages according to functionality.

Package Contents
name
java.lang Languages support classes. These are class that
java compiler itself uses and therefore they are
automatically imported. They include classes for
primitive types, strings, math functions, threads

Smt. T. LalithaKumari Page 48


PROGRAMMING IN JAVA

and exceptions.
java.util language utility classes such as Vectors, hash
tables, random Numbers, date etc
java.io Input /output support classes. They provide
facilities for input & output data.
java.awt set of classes for implementing Graphical user
interface. They include classes for windows
Buttons, lists, menus and so on.
java.net classes for networking. They include classes for
communicating with local computers as well as
with internet servers
java.applet Classes for creating and implementing applets.

Using system packages:-

there are two way to accessing the classes in a package.


1. Packagename containing the class and then appending the classname to it
using dot operator.
Syntax:- import packagename. Classname
Ex:- import java.awt.Color
2. Imports every class contained in the package.
Syntax:-import packagename.*
Ex:- import java.awt .*
Naming conventions:-
By convention, packages begin with lowercase letters and class names again by
convention begin with uppercase letters,.

double Y=java.lang.Math.sqrt(x);

This statement uses a fully qualified class name math to invoke the method
sqrt( ).
Creating a packages;-
First declare the name of the package using the package keyword by
packagename.
Creating our own by package involves the following steps;
1. Declare the package at the beginning of a file.
Package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Store the class name.java file in the directory created.
4. Compile the file this creates the .class file in the directory
Package firstpackage;
Public class Firstclass
{
\\ body of the class
}
Here package name is firstpackage .The class Firstclass is part of the
package. Now save the file Firstclass.java and located in directory name

Smt. T. LalithaKumari Page 49


PROGRAMMING IN JAVA

firstpackage. When the source file is compiled, java will create a .class file and
store it in the same directory.

Creation of sub directory under the directory:-


1. Create a sub directory under the directory where the main source files are
stored.
2. Store classname .java file in the sub directory.
3. Compile the file. This creates the .class file in the sub directory.

Syntax:-Package firstpackage.secondpackage

Accessing package:-
Accessing package approach through the import statement.

General form:-
1. Import package1[ .package2] [.package 3] .classname;
Ex:- import firstpackage.secondpackage.myclass;
2. Import packagename .*;

Using a package:-
Consider small simple programs that we use classes from other packages.
1. Consider package named package1 containing a single classA.
2. ClassA .java and stored in the sub directory package1
3. When compile ClassA. Class will be stored in the same subdirectory.
package package1;
public class ClassA
{
public void displayA( )
{
System.out.println( “Class A”);
}
}
Consider package named package2 containing a single classB.
ClassB .java and stored in the subdirectory package2.
When compile ClassB.class will be stored in the same subdirectory.
package package2;
public class ClassB
{
protected int m=10;
Public void display B( )
{
System.out.println(“class B”);
System.out.println(“m=” +m);
}
}
Importing classes from other packages:-
Import package1.classA;
Import package2.*

Smt. T. LalithaKumari Page 50


PROGRAMMING IN JAVA

class packageTest2
{
public static void main(String args[ ])
{
classA objA=new classA( );
classB objB=new classB( );
objA.displayA( );
objB.displayB( );
}
}
Output:-
` classA
classB
m=10

Sub classing an imported class:-


Import package 2.ClassB;
class ClassC Extension ClassB
{
int n=20;
void displayC( )
{
System.out.println(“class C”);
System.out.println(“m=” +m);
System.out.println( “n=” =n);
}
}
class package Test 3
{
Public static void main(String args[ ])
{
ClassC objC =new ClassC( );
objC.displayB( );
objC.displayC ( );
}
}
Output:-
classB
m=10
classC
m=10
n=20

Multiple packages contains classes with same name:-


Package pack1;
public class Teacher
{
-----------
-----------

Smt. T. LalithaKumari Page 51


PROGRAMMING IN JAVA

}
public class Student
{
-----------
-----------
}
package pack2;
public class Courses
{
-----------
-----------
}
public class Student
{
-----------
-----------
}
Creating object for those classes:-
Pack1.Student stu1;
Pack2.Student stu2;

Access protection (or) visibility control:-


Access
modifier Friendl
Private
public Protected y private
protected
Access (default)
Location
Same class
Yes Yes Yes Yes Yes
Sub class in same
Yes Yes Yes Yes No
package
Other classes in
Yes Yes Yes No No
same package
Sub classes in Yes
Yes Yes No No
other packages
Non Sub classes
Yes No No No No
in other packages

Inherit all the members of a class by subclass using “Extends” keyword.


The variables & methods of a class are visible .Everywhere in the program.
However it may be some situations to restrict to access to certain variables and
methods from outside the class. We can achieve this by applying visibility
modifiers to the instance variables and methods. The visibility modifiers are
called access modifiers. These are public, protected, private.
Public Access:-
Any variable or method declared as public is visibility and accessibility
entire class or everywhere in the program.
Private Access:-
Any variable or method declared as private is visibility or accessibility with
their own class. Private fields has highest degree protection.
Protected Access:-
The visibility level of “protected” field lies in b/w the public and friendly
access. That is the protected modifier makes the fields visibility not only all

Smt. T. LalithaKumari Page 52


PROGRAMMING IN JAVA

classes and subclasses in the same package But also to the subclasses in the
other packages.
Private Protected Access: visibility level between "protected" and "private"
Access. This modifier makes all fields visible in all subclasses regardless of
package.
Friendly Access: No Access modifier is specified the member defaults to friendly
level of access. friendly access makes fields visible only in the same package.

Wrapper classes:-
Vectors cannot handle the primitive datatypes like int, float, long, char
and double. Primitive datatypes may be converted into object types by using the
wrapper classes contained in the java.lang package.

Wrapper classes for converting simple types


Simple Wrapper class
Type
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
Converting primitive numbers to object numbering using constructor
method

Constructor calling Conversion Action


Integer IntVal= new Integer(i); Primitive integer to integer object
Float FloatVal= new Float(f); Primitive float to float object
Double DoubleVal= new Double(d); Primitive double to Double object
Long Longval= new Long(l); Primitive long to Long object

Converting object Numbers to primitive Numbers using typevalue( )


method

Method Calling Conversion Action


int i= IntVal.intValue( ); Object to primitive integer
float f= FloatVal.floatValue( ); Object to primitive float
long l= LongVal.longValue( ); Object to Primitive long
double d= DoubleVal.doubleValue( ); Object to Primitive double

Converting Numbers to strings using toString ( ) method:


Method Calling Conversion Action
str=Integer.toString(i); primitive integer to String
str=Float.toString(f); primitive float to String
str=Double.toString(d); Primitive double to String

Smt. T. LalithaKumari Page 53


PROGRAMMING IN JAVA

str=Long.toString(l); Primitive long to String

Converting String objects to numeric objects using the static method


Valueof( )

Method Calling Conversion Action


DoubleVal= Double.ValueOf(str); Converts string to Double object
FloatVal= Float.ValueOf(str); Converts string to Float object
IntVal= Integer.ValueOf(str); Converts string to Integer object
LongVal= Long.ValueOf(str); Converts string to Long object

Converting Numberic Strings to Primitive Numbers using parsing methods

Method Calling Conversion Action


Int i = Integer.parseInt(str); Converts string to Primitive integer
Long l= Long.parseLong(str); Converts string to primitive long

String Class:
 In java, strings are class objects and implemented using the two classes,
namely " String" and "String Buffer".
 A JAVA string is initiated object of string class.
 A JAVA string is not a character and is not Null terminated.
Syntax:
String stringname;
stringname= new String("string");
Example:
String firstname;
firstname= new String("Anil");
(or)
String firstname= new String("Anil");
String Arrays: we can also create & use arrays that contains strings.
Ex: String item[]= new String[3];

String Methods: The string class defines a number of methods that accomplish
a variety of string manipulation tasks.
Some most commonly used string methods
Method Call Task Performed
s2=s1.toLowerCase; Converts the string s1 to all lowercase
s2=s1.toUpperCase; Converts the string s1 to all Uppercase
s2=s1.replace('x','y'); Replace all appearances of x with y
s2=s1.trim( ); Remove white spaces at the begin and
end of the string s1.
s1.equals(s2) Returns 'true' if s1 is equals to s2.
s1.equalIgnoreCase(s2) Returns 'true' if s1=s2, ignoring the
case of characters
s1.length( ) Gives the length of s1
s1.charAt(n) Gives nth character of s1.

Smt. T. LalithaKumari Page 54


PROGRAMMING IN JAVA

S1.compareTo(s2) Retuns -ve if s1<s2, +ve if s1>s2 and


zero

Example Program: Alphabetical order of strings


class Stringordering
{
static String name[]= {"Madras", "Delhi", "Ahmedabad", "calcutta", Bombay"};
public static void main(String args[])
{
int size=name.length;
string temp=null;
for(i=0;i<size;i++)
{
for(j=i+1;j<size;j++)
{
if(name[j].compareTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}
Output:
Ahmedabad
Bombay
calcutta
Delhi
Madras
String Buffer class:
String Buffer is a peer class of string. while string creates strings of fixed length,
string buffer creates strings of flexible length that can be modified in terms of
both length and content. We can insert characters and substrings in the middle
of the string or append another string to the end.

Commonly used String Buffer Methods


Method Task
s1.setCharAt(n,'x') Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end
s1.insert(n,s2) Inserts the string s2 at the position n of the string s1
s1.setLength(n) Sets the length of the string s1 to n

Example Program on manipulation of Strings


class Stringmanip
{
public static void main(String args[])
{

Smt. T. LalithaKumari Page 55


PROGRAMMING IN JAVA

StringBuffer str=new StringBuffer("Object Language");


System.out.println("Original String=" +str);
String astr= new String(str.toString());
int pos=astr.indexOf("Language");
str.insert(pos,"Oriented");
System.out.println("Modified String:" +str);
str.setCharAt(6,'-');
System.out.println("String now" +str);
str.append("improves security");
System.out.println("Append string:" +str);
}
}
Output:
Original String : Object Language
Modified String: Object oriented Language
String now: Object-oriented Language
Append String: Object-Oriented Language improves security

Unit - 3
Exception Handling
Q) Exception Handling and Types of Exception Handling?

Exception is an event raised during while program execution, which disturb


normal execution of program. The process of handling exception is called
Exception Handling.
An exception is a condition that is caused by a run time error in program.
If we want the program to continue with the execution of the remaining code,
then we should try to catch the exception object thrown by the error condition
and display appropriate message for taking corrective actions. The task is known
as "Exception Handling".
To implement Exception Handling in our program by using the following
keywords:
try: try block will contain the set of statements which are going to raise the
exception. If the exception raised from the try block one object is created of the
type of exception class and reference of object is thrown on to catch block.

Catch: Catch block holds the reference of the object which is thrown from the
try block and reference has been is holded by the reference variable declared
type of exception thrown by the exception class.

throw: throw keyword is used to throw an exception explicitly (or) manually.

throws: It is use to ignore try and catch block within the function.

Finally: Finally block is an independent of executable block. Not dependent on


executable block. Not depending upon the exception whether raised or not.
Finally block contains the closing operations.

Types of Exceptions:
There are 2 types of exceptions
 Predefined / built in exceptions

Smt. T. LalithaKumari Page 56


PROGRAMMING IN JAVA

 User/ Programmer / Custom defined Exceptions.


Predefined Exception:
These are developed by Sun micro System developers available as a part of java
software and who's role is to deal with universal problems.
Some of the universal problems are:
 Division by zero problem.
 Invalid number format.
 Invalid bounds of the array.
Built-in-Exceptions:
Built in Exceptions are the Exceptions which are available in java libraries.
 ArithmeticException: Caused by math errors such as division by zero.
 ClassNotFoundException: Caused by when we try to access a class whose
definition is not found.
 FileNotFoundException: Caused by an attempt to access a non existent
file.
 IOException: It is thrown when an input - output operation failed (or)
interrupted.
 NoSuchFieldException: It is thrown when a class does not contain the field
or variable specified.
 NoSuchMethodException: caused by when accessing a method which is
not found.
 NullPointerException: Caused by referencing a null object.
 NumberFormatException: Caused when a method could not convert a
string into numeric format.
 OutOfMemoryException: Caused when there is not enough memory to
allocate a new object.
 RuntimeException: This represents one exception which occurs during
runtime.
 StringIndexOutOfBoundException: Caused when a program attempts to
access a nonexistent character position in a string.

User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, a user can also create exceptions which are called
‘User-Defined Exceptions’. These exceptions are deal with common problems.

Some of the common problems are:


 Trying to enter negative salary of the employee.
 Attempting to withdraw more than amount in your account.
 Attempting to enter wrong PIN in ATM.
 trying to enter digit in a name.
 trying to enter invalid username and password.

Following steps are followed for the creation of User defined Exception:

 The user should create an exception class as a subclass of exception class.


class MyException extends Exception
 We can write a default constructor in his own exception class.
MyException( ) { }

Smt. T. LalithaKumari Page 57


PROGRAMMING IN JAVA

 To raise exception of user-defined type, we need to create an object to his exception class
and throw it using throw clause, as:
MyException me=new MyException("Exception details");
throw me;
(or)
throw new MyException("exception details");

Example program for user defined exception


package exceptionhandling;
import java.util.*;
public class Dexception extends Exception
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
try
{
System.out.println("Enter the Roll no");
String rno=sc.nextInt();
if(rno.length( ) !=10)
{
throw new Dexception( );
}
System.out.println("Roll no" +rno);
}
catch(Dexception ob)
{
System.out.println("Invalid rno");

}
}
output:
enter Roll no
123
Invalid rno
Output:
enter Roll no
1234567890

Q) Exception handling Techniques in JAVA?


An Exception is a condition that is caused by a runtime error in a
program. If we want the program to continue with the exception of remaining
code, then we should try to catch the exception object thrown by the error
condition and display appropriate message for taking corrective actions. The
task is known as "Exception Handling".
Using try and catch:-
try is used to guard a block of code in which exception may occur when an
exception may occur one object is created of the type of exception class and
reference object is thrown on to catch block.
catch block holds the reference of the object which is thrown by the try
block, then the exception is handled over to the catch
block which then handles it.

Syntax:
try

Smt. T. LalithaKumari Page 58


PROGRAMMING IN JAVA

{
statement; // generator an exception
}
catch(Exceptiontype e)
{
Statement; // process the exception
}

Example program using try catch


package Exceptionhandling;
import java.util.*;
public class Dexception
{
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a value");
int x= sc.nextInt();
int k=44/x; //when x==0 exception is raised
System.out.println("The value k:" +k);
}
catch(ArithematicException ae)
{
System.out.println("only non zero value");
}
}
}

Multiple Catch block:

A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform different
tasks at the occurrence of different exceptions, use java multi-catch block.

o At a time only one exception occurs and at a time only one catch block is
executed.

Syntax:
try
{
statement; // generates an exception
}
catch(Exception_Type1 e)
{
Statement; // process the exception Type1
}
catch(Exception_Type2 e)
{
Statement; // process the exception Type2

Smt. T. LalithaKumari Page 59


PROGRAMMING IN JAVA

}
.
.
.
catch(Exception_TypeN e)
{
Statement; // process the exception TypeN
}

Example program for multiple catch blocks

package Exceptionhandling;
import java.util.*;
public class Dexception
{
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a value");
int x= sc.nextInt();
int k=44/x; //when x==0 exception is raised
System.out.println("The value k:" +k);
}
catch(ArithematicException ae)
{
System.out.println("only non zero value");
}
catch(InputMismatchException ie)
{
System.out.println("only integer value");
}
}
}
OUTPUT:
1) Enter a value
12
The value k: 3
2) Enter a value
0
Only non zero value
3) Enter a value
12.34
Only integer value.

Nested try statement:


try statement can be nested inside another block of try. Nested try block is
used when a part of block may cause one error while entire block may cause
another error.
In case if inner try block does not have a catch handler for a particular
exception then outer catch block is checked for match.
Example:
class Nestedtry
{
public static void main(String args[])
{

Smt. T. LalithaKumari Page 60


PROGRAMMING IN JAVA

try
{
int arr={5,0,1,2};
try
{
int x=a[3]/a[1];
}
catch( ArithematicExcception e)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOfBoundsException ae)
{
System.out.println(" Array Index out of bound ");
}
}
}
Output:
divide by zero
Array Index out of bound.

Finally clause:
 A finally keyword is used to create block of code that follows a try block.
 A finally block of code is always executed whether an exception has
occurred or not.
 Finally statement that can be used to handle an exception that is not
caught any of the previous catch statements.
 It may added immediately after the try block (or) after the last catch block.

Syntax:
try try
{ {
-----------; ----------;
-----------; ----------;
} }
finally catch( )
{ {
------------; ------------;
------------; -------------;
} }
catch( )
{
--------------;
--------------;
}
finally
{
------------;
------------;
}

Smt. T. LalithaKumari Page 61


PROGRAMMING IN JAVA

Example:
import java.util.*;
public class FinallyException
{
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a value");
int x=sc.nextInt( );
int k=44/x;
System.out.println("The val k:" +k);
}
catch(ArithematicException ae)
{
System.out.println("only non zero value");
}
catch(InputMismatch ie)
{
System.out.println("only integer value");
}
finally
{
System.out.println("finally always executed");
}
}
}

Throw Keyword:
Throw keyword is used to explicitly throw an exception from a
method of any block of code.
 We can throw either checked or unchecked exception in java by
throw keyword.
 The throw keyword is mainly used to throw custom exception.
 We can define our own set of conditions or rules and throw an
exception explicitly using throw keyword.
Example Program
class Exceptiondemo
{

Smt. T. LalithaKumari Page 62


PROGRAMMING IN JAVA

static void validate( int age)


{
if(age<18)
{ throw new ArithematicEception("You are not eligible for vote");
}
else
{
System.out.println("You are eligible for vote");
}
}
public static void main(String args[])
{
validate(15);
System.out.println("Program successfully completed");
}
}

Throws Keyword:
 throws is a keyword in java which is used in the signature of method to
indicate that this method might throw one of the listed type exceptions.
 The caller to these methods has to handle the exception using a try-catch
block.
 It is designed to transfer the responsibility of exception handling to its
caller.
Syntax:
type methodname(parameter list) throws exception_list
{
//definition of method
}
Example Program:
class ExceptionDemo
{
static void display( ) throws ArithmeticException
{
int a=3/0;
System.out.println(a);
}
public static void main(String args[])
{
try
{
display( );
}
catch(ArithmeticException ae)
{
System.out.println("cannot divide by zero");
}
System.out.println("Successfully Printed");
}
}
Output:
cannot divide by zero

Smt. T. LalithaKumari Page 63


PROGRAMMING IN JAVA

successfully printed.

Difference between throw and throws

No. Throw throws


1 Java throw keyword is used Java throws keyword is used
) to explicitly throw an to declare an exception.
exception.
2 Checked exception cannot Checked exception can be
) be propagated using throw propagated with throws.
only.
3 Throw is followed by an Throws is followed by class.
) instance.
4 Throw is used within the Throws is used with the
) method. method signature.
5 You cannot throw multiple You can declare multiple
) exceptions. exceptions e.g.
public void method()throws
IOException, SQLException.

Multithreading

Multithreading program can be divided into a number of small process. Each


small process can be addressed as a single thread. ( a light weight).
Threads are independent because they all have separate path of execution. All
threads of process share the common memory.
The process of executing multiple threads simultaneously is known as
Multithreading.
Main Thread:
 When we run any java program, the program execution starts from main
thread.
 The JVM creates a thread to start executing the code present in the main
method.
 This thread is called main thread.
 Main thread automatically created by obtaining a reference to calling
current thread method.
Creating a thread in a java
There are two ways to create thread in Java:
1) By Extending thread class
2) By implementing Runnable interface
Methods of Thread Class:

Methods Description
setName( ) To give thread a name
getName( ) Returns threads name
getPriority( ) Returns thread priority
isAlive( ) Checks if thread is still running or not
join( ) Wait for a thread to end

Smt. T. LalithaKumari Page 64


PROGRAMMING IN JAVA

run( ) Entry point for a thread


sleep( ) Suspend thread for a specified time
start( ) Start a thread by calling run( ) method.
1) Extending the thread class:
I. declare the class extending the thread class
Syntax: class Mythread extends Thread
{
---------------------;
---------------------;
}
II. Implementing the run ( ) method that is responsible for executing the
sequence of code that the thread will execute.
Syntax: public void run( )
{
-------------------------; // Thread code here
------------------------;
}
III. Create thread object and call start( ) method to initiate the thread
execution.
Syntax: Mythread athread= new Mythread( );
athread.start();

Example:
class Mythread extends Thread
{
public void run()
{
System.out.println("concurrent thread started running");
}
}
class MythreadDemo
{
public static void main(String args[])
{
Mythread athread= new Mythread( );
athread.start();
}
}
2) Implementing the Runnable interface:
I. Declare the class as implementing Runnable interface.
Syntax: class Mythread implements Runnable
{
--------------;
--------------;
}

Smt. T. LalithaKumari Page 65


PROGRAMMING IN JAVA

II. Implement the run method this method required to implementing the
threads in our program.
Syntax: public void run( )
{
--------------;
--------------;
}
III. create a thread by defining object that is initiated from this runnable
class as a target of the thread.
syntax: Mythread mt= new Mythread( );
Thread t= new Thread(mt);
IV. Call the threads start( )method to run( ) the thread.
Syntax: t.start( );
Example:
class Mythread implements Runnable
{
public void run()
{
System.out.println("Concurrent thread started running");
}
}
class MythreadDemo
{
public static void main(String args[])
{
Mythread mt=new Mythread();
Thread t=new Thread(mt);
t.start();
}
}

Q) Explain about Thread Priority?


 In java each thread is assigned a priority, which affects the order in which
it is scheduled for running.
 The threads of the same priority are given equal treatment by java
scheduler therefore they share the processor on the first-come first-serve
basis.
 Java permits us to set the priority of the thread using the setpriorty()
method.
ThreadName.setPriority(int number);
 The int Number is an integer value to which threads priority is set.
Thread class defines several priority constants
MIN-PRIORITY=1
Smt. T. LalithaKumari Page 66
PROGRAMMING IN JAVA

NORM-PRIORITY=5
MAX-PRIORITY=10
The int Number may assume one of these constants (or) any value between
1 to 10. Default string is NORM-PRIORITY.
 If thread is higher priority comes, the currently running thread will
be
preempted and move to the runnable state.

Example:
class A extends Thread
{
public void run( )
{
System.out.println(" thread A started");
for(int i=1;i<=4;i++)
{
System.out.println("\t from thread A: i=" +i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run( )
{
System.out.println(" thread B started");
for(int j=1;j<=4;j++)
{
System.out.println("\t from thread B: j=" +j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run( )
{
System.out.println(" thread C started");
for(int k=1;k<=4;k++)
{
System.out.println("\t from thread C: k=" +k);
}
System.out.println("Exit from C");

Smt. T. LalithaKumari Page 67


PROGRAMMING IN JAVA

}
}
class Threadpriority
{
public static void main(String args[])
{
A threadA=new A( );
B threadB=new B( );
C threadC=new C( );
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadB.getPriority( ) +1);
threadA.setPriority(Thread.MIN_PRIORTY);
threadA.start();
threadB.start();
threadC.start();
System.out.println("end of the main thread");
}
}

Life cycle of threads:

During the life time of a thread, there are many states it can enter. They are
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

Newborn state:
When we create a thread object, the thread is born and is said to be in
newborn state, the thread is not yet scheduled for running. At this state we
can do only one of the following things with in:

 schedule it for running using star( ) method.


  kill it using stop( ) method

Smt. T. LalithaKumari Page 68


PROGRAMMING IN JAVA

Runnable state:
The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor. That is the thread has joined the
queue of threads that are waiting for execution. If all threads have equal
priority then they are given time slots for execution in round robin fashion
i.e first come, first serve manner. This process of assigning time to threads
is known as time slicing.

 However, if we want a thread to control to another thread to equal priority


before its turn comes, we can do so by using the yield( ) method.
yield()

Running state:
Running means that the processor has given in time to the thread for an
execution. The thread runs until it relinquished control on its own or it is
accumulated by a higher priority thread. A running thread may relinquish in
control in one of the following situations.

1. It has been suspended using suspend( ) method. A suspended thread can


be retrieved by using the resume() method.

2. It had been made to sleep. We can put a thread to sleep for a specified
time periods using the method sleep(time) where time is in milliseconds.

3. It has been told to wait until some event occurs. This is done using wait( )
method. The thread can be scheduled to run again using the notify( )
method.

Smt. T. LalithaKumari Page 69


PROGRAMMING IN JAVA

Blocked state:
A thread is said to be blocked when it is prevented from entering into the
runnable state and subsequently the running state. This happens when the
thread is suspended, sleeping , or waiting in order to satisfy contain
requirements.
Dead state:
Every thread has a life cycle. A running thread ends in life when it has 
completed executing its runs method.  It is a natural death.

Q) Synchronization:
At times more than one thread try to access a shared resource, we need to
ensure that resource will be used only one thread at a time. The process by
which this is achieved is called Synchronization.

Syntax:

Synchronized(Object)
{
//statement tobesynchronized
}

The synchronization is mainly used to

 To prevent the Thread interface


 To prevent the consistency problem.

Example program of Synchronization:

class Table
{
synchronized void printtable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{

Smt. T. LalithaKumari Page 70


PROGRAMMING IN JAVA

System.out.println(e);
}
}
}
class Mythread extends Thread{
Table t;
Mythread(Table t)
{
this.t=t;
}
public void run()
{
t.printtable(5);
}
}
class Mythread2 extends Thread
{
Table t;
Mythread(Table t)
{
this.t=t;
public void run()
{
t.printtable(100);
}
}
public class Synchronize
{
public static void main(String args[])
{
Table obj=new Table();
Mythread1 t1=new Mythread1(obj);
Mythread2 t2=new Mythread2(obj);
t1.start();
t2.start();
}
}
OUTPUT:
5
10
15
20
25
100
200
300
400
500

Smt. T. LalithaKumari Page 71


PROGRAMMING IN JAVA

Q) Deadlock in JAVA:
Deadlock in java is a part of multithreading. Deadlock can occur in a situation
when a thread is waiting for an object lock, that is acquired by another thread
and second thread is waiting for an object lock that is acquiring by first thread.
Since both threads are waiting for each other to release the lock, this condition
is called deadlock.

Syntax:
ThreadA synchronized method2()
{
synchronized method1()
{
-----------------;
-----------------;
}
}
ThreadB synchronized method1()
{
-----------------;
-----------------;
}
}

APPLETS
An Applet is a Java program that runs in a web browser. An applet fully
functional Java application because it has the entire JAVA API at its disposal.
There are certain differences between Applet and JAVA Standalone Application
that are described below:
1. An applet is a Java class that extends the java.applet.Applet class.
2. An applet class will not define main( ).
3. Applets are designed to be embedded within an HTML page.
4. When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
5. A JVM is required to view an applet in web browser or a separate runtime
environment.
6. Applets have strict security rules that are enforced by the web browser.

Life Cycle of Applet:

Smt. T. LalithaKumari Page 72


PROGRAMMING IN JAVA

1.init():- The init( ) method is responsible for applet initialization when it is


loaded. It is called by browser or applet viewer only once.
Syntax:
public void init( )
{
//actions
}
2.start( ): It is invoked after the initialization state and applet entered into
running state. It starts the execution of Applet and the applet becomes an active
state.
Syntax:
public void start( )
{
//actions
}
3.paint():This method is used to display output on the screen. It takes
java.awt.Graphics object as a parameter. It helps to create Applet GUI such as a
colored background, drawing etc.
Syntax:
public void paint(Graphics g)
{
//Display statement
}
4.stop( ):This method is responsible to stop the execution and applet becomes
temporarily inactive state. It is invoked when Applet is stopped.
Syntax:
public void stop( )
{
//actions
}
5.destroy( ) : It destroys and removes the applet from the memory. It is invoked
only once. This is end of the life cycle of applet and it becomes dead.
syntax:
public void destroy()
{
//actions
}
Step1: Create the java program with "filename.java".
Step 2: Create the html program with "filename.html".
Step 3: Compile the java program "javac filename.java".
Step 4: View applet using "appletviewr filename.html".

Note: Both program must have the same name and both program must bein the
same folder.

Developing an Applet Program:


Steps to develop an applet program
1. Create an applet(java) code i.e. java file.
2. Compile to generate .class file.

Smt. T. LalithaKumari Page 73


PROGRAMMING IN JAVA

3. Design a HTML file with <Applet> tag.


Running the Applet Program:
There are two ways to run the applet program
1. By HTML
2. Appletviewer tool

Example: Getting a message printed through Applet

import java.awt.*;
import java.applet.*;
public class Myfirstapplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("MyFirstAppletProgram", 100, 100);
}
}
1. Save the above program:Myfirstapplet.java
2. Compile:> javac Myfirstapplet.java

//MyMyfirstapplet.html
<html>
<head> <title> Myfirstapplet</title> </head>
<body>
<applet code="Myfirstapplet.class" width="400" height="400"> </applet>
</body>
</html>

Run the complete program:


>appletviewer Myfirstapplet.html
output:

Example 2:
import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet
{

Smt. T. LalithaKumari Page 74


PROGRAMMING IN JAVA

public void paint(Graphics g)


{
g.setColor(Color.red);
g.drawRect(50,60,60,60);
g.drawRoundRect(150,50,50,50,20,40);
g.setColor(Color.green);
g.fillRect(50,60,60,60);
g.fillRoundRect(150,50,50,50,20,40);
}
}
//Myapplet.html
<applet code="Myapplet" width=400 height=400>
</applet>

Q)Common Methods used in displaying output:


Paint( ) method in Applet:
Now we are going to understand how to print a message in the
applet window by implementing a method paint() of the Applet class. Within the
method paint() we will call drawString() method to print text message in the
applet window.
 When the applet window is brought up on the screen for the first time.
 When the applet window is brought up on the screen from the minimized
state, this leads the redrawing of the applet window and hence paint()
method is automatically called.
Syntax:
public void paint(Graphics g)
{
g.drawString(string);
}
Using the object of Graphics class, we can call drawString() method of Graphics
class to write a text message in the applet window.
Example:
import java.awt.*;
import java.applet.Applet;
public class Appletlifecycle extends Applet
{
public void init()
{
setBackground(Color.blue);
System.out.println("init()called");
}
public void start()

Smt. T. LalithaKumari Page 75


PROGRAMMING IN JAVA

{
System.out.println("start()called");
}
public void paint(Graphics g)
{
System.out.println("paint()called");
}
public void distroy()
{
System.out.println("distroy()called");
}
public void stop()
{
System.out.println("stop()called");
}
}
//Appletlifecycle.html
<body>
<applet code="Appletlifecycle.class" width="100" height="100"> </applet>
</body>

EVENT HANDLING
Event is the change in the state of the object or source. Events are
generated as result of user interaction with the graphical user
interaction components. For example, clicking on a button, moving
on a mouse, entering a character through keyboard, selecting an
item from list, scrolling the page are the activities that causes an
event to happen.

Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs. This mechanism have the
code which is known as event handler that is executed when an
event occurs.

Types of events

In java event handling may comprised the following four classes:

Event source: Sources for generating an event may be the


components. In java java.awt component specifies the components
that may or may not generate events. These event sources may be
the button, combo box, textbox etc.

Smt. T. LalithaKumari Page 76


PROGRAMMING IN JAVA

Event Classes: Event Classes in java are the classes defined for
almost all the components that may generate events.

ActiveEvent: Button , TextField, List, Menu


WindowEvent: Frame
ItemEvent: Checkbox, List
AdjustmentEvent: Scrollbar
MouseEvent: Mouse
KeyEvent: Keyboard

Event Listeners: Event Listeners are the java interfaces that


provides various methods to use in the implemented class. Listeners
listens the event generated by a component. For example, there is a
Listener named ActionListener handles the events generated from
button, textfield, list, menus.

Event Classes and Interfaces

Event Classes Description Listener Interface


ActionEvent Generated when button ActionListener
is pressed menu-item is
selected, list-item is
double clicked
MouseEvent Generated when mouse MouseListener
is dragged, moved,
clicked, pressed or
released and also when
it enters or exit a
component
KeyEvent Generated when input is KeyListener
received from keyboard
ItemEvent Generated when check- ItemListener
box or list item is clicked
TextEvent Generated when value of TextListener
text area or text field is
changed
MouseWheelEven Generated when mouse MouseWheelListene
Smt. T. LalithaKumari Page 77
PROGRAMMING IN JAVA

t wheel is moved r
WindowEvent Generated when window WindowListener
is activated, deactivated,
deiconified, iconified,
opened or closed
ComponentEvent Generated when ComponentEventLi
component is hidden, stener
moved, resized or set
visible
ContainerEvent Generated when ContainerListener
component is added or
removed from container
AdjustmentEvent Generated when AdjustmentListener
scrollbar is manipulated
FocusEvent Generated when FocusListener
component gains or
losses keyboard focus

Smt. T. LalithaKumari Page 78


PROGRAMMING IN JAVA

EXAMPLE PROGRAM ON EVENT LISTENER:


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Ex extends Applet implements ActionListener
{
String msg=" ";
Button yes,no,maybe;
public void init()
{
yes=new Button("Yes");
no=new Button("No");
maybe=new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
if(str.equals("Yes"))
msg="yes pressed";
else if(str.equals("No"))

Smt. T. LalithaKumari Page 79


PROGRAMMING IN JAVA

msg="no pressed";
else
msg="You pressed undecided";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,60,100);
}
}
Ex.html
<applet code="Ex.class" width=400 height=400>
</applet>

How to Handle checkboxes:


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Ex1 extends Applet implements ItemListener
{
String msg=" ";
Checkbox banana,grape,apple;
public void init()
{
banana=new Checkbox("banana",null,true);
grape=new Checkbox("grape");
apple=new Checkbox("apple");
add(banana);
add(grape);
add(apple);
banana.addItemListener(this);
grape.addItemListener(this);
apple.addItemListener(this);
Smt. T. LalithaKumari Page 80
PROGRAMMING IN JAVA

}
public void itemStateChanged(ItemEvent i)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current state";
g.drawString(msg,6,80);
msg="banana:"+banana.getState();
g.drawString(msg,6,100);
msg="grape:"+grape.getState();
g.drawString(msg,6,120);
msg="apple:"+apple.getState();
g.drawString(msg,6,140);
}
}

Ex1.html
<applet code="Ex1.class" width=400 height=400>
</applet>

How to handle KeyListener


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Ex3 extends Applet implements KeyListener
{
String msg=" ";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("key pressed");
Smt. T. LalithaKumari Page 81
PROGRAMMING IN JAVA

}
public void keyReleased(KeyEvent k)
{
showStatus("key released");
}
public void keyTyped(KeyEvent k)
{
msg=msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,40);
}
}

Ex3.html
<applet code="Ex3.class" height=300 width=300>

</applet>
How to handle the Mouse Events:

import java.awt.*;
import java.awt.event.*;
public class MouseEventex extends Frame implements
MouseListener
{
Label l;
MouseEvent()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
Smt. T. LalithaKumari Page 82
PROGRAMMING IN JAVA

setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("mouseclicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("mouse entered");
}
public void mouseReleased(MouseEvent e)
{
l.setText("mouseReleased");
}
public static void main(String args[])
{
new MouseEvent();
}

ABSTRACT WINDOW TOOLKIT (AWT)


Abstract Window Toolkit (AWT):

 Part of a java programming environment.


 Contains a complete set of classes and components for creating
GUI based programs.
 Components can be include windows, menubars, buttons and
textfields.
 Containers contains other components including other
containers, most common form of container is the panel.
 Canvases, simple drawing surface that represents the
rectangular area.

Smt. T. LalithaKumari Page 83


PROGRAMMING IN JAVA

 User interface component include buttons, lists, checkboxes


and other typical elements.

AWT Hierarchy(components and containers)

import java.awt.*;
class Frameex1
{
public static void main(String args[])
{
Frame f = new Frame("Layout");
f.setSize(400,600);
f.setVisible(true);
}
}

Components:
Following some components of Java AWT are explained:

Lables: This is the simplest component of Java Abstract Window


Toolkit. This component is generally used to show the text or string
in your application and label never perform any type of action.

Syntax:
Label label_name = new Label("This is the label text");

Buttons: This is the component of Java Abstract Window Toolkit


and is used to trigger actions and other events required for your
application.

Smt. T. LalithaKumari Page 84


PROGRAMMING IN JAVA

Syntax:
Button button_name = new Button("This is the label button");

Check Boxes: This component of Java AWT allows you to create


check boxes in your applications.

Syntax:
Checkbox checkbox_name = new checkbox("Optional check box1,"
false);
You can also see and get the state of the checkbox using the set state
(boolean) and getState() method provided by the checkbox class.

Radio Button: This is the special case of checkbox component of


Java AWT package. This is used as a group of checkboxes which
group name is same only one checkbox from a checkbox group can
be selected at a time.

Syntax:
CheckboxGroup chkgp = new CheckboxGroup();
add(new Checkbox("One", chkgp, false);
add(new Checkbox("Two", chkgp, false);
add(new Checkbox("Three",chkgp, false);

Text Area: This is the text container component of Java AWT


package. The Text Area contains plain text. Text Area can be declared
as follows:
Syntax:
TextArea txtArea_name = new TextArea();

Text Field: This is also the text container component of Java AWT
package. This component contains single line and limited text
information.

Syntax:
TextField txtfield = new TextField(20);

Containers: Container is a component in AWT that contains


another component like button, text field, tables etc. Container is a
subclass of component class. Container class keeps track of
components that are added to another component.

Smt. T. LalithaKumari Page 85


PROGRAMMING IN JAVA

Panel: Panel class is a concrete subclass of Container. Panel does


not contain title bar, menu bar or border. It is container that is used
for holding components.

Window Class: Window class creates a top level window. Window


does not have borders and menubar.

Frame: Frame is a subclass of Window and have resizing canvas. It


is a container that contain several different components like button,
title bar, textfield, label etc. In Java, most of the AWT applications
are created using Frame window. Frame class has two different
constructors,
Frame() throws HeadlessException
Frame(String title) throws HeadlessException

Creation of panel
import java.awt.*;
class Ex2
{
public static void main(String args[])
{
Frame f;
Panel p;
f=new Frame("I am frame with panel");
p= new Panel();
f.add(p);
f.setSize(400,600);
f.setVisible(true);
}
}

Creating Labels, Textfileds & Textareas

import java.awt.*;
class Labeltext
{

Smt. T. LalithaKumari Page 86


PROGRAMMING IN JAVA

public static void main(String args[])


{
Frame f=new Frame("ComponentsFrame");
TextField t1=new TextField(35);
TextField t2=new TextField(10);
TextArea ta=new TextArea();
Label lb1=new Label("Name:");
Label lb2= new Label("Address:");
Label lb3=new Label("Phone no:");
f.setLayout(new FlowLayout());
f.add(lb1);
f.add(t1);
f.add(lb2);
f.add(ta);
f.add(lb3);
f.add(t2);
f.setSize(500,500);
f.show();
}
}
Creating Buttons & Checkboxes:

import java.awt.*;
class Buttoncheck
{
public static void main(String args[])
{
Frame f=new Frame("ComponentsFrame");
Button b1=new Button("Hai");
Button b2=new Button("Hello");
Label lb1=new Label("What do you plays:");
Checkbox c1= new Checkbox("Cricket",false);
Checkbox c2= new Checkbox("Chess",false);
Checkbox c3= new Checkbox("Football",false);
f.setLayout(new FlowLayout());
f.add(b1);
Smt. T. LalithaKumari Page 87
PROGRAMMING IN JAVA

f.add(b2);
f.add(lb1);
f.add(c1);
f.add(c2);
f.add(c3);
f.setSize(500,500);
f.show();
}
}

Creating Option Buttons:

import java.awt.*;
class Option
{
public static void main(String args[])
{
Frame f=new Frame("ComponentsFrame");
Label lb1=new Label("Select What is your Mother Tongue:");
CheckboxGroup cg=new CheckboxGroup();
Checkbox o1= new Checkbox("Telugu",cg,true);
Checkbox o2= new Checkbox("English",cg,false);
Checkbox o3= new Checkbox("Hindi",cg,false);
Checkbox o4= new Checkbox("Tamil",cg,false);
f.setLayout(new FlowLayout());
f.add(lb1);
f.add(o1);
f.add(o2);
f.add(o3);
f.add(o4);
f.setSize(500,500);
f.show();
}

Smt. T. LalithaKumari Page 88


PROGRAMMING IN JAVA

AWT Layout Management:


Are set of classes that position the components.
Determines how AWT components are dynamically arranged on the
screen.
Layout is a logical container used to arrange the GUI component in
proper order within the frame, in java.awt package some of the layout
is existing an predefined classes as shown below:
 FlowLayout
 BoarderLayout
 GridLayout
 GridbagLayout
 CardLayout

Flow Layout:
This layout is used to arrange the GUI components in a
sequential flow(that means one after another in horizontal way).
Default layout manager.
You can also set flow layout of components like flow from left,
flow from right. Default alignment will be center.

Syntax:
Frame f = new Frame();
f.setLayout(new FlowLayout());
Program:
import java.awt.*;
class FlowLayoutex
{
public static void main(String args[])
{
Frame f = new Frame("Layout");
String s[] = {"1","2","3","4","5","6","7","8","9"};
Button b[] = new Button[s.length];
f.setLayout(new FlowLayout());
for(int i=0;i<s.length;i++)
{
b[i] = new Button(s[i]);
f.add(b[i]);
}
f.setSize(500,500);
f.show();
Smt. T. LalithaKumari Page 89
PROGRAMMING IN JAVA

}
}
OUTPUT

Border Layout:
This Layout is used to arrange the GUI components in S directions of
frame.
Used for placement of components in Geographical direction.
Takes two arguments:
 position of component within layout
 specifies the component
Syntax:
Frame f = new Frame();
f.setLayout(new BorderLayout());
Program:
import java.awt.*;
class BorderLayoutex
{
public static void main(String args[])
{
Frame f = new Frame("Layout");
Button b[];
String border[] = {"East","West","North","South","Center"};
String s[] = {"1","2","3","4","5"};
f.setLayout(new BorderLayout());
b= new Button[s.length];
for(int i=0;i<s.length;i++)
{
b[i] = new Button(s[i]);
f.add(border[i],b[i]);
}
f.setSize(500,500);
f.show();
}
}
output:

Smt. T. LalithaKumari Page 90


PROGRAMMING IN JAVA

Grid Layout:
This layout is used to arrange the GUI components in the table
format. In Grid layout all elements are in same.

Syntax:
Frame f = new Frame();
f.setLayout(new GridLayout(n,n));

Gridbag Layout:

This layout is used to arrange the GUI components in un-order


table structured.
 Allows user to arrange components in a grid like layout.
 Allows the user to control the span of individual cells in the
grid.
 Overall layout based on relationship between gridbag the
constraints and components.

Card Layout:
This layout is used to arrange multiple cards within the same
frame. It used to produce slide show components. Different panels
can be added at a time only one can be displayed at a time.Few
buttons can be set to native b/w different cards.
native buttons different cards: show()
first()
last()
next()

Introduction to swing classes

Smt. T. LalithaKumari Page 91


PROGRAMMING IN JAVA

JFrame – A frame is an instance of JFrame. Frame is a window that can have


title, border, menu, buttons, text fields and several other components. A Swing
application must have a frame to have the components added to it.

JPanel – A panel is an instance of JPanel. A frame can have more than one
panels and each panel can have several components. You can also call them
parts of Frame. Panels are useful for grouping components and placing them to
appropriate locations in a frame.

JLabel – A label is an instance of JLabel class. A label is unselectable text and


images. If you want to display a string or an image on a frame, you can do so by
using labels. In the above example we wanted to display texts “User” &
“Password” just before the text fields , we did this by creating and adding labels
to the appropriate positions.

JTextField – Used for capturing user inputs, these are the text boxes where
user enters the data.

JPasswordField – Similar to text fields but the entered data gets hidden and
displayed as dots on GUI.

JButton – A button is an instance of JButton class. 

Q)Components in Swings:

Smt. T. LalithaKumari Page 92


PROGRAMMING IN JAVA

All components in swing are JComponent which can be added to container


classes.
container class

Container classes are classes that can have other components on it. So for
creating a GUI, we need at least one container object. There are 3 types of
containers.

1. Panel: It is a pure container and is not a window in itself. The sole


purpose of a Panel is to organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a
message has to be displayed. It is not a fully functioning window like the
Frame.

Java GUI Example

Example: To learn to design GUI in Java


Step 1) Copy the following code into an editor

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of
frame
frame.setVisible(true);
}
}

Step 2) Save, Compile, and Run the code.


Step 3) Now let's Add a Button to our frame.  Copy following code into an editor

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);

Smt. T. LalithaKumari Page 93


PROGRAMMING IN JAVA

}
}

Step 4) Execute the code. You will  get a big button

Step 5) How about adding two buttons? Copy the following code into an editor.

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setVisible(true);
}
}

Step 6) Save , Compile , and Run the program.


Step 7) Unexpected output =? Buttons are getting overlapped.

Java Layout Manger

The Layout manager is used to layout (or arrange) the GUI java components
inside a container.There are many layout managers, but the most frequently
used are-

Java BorderLayout

A BorderLayout places components in up to five areas: top, bottom, left, right,


and center. It is the default layout manager for every java JFrame

Smt. T. LalithaKumari Page 94


PROGRAMMING IN JAVA

Java FlowLayout

FlowLayout is the default layout manager for every JPanel. It simply lays out
components in a single row one after the other.

Java GridBagLayout

It is the more sophisticated of all layouts. It aligns components by placing them


within a grid of cells, allowing components to span more than one cell.

How about creating a chat frame like below?

Smt. T. LalithaKumari Page 95


PROGRAMMING IN JAVA

Try to code yourself before looking at the program below.

//Usually you will require both swing and awt packages


// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String args[]) {

//Creating the Frame


JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

//Creating the MenuBar and adding components


JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
m1.add(m11);
m1.add(m22);

//Creating the panel at bottom and adding components


JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");

Smt. T. LalithaKumari Page 96


PROGRAMMING IN JAVA

panel.add(label); // Components Added using Flow Layout


panel.add(label); // Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);

// Text Area at the Center


JTextArea ta = new JTextArea();

//Adding Components to the frame.


frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, mb);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
}
}

12.DATABASE HANDLING
JAVA JDBC:

Java JDBC is a Java API to connect and execute query with the database. JDBC
API used JDBC drivers to connect with the database.

We can use JDBC API to access tabular data stored into any relational
database.

Why should we use JDBC?

Before JDBC, ODBC API was the database API to connect and
execute query with the database. But, ODBC API used ODBC driver which is
written in C language (i.e. platform dependent and unsecured).That is why Java
has defined its own API (JDBC API) that uses JDBC drivers (written in Java
Language).

Smt. T. LalithaKumari Page 97


PROGRAMMING IN JAVA

We can use JDBCAPI to database using Java program and can perform
following activities:

 Connect to the database


 Execute queries and update statements to the database.
 Retrieve the result received from the database.

TYPES of JDBC Drivers


JDBC Driver is a software component that enables java application to
interact with the database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls
into the ODBC function calls.

Note: Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of your database
instead of the JDBC-ODBC Bridge.

Advantages:
o easy to use.
o can be easily connected to any database.
o It is a database independent driver
o No need to install separately (This driver software is built-in with JDK).

Disadvantages:
o Performance degraded because JDBC method call is converted into the
ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
o It is slow driver so not used in real time applications.

Smt. T. LalithaKumari Page 98


PROGRAMMING IN JAVA

o It is not suitable for applet to connect with database.


2) Native-API driver
The Native API driver uses the client-side libraries of the database. The
driver converts JDBC method calls into native calls of the database API.
It is not written entirely in java.

Advantage:
o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is
fully written in java.

Advantage:
o No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.

Disadvantages:
o Network support is required on client machine.

Smt. T. LalithaKumari Page 99


PROGRAMMING IN JAVA

o Requires database-specific coding to be done in the middle tier.


o Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver. It is fully
written in Java language.

Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.

Disadvantage:
o Drivers depend on the Database.
JDBC CONNECTIVITY
There are 5 steps to connect any java application with the database using
JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException  

Smt. T. LalithaKumari Page 100


PROGRAMMING IN JAVA

Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to
put vender's Jar in the classpath, and then JDBC driver manager can detect and
load the driver automatically.

Example to register the OracleDriver class

Here, Java program is loading oracle driver to establish database connection.


Class.forName("oracle.jdbc.driver.OracleDriver");  

2) Create the connection object


The getConnection() method of DriverManager class is used to establish
connection with the database.

Syntax of getConnection() method


public static Connection getConnection(String url)throws SQLException  
 public static Connection getConnection(String url,String name,String password
)  throws SQLException  

Example
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","password");  

3) Create the Statement object


The createStatement() method of Connection interface is used to create
statement. The object of statement is responsible to execute queries with
the database.

Syntax

public Statement createStatement()throws SQLException  

Example
Statement stmt=con.createStatement();  

4) Execute the query


The executeQuery() method of Statement interface is used to execute
queries to the database. This method returns the object of ResultSet that
can be used to get all the records of a table.

Syntax
public ResultSet executeQuery(String sql)throws SQLException  

Example

ResultSet rs=stmt.executeQuery("select * from emp");  
  

Smt. T. LalithaKumari Page 101


PROGRAMMING IN JAVA

while(rs.next()){  
System.out.println(rs.getInt(1)+" "+rs.getString(2));  
}  

5) Close the connection object


By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to
close the connection.

Syntax

public void close()throws SQLException  

Example

con.close();  

Note: Since Java 7, JDBC has ability to use try-with-resources statement to


automatically close resources of type Connection, ResultSet, and Statement.

Java Database Connectivity with Oracle


To connect java application with the oracle database, we need to follow 5
following steps. In this example, we are using Oracle 10g as the database.
So we need to know following information for the oracle database:

1. Driver class: The driver class for the oracle database


is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API,
oracle is the database, thin is the driver, localhost is the server
name on which oracle is running, we may also use IP address, 1521
is the port number and XE is the Oracle service name. You may get
all these information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of
installing the oracle database.

Create a Table

Before establishing connection, let's first create a table in oracle database.


Following is the SQL query to create a table.

create table emp(id number(10),name varchar2(40),age number(3));  

Smt. T. LalithaKumari Page 102


PROGRAMMING IN JAVA

Example to Connect Java Application with Oracle database

In this example, we are connecting to an Oracle database and getting data


from emp table. Here, system and oracle are the username and password of the
Oracle database.

import java.sql.*;  
class OracleCon{  
public static void main(String args[]){  
try{  
//step1 load the driver class  
Class.forName("oracle.jdbc.driver.OracleDriver");  
  
//step2 create  the connection object  
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  
//step3 create the statement object  
Statement stmt=con.createStatement();  
  
//step4 execute query  
ResultSet rs=stmt.executeQuery("select * from emp");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
  
//step5 close the connection object  
con.close();  
  
}catch(Exception e){ System.out.println(e);}  
  
}  
}  

Smt. T. LalithaKumari Page 103

You might also like