0% found this document useful (0 votes)
10 views

Complete Java Notes Axis

The document provides an introduction to the Java programming language including: 1) Java was developed by Sun Microsystems in 1991 and is now owned by Oracle. It is a simple, platform independent language for application programming. 2) The Java programming process involves writing source code, compiling it to bytecode using javac, and executing the bytecode using the Java Virtual Machine (JVM). 3) Key features of Java include its object oriented design, robustness through features like garbage collection, and portability through platform independent bytecode.

Uploaded by

halfengineer470
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Complete Java Notes Axis

The document provides an introduction to the Java programming language including: 1) Java was developed by Sun Microsystems in 1991 and is now owned by Oracle. It is a simple, platform independent language for application programming. 2) The Java programming process involves writing source code, compiling it to bytecode using javac, and executing the bytecode using the Java Virtual Machine (JVM). 3) Key features of Java include its object oriented design, robustness through features like garbage collection, and portability through platform independent bytecode.

Uploaded by

halfengineer470
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Introduction to Java programming

JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It
was developed by James Gosling and Patrick Naughton. It is a simple programming
language. Writing, compiling and debugging a program is easy in java. It helps to create
modular programs and reusable code.

Java Terminology

Java Virtual Machine (JVM) :

1) First Phase, Writing of the program

2) Second Phase, Compilation of program is done by javac compiler. It takes java program as
input and generates java bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run
phase.

Compilation Flow:

When we compile Java program using javac tool, the Java compiler converts the source code into
byte code.

JVM is to execute the bytecode produced by compiler. Each operating system has different
JVM; however the output they produce after execution of bytecode is same across all
operating systems. That is why we call java as platform independent language.

Bytecode: JDK compiles the java source code into bytecode so that it can be executed by JVM.
The bytecode is saved in a .class file by compiler.
Java Development Kit(JDK): This is complete java development kit that includes JRE (Java
Runtime Environment), compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on computer.

Java Runtime Environment (JRE)

JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your
system, you can run a java program however you won’t be able to compile it.

Main Features of JAVA

Java is a platform independent language

Compiler (javac) converts source code (.java file) to the byte code (.class file). As mentioned
above, JVM executes the bytecode produced by compiler. This byte code can run on any
platform such as Windows, Linux, and Mac OS etc. Which means a program that is compiled on
windows can run on Linux and vice-versa. Each operating system has different JVM; however
the output they produce after execution of bytecode is same across all operating systems. That is
why we call java as platform independent language.

Java is an Object Oriented language

Object oriented programming is a way of organizing programs as collection of objects, each of


which represents an instance of a class.

4 main concepts of Object Oriented programming are:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Simple

Java is considered as one of simple language because it does not have complex features like
Operator overloading, multiple inheritance, pointers and explicit memory allocation.

Robust Language

Robust means reliable. Java programming language is developed in a way that puts a lot of
emphasis on early checking for possible errors, that’s why java compiler is able to detect errors
that are not easy to detect in other programming languages. The main features of java that makes
it robust are garbage collection, Exception Handling and memory allocation.
Secure: don’t have pointers. That’s why several security flaws like stack corruption or buffer
overflow is impossible to exploit in Java.

Java is distributed

Using java programming language we can create distributed applications. RMI (Remote Method
Invocation) and EJB (Enterprise Java Beans) are used for creating distributed applications in
java.

Multithreading

Java supports multithreading. Multithreading is a Java feature that allows concurrent execution
of two or more parts of a program for maximum utilization of CPU.

Portable

Java code that is written on one machine can run on another machine. The platform independent
byte code can be carried to any platform for execution that makes java code portable.
Difference between C++ vs Java

Comparison C++ Java


Index

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
Windows-based, web-based,
enterprise, and mobile
applications.

Design Goal C++ was designed for systems Java was designed and created as
and applications programming. It an interpreter for printing systems
was an extension of the C but later extended as a support
programming language. network computing. It was
designed to be easy to use and
accessible to a broader audience.

