DPP Java
DPP Java
DPP Java
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.
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.
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.
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.
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.
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
8 DPP
CORE JAVA
4. *, /, % Left
5. +, - Left
8. ==, != Left
9. & Left
10. | 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
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:-
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:
Class in Java
fields
methods
constructors
blocks
nested class and interface
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
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.
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
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.
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);
Output:
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);}
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.
<class_name>(){}
Output:
Bike is created
23 DPP
CORE JAVA
Default constructor provides the default values to the object like 0, null etc. depending on
the type.
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.
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;
Output:
111 Karan
222 Aryan
There are many differences between constructors and methods. They are given below.
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);}
Output:
111 Karan
111 Karan
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);}
Output:
111 Karan
111 Karan
Ans:yes, that is current class instance (You cannot use return type yet it returns a value).
Yes, like object creation, starting a thread, calling method etc. You can perform any
operation in the constructor as you perform in the method.
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”.
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.
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.
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
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...
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
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.
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
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.
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;
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
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
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.
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
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 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
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.
In java, Method Overloading is not possible by changing the return type of the
method only.
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
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
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:
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.
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.
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
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
39 DPP
CORE JAVA
2) Java final method
class Bike{
final void run(){System.out.println("running");}
}
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.
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
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 A{ }
abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
running safely..
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
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.
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.
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.
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.
45 DPP
CORE JAVA
Example of priority of a Thread:
OUTPUT:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
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
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
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;
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
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
There are given some scenarios where unchecked exceptions can occur. They are as
follows:
1. int a=50/0;//ArithmeticException
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
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. try
2. catch
3. finally
4. throw
5. throws
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
Java catch block is used to handle the Exception. It must be used after the try block
only.
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:
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.
Output:
51 DPP
CORE JAVA
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:
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
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.
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. }
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.
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. }
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.
throw exception;
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.
Output:
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.
56 DPP
CORE JAVA
//method code
}
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
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
Drawback of Applet
There are some important differences between an applet and a standalone Java
application, including the following −
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
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.
1. By html file.
2. By appletViewer tool (for testing purpose).
import java.applet.*;
import java.awt.*;
60 DPP
CORE JAVA
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.
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.
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.
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 −
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">
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.
setBackground (Color.black);
setForeground (fg);
}
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.
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>
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.
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 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.
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.
Method Description
public void setSize(int width,int sets the size (width and height) of the
height) component.
To create simple awt example, you need a frame. There are two ways to create a frame in
AWT.
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
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
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
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){}
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
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
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
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:
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component
is displayed in each rectangle.
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.
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.
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.
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:
74 DPP
CORE JAVA
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.
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.
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.
Java GridBagLayout
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
weights.
77 DPP
CORE JAVA
78 DPP