Vous êtes sur la page 1sur 78

CORE JAVA

B.C.A. Part – III


(Sem- VI)
Paper No-604: Java Programming
Unit- 1- Introduction To Java 12
1.1 History and features of Java Programming
1.2 Difference between Java & C++
1.3 Java Environment
1.4 Java tokens, constants, variables, data types, type casting
1.5 Operators and Expressions
1.6 Implementing Java Program
1.7 Branching and looping statements
1.8 Class, objects, methods
1.9 Constructors and destructor
Unit-2- Inheritance and Packages 12
2.1 Defining sub class, subclass constructor
2.2 Inheritance-Multiple and hierarchical
2.3 Defining packages, system packages
2.4 Creating & accessing packages
2.5 Adding a class to package
2.6 Polymorphism- function overloading and over ridding, its difference
Unit-3- Multithreading and Exception Handling 12
3.1 Creating threads, extending a thread class- declaring the class, run()
method
3.2 Stopping and blocking threads
3.3 Life cycle of thread
3.4 Using thread method
3.5 Thread priority
3.6 Introduction to exception
3.7 Syntax of exception handling code
3.8 Multiple catch statement
3.9 Using finally statement
3.10 Throwing exception
B.C.A Revised Syllabus w.e.f. 2015-16
Unit- 4- Applets Programming & Introduction to AWT 12
4.1 Introduction to applets
4.2 Building applet code
4.3 Applet life cycle
4.4 Adding applet code to HTML file
4.5 Introduction to Abstract Window Toolkit (AWT)
Reference Books:
1. Programming with JAVA, A Primer, 2nd Editions, E Balagurusamy
2. Java Programming- Rajendra Salokhe (Aruta Pub)
3. Core Java an integrated approach – Dr R. Nageshwara

1 DPP
CORE JAVA
Unit- 1- Introduction To Java
1.1 History and features of Java Programming
1.2 Difference between Java & C++
1.3 Java Environment
1.4 Java tokens, constants, variables, data types, type casting
1.5 Operators and Expressions
1.6 Implementing Java Program
1.7 Branching and looping statements
1.8 Class, objects, methods
1.9 Constructors and destructor

History of JAVA:
JAVA is a distributed technology developed by James Gosling, Patric Naugton, etc., at
Sun Micro System has released lot of rules for JAVA and those rules are implemented by
JavaSoft Inc, USA (which is the software division of Sun Micro System) in the year 1990.
The original name of JAVA is OAK (which is a tree name). In the year 1995, OAK was
revised and developed software called JAVA (which is a coffee seed name). JAVA released
to the market in three categories J2SE (JAVA 2 Standard Edition), J2EE (JAVA 2
Enterprise Edition) and J2ME (JAVA 2 Micro/Mobile Edition).
i. J2SE is basically used for developing client side applications/programs.
ii. J2EE is used for developing server side applications/programs.
iii. J2ME is used for developing server side applications/programs.
If you exchange the data between client and server programs (J2SE and J2EE), by default
JAVA is having on internal support with a protocol called http. J2ME is used for
developing mobile applications and lower/system level applications. To develop J2ME
applications we must use a protocol called WAP (Wireless Applications Protocol).

FEATURES of java:
Simple: JAVA is simple because of the following factors:
JAVA is free from pointers hence we can achieve less development time and less
execution time [whenever we write a JAVA program we write without pointers and
internally it is converted into the equivalent pointer program].
Rich set of API (application protocol interface) is available to develop any complex
application. The software JAVA contains a program called garbage collector which is
always used to collect unreferenced (unused) memory location for improving performance
of a JAVA program. [Garbage collector is the system JAVA program which runs in the
background along with regular JAVA program to collect unreferenced memory locations
by running at periodical interval of times for improving performance of JAVA applications.
JAVA contains user friendly syntax’s for developing JAVA applications.
Platform Independent:
A program or technology is said to be platform independent if and only if which can run
on all available operating systems.The languages like C, Cpp are treated as platform
dependent languages since these languages are taking various amount of memory spaces
on various operating systems The language like JAVA will have a common data types and
the common memory spaces on all operating systems and the JAVA software contains the
special programs which converts the
format of one operating system to another format of other operating system. Hence JAVA
language is treated as platform independent language.
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
Architecture-neutral: Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with the presence of
Java runtime system.
Portable: Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
2 DPP
CORE JAVA
Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
Interpreted: Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
Distributed: Java is designed for the distributed environment of the internet.
Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.

Advantage of Java technology :-


1. Get started quickly: - Although the java programming language is a powerful object-
oriented language, it’s easy to learn, especially for programmers already familiar with C or
C++.
2. Write less code: - Comparisons of program metrics suggest that a program written in
the java programming language can be four times than the same program in C++.
3. Write better code:- The java programming language encourages good coding practices,
and its garbage collection helps you avoid memory leaks. Its object orientation, its java
Beans component architecture, and its wide- ranging, easily extendible API let you reuse
other people’s tested code and introduce fewer bugs.
4. Develop program faster:- Your development time may be as much as twice and fast
versus writing the same program in C++.
5. Avoid platform independencies with 100% pure java:- You can keep your program
portable by following the purity tips mentioned throughout this tutorial and avoiding the
use of libraries written in other language.
6. Write once run anywhere:- Because 100% pure java programs are compiled into
machine independent Bytecode, they run consistently on any java platform.
7. Distribute software more easily:- You can upgrade applets easly from a central
server. Applets take advantage of the feature of allowing new classes to be loaded “on the
fly,” without recompiling the entire program.
Java Development Kit Tools :- The JDK is a development environment for building
applications, applets, and the components using the java programming language. In more
technical terms, the current version is called Java TM Platform, Standard edition 8 JDK.
The JDK 8 includes tools useful for developing and testing programs written in java. They
help us to running them on the java platform. These tools are designed to be used from
the command line. They do not provide a GUI. The only exception is the “appletviewer”.
Let us describe the contents of JDK 8 in details.
1. Development tools :- Tools and utilities that will help one to develop, execute, debug,
and document program written in the java programming language are provided in the
“bin” sub-directory. These tools are the foundation of the JDK 6.The basic tools are
describe in the given below:
a. Javac The compiler of java programming language.
b. Java The launcher for java applications. In this release, a single launcher used for both
development and deployment.
c. Javadoc API documentation generator.
d. Appletviewer Run and debug applets without a web browser.
e. Jar Manage java Archive (JAR) files.
f. Jdb The java debugger.
g. Javah C header and sub generator. used to write native methods.
h. Javap Class file disassemble.
2. Runtime Environment :- An implementation of the java 2 runtime environment for
use by the SDK. The runtime environment includes a JVM, Class libraries, and other files

3 DPP
CORE JAVA
that support the execution of program written in the java programming language. These
are present in “jre” sub directory.
3. Addition documentation:- Addition class libraries and support files required by the
development tools are present in the “lib” sub directory.

Java Program structure :-


public class <Class Name>
{
public static void main(String arg[])
{
<Datatypes>;
…………………….
<Set of codes>;
}
}
Example:- File Name- FirstJava.java
public class FirstJava
{
public static void main(String arg[])
{
System.out.println(“This is my first java program”);
}
}
Compile and execute the program:-
C:\>javac FirstJava.java
C:\>java FirstJava
This is my first java program
C:\>

Basic Syntax
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive, which means identifier Helloand hello would
have different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example: class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case.
Example: public void myMethodName()
Program File Name - Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile). Example: Assume 'MyFirstJavaProgram' is
the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) - Java program processing starts from the main()
method which is a mandatory part of every Java program.