Goto C++ supports the goto statement. Java doesn't support the goto
statement.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can be
achieved by using interfaces in
java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You can Java supports pointer internally.
write a pointer program in C++. However, you can't write the
pointer program in java. It means
java has restricted pointer support
in java.

Compiler and C++ uses compiler only. C++ is Java uses both compiler and
Interpreter compiled and run using the interpreter. Java source code is
compiler which converts source converted into bytecode at
code into machine code so, C++ compilation time. The interpreter
is platform dependent. executes this bytecode at runtime
and produces output. Java is
interpreted that is why it is
platform-independent.
Call by Value C++ supports both call by value Java supports call by value only.
and Call by and call by reference. There is no call by reference in
reference java.

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread Support C++ doesn't have built-in support Java has built-in thread support.
for threads. It relies on third-
party libraries for thread support.

Documentation C++ doesn't support Java supports documentation


comment documentation comments. comment (/** ... */) to create
documentation for java source
code.

Virtual Keyword C++ supports virtual keyword so Java has no virtual keyword. We
that we can decide whether or can override all non-static
not to override a function. methods by default. In other
words, non-static methods are
virtual by default.

unsigned right C++ doesn't support >>> Java supports unsigned right shift
shift >>> operator. >>> operator that fills zero at the
top for the negative numbers. For
positive numbers, it works same
like >> operator.

Inheritance Tree C++ always creates a new Java always uses a single
inheritance tree. inheritance tree because all classes
are the child of the Object class in
Java. The Object class is the root
of the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with


hardware.

Object-oriented C++ is an object-oriented Java is also an object-


language. However, in the C oriented language. However,
language, a single root hierarchy everything (except fundamental
is not possible. types) is an object in Java. It is a
single root hierarchy as everything
gets derived from
java.lang.Object.
Java Install

Some PCs might have Java already installed.

To check if you have Java installed on a Windows PC, search in the start bar for Java or type the
following in Command Prompt (cmd.exe):

C:\Users\Your Name>java -version

If Java is installed, you will see something like this (depending on version):

java version "11.0.1" 2018-10-16 LTS


Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)

Setup for Windows

To install Java on Windows:

1. Go to "System Properties" (Can be found on Control Panel > System and Security >
System > Advanced System Settings)
2. Click on the "Environment variables" button under the "Advanced" tab
3. Then, select the "Path" variable in System variables and click on the "Edit" button
4. Click on the "New" button and add the path where Java is installed, followed by \bin. By
default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was
specified when you installed it). In that case, You will have to add a new path
with: C:\Program Files\Java\jdk-11.0.1\bin
Then, click "OK", and save the settings
5. At last, open Command Prompt (cmd.exe) and type java -version to see if Java is
running on your machine

Show how to install Java step-by-step with images »


Step 1
Step 2
Step 3
Step 4

Step 5

Write the following in the command line (cmd.exe):

C:\Users\Your Name>java -version

If Java was successfully installed, you will see something like this (depending on version):

java version "11.0.1" 2018-10-16 LTS


Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)
Let's create our first Java file, called Main.java, which can be done in any text editor (like
Notepad).

The file should contain a "Hello World" message, which is written with the following code:

Save the code in Notepad as "Main.java". Open Command Prompt (cmd.exe), navigate to the
directory where you saved your file, and type "javac Main.java":

This will compile your code. If there are no errors in the code, the command prompt will take
you to the next line. Now, type "java Main" to run the file:

The output should read:


Parameters used in First Java Program
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an object to
invoke the static method. The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it in
coming section.
o System.out.println() is used to print statement. Here, System is a class, out is an object
of the PrintStream class, println() is a method of the PrintStream class. We will discuss
the internal working of System.out.println() statement in the coming section.

In how many ways we can write a Java program?

There are many ways to write a Java program. The modifications that can be done in a Java
program are given below:

1) By changing the sequence of the modifiers, method prototype is not changed in Java.

Let's see the simple code of the main method.

static public void main(String args[])


2) The subscript notation in the Java array can be used after type, before the variable or
after the variable.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
3) You can provide var-args support to the main() method by passing 3 ellipses (dots)
public static void main(String... args)

4) Having a semicolon at the end of class is optional in Java.


Let's see the simple code.

class A{
static public void main(String... args){
System.out.println("hello java4");
}
};

Valid Java main() method signature


public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)
public static final void main(String[] args)
final public static void main(String[] args)
final strictfp public static void main(String[] args)

Invalid Java main() method signature


public void main(String[] args)
static void main(String[] args)
public void static main(String[] args)
abstract public static void main(String[] args)
JVM (Java Virtual Machine) Architecture

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java byte code can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by
Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.

What it does

The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

Java Comments

Comments can be used to explain Java code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.

Single-line Comments

Single-line comments start with two forward slashes (//).

Java Data Types

here are two data types available in Java −

 Primitive Data Types


 Reference/Object Data Types

1. Java Primitive Data Types

Primitive data types are predefined by the language and named by a keyword. There are eight
primitive data types supported by Java.
Data Type Size Description

Byte 1 byte Stores whole numbers from -128 to 127

Short 2 bytes Stores whole numbers from -32,768 to 32,767

Int 4 bytes Stores whole numbers from -2,147,483,648 to


2,147,483,647

Long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808


to 9,223,372,036,854,775,807

Float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7


decimal digits

Double 8 bytes Stores fractional numbers. Sufficient for storing 15


decimal digits

Boolean 1 bit Stores true or false values

Char 2 bytes Stores a single character/letter or ASCII values

Java divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &


bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator Example: ++ and –

public class OperatorExample{


public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}

Java Arithmetic Operator Example

public class OperatorExample{

public static void main(String args[]){


int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Java Control Statements | Control Flow in Java

Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be used
to control the flow of Java code. Such statements are called control flow statements. It is one of
the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.

if(condition) {
statement 1; //executes when condition is true
}

Example:

class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}}}

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

Example:
class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}}}

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.

Syntax of if-else-if statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

Example:
class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
} } }

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.

The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;
. . .
case valueN:
statementN;
break;
default:
default statement; }

Example:

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
} }}

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of instructions
in a repeated order. The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Java for loop


for(initialization, condition, increment/decrement) {
//block of statements
}
EXAMPLE:

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
} }

Java for-each loop

Java provides an enhanced for loop to traverse the data structures like array or collection. In the
for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in
java is given below.

for(data_type var : array_name/collection_name){


//statements
}

Example:
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}} }
Java while loop

The while loop is also used to iterate over the number of statements multiple times. However, if
we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.

The syntax of the while loop is given below.

while(condition){
//looping statements }

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
What is an object in Java

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc.
An object has three characteristics:
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. However, 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, known as its state. It is used
to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.

What is a 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;
}

Instance variable in Java : A variable which is created inside the class but outside the method
is known as an instance variable. Instance variable doesn't get memory at compile time. It gets
memory at runtime when an object or instance is created. That is why it is known as an instance
variable.

Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method
Code Reusability
Code Optimization

Object and Class Example: main within the class


class Student{
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Object and Class Example: main outside the class


class S1tudent{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
} }

Ways to initialize object

There are 3 ways to initialize object in Java.


By reference variable
By method
By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we are
going to initialize the object through a reference variable.

Example :
class Student{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
}}

2) Object and Class Example: Initialization through method

class Student {
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4 {
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
}}
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

Rules for creating Java constructor


There are two rules defined for the constructor.
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:
 Default constructor (no-arg constructor)
 Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter. The default
constructor is used to provide the default values to the object like 0, null, etc., depending on the
type.

Syntax of default constructor:


<class_name>()
{
}

Example:
class Bike1{
Bike1(){
System.out.println("Bike is created");
}
public static void main(String args[])
{

Bike1 b=new Bike1();


}
}
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}

Example of parameterized constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

class Student4{
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();
}}
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.