Basic Building Block.


Any java program consist of few building blocks like comments, declarations statements
and methods. These blocks are formatted by some small atomic quantity is known as
tokens.
Java Identifiers
All Java components require names. Names used for classes, variables, and methods are
called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:

4 DPP
CORE JAVA
1. All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
2. After the first character, identifiers can have any combination of characters.
3. A key word cannot be used as an identifier.
4. Most importantly, identifiers are case sensitive.
5. Examples of legal identifiers: age, $salary, _value, __1_value.
6. Examples of illegal identifiers: 123abc, -salary.

Comments :- Comments are that part of the program, which are supported to give more
information to the reader. They increase the readability of the program. The compiler does
not convert it in to code. (We may say that compiler ignore it.). In java, the comments are
enclosed in pair of /* and */, such comments can be of one or more lines. In addition java
uses double slash (//) for single line comments. Any text from // to be end of that line is
treated as comment.

Variables & Data Types:-


Variable:- Variable is a name location in memory which holds the constant.
According to programming rule variable is an identifier. Hence, rule for formatting
variables same as those for formatting identifiers. Rules for variable names can be started
as follows:
1. Variable names are formatted with the help of letters and digits.
2. Alphabets can be in upper or lower case.
3. Only letters are allowed as far as string character. Underscore character (_) and Dollar
($) are treated as letter as far as variables re concerned.
4. The first character cannot be a digit.
5. There is no restriction on number of characters in variables.
6. As white space characters are used to separate tokens, they cannot be a part of
variables.

Keywords in java
abstract continue goto package synchronized
assert default if private this
Boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
Data Types:- The Data that is stored in memory can be of many types for example a
person’s age is store as a numeric value and an address is stored as alphanumeric
characters.
Data type are use to define the operations possible on them and the storage method.
The data type in java is classified in two types:-
1. Primitive or slandered data type.
2. Abstract or derived data type.

1. Primitive or standared data type.


Primitive data type also known as standard data types, are the data types that are built
into the java language. The java compiler contains details introduction on each legel
option supported by the data type. There are eight data types in java i.s;
I. byte 1 Byte (8 Bits). -128 to 127
II. short 2 Byte (16 Bits). -32768 to 32767
III. int 4 Byte (32 Bits). -2147473648 to 2147473647
IV. long 8 Byte (64 Bits). -9223372036854775808 to 9223372036854775807
V. float 4 Byte (32 Bits). -3.4E38 to +3.4E38
5 DPP
CORE JAVA
VI. double 8 Byte (64 Bits). -1.7E308 to +1.7E308
VII. char 2 Byte (16 Bits).
VIII. boolean 2 Byte (16 Bits).

NOTE :- Data is internally separated as binary digits (0 and 1).Bits stand for binary digit.
A bit can store either 0 or 1.
2. Abstract or Derived data type.
Abstract data types are base on primitive data type and have move functionality than
primitive data type. For example String is an abstract data type. That can store letters
digits and others character like /, (, ), :, ;, $, #,…….
The data type cannot perform calculations on a variable of a String data type even if the
data stored in it has digits. However String provides methods for one String within
another extracting the position of a string. The primitive data type does not have these
features.

Operators perform operations on operands. Operands may be one two or three. Operands
are either variables or constants. The operators, which take single operand are called
unary operators. Those takes two operands are known as binary operators and one
having three operands is known as ternary operator.
Most of the operators are binary operators, few are unary while there is only one ternary
operator (for example “?:” operator).
1. Arithmetic operators.
2. Assignment operators.
3. Relational operators.
4. Logical operators.
5. Unary operators.
6. Bitwise operators.
7. Others operators.

1. Arithmetic operators:-
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulo Division)(Remainder)
Note :-
When the use of plush (+) operator use with numeric operands, the result is numeric
when both the operands are Strings the plush operator concatenates (joins) then when
one of the operands is a String objects, the second operand is converted in to String
before concatenation.
Example:-
Operend1 + Operend2 = Result
5 6 11
5 “AB
“ABC” 5
“ABC” “XY
2. Java use toString() method of java.lang.object class to convert data to the String Data
Type.

Example1:-
import java.io.*;
public class ArithmeticOperator
{
public static void main(String arg[])throws IOException
{
BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in));
int rad;
float circlearea,pi=3.14f;
6 DPP
CORE JAVA
System.out.println(“Enter a radius of circle”);
rad=Integer.valueOf(obj.readLine()).intValue();
circlearea=pi*rad*rad;
System.out.println(“Area of circle is “+circlearea);
}
}

2. Assignment Operator :-
We have seen equal to (=) is a basic assignment operator. It assigns value on right hand
side to variable on left hand side.
Var = <constant/variable/expression>;
Example:-
Marks=90;
Note:-
To handle such situation java provides some shortcut assignment operator, with the
combination of arithmetic operator and assignment operator. i.e;
+= Assign Sum a+=20; a=a+20;
-= Assign Difference a-=20; a=a-20;
*= Assign Product a*=20; a=a*20;
/ = Assign Quotient a/=20; a=a/20;
%= Assign Remainder a%=20; a=a%20;
3. Relational Operator :-

When we use relational operator in an expression it returns Boolean Value true or false.
Java provides these relational operators.
< Less than
<= less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
4. Logical Operator :-
The logical operator combines the result of Boolean expressions. The following logical
operators used in java are:
&&(Logical And) :-
Evaluates to true if both the conditions evaluate to true, false if otherwise.
Example
X=5;
Y=10;
x>=5 && y==10 true
x>=5 && y>10 false
x<5 && y==10 false
x>5 && y<10 false
||(Logical or) :-
Logical or operator evaluates to true if at least one of the condition true, and false if none
of the conditions evaluates to true.
Example
X=5;
Y=10;
x>=5 || y==10 true
x>=5 || y>10 true
x<5 || y==10 true
x>5 || y<10 false

!(Logical Not) :-
This operator is used to change the true to false and false to true. It is an unary operator.
Example
7 DPP
CORE JAVA
Y=10;
!(y==10) false
!(y>10) true
5. Unary Operator :-
Java support basically two unary operator. I.e;
++ :-
Increase the value of the operand by one.
Ex:-
X=10;
X++; X=11;
++X X=11;
-- :-
Decrease the value of the operand by one.
Ex:-
X=10;
X--; X=9;
--X X=9;
Note: - Increment (++) and Decrement (--) operator is used as postfix and prefix order. If it
is used as postfix then first drop the value of operand first after that performs the job of
operator. And in case of prefix first perform the job of operator and lastly drop the value of
operands.
6. Bitwise Operator :-
Those types of operator which perform own job upon the smallest unit of memory (Bits) is
known as bitwise operators. Java supports following bitwise operators:
1. & Bitwise And
2. | Bitwise Or
3. ^ Bitwise XOR
4. ~ Bitwise Complements.
5. >> Bitwise Right Shift
6. << Bitwise Left Shift
7. Others Operator :-
1. Conditional Operator:-
Syntax:
(Condition)?value1:value2;
This operator evaluates the value 1 if the condition result return true and value2 if the
condition returns false.
Example:-
X=(y>z)?y:z;
X is assigned the value of y if y is greater than z else x is assigned the value of z.

2. New Operator:-
When user creates an instance of a class, user needs to allocate memory for it. When user
declares an object, user merely states its data type.
Syntax
Class name object_ref_variable=new Class Name();
Or
Class name object_ref_var1,Object_ref_var2,…;
Object_ref_var1=new Class name();
Order of precedence of operator

Operator Precedence Group Associativity


1. (), [], Postfix ++, Postfix -- Left

2. Unary +, Unary-, Prefix ++, Prefix--, ~, Right


!
3. (type), new Left

8 DPP
CORE JAVA
4. *, /, % Left

5. +, - Left

6. <<, >>, >>> Left

7. <, <=, >, >= Left

8. ==, != Left

9. & Left

10. | Left

11. && Left

12. || Left

13. ?: Left

14. =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, Right
&=, |=, ^=
Final Keyword:-
The variables are for holding different values at different times. If we want to keep a value
constant, we may declare a variable as final. Such a variable has initialized only once.
final <data type> var=value;
Example:- final int num=30;
Order of precedence of operator
Operator Precedence Group Associativity
1. (), [], Postfix ++, Postfix -- Left
2. Unary +, Unary-, Prefix ++, Prefix--, ~, ! Right
3. (type), new Left
4. *, /, % Left
5. +, - Left
6. <<, >>, >>> Left
7. <, <=, >, >= Left
8. ==, != Left
9. & Left
10. | Left
11. && Left
12. || Left
13. ?: Left
14. =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^= Right

Writing a Java hello world program


Open a simple text editor program such as Notepad and type the following content:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Save the file as HelloWorld.java (note that the extension is .java) under a directory, let’s
say, C:\Java.

9 DPP
CORE JAVA

Every Java program starts from the main() method. This program simply prints “Hello
world” to screen.
Compiling it
Now let’s compile our first program in the HelloWorld.java file using javac tool. Type the
following command to change the current directory to the one where the source file is
stored:
cd C:\Java
And type the following command:
javac HelloWorld.java
That invokes the Java compiler to compile code in the HelloWorld.java file into bytecode.
Note that the file name ends with .java extension. You would see the following output:

If everything is fine (e.g. no error), the Java compiler quits silently, no fuss. After
compiling, it generates the HelloWorld.class file which is bytecode form of
the HelloWorld.java file. Now try to type dir in the command line, we’ll see the .class file:

So remember a Java program will be compiled into bytecode form (.class file).
Running it
It’s now ready to run our first Java program. Type the following command:
java HelloWorld
That invokes the Java Virtual Machine to run the program called HelloWorld (note that
there is no .java or .class extension). You would see the following output:

It just prints out “Hello world!” to the screen and quits. Congratulations! You have
successfully run your first Java program!

10 DPP
CORE JAVA

-: Control Statement:-
Java supports three type of control statement for controlling the set of statements. These
are:
1. Selection Statement
2. Looping Statement
3. Jump Statement
1. Selection Statement :-

Java supports two type of selection statement, if and switch. These statements allow
controlling the flow of our programs execution based upon conditions known only during
run time.
(a) if … construct:-

The if decision construct is followed by a logical expression in which data is compared