Example of Constructor Overloading


class Student5{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}}
There are many differences between constructors and methods. They are given below

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the behavior
object. of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor The method is not provided by the
if you don't have any constructor in a class. compiler in any case.

The constructor name must be same as the class The method name may or may not be
name. same as the class name.

this keyword in Java

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

Usage of Java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
Understanding the problem without this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:
111 ankit 5000.0
112 sumit 6000.0

If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
Inheritance in Java
It is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).
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 the parent
class. Moreover, you can add new methods and fields in your current class also.

Why use inheritance in java


 For Method Overriding
 For Code Reusability

The 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.

Example:

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);
}
}

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

When one class inherits multiple classes, it is known as multiple inheritances.


For Example:

Single 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();
}}
Multilevel Inheritance Example

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

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
 Abstract class
 Interface

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the
method

Example of abstract class


abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example of abstract method
abstract void printStatus();//no method body and abstract
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();
} }

Interface in Java

Interface just like a class, which contains only abstract method.


An interface in Java is a blueprint of a class. It has static constants and abstract methods.
To achieve a interface in java implements keywords is used.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Why use Java interface?


There are mainly three reasons to use interface.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritances.
Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.

Example:

import java.util.Scanner;
interface client
{
void input();
void output();
}
class Raju implements client{
String name; double sal;
public void input()
{
Scanner r=new Scanner(System.in);
System.out.println("enter name");
name=r.nextLine();
System.out.println("enter salary");
sal=r.nextDouble();
}
public void output()
{
System.out.println(name+ "" + sal);
}
public static void main( String args[]){
client c= new Raju();
c.input();
c.output();
}
}
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two forms,
Built-in package and
User-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
4) The package keyword is used to create a package in java.

Simple example of java package

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to access package from another package?

There are three ways to access the package from outside the package.
import package.*;
import package.classname;

fully qualified name.


1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.

Example of package by import fully qualified name


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
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 platforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet:
 Plugin is required at client browser to execute applet.
 Hierarchy of Applet

Lifecycle of Java Applet:


 Applet is initialized.
 Applet is started.
 Applet is painted.
 Applet is stopped.
 Applet is destroyed.
o init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init() method
within the applet.
o start(): The start() method contains the actual code of the applet and starts the applet. It
is invoked immediately after the init() method is invoked. Every time the browser is
loaded or refreshed, the start() method is invoked. It is also invoked whenever the applet
is maximized, restored, or moving from one tab to another in the browser. It is in an
inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to another in
the browser, the stop() method is invoked. When we go back to that page, the start()
method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is invoked
when the applet window is closed or when the tab containing the webpage is closed. It
removes the applet object from memory and is executed only once. We cannot start the
applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.

Sequence of method execution when an applet is executed:

1. init()
2. start()
3. paint()

Sequence of method execution when an applet is executed:

1. stop()
2. destroy()

Flow of Applet Life Cycle:

These methods are invoked by the browser automatically. There is no need to call them
explicitly.
How to run an Applet?

There are two ways to run an applet


 By html file.
 By appletViewer tool (for testing purpose).

How to run an Applet?


To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.

Example
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.html

Example:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180); } }

HTML Code:
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body> </html>
Java AWT

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).
It was developed by Sun Microsystems In 1995. It is heavy-weight in use because it is generated
by the system’s host operating system. It contains a large number of classes and methods, which
are used for creating and managing GUI.
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Characteristics:
 It is a set of native user interface components.
 It is very robust in nature.
 It includes various editing tools like graphics tool and imaging tools.
 It uses native window-system controls.
 It provides functionality to include shapes, colors and font classes.

Advantages
 It takes very less memory for development of GUI and executing programs.
 It is highly stable as it rarely crashes.
 It is dependent on operating system so performance is high.
 It is easy to use for beginners due to its easy interface.
Disadvantages
 The buttons of AWT does not support pictures.
 It is heavyweight in nature.