and decision is made based on the result of the comparison.
Syntax
if(<Boolean expression>)
{
<Set of Statements>;
}
else
{
<Set of statements>;
}
Example:
public class IfElse1
{
public static void main(String arg[])
{
int x=20;
int y=30;
if(x>y)
{
System.out.println(“X is greater than Y”);
}
else
{
System.out.println(“Y is greater than X”);
}
}
}
(b) Nested if … construct:-
A nested if is an if statement that is the target of another if or else. Nested if is very
common in programming.
Syntax
if(<Boolean expression>)
{
<Set of Statements>;
if(<Boolean expression>)
{
<Set of Statements>;
}
else
{
<Set of statements>;
}
}
11 DPP
CORE JAVA
else
{
<Set of statements>;
if(<Boolean expression>)
{
<Set of Statements>;
}
}
Example:
public class IfElse2
{
public static void main(String arg[])
{
int x=20;
int y=30;
int z=40;
if(x>y)
{
if(x>z)
{
System.out.println(“X is greater”);
}
else
{
if(z>y) {
System.out.println(“Z is greater”);
}
}
}
else
{
if(y>z)
{
System.out.println(“Y is greater”);
}
else
{
System.out.println(“Z is greater ”);
}
}
}
}
(c) If-else-if … construct:-
Java supports an else-if word. By using it we will check the condition in option part of our
conditional statement.
Syntax
if(<Boolean expression>)
{
<Set of Statements>;
else if(<Boolean expression>)
{
<Set of Statements>;
}
else if(<Boolean expression>)
{
<Set of statements>;
}
else
12 DPP
CORE JAVA
{
<Set of statements>;
}
Example:
public class IfElseIf1
{
public static void main(String arg[]) {
int x=20;
int y=30;
int z=40;
if(x>y&&x>z)
{
System.out.println(“X is greater”);
}
else if(y>x&&y>z)
{
System.out.println(“Y is greater”);
}
else
{
System.out.println(“Z is greater ”);
}
}
}
(d) Switch case:-
Switch case structure is used to execute sequence of statements based on selection
specified with case statements.
Syntax
switch (choice)
{
case 1:
<Set Of Statements>;
break;
case 2:
<Set Of Statements>;
break;
case 3:
<Set Of Statements>;
break;
default:
<Set Of Statements>;
}
Note:-
 Only constraint numeric and character value are allowed with case statements.
 Variable or expression is allowed within the parenthesis of switch case.
 Default is optional and can be used if required.
 Break within switch can be used to break the control of execution and continue on
resume it just very next close curly braces encountered.
 The switch case is internally working on numeric constant.
 Maximum of 33 switch structure can be a target of another switch.

Example
import java.io.*;
public class SwitchCase
{
public static void main(String arg[])throws IOException
{

13 DPP
CORE JAVA
BufferedReader obj=new BuggeredReader(new InputStreamReader(System.in));
int dno;
System.out.println(“Enter day Number”);
dno=Integer.valueOf(obj.readLine()).intValue();
switch(dno)
{
case 1:
System.out.println(“SunDay”);
break;
case 2:
System.out.println(“MonDay”);
break;
case 3:
System.out.println(“TuesDay”);
break;
case 4:
System.out.println(“WedDay”);
break;
………..
case 7:
System.out.println(“SaturDay”);
break;
default :
System.out.println(“Invalid Day Number”);
break;
}
}
}
2. Looping Statement :-
A loop causes a section of a program to be repeated a certain number of times. The
repetition continues while the condition becomes false. The loop ends and the control are
passed to the statement following the loop.
Java support three looping constructs
1. While … loop
2. Do … while loop
3. For … loop
While loop:-
The while statement continually executes a block of statements while a particular
condition is true. Its syntax can be expressed as:
Syntax
while (expression)
{
<Set of statement(s)>;
< Increment /Decrement>;
}
NOTE:-
The while statement evaluates expression, which must return a Boolean value. If the
expression evaluates to true, the while statement executes the set of statement(s) in the
while block. The while statement continues testing the expression and executing its block
until the expression evaluates to false.
1. Increment/ Decrement statement is required to break the loop in certain period.
2. If no Increment/ Decrement statement is found in the body of loop, the loop becomes
infinite.

Example
public class WhileDemo
{
public static void main(String[] args)
14 DPP
CORE JAVA
{
int count = 1;
while (count < 11)
{
System.out.println("Count is: " + count);
count++;
}
}
}
Do…While loop:-
In some conditions in java, you need to run some statements and processes once at least.
For that you have to use the do while loop in after that check the condition then we use
the do-while loop statement. do-while loop is same as the while loop statement but while
loop checks the certain condition is first and if condition is true then statements or
processes are executed otherwise all the statements written under the while loop is
ignored by the interpreter but do - while loop executes all the statements first at once and
then check the condition if the condition is true then all the statements are also executed
in second times otherwise second times ignored all the statements.
Syntax
do { <Set of statement(s)>;
< Increment /Decrement>;
}while(condition);
NOTE:-
1. In a do…while structure the condition is checked at the end /bottom so, if very first time
condition is false, the loop body executed at the last one time.
2. The do…while loop is basically used for menu driven programming.
3. The condition terminated by semicolon.

Example
public class DoWhile
{ public static void main(String[] args)
{ int n = 12345; int t,r = 0; System.out.println("The original number : " + n); do
{ t = n % 10; r = r * 10 + t; n = n / 10; }while (n > 0); System.out.println("The reverse number
: " + r);
}}
For loop:-
The for statement provides a compact way to iterate over a range of values. Programmers
often refer to it as the "for loop" because of the way in which it repeatedly loops until a
particular condition is satisfied.
Syntax
for (initialization; termination; increment)
{
<Set of statement(s)>;
}
NOTE:-
1. The initialization expression initializes the loop; it's executed once, as the loop begins.
2. When the termination expression evaluates to false, the loop terminates.
3. The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.

Example
public class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<11; i++)
{
System.out.println("Count is: " + i);
15 DPP
CORE JAVA
}
}
}
3. Jump Statement :-
Java support four jump statements; break, continue, return an exit(). These statements
transfer control to another part of program.
Break:
The break statement is used in many programming languages such as c, c++, java etc.
Sometimes we need to exit from a loop before the completion of the loop then we use
break statement and exit from the loop and loop is terminated. The break statement is
used in while loop, do - while loop, for loop and also used in the switch statement.
Break statement is used in java for jump the control very next close curly braces. And
execute continue the program.
Syntax
break;
Example:- Checking prime number with in 1 to 50
public class Break
{ public static void main(String[] args)
{ int i,j; System.out.println("Prime numbers between 1 to 50 : "); for (i = 1;i < 50;i++ )
{ for (j = 2;j < i;j++ )
{ if(i % j == 0) { break; } } if(i == j) { System.out.print(" " + i); } }
}
}
Continue:
The continue statement is used in many programming languages such as C, C++, java
etc. Sometimes we do not need to execute some statements under the loop then we use
the continue statement that stops the normal flow of the control and control returns to
the loop without executing the statements written after the continue statement. There is
the difference between break and continue statement that the break statement exit
control from the loop but continue statement keeps continuity in loop without executing
the statement written after the continue statement according to the conditions.
Syntax
continue;
Example 1:-
public class MainClass
{ public static void main(String[] args)
{ for (int i = 0; i < 10; i++)
{
if (i == 5)
{ continue; } System.out.println(i);
}
}}
Example 2:-
public class MainClass
{ public static void main(String[] args)
{ int limit = 20; int factorial = 1; OuterLoop: for (int i = 1; i <= limit; i++)
{ factorial = 1; for (int j = 2; j <= i; j++)
{ if (i > 10 && i % 2 == 1)
{ continue OuterLoop; } factorial *= j;
}
System.out.println(i + "! is " + factorial);
}}
}
Example 3:-
public class MainClass
{ public static void main(String[] args)
{ int nValues = 50; OuterLoop: for (int i = 2; i <= nValues; i++)
{ for (int j = 2; j < i; j++)
16 DPP
CORE JAVA
{ if (i % j == 0)
{ continue OuterLoop; } } System.out.println(i);
}}
}
Return :

The return statement is used to explicitly return from a method. That is, it causes
program control to transfer back to the caller of the method. As such, it is categorized as
a jump statement. A brief look at return is presented here.
At any time in a method the return statement can be used to cause execution to branch
back to the caller of the method. Thus, the return statement immediately terminates the
method in which it is executed.
Syntax
return;
or
return(var/const/expression);
Example:-
public class ReturnAllValues {
public static String name = "Faith Hill"; public static void main(String [] args) { String
myName = getName(); System.out.println(myName); } public String getName() { return name;
}
}
exit() :

exit() is a control statement. Which is used to exit from JVM(Java Virtual Machine). It is a
method of System class of Java.lang package.
Syntax
System.exit(int const.);
Example :-
Import java.io.*;
public class DemoExit
{
public static void main(String arg[])throws IOException
{
BufferedReadder b=new BufferedReader(new InputStreamReader(System.in));
Int num;
System.out.println(“Enter a numbe!! if You want to exit then press 5. ”);
Num=Integer.valueOf(b.readLine()).intValue();
if(i==5)
{
System.exit(1);
}
else
{
System.out.println(“Value Enter “+num);
}
}
}

Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java

17 DPP
CORE JAVA

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tangible and intangible). The example of
intangible object is banking system.
An object has three characteristics:

 state: represents data (value) of an object.


 behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
 identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify each
object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state.
It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.
Object Definitions:
 Object is a real world entity.
 Object is a run time entity.
 Object is an entity which has state and behavior.
 Object is an instance of a class.

Class in Java

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. It can't be physical.
A class in Java can contain:

 fields
 methods
 constructors
 blocks
 nested class and interface

Syntax to declare a class:

class <class_name>{
field;
method;
}

Fields
A class can contain any of the following variable(fields) types.

 Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
 Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.

18 DPP
CORE JAVA
 Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.

Method in Java

In java, a method is like function i.e. used to expose behavior of an object.

Advantage of Method

 Code Reusability
 Code Optimization
new keyword in Java
The new keyword is used to allocate memory at run time. All objects get memory in Heap
memory area.

Object and Class Example: main within class


In this example, we have created a Student class that have two data members id and
name. We are creating the object of the Student class by new keyword and printing the
objects value.
Here, we are creating main() method inside the class.
File: Student.java
class Student
{ int id;//field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
} }
Output:
0
null
Object and Class Example: main outside class
In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main()
method in another class.
We can have multiple classes in different java files or single java file. If you define multiple
classes in a single java source file, it is a good idea to save the file name with the class
name which has main() method.
File: TestStudent1.java
class Student{
int id;
String name;
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
Null

way to create an object in java. They are:


 By new keyword
19 DPP
CORE JAVA
Calling method through reference:
Calculation c=new Calculation();
c.fact(5);

The java command-line argument is an argument i.e. passed at the time of running the
java program.
The arguments passed from the console can be received in the java program and it can be
used as an input.
So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N(1,2,3 and so on) numbers of arguments from the command
prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.

class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo

Java Scanner class


There are various ways to read input from the keyboard, the java.util.Scanner class is one
of them.
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using
regular expression.
Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.
Commonly used methods of Scanner class
There is a list of commonly used Scanner class methods:

Method Description

public String next() it returns the next token from the scanner.

public String nextLine() it moves the scanner position to the next line and returns the
value as a string.

public byte nextByte() it scans the next token as a byte.

public short it scans the next token as a short value.


nextShort()

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.


20 DPP
CORE JAVA
public double it scans the next token as a double value.
nextDouble()

Java Scanner Example to get input from console

Let's see the simple example of the Java Scanner class which reads the int, string and
double value as an input:

import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);

System.out.println("Enter your rollno");


int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}

Output:

Enter your rollno


111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

Java Scanner Example with delimiter

Let's see the example of Scanner class with delimiter. The \s represents whitespace.

import java.util.*;
public class ScannerTest2{
public static void main(String args[]){
String input = "10 tea 20 coffee 30 tea buiscuits";
Scanner s = new Scanner(input).useDelimiter("\\s");
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();
}}

Output:

21 DPP
CORE JAVA
10
tea
20
coffee

class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}

Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

Output:

111 Karan
111
Karan

22 DPP
CORE JAVA

Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

<class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}

Output:

Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

23 DPP
CORE JAVA

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on
the type.

Example of default constructor that displays the default values

1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
13. }
Test it Now

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides
you a default constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student4{
24 DPP
CORE JAVA
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Test it Now

Output:

111 Karan
222 Aryan

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method


Constructor is used to initialize the state of an Method is used to expose
object. behaviour of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if Method is not provided by compiler
you don't have any constructor. in any case.
Method name may or may not be
Constructor name must be same as the class name.
same as class name.

class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}

Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
25 DPP
CORE JAVA
s1.display();
s2.display();
}
}

Output:

111 Karan
111 Karan

Copying values without constructor

We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.

class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}

Output:

111 Karan
111 Karan

Q) Does constructor return any value?

Ans:yes, that is current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any
operation in the constructor as you perform in the method.

Differences between methods and constructors.


There is no return type given in a constructor signature (header). The value is this object
itself so there is no need to indicate a return value.
26 DPP
CORE JAVA
There is no return statement in the body of the constructor.
The first line of a constructor must either be a call on another constructor in the same
class (using this), or a call on the superclass constructor (using super). If the first line is
neither of these, the compiler automatically inserts a call to the parameterless super class
constructor.

finalize() Java Destructor


About finalize() Java Destructor method
The finalize() method is equivalent to a destructor of C++. When the job of an object is
over, or to say, the object is no more used in the program, the object is known
as garbage. The process of removing the object from a running program is known
as garbage collection. Garbage collectionfrees the memory and this memory can be
used by other programs or the same program further in its execution. Before an object is
garbage collected, the JRE (Java Runtime Environment) calls the finalize() method.
finalize() method can be best utilized by the programmer to close the I/O streams, JDBC
connections or socket handles etc.
Following is the method signature as defined in Object class.

27 DPP
CORE JAVA
Unit-2- Inheritance and Packages 12
2.1 Defining sub class, subclass constructor
2.2 Inheritance-Multiple and hierarchical
2.3 Defining packages, system packages
2.4 Creating & accessing packages
2.5 Adding a class to package
2.6 Polymorphism- function overloading and over ridding, its difference
Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance is one of the main concepts of object oriented
programming. The idea behind inheritance in java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of parent class, and you can add new methods and fields also.The
base class is named superclass and the child class is named subclass. Using inheritance
we can achieve the concepts of reusability. The child class can use the methods and
variables of the superclass and add to them its own methods and variables. Inheritance
represents problems in the real world.

Notes:-
1) Subclass can only inherit public and protected members but not private members.
2) You can only inherit from single class. (Single inheritance).That is means there is no
multiple inheritance in Java. But as a solution to the multiple inheritance java supported
class types called “interfaces”.

Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

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

In the terminology of Java, a class which is inherited is called parent or super class and
the new class is called child or subclass.

Java Inheritance Example

28 DPP
CORE JAVA
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A Employee.It means
that Programmer is a type of Employee.

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);
}
}
OUTPUT
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

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.

Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:

29 DPP
CORE JAVA

Single Inheritance
An inheritance in side which a single base class inherits a single derive class is known as
single inheritance.
When a subclass is derived simply from it's parent class then this mechanism is known
as simple inheritance. In case of simple inheritance there is only a sub class and it's
parent class. It is also called single inheritance or one level inheritance.

Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Output:

barking...
eating...

Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a
derived class then this mechanism is known as the multilevel inheritance. The derived
class is called the subclass or child class for it's parent class and this parent class works
as the child class for it's just above (parent) class. Multilevel inheritance can go up to any
number of levels.

Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
30 DPP
CORE JAVA
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance

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(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}}

Output:

meowing...
eating...

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported
in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object, there
will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error
if you inherit 2 classes. So whether you have same method or different, there will be
compile time error now.
31 DPP
CORE JAVA
super keyword
The super is java keyword. As the name suggest super is used to access the members of
the super class.It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class
hidden by the sub class.
e.g. Suppose class A is the super class that has two instance variables as int a and float
b. class B is the subclass that also contains its own data members named a and b. then
we can access the super class (class A) variables a and b inside the subclass class B just
by calling the following command.
super.member;
Here member can either be an instance variable or a method. This form of super most
useful to handle situations where the local members of a subclass hides the members of a
super class having the same name. The following example clarify all the confusions
Example
class A
{
int a;
float b;
void Show()
{
System.out.println("b in super class: " + b);
}
}
class B extends A
{
int a;
float b;
B( int p, float q) {
a = p;
super.b = q;
}
void Show()
{
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args)
{
B subobj = new B(1, 5);
subobj.Show();
}
}
Use of super to call super class constructor:
The second use of the keyword super in java is to call super class constructor in the
subclass. This functionality can be achieved just by using the following command.
super(param-list);
Here parameter list is the list of the parameter requires by the constructor in the super
class. super must be the first statement executed inside a super class constructor. If we
want to call the default constructor then we pass the empty parameter list. The following
program illustrates the use of the super keyword to call a super class constructor.
Example
class A
{
int a;
int b;
int c;
A(int p, int q, int r)
32 DPP
CORE JAVA
{
a=p;
b=q;
c=r;
}
}
class B extends A
{
int d;
B(int l, int m, int n, int o) {
super(l,m,n);
d=o;
}
void Show()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
public static void main(String args[])
{
B b = new B(4,3,8,7);
b.Show();
}
}

Packages

A package as the name suggests is a pack(group) of classes, interfaces and other


packages. In java we use packages to organize our classes and interfaces. We have
two types of packages in Java: built-in packages and the packages we can create (also
known as user defined package).

In java we have several built-in packages, for example when we need user input, we
import a package like this:

import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.

Advantages of using a package in Java

These are the reasons why you should use packages in Java:

 Reusability: While developing a project in java, we often feel that there are few
things that we are writing again and again in our code. Using packages, you can
create such things in form of classes inside a package and whenever you need to
perform that same task, just import that package and use the class.
 Better Organization: Again, in large java projects where we have several hundreds
of classes, it is always required to group the similar types of classes in a
meaningful package name so that you can organize your project better and when
you need something you can quickly locate it and use it, which improves the
efficiency.

33 DPP
CORE JAVA
 Name Conflicts: We can define two classes with the same name in different
packages so to avoid name collision, we can use packages

Types of packages in Java

As mentioned in the beginning of this guide that we have two types of packages in java.
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known
as built-in packages.

lets discuss user-defined packages with the help of examples.

Example 1: Java packages

I have created a class Calculator inside a package name letmecalculate. To create a class
inside a package, declare the package name in the first statement in your program. A
class can have only one package declaration.
Calculator.java file created inside a package letmecalculate

package letmecalculate;

public class Calculator {


public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
Now lets see how to use this package in another program.

import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
To use the class Calculator, I have imported the package letmecalculate. In the above
program I have imported the package as letmecalculate.Calculator, this only imports the
Calculator class. However if you have several classes inside package letmecalculate then
you can import the package like this, to use all the classes of this package.

import letmecalculate.*;
Example 2: Creating a class inside package while importing another package

As we have seen that both package declaration and package import should be the first
statement in your java program. Lets see what should be the order when we are creating
a class inside a package while importing another package.

//Declaring a package
package anotherpackage;
//importing a package
import letmecalculate.Calculator;
34 DPP
CORE JAVA
public class Example{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
So the order in this case should be:
→ package declaration
→ package import

Example 3: Using fully qualified name while importing a class

You can use fully qualified name to avoid the import statement. Lets see an example to
understand this:
Calculator.java

package letmecalculate;
public class Calculator {
public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
Example.java

//Declaring a package
package anotherpackage;
public class Example{
public static void main(String args[]){
//Using fully qualified name instead of import
letmecalculate.Calculator obj =
new letmecalculate.Calculator();
System.out.println(obj.add(100, 200));
}
}
In the Example class, instead of importing the package, I have used the full qualified
name such as package_name.class_name to create the object of it.

Polymorphism

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 method overriding.

Usage of Java Method Overriding

35 DPP
CORE JAVA
o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method 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 of Java Method Overriding

Consider a scenario, Bank is a class that provides functionality to get rate of interest.
But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks
could provide 8%, 7% and 9% rate of interest.

class Bank{
int getRateOfInterest(){return 0;}
}

class SBI extends Bank{


int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}

class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

36 DPP
CORE JAVA
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In java, Method Overloading is not possible by changing the return type of the
method only.

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance
for calling methods.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output:
37 DPP
CORE JAVA
22
33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Output:

22
24.9

Difference between method overloading and method overriding in java

There are many differences between method overloading and method overriding in java. A
list of differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase Method overriding is used to provide


the readability of the program. the specific implementation of the
method that is already provided by
its super class.

2) Method overloading is performed within Method overriding occurs in two


class. classes that have IS-A (inheritance)
relationship.

3) In case of method In case of method


overloading, parameter must be overriding, parameter must be
different. same.

4) Method overloading is the example Method overriding is the example


of compile time polymorphism. of run time polymorphism.

5) In java, method overloading can't be Return type must be same or


performed by changing return type of

38 DPP
CORE JAVA
the method only. Return type can be covariant in method overriding.
same or different in method
overloading. But you must have to
change the parameter.

Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:Compile Time Error

39 DPP
CORE JAVA
2) Java final method

If you make any method as final, you cannot override it.

Example of final method

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error

3) Java final class

If you make any class as final, you cannot extend it.

Example of final class

final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}

Output:Compile Time Error

abstract class :-
An abstract class is a class that is declared by using the abstract keyword. It may or may
not have abstract methods. Abstract classes cannot be instantiated, but they can be
extended into sub-classes.
Java provides a special type of class called an abstract class. Which helps us to organize
our classes based on common methods. An abstract class lets you put the common
method names in one abstract class without having to write the actual implementation
code.
An abstract class can be extended into sub-classes, these sub-classes usually provide
implementations for all of the abstract methods.
The key idea with an abstract class is useful when there is common functionality that's
like to implement in a superclass and some behavior is unique to specific classes. So you
implement the superclass as an abstract class and define methods that have common
subclasses. Then you implement each subclass by extending the abstract class and add
the methods unique to the class.
Points of abstract class :
 Abstract class contains abstract methods.
40 DPP
CORE JAVA
 Program can't instantiate an abstract class.
 Abstract classes contain mixture of non-abstract and abstract methods.
 If any class contains abstract methods then it must implements all the abstract methods
of the abstract class.

In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier
curves, and many other graphic objects. These objects all have certain states (for
example: position, orientation, line color, fill color) and behaviors (for example: moveTo,
rotate, resize, draw) in common. Some of these states and behaviors are the same for all
graphic objects—for example: position, fill color, and moveTo. Others require different
implementations—for example, resize or draw. All GraphicObjects must know how to
draw or resize themselves; they just differ in how they do it. This is a perfect situation for
an abstract superclass. You can take advantage of the similarities and declare all the
graphic objects to inherit from the same abstract parent object—for example,
GraphicObject, as shown in the following figure.

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in java. It can
have abstract and non-abstract methods (method with body).

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended


and its method implemented. It cannot be instantiated.

Example abstract class

abstract class A{ }

abstract method

A method that is declared as abstract and does not have implementation is known as
abstract method.

Example abstract method

abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method


41 DPP
CORE JAVA
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

running safely..

Unit-3- Multithreading and Exception Handling 12


3.1 Creating threads, extending a thread class- declaring the class, run()
method
3.2 Stopping and blocking threads
3.3 Life cycle of thread
3.4 Using thread method
3.5 Thread priority
3.6 Introduction to exception
3.7 Syntax of exception handling code
3.8 Multiple catch statement
3.9 Using finally statement
3.10 Throwing exception

A thread is a program's path of execution. Most programs written today run as a single
thread, causing problems when multiple events or actions need to occur at the same time.
Let's say, for example, a program is not capable of drawing pictures while reading
keystrokes. The program must give its full attention to the keyboard input lacking the
ability to handle more than one event at a time. The ideal solution to this problem is the
seamless execution of two or more sections of a program at the same time. Threads allows
us to do this.
Multithreaded applications deliver their potent power by running many threads
concurrently within a single program. From a logical point of view, multithreading means
multiple lines of a single program can be executed at the same time, however, it is not the
same as starting a program twice and saying that there are multiple lines of a program

42 DPP
CORE JAVA
being executed at the same time. In this case, the operating system is treating the
programs as two separate and distinct processes.
Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in javanew, runnable, non-runnable and terminated. There is no
running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

43 DPP
CORE JAVA
4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Creating threads
The first method of creating a thread is to simply extend from
the Thread class. Do this only if the class you need executed as a thread does not ever
need to be extended from another class. The Thread class is defined in the package
java.lang, which needs to be imported so that our classes are aware of its definition.

import java.lang.*;
public class Counter extends Thread
{
public void run()
{
....
}
}

44 DPP
CORE JAVA
The above example creates a new class Counter that extends the Thread class and
overrides the Thread.run() method for its own implementation. The run()method is where
all the work of the Counter class thread is done.