Two very important components trees and tables are not present.
AWT Hierarchy
Component:
In the AWT class hierarchy, the Component class is derived from the Object class. Component
class is an abstract class. It is the superclass of all the GUI element classes like Container,
Button, Label, Checkbox, Choice, and List. Therefore, Component class is responsible for an
overall graphical interface.

Container:
A Container in AWT is a component, which holds all the other components used for building the
interface. We can insert another container inside the main container.
There are four types of container available in AWT:

Window:
A window is a rectangular box shaped area displayed on the screen. It is an instance of Window
class. It does not have any menu bar, toolbar, or border. It should always be placed inside
another window, frame, or dialog.

Frame:
A Frame is a subclass of Window. It has a border, menu bar, title bar. The size of the frame can
also be changed. It can hold all other AWT components like buttons, checkboxes, etc. Frames
are the most widely used type of AWT container.

Dialog:
Dialog is a subclass of Window. It contains a border and title bar. To create a dialog object, an
instance of the associated Frame class is always needed.
Panel:
A Panel is a subclass of Container. The Panel does not have any border, title bar, or menu bar. It
is a generic container that holds other GUI components. An instance of Panel class is necessary
in order to insert the components.
Button:
The Button class allows the developer to create a button with an appropriate label on it. It also
provides a way to define functionality after clicking the button.
List:
A List class is used to display a list of required items. Using a list, the user can select one or
multiple items in it.
Checkbox:
A Checkbox can be used when an application wants the user to choose from either true or false.
Label:
A Label provides descriptive text information on the application window. It is placed inside a
container.
Choice:
A Choice class is used to display a drop-down menu. The selected choice can be seen on the
head.

AWT Classes:
The various AWT classes have their own constructors and methods. Some of these constructors
and methods of AWT classes are explained below.
Window:
The Window class is the area where other graphical components are placed. It do not consists of
a border and menu bar.
Constructors of the Window class
Constructor Description

Window(Frame parentframe) Creates a new Window inside the specified Frame.

Window(Window parentwindow) Creates a new Window inside the specified Window.

Window(Window parentwindow, Creates a new Window inside the specified Window with a
GraphicsConfigurationgc) GraphicsConfiguration of the display device.
Methods of the Window class
Method Description

voidpaint(Graphics g) Paints the window.

void setIconImage(Image ig) Uses the image in argument as the icon of the window.
Sets the size of window with values of height and width
void setSize(int width, int height)
arguments.

void setBounds(int x, int y, int width, int Used to set the height and width of the window using initial
height) points x and y.

Window getOwner() Returns the parent frame or window of the current window.

Frame
The Frame is a subclass of Window. It has a border, title bar, and menu bar. Frame class has its
default layout as BorderLayout.

Constructors of the Frame Class


Constructor Description

Frame() Creates a new Frame object.

Creates a new Frame with a GraphicsConfiguration of the display


Frame(GraphicsConfigurationgc)
device.

Frame(String name) Creates a new frame with a name passed as a title of the frame.
Methods of the FrameClass
Method Description

Checks whether the frame is resizable. Returns True or False


booleanisResizable()
accordingly.

MenuBargetMenuBar() Returns the menu bar of the Frame.

void setMenuBar(MenuBar
Sets the menu bar of the Frame to another specified Frame.
m)

void setState(int s) Sets the state of the Frame.

void setTitle(String t) Changes the title of the Frame with the new title specified.
Panel:
A Panel is a subclass of Container. The Panel does not have any border, title bar, or menu bar. It
has FlowLayout as its default layout.
Constructors of Panel Class
Constructor Description

Panel() Constructs a new Panel using FlowLayout.

Panel(LayoutManagerlm) Constructs a new Panel with the mentioned layout.

Methods of Panel Class

Description
Method

void addNotify() Makes the Panel visible on the device.

AccessibleContextgetAccessibleContext() Returns the AccessibleContext connected to the Panel.

Dialog:
Dialog is a subclass of Window. It contains a border and title bar.
Constructors of the Dialog Class
Constructor Description