class can be created by implementing Runnable:

import java.lang.*;
public class Counter implements Runnable
{
Thread T;
public void run()
{
....
}
}
Here, the abstract run() method is defined in the Runnable interface and is being
implemented. Note that we have an instance of the Thread class as a variable of
the Counter class. The only difference between the two methods is that by implementing
Runnable, there is greater flexibility in the creation of the class Counter. In the above
example, the opportunity still exists to extend the Counter class, if needed. The majority
of classes created that need to be run as a thread will implement Runnable since they
probably are extending some other functionality from another class.

Thread Class vs Runnable Interface

1. If we extend the Thread class, our class cannot extend any other class because Java
doesn’t support multiple inheritance. But, if we implement the Runnable interface, our
class can still extend other base classes.

2. We can achieve basic functionality of a thread by extending Thread class because it


provides some inbuilt methods like yield(), interrupt() etc. that are not available in
Runnable interface.

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread schedular schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on
JVM specification that which scheduling it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1


and the value of MAX_PRIORITY is 10.

45 DPP
CORE JAVA
Example of priority of a Thread:

1. class TestMultiPriority1 extends Thread{


2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
5.
6. }
7. public static void main(String args[]){
8. TestMultiPriority1 m1=new TestMultiPriority1();
9. TestMultiPriority1 m2=new TestMultiPriority1();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }

OUTPUT:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Exception Handling in Java

The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

What is exception

Dictionary Meaning: Exception is an abnormal condition.

In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

What is exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound,


IO, SQL, Remote etc.

46 DPP
CORE JAVA
Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there is 10 statements in your program and there occurs an exception at


statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we
perform exception handling, rest of the statement will be executed. That is why we use
exception handling in java.

47 DPP
CORE JAVA

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:

1. Checked Exception
2. Unchecked Exception

48 DPP
CORE JAVA
3. Error

Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are
checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as
follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I have
a string variable that have characters, converting this variable into digit will occur
NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

49 DPP
CORE JAVA
4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

1. try
2. catch
3. finally
4. throw
5. throws

Java try block

Java try block is used to enclose the code that might throw an exception. It must be used
within the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch


1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block


1. try{
2. //code that may throw exception
3. }finally{}

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block
only.

You can use multiple catch block with a single try.

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.

50 DPP
CORE JAVA
1. public class Testtrycatch1{
2. public static void main(String args[]){
3. int data=50/0;//may throw exception
4. System.out.println("rest of the code...");
5. }
6. }

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of
the code... statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will not be
executed.

Solution by exception handling

Let's see the solution of above problem by java try-catch block.

1. public class Testtrycatch2{


2. public static void main(String args[]){
3. try{
4. int data=50/0;
5. }catch(ArithmeticException e){System.out.println(e);}
6. System.out.println("rest of the code...");
7. }
8. }

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code.

51 DPP
CORE JAVA

Internal working of java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the


application is maintained i.e. rest of the code is executed.

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.

Let's see a simple example of java multi-catch block.

1. public class TestMultipleCatchBlock{


2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
9. catch(Exception e){System.out.println("common task completed");}

52 DPP
CORE JAVA
10.
11. System.out.println("rest of the code...");
12. }
13. }

Output:task1 completed
rest of the code...
Java Nested try block

The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be
nested.

Syntax:

1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }

Java nested try example

Let's see a simple example of java nested try block.

1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");

53 DPP
CORE JAVA
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
13.
14. System.out.println("other statement);
15. }catch(Exception e){System.out.println("handeled");}
16.
17. System.out.println("normal flow..");
18. }
19. }

Java finally block is a block that is used to execute important code such as closing
connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Why use java finally


o Finally block in java can be used to put "cleanup" code such as closing a file,
closing connection etc.

54 DPP
CORE JAVA
Usage of Java finally

Let's see the different cases where java finally block can be used.

Case 1

Let's see the java finally example where exception doesn't occur.

1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

Output:5
finally block is always executed
rest of the code...

Case 2

Let's see the java finally example where exception occurs and not handled.

1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

Output:finally block is always executed


Exception in thread main java.lang.ArithmeticException:/ by zero

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

55 DPP
CORE JAVA
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

throw exception;

Let's see the example of throw IOException.

throw new IOException("sorry device error);

java throw keyword example

In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.

public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:not valid

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is
not performing check up before the code being used.

Syntax of java throws

return_type method_name() throws exception_class_name{

56 DPP
CORE JAVA
//method code
}

Which exception should be declared

Ans) checked exception only, because:

o unchecked Exception: under your control so correct your code.


o error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws example

Let's see the example of java throws clause which describes that checked exceptions can
be propagated by throws keyword.

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

Output:

exception handled
normal flow...
57 DPP
CORE JAVA

58 DPP
CORE JAVA

Unit- 4- Applets Programming & Introduction to AWT 12


4.1 Introduction to applets
4.2 Building applet code
4.3 Applet life cycle
4.4 Adding applet code to HTML file

4.5 Introduction to Abstract Window Toolkit (AWT)

Java Applet

Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

 It works at client side so less response time.


 Secured
 It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet

 Plugin is required at client browser to execute applet.

There are some important differences between an applet and a standalone Java
application, including the following −

 An applet is a Java class that extends the java.applet.Applet class.


 A main() method is not invoked on an applet, and an applet class will not define main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser
or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in
a sandbox with various rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

59 DPP
CORE JAVA
Life Cycle of an Applet

Four methods in the Applet class gives you the framework on which you build any serious
applet −

 init − This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
 start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
 stop − This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
 paint − Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the java.awt.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser
is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

A "Hello, World" Applet

Following is a simple applet named HelloWorldApplet.java −

import java.applet.*;
import java.awt.*;

60 DPP
CORE JAVA

public class HelloWorldApplet extends Applet {


public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}

These import statements bring the classes into the scope of our applet class −

 java.applet.Applet
 java.awt.Graphics

Without those import statements, the Java compiler would not recognize the classes
Applet and Graphics, which the applet class refers to.

The Applet Class

Every applet is an extension of the java.applet.Applet class. The base Applet class
provides methods that a derived Applet class may call to obtain information and services
from the browser context.

These include methods that do the following −

 Get applet parameters


 Get the network location of the HTML file that contains the applet
 Get the network location of the applet class directory
 Print a status message in the browser
 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet

Additionally, the Applet class provides an interface by which the viewer or browser
obtains information about the applet and controls the applet's execution. The viewer may

 Request information about the author, version, and copyright of the applet
 Request a description of the parameters the applet recognizes
 Initialize the applet
 Destroy the applet
 Start the applet's execution
 Stop the applet's execution

The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.

The "Hello, World" applet is complete as it stands. The only method overridden is the
paint method.

Invoking an Applet

An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Following is an
example that invokes the "Hello, World" applet −

61 DPP
CORE JAVA
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>

The code attribute of the <applet> tag is required. It specifies the Applet class to run.
Width and height are also required to specify the initial size of the panel in which an
applet runs. The applet directive must be closed with an </applet> tag.

If an applet takes parameters, values may be passed for the parameters by adding
<param> tags between <applet> and </applet>. The browser ignores text and other tags
between the applet tags.

Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything


that appears between the tags, not related to the applet, is visible in non-Java-enabled
browsers.

The viewer or browser looks for the compiled Java code at the location of the document.
To specify otherwise, use the codebase attribute of the <applet> tag as shown −

<applet codebase = "https://amrood.com/applets" code = "HelloWorldApplet.class"


width = "320" height = "120">

If an applet resides in a package other than the default, the holding package must be
specified in the code attribute using the period character (.) to separate package/class
components. For example −

<applet = "mypackage.subpackage.TestApplet.class"
width = "320" height = "120">

Getting Applet Parameters

The following example demonstrates how to make an applet respond to setup parameters
specified in the document. This applet displays a checkerboard pattern of black and a
second color.

The second color and the size of each square may be specified as parameters to the applet
within the document.

CheckerApplet gets its parameters in the init() method. It may also get its parameters in
the paint() method. However, getting the values and saving the settings once at the start
of the applet, instead of at every refresh, is convenient and efficient.

The applet viewer or browser calls the init() method of each applet it runs. The viewer calls
init() once, immediately after loading the applet. (Applet.init() is implemented to do
nothing.) Override the default implementation to insert custom initialization code.

The Applet.getParameter() method fetches a parameter given the parameter's name (the
value of a parameter is always a string). If the value is numeric or other non-character
data, the string must be parsed.

The following is a skeleton of CheckerApplet.java −


62 DPP
CORE JAVA
import java.applet.*;
import java.awt.*;

public class CheckerApplet extends Applet {


int squareSize = 50; // initialized to default size
public void init() {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}

Here are CheckerApplet's init() and private parseSquareSize() methods −

public void init () {


String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);

String colorParam = getParameter ("color");


Color fg = parseColor (colorParam);

setBackground (Color.black);
setForeground (fg);
}

private void parseSquareSize (String param) {


if (param == null) return;
try {
squareSize = Integer.parseInt (param);
} catch (Exception e) {
// Let default value remain
}
}

The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize()


calls the library method Integer.parseInt(), which parses a string and returns an integer.
Integer.parseInt() throws an exception whenever its argument is invalid.

Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on
bad input.

The applet calls parseColor() to parse the color parameter into a Color value. parseColor()
does a series of string comparisons to match the parameter value to the name of a
predefined color. You need to implement these methods to make this applet work.

Specifying Applet Parameters

The following is an example of an HTML file with a CheckerApplet embedded in it. The
HTML file specifies both parameters to the applet by means of the <param> tag.

<html>
<title>Checkerboard Applet</title>
<hr>
<applet code = "CheckerApplet.class" width = "480" height = "320">
<param name = "color" value = "blue">
<param name = "squaresize" value = "30">
</applet>
<hr>
63 DPP
CORE JAVA
</html>

Note − Parameter names are not case sensitive.

Application Conversion to Applets

It is easy to convert a graphical Java application (that is, an application that uses the
AWT and that you can start with the Java program launcher) into an applet that you can
embed in a web page.

Following are the specific steps for converting an application to an applet.

 Make an HTML page with the appropriate tag to load the applet code.
 Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet
cannot be loaded.
 Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.
 Move any initialization code from the frame window constructor to the init method of the
applet. You don't need to explicitly construct the applet object. The browser instantiates it
for you and calls the init method.
 Remove the call to setSize; for applets, sizing is done with the width and height
parameters in the HTML file.
 Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates
when the browser exits.
 If the application calls setTitle, eliminate the call to the method. Applets cannot have title
bars. (You can, of course, title the web page itself, using the HTML title tag.)
 Don't call setVisible(true). The applet is displayed automatically.

Java AWT

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.

Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

64 DPP
CORE JAVA

Container

The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The classes that extends Container class are known as
container such as Frame, Dialog and Panel.

Window

The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have
other components like button, textfield etc.

Useful Methods of Component class


65 DPP
CORE JAVA

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int sets the size (width and height) of the
height) component.

public void defines the layout manager for the


setLayout(LayoutManager m) component.

public void setVisible(boolean changes the visibility of the component, by


status) default false.

Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a frame in
AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.

import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above
example that sets the position of the awt button.

66 DPP
CORE JAVA

AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here,
we are showing Button component on the Frame.

import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}

67 DPP
CORE JAVA

Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the registration
methods. For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
68 DPP
CORE JAVA
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code

We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
69 DPP
CORE JAVA
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in
the above example that sets the position of the component it may be button, textfield
etc.

Java event handling by outer class

import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener

70 DPP
CORE JAVA
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}

import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}

Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner.


LayoutManager is an interface that is implemented by all the classes of layout managers.
There are following classes that represents the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east,
west and center. Each region (area) may contain one component only. It is the default
layout of frame or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
71 DPP
CORE JAVA
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the


components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

Example of BorderLayout class:

Java GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component
is displayed in each rectangle.

Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout
with the given rows and columns alongwith given horizontal and vertical gaps.

Example of GridLayout class

72 DPP
CORE JAVA

ava FlowLayout

The FlowLayout is used to arrange the components in a line, one after another (in a flow).
It is the default layout of applet or panel.

Fields of FlowLayout class

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

Example of FlowLayout class

73 DPP
CORE JAVA

Java BoxLayout

The BoxLayout is used to arrange the components either vertically or horizontally. For
this purpose, BoxLayout provides four constants. They are as follows:

Fields of BoxLayout class

1. public static final int X_AXIS


2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class

1. BoxLayout(Container c, int axis): creates a box layout that arranges the


components with the given axis.

Example of BoxLayout class with Y-AXIS:

74 DPP
CORE JAVA

Example of BoxLayout class with X-AXIS

Java CardLayout

The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known
as CardLayout.

Constructors of CardLayout class

1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal
and vertical gap.

Commonly used methods of CardLayout class

o public void next(Container parent): is used to flip to the next card of the given
container.
75 DPP
CORE JAVA
o public void previous(Container parent): is used to flip to the previous card of the
given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the specified
card with the given name.

Example of CardLayout class

Java GridBagLayout

The Java GridBagLayout class is used to align components vertically, horizontally or


along their baseline.

The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as
its display area. Each component associates an instance of GridBagConstraints. With the
help of constraints object we arrange component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine component's size.

Fields

Modifier and Type Field Description

double[] columnWeights It is used to


hold the
overrides to
the column
76 DPP
CORE JAVA

weights.

int[] columnWidths It is used to


hold the
overrides to
the column
minimum
width.

protected comptable It is used to


Hashtable<Component,GridBagConstraints> maintains
the
association
between a
component
and its
gridbag
constraints.

protected GridBagConstraints defaultConstraints It is used to


hold a
gridbag
constraints
instance
containing
the default
values.

protected GridBagLayoutInfo layoutInfo It is used to


hold the
layout
information
for the
gridbag.

protected static int MAXGRIDSIZE No longer in


use just for
backward
compatibility

77 DPP
CORE JAVA

protected static int MINSIZE It is smallest


grid that can
be laid out
by the grid
bag layout.

protected static int PREFERREDSIZE It is


preferred
grid size
that can be
laid out by
the grid bag
layout.

int[] rowHeights It is used to


hold the
overrides to
the row
minimum
heights.

double[] rowWeights It is used to


hold the
overrides to
the row
weights.

78 DPP

Vous aimerez peut-être aussi