Creates a new dialog with the connected parent dialog and without any
Dialog(Dialog Parent)
title.

Dialog(Dialog Parent, String Creates a new dialog with the connected parent dialog and with the
s) mentioned title.

Creates a new dialog with assigned Frame as a parent and without any
Dialog(Frame Parent)
title.

Dialog(Frame Parent, String Creates a new dialog with assigned Frame as a parent and with the
s) mentioned title.
Methods of the Dialog Class
Method Description

String getTitle() Returns the assigned title of the Dialog.

Boolean isResizable() Checks whether the dialog is resizable. Returns True or False accordingly.
void setTitle(String s) Changes the title of the dialog with the new specified title.

void setVisible(boolean b) Hides or displays the dialog according to the argument value passed.

Programs for AWT Classes


The following programs demonstrate the implementation of AWT classes with their methods and
constructors using Java programming.

SampleFrame.java

import java.awt.*;
public class SampleFrame extends Frame
{
SampleFrame()
{
/* Declare a button */
Button b1=new Button("Button!!");
/* Position the button on screen */
b1.setBounds(50,50,50,50);
/* Add button on the frame */
add(b1);
/* Set width and height of the frame*/
setSize(500,300);
/* Set title of the Frame */
setTitle("This is my First AWT example");
/* Set the layout for the Frame */
setLayout(new FlowLayout());
/* Display the frame on screen */
setVisible(true);
}
/* Driver Code */
public static void main(String args[])
{
SampleFramefr = new SampleFrame();
}
}
Output:

Class SampleFrame inherits the Frame class in order to construct a new empty frame.
A button b1 is created using the Button class. The size of the button and window is adjusted.
The button is placed on the frame using the add() method. And the title of the Frame is set using
the setTitle() method.

Finally the Frame is displayed on the screen using the setVisible() method.

SamplePanel.java

import java.awt.*;
/* Parent Frame */
class SampleJavaPanel extends Frame
{
/* Create instances of Panel class */
Panel p1,p2,p3 ;
/* Create instances of Label class */
Label lb1,lb2,lb3;
SampleJavaPanel()
{
setLayout(new FlowLayout());
/* Panel 1: Adds a label and button on Panel 1 */
p1 = new Panel();
lb1 = new Label("Panel 1 Red");
p1.add(lb1);
Button bt1 = new Button("Button 1");
p1.add(bt1);
p1.setBackground(Color.red);
add(p1);
/* Panel 2 Adds a label and button on Panel 2 */
p2=new Panel();
lb2 = new Label("Panel 2 Blue");
p2.add(lb2);
Button bt2 = new Button("Button 2");
p2.add(bt2);
p2.setBackground(Color.blue);
add(p2);
}
}
public class SamplePanel
{
/* Driver Code */
public static void main(String[] args)
{
/* Creates an instance of SampleJavaPanel. */
SampleJavaPanelpanelframe = new SampleJavaPanel();
/* Sets the title of the Frame. */
panelframe.setTitle("Java AWT Panels Example");
/* Sets the size of the Frame. */
panelframe.setSize(500,300);
/* Displays the Frame containing Panel on Screen. */
panelframe.setVisible(true);
}
}
Output:

In the above code , the class SamplePanel constructs a Frame with panelframe as an instance
name. And the constructor SampleJavaPanel() of class SampleJavaPanelconstructs two
panels’ p1 and p2 with labels lb1 and lb2, buttons b1 and b2 on it, respectively.
SampleDialog.java
import java.awt.*;
import java.awt.event.*;
public class SampleDialog
{
/* Driver Code */
public static void main(String[] args)
{
/* Creates a Frame. */
Frame frame = new Frame("Java AWT Dialog Example");
frame.setLayout(new FlowLayout());
frame.setSize(400, 400);
frame.setBackground(Color.white);
frame.setVisible(true);
/* Creates a dialog inside the Frame. */
Dialog d1 = new Dialog(null, true);
d1.setLayout(new FlowLayout());
d1.setTitle("Java Dialog");
d1.setSize(400, 200);
d1.setBackground(Color.gray);
/* Creates a Button displayed on the Dialog. */
Button bt1 = new Button("Button!!");
bt1.setSize(20,10);
d1.add(bt1);
d1.setVisible(true);
}
}
Output:
Here, the class SampleDialog constructs a Frame with frame as an instance name. Using the
methods of Frame class properties like frame layout, frame size, background color and frame
visibility are set. Dialog d1 is created and its properties are set using methods given
in Dialog class. Buttonbt1 is added on the dialog. And lastly, visibility of d1 is set to True so that
the dialog box is visible.
SampleButton.java
import java.awt.*;
public class SampleButton
{
/* Creates object of Frame and Button. */
Frame f;
Button bt1, bt2, bt3;
SampleButton()
{
f = new Frame("Java AWT Button Example");
/* Create Buttons bt1, bt2, bt3. */
bt1= new Button();
bt2= new Button("Click here");
bt3= new Button();
/* Sets text on the Button. */
bt3.setLabel("Button3");
/* Add Buttons on the Frame. */
f.add(bt1);
f.add(bt2);
f.add(bt3);
/* Set properties of the Frame. */
f.setLayout(new FlowLayout());
f.setSize(260,220);
f.setVisible(true);
}
/* Driver Code */
public static void main(String[] ar)
{
SampleButtonsb = new SampleButton();
}
}
Output:

In the above code snippet, the class SampleButton constructs a Frame with f as an instance name.
And the constructor SampleButton() of class SampleButtoncreates three Buttons bt1,
bt2, and bt3.
SampleList.java
import java.awt.*;
public class SampleList
{
/* Creates object of Frame, List, Label and String array. */
Frame f;
List list;
Label lb1;
String[] country;
SampleList()
{
f = new Frame("Java AWT List Example");
/* Creates a list with 6 items. */
list= new List(6);
lb1 = new Label("Select your country from the list: ");
/* Adding items in the list. */
list.add("India");
list.add("Australia");
list.add("America");
list.add("Russia");
list.add("France");
list.add("China");
/* Add label and list on the Frame. */
f.add(lb1);
f.add(list);
/* Set properties of the Frame. */
f.setLayout(new FlowLayout());
f.setSize(260,220);
f.setVisible(true);
}
/* Driver Code */
public static void main(String[] ar)
{
SampleListsl = new SampleList();
}
}
Output:

In the above code snippet, the class SampleList constructs a Frame with f as an instance name.
And the constructor SampleList() of class SampleListcreates a list with 6 items in the list.
The list and Label lb1 is added to the Frame f.
SampleCheckbox.java
import java.awt.*;
public class SampleCheckbox
{
/* Creates object of Frame and Checkbox. */
Frame f;
Checkbox cb1, cb2, cb3;
SampleCheckbox()
{
f= new Frame("Java AWT Checkbox Example");
/* Creates a no message Checkbox. */
cb1 = new Checkbox();
/* Creates a pre-selected Checkbox with a message. */
cb2 = new Checkbox("Yes",true);
/* Creates an unselected Checkbox with a message. */
cb3 = new Checkbox("No");
/* Add Checkboxes on the Frame. */
f.add(cb1);
f.add(cb2);
f.add(cb3);
/* Set properties of the Frame. */
f.setLayout(new GridLayout());
f.setSize(260,220);
f.setVisible(true);
}
/* Driver Code */
public static void main(String[] ar)
{
SampleCheckboxsc = new SampleCheckbox();
}
}
Output:
In the above code snippet, the class SampleCheckbox constructs a Frame with f as an instance
name. And the constructor SampleCheckbox() of class SampleCheckboxcreates three
Checkboxes cb1with no message,cb2 with a message, checked value and cb3 with a message and
unchecked value.
SampleLable.java
import java.awt.*;
public class SampleLabel
{
/* Creates object of Frame and Label. */
Frame f;
Label lb1, lb2, lb3, lb4;
SampleLabel()
{
f = new Frame("Java AWT Label Example");
lb1 = new Label("Hi!");
lb2 = new Label("Good Morning!!");
lb3 = new Label("Have a great day, Take care!");
lb4 = new Label("Thanks");
/* Setting text on the Labels. */
lb4.setText("Thank you and Hello!");
/* Add Labels on the Frame. */
f.add(lb1);
f.add(lb2);
f.add(lb3);
f.add(lb4);
/* Set properties of the Frame. */
f.setLayout(new FlowLayout());
f.setSize(260,220);
f.setVisible(true);
}
/* Driver Code */
public static void main(String[] ar)
{
SampleLabelsl = new SampleLabel();
}
}
Output:
In the above code snippet, the class SampleBLabelconstructs a Frame with f as an instance name.
And the constructor SampleLabel() of class SampleLabelcreates for Labels lb1,lb2, lb3, and lb4.
The Labels are added on the Frame f.
SampleChoice.java
import java.awt.*;
public class SampleChoice
{
/* Creates object of Frame, Choice, Label and Button. */
Frame f;
Choice ch;
Label lb1;
Button bt1;
SampleChoice()
{
f = new Frame("Java AWT Choice Example");
ch = new Choice();
lb1 = new Label("Select your country from the Menu: ");
/* Adding items in the list. */
ch.add("India");
ch.add("Australia");
ch.add("America");
ch.add("Russia");
ch.add("France");
ch.add("China");
bt1= new Button("Submit");
/* Add label and choice menu on the Frame. */
f.add(lb1);
f.add(ch);
f.add(bt1);
/* Set properties of the Frame. */
f.setLayout(new FlowLayout());
f.setSize(260,220);
f.setVisible(true);
}
/* Driver Code */
public static void main(String[] ar)
{
SampleChoicesl = new SampleChoice();
}
}
Output:

In the above code snippet, the class SampleChoice constructs a Frame with f as an instance
name. And the constructor SampleChoice() of class SampleChoicecreates a Choice ch. Total 6
Items are added to the choice list. And the choice ch is added to Frame f.
This article explains the basic concept of Java AWT classes with their constructors and methods.
We have also discussed how to implement AWT classes using the methods available
in java.awt package.

Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT,
there are classes for each component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them to a container.
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.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a
container inside container.
Types of containers:
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog
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. We need to create an instance of Window class to create
this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have
other components like button, text field, scrollbar etc. Frame is most widely used container while
developing an AWT application.
Useful Methods of Component Class

Method Description

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

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

public void setLayout(LayoutManager m) Defines the layout manager for the component.

public void setVisible(boolean status) Changes the visibility of the component, by default
false.
Java AWT Example
To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.
By extending Frame class (inheritance)
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.

AWTExample1.java
// importing Java AWT class
import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


b.setBounds(30,100,80,30);

// adding button into frame


add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample1 f = new AWTExample1();

}
download this example
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example
that sets the position of the awt button.
Output:

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
creating a TextField, Label and Button component on the Frame.
AWTExample2.java
// importing Java AWT class
import java.awt.*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

// creating a Frame
Frame f = new Frame();

// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);

// adding components into frame


f.add(b);
f.add(l);
f.add(t);

// frame size 300 width and 300 height


f.setSize(400,300);

// setting the title of frame


f.setTitle("Employee info");

// no layout
f.setLayout(null);

// setting visibility of frame


f.setVisible(true);
}

// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

}
download this example
Output:
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.
Classification of Events
Foreground Events
Background Events

Types of Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events
are generated due to interaction by the user on components in Graphic User Interface (GUI).
Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an
event occur. To handle the events, Java follows the Delegation Event model.
Delegation Event model
It has Sources and Listeners.

Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate
events.
Listeners: Listeners are used for handling the events generated from the source. Each of these
listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.
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

Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:
Within class
Other class
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);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}

2) 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
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");
}
}

3) Java event handling by anonymous class


import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}

You might also like