Download as pdf or txt
Download as pdf or txt
You are on page 1of 95

Every programing language have their own syntax and semantics.

The syntax is the rule of the language


and the semantics is the meaning of those syntax. The Java language specification is a technical
definition of the language that includes the syntax and semantics of the Java programming language. The
application program interface (API) contains predefined classes and interfaces for
developing Java programs.

Java is a full-fledged and powerful language that can be used in many ways. It comes in
three editions: Java Standard Edition (Java SE), Java Enterprise Edition (Java EE), and Java
Micro Edition (Java ME). Java SE can be used to develop client-side standalone applications
or applets. Java EE can be used to develop server-side applications, such as Java servlets and
Java Server Pages. Java ME can be used to develop applications for mobile devices, such as
cell phones. For this course Java SE is used.

There are many versions of Java SE. Sun releases each version with a Java Development Toolkit (JDK).

JDK consists of a set of separate programs, each invoked from a command line, for developing and testing
Java programs. Besides JDK, you can use a Java development tool (e.g., NetBeans, Eclipse, and TextPad)
software that provides an integrated development environment (IDE) for rapidly developing Java
programs. Editing, compiling, building, debugging, and online help are integrated in one graphical user
interface. The two popular java editors are:

Netbeans: is a Java IDE that is open-source and free which can be downloaded from
http://www.netbeans.org/index.html.
Eclipse: is also a Java IDE developed by the eclipse open-source community and can be
downloaded from http://www.eclipse.org/. Eclipse is selected for this course class exercise and lab
exercise.
Figure 1, The Java program-development process consists of repeatedly creating/modifying source
code, compiling, and executing programs

The Java language is a high-level language while Java bytecode is a low-level language. The bytecode
is similar to machine instructions but is architecture neutral and can run on any platform that has
a Java Virtual Machine (JVM), as shown in Figure below Rather than a physical machine, the
virtual machine is a program that interprets Java bytecode. This is one of Java’s primary advantages:
Java bytecode can run on a variety of hardware platforms and operating systems.

Figure 2 Java is platform independent

What is JVM, and JRE?

2
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed. JVMs are available for many hardware and
software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS
differs. But, Java is platform independent.

JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It is the
implementation of JVM. It physically exists. It contains set of libraries + other files that JVM uses at
run time. Implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.

JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.

Figure 3JDK, JVM, and JRE

 Assignment: read about the properties of Java in detail.

Java development environment

You must first install and configure JDK before compiling and running programs.

Once you installed Java and JDK on your machine, you would need to set the PATH environment
variables to point to correct installation directories:

3
The path environment variable on your computer designates which directories the computer searches
when looking for applications, such as the applications that enables you to compile and run your java
applications (called javac.exe and java.exe respectively).

Assuming you have installed Java in c:\Program Files\Java\jdk Version\bin; directory. Copy this path
and follow the following steps to set up the Path environmental variable.

1) Opening the system properties dialog. Right click on my computer icon on your desktop and
select properties from the menu.
2) Opening the environment variable dialog. Select the advanced tap at the top of the system
properties dialog. Click the environment variables button to display the environment variable
dialog.
3) Editing the Path variable. Scroll down inside the system variables box to select the PATH
variable. Click the Edit button. This will cause the Edit system variable dialog to appear.
4) Changing the contents of the PATH variable. Place the curser inside the variable value field.
Use the left-arrow key to move the cursor to the beginning of the list. At the beginning of the
list, past the name of the JDK path file (c:\Program Files\Java\jdk Version\bin ;).

When we consider a Java program it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods and
instance variables mean.

 Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
 Class - A class can be defined as a template/ blue print that describes the behaviors/states
that object of its type support.
 Methods - A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.
 Instance Variables - Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.

Basic Syntax

When you are think to write a program using Java programming language, it is very important to keep
in mind the following points.

 Case Sensitivity - Java is case sensitive, which means identifier Hello and 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 letters hould be in Upper Case.
Example: class MyFirstJavaClass

4
 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 (Stringargs[]args) - Java program processing starts from the main
method which is a mandatory part of every Java program.

Let us begin with a simple Java program that displays the message “Welcome to Java!”

Welcome.java // file name always must be the same with the class name
1 public class Welcome {
2 public static void main(String[] args) {
3 // Display message Welcome to Java! to the console
4 System.out.println("Welcome to Java!");
5 }

6 }

Displays Welcome to Java!

Description of the Program

The line numbers are displayed for reference purposes but are not part of the program. So, don’t type line
numbers in your programs.

Line 1 defines a class. Every Java program must have at least one class. Each class has a
name. By convention, class names start with an uppercase letter. In this example, the class
name is Welcome.

Line 2 defines the main method. In order to run a class, the class must contain a method named main.
The program is executed from the main method. A method is a construct that contains statements. The
main method in this program contains the System.out.println statement. This statement prints a
message "Welcome to Java!" to the console (line 4). Every statement in Java ends with a semicolon
(;), known as the statement terminator.
Reserved words, or keywords, have a specific meaning to the compiler and cannot be used for other
purposes in the program. For example, when the compiler sees the word class, it understands that the
word after class is the name for the class. Other reserved words in this program are public, static, and
void.
Line 3 is a comment that documents what the program is and how it is constructed. Comments help
programmers to communicate and understand the program. They are not programming statements and
thus are ignored by the compiler. In Java, comments are preceded by two slashes (//) on a line, called a
line comment, or enclosed between /* and */ on one or several lines, called a block comment. When the
compiler sees //, it ignores all text after // on the same line. When it sees /*, it scans for the next */ and
ignores any text between /* and */. Here are examples of comments:

5
// This application program prints Welcome to Java!
/* This application program prints Welcome to Java! */
/* This application program
prints Welcome to Java! */
A pair of braces in a program forms a block that groups the program’s components. In Java, each block
begins with an opening brace ({) and ends with a closing brace (}). Every class has a class block that
groups the data and methods of the class. Every method has a method block that groups the statements
in the method. Blocks can be nested, meaning that one block can be placed within another, as shown in
the following code.

Java Identifiers:

All Java components require names. Names used for classes, variables and methods are called
identifiers. In Java, there are several points to remember about identifiers:

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

Java Keywords

Just like as C++ language or any other programming language java also have its own keywords or
reserved words. These reserved words not allowed to be used as constant or variable or any other
identifier names.
The following fifty keywords are reserved for use by the java languages:

6
Variable type

Variables are used to store values to be used later in a program. They are called variables because their
values can be changed. All variables must be declared with a name and a type before they can be used.
There are three types of variables in java.

1) 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.
2) 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.
3) Class variables: Class variables are variables declared with in a class, outside any method, with
the static keyword.

Local variable

 Local variables are declared in methods, constructors, or blocks.


 Local variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables so local variables should be declared and an initial
value should be assigned before the first use.

Here, age is a local variable. This is defined inside pupAge method and its scope is limited to this
method only.

Instance variables:

 Instance variables are declared in a class, but outside a method, constructor or any block. When a
space is allocated for an object in the heap, a slot for each instance variable value is created.
 Instance variables are created when an object is created with the use of the keyword 'new' and
destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method, constructor or
block, or essential parts of an object's state that must be present throughout the class.

7
 Instance variables can be declared in class level before or after use. Access modifiers can be
given for instance variables.
 The instance variables are visible for all methods, constructors and block in the class. Normally,
it is recommended to make these variables private accesslevel. However visibility for subclasses
can be given for these variables with the use of access modifiers.
 Instance variables have default values. For numbers the default value is 0, for Booleans it is false
and for object references it is null. Values can be assigned during the declaration or within the
constructor.
 Instance variables can be accessed directly by calling the variable name inside the class.
However within static methods and different class when instance variables are given
accessibility should be called using the fully qualified name: Object Reference. Variable Name.

Import java.io.*;

What is the output of this program?

Class/static variables:

 Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block. There would only be one copy of each class variable per
class, regardless of how many objects are created from it.

8
 Static variables are rarely used other than being declared as constants. Constants are variables that
are declared as public/private, final and static. Constant variables never change from their initial
value.
 Static variables are stored in static memory. It is rare to use static variables other than declared final
and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program stops.
Visibility is similar to instance variables. However, most static variables are declared public since
they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is
false; and for object references, it is null. Values can be assigned during the declaration or within
the constructor. Additionally values can be assigned in special static initializer blocks.
 Static variables can be accessed by calling with the class name Class Name.Variable Name. When
declaring class variables as public static final, then variables names constants are all in upper case.
If the static variables are not public and final the naming syntax is the same as instance and local
variables.
What is the output of this program?

Escape sequence

There are some special characters that changes the output forms in the System.out.printl () statement.
Some of the common escape sequences are:

9
Data type

Based on the data type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory. There are two data types available in Java:

 Primitive Data Types


 Reference/Object Data Types

Primitive Data Types:

There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword. Those are byte, short, boolean, char, int, long, float, double.

Reference Data Types:

 Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.
For example, Employee, Human etc.
 Class objects, and various type of array variables come under reference data type. Default value
of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any compatible
type. Example: Animal animal = new Animal " giraffe " ;

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups:

 Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra. *, /, +, - operations

10
 Relational Operators: a condition is an expression that can be either true or false. Condition in if
statements can be formed by using the equality operators (== and !=) and relational operators
(>,<,>=,and <=)
 Bitwise Operators: Bitwise operator works on bits and performs bit-by-bit operation. Java defines
several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.
(&,|,^, ~,<<,>>)
 Logical Operators: are used to evaluate two expression based on their conditions (&&,||,!).
 Assignment Operators: are used to assign values to variable and for expressing short hand
expression (=, +=,-=,*=,/=)

 Misc Operators (conditional and instanceof): reading assignment

Increment and decrement operators: the prefixes ++x and --x are referred to, respectively, as the
preincrement operator and the predecrement operator; and the suffixes x++ and x--are referred to,
respectively, as the postincrement operator and the postdecrement operator.

The effect in expression is either to increase the value of the variable by 1 or to decrease the value by 1
before or after evaluating the expression.

11
Precedence of Java Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom. Within an expression, higher precedence operators will be evaluated first.

Though Java has its own way to evaluate an expression behind the scene, the result of a Java expression
and its corresponding arithmetic expression are the same. Therefore, you can safely apply the
arithmetic rule for evaluating a Java expression. Operators contained within pairs of parentheses are
evaluated first. Parentheses can be nested, in which case the expression in the inner parentheses is
evaluated first.

Java Package:

In simple, it is a way of categorizing the classes and interfaces. Collectively, Java’s packages are
referred to as the java class library, or the Java Application Programming Interface (Java API).
Programmers use import declarations to identify the predefined classes used in a Java program. All
import declarations must appear before the first class declaration in the file.

Example write a program that performs addition of two numbers that accepting from user.

12
Reading Input from the console

To use different value for the variable or to accept input data from the user we use the Scanner class
for console input.

Java uses System.out to refer to the standard output device and System.in to the standard input device.
Console input is not directly supported in java, but you can use the Scanner class to create an object to
read input from System.in, as follows:

Scanner input = new Scanner (System.in);

The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner input
declares that input is a variable whose type is Scanner. The whole line Scanner input = new
Scanner(System.in) creates a Scanner object and assigns its reference to the variable input. An object
may invoke its methods. To invoke a method on an object is to ask the object to perform a task. You
can invoke the methods in Table 2.1 to read various types of input.

13
 Exercise: write a java program that calculates the area of a circle, accepting the value of the
radius from the console double type.

Numeric Type Conversions

If an integer and a floating-point number are involved in a binary operation, Java automatically
converts the integer to a floating-point value. So, 3 * 4.5 is same as 3.0 * 4.5. You can always assign a
value to a numeric variable whose type supports a larger range of values; thus, for instance, you can
assign a long value to a float variable. You cannot, however, assign a value to a variable of a type with
smaller range unless you use type casting. Casting is an operation that converts a value of one data type
into a value of another data type. There are two types of casting: implicitly and explicitly type casting.

Implicitly type casting is happen automatically when a variable of a type with a small range to a
variable of a type with a larger rang. For example Java automatically converts the integer to a floating-
point value. So, 3 * 4.5 is same as 3.0 * 4.5.

Explicitly type casting is performed by its own syntax: (data type) operand or (data type) (expression);
when a variable of a type with a large range to a variable of a type smaller range. For example, the
following statement: System.out.println((int)1.7);
displays 1. When a double value is cast into an int value, the fractional part is truncated.

The String Type

The char type represents only one character. To represent a string of characters, use the data type called
String. For example, the following code declares the message to be a string with value “Welcome to
Java”.
String message = "Welcome to Java";

The String type is not a primitive type. It is known as a reference type. Any Java class can be used as a
reference type for a variable.

14
The plus sign (+) is the concatenation operator if one of the operands is a string. If one of the operands
is a non-string (e.g., a number), the non-string value is converted into a string and concatenated with
the other string. Here are some examples:

// Three strings are concatenated


String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

To read a string from the console, invoke the next() method on a Scanner object. For example, the
following code reads three strings from the keyboard:

Scanner input = new Scanner(System.in);


System.out.println("Enter three strings: ");
String s1 = input.next();

String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);

The next() method reads a string that ends with a whitespace character (i.e., ' ', '\t',
'\f', '\r', or '\n').
You can use the nextLine() method to read an entire line of text. The nextLine() method reads a string
that ends with the Enter key pressed. For example, the following statements read a line of text.

Scanner input = new Scanner(System.in);


System.out.println("Enter a string: ");
String s = input.nextLine();
System.out.println("The string entered is " + s);

Java Modifiers:

To specify the accessibility of data, class, and method java uses modifiers. There are two types of
modifiers in java:

 Access Modifiers: default, public, protected, private


 Non-access Modifiers: final, abstract, strictfp

Java provides a number of access modifiers to set access levels for classes, variables, methods
and constructors.

Default Access Modifier - No keyword:

15
Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc. A variable or method declared without any access control modifier is available to any
other class in the same package.

Example:

String version = "1.5.1";


boolean processOrder() {

return true;
}
Private Access Modifier - private:

Methods, Variables and Constructors that are declared private can only be accessed within the declared
class itself. Private access modifier is the most restrictive access level. Class and interfaces cannot be
private. Variables that are declared private can be accessed outside the class if public getter methods are
present in the class. Using the private modifier is the main way that an object encapsulates itself and
hide data from the outside world. Example

Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or
set its value directly. So to make this variable available to the outside world, we defined two public
methods: getFormat, which returns the value of format, and setFormatString, which sets its value.

Public Access Modifier - public:

A class, method, constructor, interface etc declared public can be accessed from any other class.
Therefore fields, methods, blocks declared inside a public class can be accessed from any class
belonging to the Java Universe. However if the public class we are trying to access is in a different
package, then the public class still need to be imported. Because of class inheritance, all public methods
and variables of a class are inherited by its subclasses.

Protected Access Modifier - protected: Variables, methods and constructors which are declared
protected in a superclass can be accessed only by the subclasses in other package or any class within
the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared
protected, however methods and fields in an interface cannot be declared protected. Protected access
gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class
from trying to use it.

16
Example:

Here, if we define openSpeaker method as private, then it would not be accessible from any other class
other than AudioPlayer. If we define it as public, then it would become accessible to all the outside
world. But our intension is to expose this method to its subclass only, thats why we used protected
modifier.

Java provides a number of non-access modifiers to achieve many other functionality.

 The static modifier for creating class methods and variables


 The final modifier for finalizing the implementations of classes, methods, and variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.

The static Modifier:


Static Variables:
The static key word is used to create variables that will exist independently of any instances created for
the class. Only one copy of the static variable exists regardless of the number of instances of the class.
Static variables are also known as class variables. Local variables cannot be declared static.
Static Methods:
The static key word is used to create methods that will exist independently of any instances created for
the class. Example what is the out of this program?

17
Static methods do not use any instance variables of any object of the class they are defined in. Static
methods take all the data from parameters and compute something from those parameters, with no
reference to variables. Class variables and methods can be accessed using the class name followed by a
dot and the name of the variable or method.

The final Modifier:

final Variables:

A final variable can be explicitly initialized only once. A reference variable declared final can never be
reassigned to refer to a different object. However the data within the object can be changed. So the state
of the object can be changed but not the reference. With variables, the final modifier often is used with
static to make the constant a class variable.

final Methods:

A final method cannot be overridden by any subclasses. As mentioned previously the final modifier
prevents a method from being modified in a subclass.

The main intention of making a method final would be that the content of the method should not be
changed by any outsider.

final Classes:

The main purpose of using a class being declared as final is to prevent the class from being subclassed.
If a class is marked as final then no class can inherit any feature from the final class.

The abstract Modifier:

abstract Class:

An abstract class can never be instantiated. If a class is declared as abstract then the sole purpose is for
the class to be extended.

18
A class cannot be both abstract and final. Since a final class cannot be extended. If a class contains
abstract methods then the class should be declared abstract. Otherwise a compile error will be thrown.
An abstract class may contain both abstract methods as well normal methods.

abstract Methods:An abstract method is a method declared without any implementation. The methods
body implementation is provided by the subclass. Abstract methods can never be final or strict. Any
class that extends an abstract class must implement all the abstract methods of the super class unless the
subclass is also an abstract class. If a class contains one or more abstract methods then the class must be
declared abstract.

An abstract class does not need to contain abstract methods. The abstract method ends with a
semicolon. Example: public abstract sample;

 Reading assignment about synchronized, volatile, and transient non access modifiers.

Java program statements can be executed sequentially, conditionally (with the help of if-else, and
switch), iteratively (with the help of loops) or by following a combination of all depending upon the
program logic. Conditional and iterative execution of program statements is done by control flow
statements. There are two types of control structure:

Selective (conditional) statement: if, if---else, and switch

Iterative (repetition) statements: while, do—while, and for loops.

Conditional Statements

To facilitate conditional control flow in Java there are relational and logical operators to form a
conditional expression that returns either true or false. Words true and false look like keywords but they
are boolean literals actually and cannot be used as identifiers in Java programs. Java program decides
the execution path on basis of the truth or falsehood of conditional expression.

In a Java program zero or more statements enclosed in a pair of curly braces make a block of
statements.

19
 The general syntax of if statement:

if (booleanExpression)

statement-1;

OR

if (booleanExpression) {

Statement-n;

The Boolean Expression in parentheses must return a boolean true or false or Boolean (boolean
wrapper). The expression can be a relational or logical expression or a function call that returns a
boolean literal. Above syntax will execute statement-1 to statement-n if the booleanExpression in
parentheses returns true, nothing will execute otherwise.

By default if controls only one statement, therefore if you wish to control only one statement by if, you
need not to enclose the only statement within curly braces. But, it is good to use braces every time with
if because it increases readability of the program. If there are two or more statements to be controlled
by if conditional, they all must be enclosed in curly braces. A set of statements enclosed in braces is
called a block or a compound statement.

Example if statement:

20
The output of the program is:

 Number is positive
 This statement is always executed.

Let’s assume that is the value of the variable number is -4; which statement is executed?

if----else statement

An if statement can be followed by an optional else statement, Statements inside the body of else
statement are executed if the test expression is evaluated to false. Syntax:

Let us see how does if –else statement works:

Example of if – else statement

21
When you run the program, the output will be:

 Number is positive.
 This statement is always executed.

What will be if the number value is less than 0?

Java if..else..if Statement

In Java, it's possible to execute one block of code among many. For that, you can use if..else...if ladder.

Example if..else..if

The output is:

 Number is 0.
 Assignment: read about nested if..else statements.

22
Switch Statement

A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.

The following rules apply to a switch statement:

 The variable used in a switch statement can only be integers, convertable integer’s byte, short,
char, strings and enums.
 You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch and it must be a
constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.

The syntax for switch statement is:

It's also important to note that switch statement in Java only works with:

 Primitive data types: byte, short, char and int


 Enumerated types (Java enums)
 String class
 a few classes that wrap primitive types: Character, Byte, Short, and Integer.

23
Example of java switch statements:

The output of the program is: Wednesday


Write a program using switch statements that perform arithmetic operations. The value of the variable
is from keyboard.

Loops (iterative statements)

Loop is used in programming to repeat a specific block of code until certain condition is met (test
expression is false).
Loops are what makes computers interesting machines. Imagine you need to print a sentence 50 times
on your screen. Well, you can do it by using print statement 50 times (without using loops). How about
you need to print a sentence one million times? You need to use loops.
There are three types of loops:

 while loop
 do—while loop, and for loop

24
While loop

A while loop statement in java programming language repeatedly executes a target statement as
long as a given condition is true.
The syntax of while loop is:

Flowchart of while Loop

How while loop works?

The test expression inside parenthesis is a boolean expression. If the test expression is evaluated to true,

 Statements inside the while loop are executed: then, the test expression is evaluated again. This
process goes on until the test expression is evaluated to false.
 If the test expression is evaluated to false, while loop is terminated.

Example of while loop

Example 2

25
do...while Loop

The do...while loop is similar to while loop with one key difference. The body of do...while loop is
executed for once before the test expression is checked.

How do...while loop works?


The body of do...while loop is executed once (before checking the test expression). Only then, the test
expression is checked.
If the test expression is evaluated to true, codes inside the body of the loop are executed, and the test
expression is evaluated again. This process goes on until the test expression is evaluated to false. When
the test expression is false, the do..while loop terminates.
The flow chart of do while loop

26
Example of do—while loop

for loop in java

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times. Syntax:

How for loop works?


1. The initialization expression is executed only once.
2. Then, the test expression is evaluated. Here, test expression is a boolean expression.
3. If the test expression is evaluated to true,
o Codes inside the body of for loop is executed.
o Then the update expression is executed.
o Again, the test expression is evaluated.
o If the test expression is true, codes inside the body of for loop is executed and update
expression is executed.
o This process goes on until the test expression is evaluated to false.
4. If the test expression is evaluated to false, for loop terminates.
For loop flow chart

27
Example of for loop:

Continue and break statements

Suppose you are working with loops. It is sometimes desirable to skip some statements inside the loop
or terminate the loop immediately without checking the test expression. In such cases, break and
continue statements are used.
The break statement terminates the loop immediately, and the control of the program moves to the next
statement following the loop. Syntax is: break;
How break statement work in a different loops?

Example

28
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.

 In a for loop, the continue keyword causes control to immediately jump to the update
statement.
 In a while loop or do/while loop, control immediately jumps to the Boolean expression.

How continue statement works?

Example

The output is:

10

20

40

29
An array is a group of variables (called elements or components) containing values that all have the
same type. Arrays are objects, so they are considered reference types. The elements of an array can be
either primitive types or reference types. To refer to a particular element in an array, we specify the
name of the reference to the array and the position number of the elements in the array. The position
number of the element is called the elements index or subscript.

Suppose, for instance, that you need to read 100 numbers, compute their average, and find out how
many numbers are above the average. Your program first reads the numbers and computes their
average, then compares each number with the average to determine whether it is above the average.

Instead of declaring individual variables, such as number0, number1, and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and numbers[99] to represent
individual variables.

30
Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array and specify the array’s
element type. Here is the syntax for declaring an array variable:

elementType [ ] arrayRefVar;

The elementType can be any data type, and all elements in the array will have the same data type. For
example, the following code declares a variable myList that references an array of double elements.

double [ ] myList;

Creating Arrays

You cannot assign elements to an array unless it has already been created. After an
array variable is declared, you can create an array by using the new operator with the following syntax:
arrayRefVar = new elementType[arraySize];

This statement does two things:

(1) It creates an array using new elementType[arraySize];

(2) It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below:
elementType arrayRefVar = new elementType[arraySize];
or
elementType arrayRefVar [ ] = new elementType[arraySize];

Here is an example of such a statement: double[] myList = new double[10];


This statement declares an array variable, myList, creates an array of ten elements of double type, and
assigns its reference to myList. To assign values to the elements, use the syntax:
arrayRefVar[index] = value;
For example, the following code initializes the array.
myList[0] = 5.6;
myList[1] = 4.5;
myList[2] = 3.3;
myList[3] = 13.2;

The size of an array cannot be changed after the array is created. Size can be obtained using
arrayRefVar.length. For example, myList.length is 10.

31
The array elements are accessed through their index. Array indices are range from 0 to
arrayRefVar.length-1. Each element in the array is represented using the following syntax, known as
an indexed variable:
arrayRefVar[index];

After an array is created, an indexed variable can be used in the same way as a regular variable. For

example, the following code adds the values in myList[0] and myList[1] to myList[2].
myList[2] = myList[0] + myList[1];

Array Initializers

Java has a shorthand notation, known as the array initializer, which combines in one statement
declaring an array, creating an array, and initializing, using the following syntax:
elementType[] arrayRefVar = {value0, value1, ..., valuek};
For example: double [ ] myList = {1.9, 2.9, 3.4, 3.5};

This statement declares, creates, and initializes the array myList with four elements, which is
equivalent to the statements shown below:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

The new operator is not used in the array-initializer syntax.

Using an array initializer, you have to declare, create, and initialize the array all in one statement.
Splitting it would cause a syntax error. Thus the next statement is wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};

32
When processing array elements, you will often use a for loop—for two reasons:
■ All of the elements in an array are of the same type. They are evenly processed in the same
fashion repeatedly using a loop.
■ Since the size of the array is known, it is natural to use a for loop.

Initializing arrays with input values: The following loop initializes the array myList
with user input values.
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();

Let's write a simple program to print elements of this array.

What is the output of the program?

Multidimensional Arrays

It's also possible to create an array of arrays known as multidimensional array. One-dimensional arrays
used to store linear collections of elements, and you can use a two-dimensional array to store a matrix
or a table. Two subscripts are used in a two-dimensional array, one for the row and the other for the
column, three subscripts for three-dimensional array, and soon. The index of each subscript of a two-
dimensional array is an int value, starting from 0. A two-dimensional array is actually an array in
which each element is a one-dimensional array. The length of an array x is the number of elements in
the array, which can be obtained using x.length. x[0], x[1], and x[x.length-1] are arrays.
For example, the following table that describes the distances between the cities can be stored using a
two-dimensional array.

33
How to Declare?

Here is the syntax for declaring a two-dimensional array:


elementType [ ][ ] arrayRefVar;
As an example, here is how you would declare a two-dimensional array variable matrix of
int values: int[ ][ ] matrix;

You can create a two-dimensional array of 5-by-5 int values and assign it to matrix using this syntax:
matrix = new int[5][5];

Assigning value to a specific element in two-dimensional array is possible by identifying its row and
column index. To assign the value 7 to a specific element at row 2 and column 1, you can use the
following: matrix[2][1] = 7;

int[][] a = new int[3][4]; // creating an a array; this array have 12 elements type int

How to initialize a 2d array in Java?


An array a can initialized in the following for:

Each component of array a is an array in itself, and length of each rows is also different.

34
Example

Output : Length of row 1: 3

Length of row 2: 4

Length of row 3: 1

Print all elements of 2d array Using Loop

Output:

-2

-4

35
Object-oriented programming (OOP) involves programming using objects. An object represents an
entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a
button, and even a loan can all be viewed as objects. An object has a unique identity, state, and
behavior.

 The state of an object (also known as its properties or attributes) is represented by data fields
with their current values. A circle object, for example, has a data field radius, which is the
property that characterizes a circle. A rectangle object has data fields’ width and height, which
are the properties that characterize a rectangle.
 The behavior of an object (also known as its actions) is defined by methods. To invoke a method
on an object is to ask the object to perform an action. For example, you may define a method
named getArea() for circle objects. A circle object may invoke getArea() to return its area.

Objects of the same type are defined using a common class. A class is a template, blueprint, or contract
that defines what an object’s data fields and methods will be. An object is an instance of a class. You
can create many instances of a class. Creating an instance is referred to as instantiation. A Java class
uses variables to define data fields and methods to define actions. Additionally, a class provides
methods of a special type, known as constructors, which are invoked to create a new object.

A constructor can perform any action, but constructors are designed to perform initializing actions,
such as initializing the data fields of objects. The class that contains the main method will be referred
to in this handout, for convenience, as the main class. A class that does not have main method cannot
run. In a program you can put two classes into one file, but only one class in the file can be a public
class. Furthermore, the public class must have the same name as the file name or .java extension file
name.

36
Let’s look another example about object that shares two characteristics (state, and behavior):

1. Lamp is an object
o It can be in on or off state.
o You can turn on and turn off lamp (behavior).
2. Bicycle is an object
o It has current gear, two wheels, number of gear etc. states.
o It has braking, accelerating, changing gears etc. behavior.

Before you create objects in Java, you need to define a class. A class is a blueprint for the object. We
can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors,
windows etc. Based on these descriptions we build the house. House is the object.

How to define a class in Java?

Here is an examples

Here, we defined a class named Lamp.

The class has one instance variable (variable defined inside class) isOn and two methods turnOn( )
and turnOff ( ). These variables and methods defined within a class are called members of the class.

Notice two keywords, private and public in the above program. These are access modifiers which will
be discussed in detail in chapter two. For now, just remember:

37
 The private keyword makes instance variables and methods private which can be accessed only
from inside the same class.
 The public keyword makes instance variables and methods public which can be accessed from
outside of the class.

In the above program, isOn variable is private whereas turnOn() and turnOff() methods are public.

If you try to access private members from outside of the class, compiler throws error.

When class is defined, only the specification for the object is defined; no memory or storage is
allocated. Objects are accessed via object reference variables, which contain references to the objects.
Such variables are declared using the following syntax:
ClassName objectRefVar;

Declare the variable l1 to be of the Lamp type: Lamp l1; the variable l1 can reference a Lamp object.
The next statement creates an object and assigns its reference to L1: l1 = new Lamp();
Using the syntax shown below, you can write a single statement that combines the declaration of an
object reference variable, the creation of an object, and the assigning of an object reference to the
variable.
ClassName objectRefVar = new ClassName(); //remember the Scanner class

To access members defined within the class, you need to create objects. Let's create objects
of Lamp class.

This program creates two objects l1 and l2 of class Lamp.

How to access member?

38
You can access members (call methods and access instance variables) by using . operator. For example,

This statement calls turnOn() method inside Lamp class for l1 object. When you call the
method using the above statement, all statements within the body of turnOn ( ) method are executed.

Then, the control of program jumps back to the statement following l1.turnOn( );

Similarly, the instance variable can be accessed as: l2.isOn = false;

It is important to note that, the private members can be accessed only from inside the class. If the
code l2.isOn = false; lies within the main() method (outside of the Lampclass), compiler will show
error.

39
Example Java class and object

When you run the program, the output will be:

Light on? true

Light on? false

In the above program,

 Lamp class is created.


 The class has an instance variable isOn and three methods turnOn(), and turnoff() and
displayLightStatus();
 Two objects l1 and l2 of Lamp class are created in the main() function.
 Here, turnOn() method is called using l1 object: l1.turnOn();
 This method sets isOn instance variable of l1 object to true.
 And, turnOff() method is called using l2 object: l2.turnOff();
 This method sets isOff instance variable of l2 object to false.
 Finally, l1.displayLightStatus(); statement displays Light on? true because isOn variable
holds true for l1 object.
 And, l2.displayLightStatus(); statement displays Light on? false because isOn variable
holds false for l2 object.

Note: Every variable represents a memory location that holds a value. When you declare a variable,
you are telling the compiler what type of value the variable can hold. For a variable of a primitive type,

40
the value is of the primitive type. For a variable of a reference type, the value is a reference to where
an object is located.

This is enough for object and class next topic is about methods.

In mathematics, you might have studied about functions. For example, f(x) = x2 is a function that
returns squared value of x.

If x = 2, then f(2) = 4

If x = 3, f(3) = 9

and so on.

Similarly, in programming, a function is a block of code that performs a specific task. In object-
oriented programming, method is a jargon used for function. Methods are bound to a class and they
define the behavior of a class.

Suppose that you need to find the sum of integers from 1 to 10, from 20 to 30, and from 35
to 45, respectively. You may write the code as follows:
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
You may have observed that computing sum from 1 to 10, from 20 to 30, and from 35 to 45 are very
similar except that the starting and ending integers are different. Wouldn’t it be nice if we could write
the common code once and reuse it without rewriting it? We can do so by defining a method. The
method is for creating reusable code.

The preceding code can be simplified as follows:

public class SummationDifferentNumber{

public static int sum(int i1, int i2) {


int sum = 0;

41
for (int i = i1; i <= i2; i++)
sum += i;
return sum;

}//end of sum mehtod


public static void main(String[] args) {
System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 20 to 30 is " + sum(20, 30));
System.out.println("Sum from 35 to 45 is " + sum(35, 45));
}// end of main method

} // end of SummationDifferentNumber class

Here in the System.out.println("Sum from 1 to 10 is " + sum(1, 10)); statement calls the method sum
with the argument of different values and compute the sum. The sum method body is reusable in the
program with different arguments.

A method is a collection of statements grouped together to perform an operation. In object-oriented


programming, method is a jargon used for function. Methods are bound to a class and they define the
behavior of a class. Depending on whether a method is defined by the user, or available in standard
library, there are two types of methods:

 Standard Library Methods


 User-defined Methods

Standard Library Methods

The standard library methods are built-in methods in Java that are readily available for use. These
standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM
and JRE. For example,

 print() is a method of java.io.PrintSteam. The print("...") prints the string inside quotation marks.

 sqrt() is a method of Math class. It returns square root of a number.

The syntax for defining a method is as follows:


modifier returnValueType methodName(list of parameters) {
// Method body;
}

42
Let’s look at a method created to find which of two integers is bigger. This method, named max, has
two int parameters, num1 and num2, the larger of which is returned by the method.

The method header specifies the modifiers, return value type, method name, and parameters of the
method.
A method may return a value. The return Value Type is the data type of the value the method returns.
Some methods perform desired operations without returning a value. In this case, the return Value
Type is the keyword void. If a method returns a value, it is called a value returning method, otherwise
it is a void method.

The variables defined in the method header are known as formal parameters or simply parameters. A
parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This
value is referred to as an actual parameter or argument. The parameter list refers to the type, order,
and number of the parameters of a method. The method name and the parameter list together constitute
the method signature. Parameters are optional; that is, a method may contain no parameters.

The method body contains a collection of statements that define what the method does. The method
body of the max method uses an if statement to determine which number is larger and return the value
of that number. In order for a value-returning method to return a result, a return statement using the
keyword return is required. The method terminates when a return statement is executed.

The complete syntax for defining a Java method is:

Here:

 modifier - defines access type whether the method is public, private and so on.

43
 static - If you use static keyword in a method then it becomes a static method. Static methods
can be called without creating an instance of a class.
 returnType - A method can return a value. It can return native data types (int, float, double
etc.), native objects (String, Map, List etc.), or any other built-in and user defined objects. If the
method does not return a value, its return type is void.
 nameOfMethod - The name of the method is an identifier. You can give any name to a method.
However, it is more conventional to name it after the tasks it performs. For example,
calculateInterest, calculateArea, and so on.

 Parameters (arguments) - Parameters are the values passed to a method. You can pass any
number of arguments to a method.

 Method body - It defines what the method actually does, how the parameters are manipulated
with programming statements and what values are returned. The codes inside curly braces { } is
the body of the method.

How to call a Java Method?

In creating a method, you define what the method is to do. To use a method, you have to call or invoke
it. There are two ways to call a method, depending on whether the method returns a value or not.

If the method returns a value, a call to the method is usually treated as a value. For example,
int larger = max(3, 4);
calls max(3, 4) and assigns the result of the method to the variable larger. Another example of a call
that is treated as a value is System.out.println(max(3, 4));
which prints the return value of the method call max(3, 4).
If the method returns void, a call to the method must be a statement. For example, the method println
returns void. The following call is a statement: System.out.println("Welcome to Java!");

When a program calls a method, program control is transferred to the called method. A called method
returns control to the caller when its return statement is executed or when its method ending closing
brace is reached.

public class TestMax {


/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = ;
System.out.println("The maximum between " + i + " and " + j + " is " + k);

} /** Return the max between two numbers */

Public static int max(int num1, int num2) {


int result;
if (num1 > num2)
result = num1;

44
else
result = num2;

return result;
}
}
This program contains the main method and the max method. The main method is just like any other
method except that it is invoked by the JVM.

The statements in main may invoke other methods that are defined in the class that contains the main
method or in other classes. In this example, the main method invokes max(i,j), which is defined in the
same class with the main method.

When the max method is invoked, variable i’s value 5 is passed to num1, and variable j’s value 2 is
passed to num2 in the max method. The flow of control transfers to the max method. The max method
is executed. When the return statement in the max method is executed, the max method returns the
control to its caller (in this case the caller is the main method).

When the max method is invoked, the flow of control transfers to it. Once the max method is finished,
it returns control back to the caller.

Diagrammatically calling a method and executing the code is:

1. While Java is executing the program code, it encounters myFunction(); in the code.
2. The execution then branches to the myFunction() method, and executes code inside the body of
the method.
3. After the codes execution inside the method body is completed, the program returns to the
original state and executes the next statement.

45
Example2 java method calling

The output is:

Note that, we called the method without creating object of the class. It was possible because
myMethod() is static. Here's another example. In this example, our method is non-static and is inside
another class.

46
Why main method is static in Java?

1) Since main method is static Java virtual Machine can call it without creating any instance of
class which contains main method.
2) Anything which is declared in Java class comes under reference type and requires object to be
created before using them but static method and static data are loaded into separate memory
inside JVM called context which is created when a class is loaded. If main method is static than
it will be loaded in JVM context and are available to execution.

Method Overloading

If you call max with int parameters, the max method that expects int parameters will be invoked; if
you call max with double parameters, the max method that expects double parameters will be
invoked. This is referred to as method overloading; that is, two methods have the same name but
different parameter lists within one class. The Java compiler determines which method is used based on
the method signature.

47
When calling max(3, 4) (line 6), the max method for finding the maximum of two integers is invoked.
When calling max(3.0, 5.4) (line 10), the max method for finding the maximum of two doubles is
invoked. When calling max(3.0, 5.4, 10.14) (line 14), the max method for finding the maximum of
three double values is invoked.

What are the advantages of using methods?

 The main advantage is code reusability. You can write a method once, and use it multiple times.
You do not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple
times."
 Methods make code more readable and easier to debug. For example, getSalaryInformation()
method is so readable, that we can know what this method will be doing than actually reading
the lines of code that make this method.

Constructors are a special kind of method. They have three peculiarities:

 A constructor must have the same name as the class itself.


 Constructors do not have a return type—not even void.
 Constructors are invoked using the new operator when an object is created. Constructors play
the role of initializing objects.

Like regular methods, constructors can be overloaded (i.e., multiple constructors can have the same
name but different signatures), making it easy to construct objects with different initial data values.
Constructors are used to construct objects. To construct an object from a class, invoke a constructor of
the class using the new operator, as follows:
new ClassName(arguments);

A class normally provides a constructor without arguments (e.g., Circle()). Such a constructor is
referred to as a no-arg or no-argument constructor. Constructors can be very useful for setting initial
values for certain member variables.
A class may be defined without constructors. In this case, a no-arg constructor with an empty body is
implicitly defined in the class. This constructor, called a default constructor, is provided automatically
only if no constructors are explicitly defined in the class.

Accessing objects via a reference variable

Newly created objects are allocated in the memory. They can be accessed via reference variables.

48
Objects are accessed via object reference variables, which contain references to the objects. Such
variables are declared using the following syntax:

ClassName objectRefVar;

A class is essentially a programmer-defined type. A class is a reference type, which means that a
variable of the class type can reference an instance of the class. The following statement declares the
variable myCircle to be of the Circle type:
Circle myCircle;
The variable myCircle can reference a Circle object. The next statement creates an object
and assigns its reference to myCircle:
myCircle = new Circle();
Using the syntax shown below, you can write a single statement that combines the declaration of an
object reference variable, the creation of an object, and the assigning of an object reference to the
variable.
ClassName objectRefVar = new ClassName();
Here is an example:
Circle myCircle = new Circle();
The variable myCircle holds a reference to a Circle object.

Accessing an Object’s Data and Methods

After an object is created, its data can be accessed and its methods invoked using the dot operator (.),
also known as the object member access operator:

 objectRefVar.dataField references a data field in the object.


 objectRefVar.method(arguments) invokes a method on the object.

Differences between Variables of Primitive Types and Reference Types

Every variable represents a memory location that holds a value. When you declare a variable, you are
telling the compiler what type of value the variable can hold. For a variable of a primitive type, the
value is of the primitive type. For a variable of a reference type, the value is a reference to where an
object is located. For example, as shown in Figure below the value of int variable i is int value 1, and
the value of Circle object c holds a reference to where the contents of the Circle object are stored in the
memory.

A variable of a primitive type holds a value of the primitive type, and a variable of a reference type
holds a reference to where an object is stored in memory.

49
Destructor, finalize () method and Garbage Collector

Destructor: It is a special method called when the object’s lifecycle is over, in order to free memory
and de-allocate resources. It is very prominent in languages with manual memory management
(where the developer has to invoke in explicitly), and extremely important to use it in order to avoid
memory leaks.

Garbage Collector: The garbage collector is a program that runs on the JVM and recovers memory by
deleting objects that are not used anymore or are not accessible from the code (and are considered
garbage, hence the name). It runs automatically and periodically checks the references in contrast to the
objects in the memory heap. If an unreferenced object is found, that means that there is no way to
access it anymore and it is useless, so the garbage collector gets rid of it and frees the memory.

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

50
Introduction

Inheritance is one of the OOP features, which is a form of software reuse in which a new class is
created by absorbing an existing class’s members and embellishing them with new or modified
capabilities. With inheritance, programmers save time during program development by reusing proven
and debugged high-quality software.

When creating a class, rather than declaring completely new members, the programmer can designate
that the new class should inherit the members of an existing class. The existing class is called the
Superclass, and the new class is the subclass. Each subclass can become the superclass for future
subclasses. The subclass inherits the properties and methods from the superclass. Inheritance in java is
an important and powerful feature in java for reusing software, avoids redundancy and make the system
easy to comprehend and easy to maintain.

The direct superclass is the superclass from which the subclass explicitly inherits. An indirect
superclass is any class above the direct superclass in the class hierarchy, which defines the inheritance
relationships between classes. Java supports single inheritance, i.e., a class is derived from one direct
superclass. It does not support multiple inheritance (which occurs when a class is derived from more
than one direct superclass).

The following points regarding inheritance are worthwhile to note:

 Contrary to the conventional interpretation, a subclass is not a subset of its superclass. In fact, a
subclass usually contains more information and methods than its superclass.
 Private data fields in a superclass are not accessible outside the class. Therefore, they cannot be
used directly in a subclass. They can, however, be accessed/mutated through public accessor/
mutator if defined in the superclass.
 Not all is-a relationships should be modeled using inheritance. For example, a square is a
rectangle, but you should not define a Square class to extend a Rectangle class, because there
is nothing to extend (or supplement) from a rectangle to a square. Rather you should define a
Square class to extend the GeometricObject class. For class A to extend class B, A should
contain more detailed information than B.
 Inheritance is used to model the is-a relationship. Do not blindly extend a class just for the sake
of reusing methods. For example, it makes no sense for a Tree class to extend a Person class,
even though they share common properties such as height and weight. A subclass and its
superclass must have the is-a relationship.
 Some programming languages allow you to derive a subclass from several classes. This
capability is known as multiple inheritance. Java, however, does not allow multiple inheritance.
This restriction is known as single inheritance. If you use the extends keyword to define a
subclass, it allows only one parent class.

51
extend keyword is used to inherit the properties of a super class. The syntax is

Below given is an example demonstrating Java inheritance. In this example you can observe two
classes namely Calculation and My_Calculation. Using extends keyword the My_Calculation inherits
the methods addition and Subtraction of Calculation class.

Output of the program:

The sum of the given numbers: 30


The difference between the given numbers: 10
The product of the given numbers: 200

A subclass inherits all the members’ fields, methods, and nested classes from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the
superclass can be invoked from the subclass.

52
The super keyword is used to differentiate the members of superclass from the members of subclass,
if they have same names. ,Also it is used to invoke the superclass constructor from subclass.

Example

The output of the program:

This is the display method of subclass


This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

Invoking Superclass constructor

If you want to call a parameterized constructor of the super class, you need to use the super keyword as:
super(values);

53
Output of the program:

The value of the variable named age in super class is: 24

IS-A Relationship:

IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is
used to achieve inheritance.

Now, based on the above example, In Object Oriented terms, the following are true:
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say:


Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well

54
With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.

There are various types of inheritance:

A very important fact to remember is that Java does not support multiple inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal:
public class extends Animal, Mammal{}

The this keyword

this is a keyword in Java which is used as a reference to the object of the current class, with in an
instance method or a constructor. Using this you can refer the members of a class such as constructors,
variables and methods. The keyword this is used only within instance methods or constructors.

this keyword with a field(Instance Variable)

55
this keyword can be very useful in the handling of Variable Hiding. We can not create two
instances/local variables with the same name. However, it is legal to create one instance variable & one
local variable or Method parameter with the same name. In this scenario, the local variable will hide the
instance variable this is called Variable Hiding.

1. class JBT {
2.
3. int variable = 5;
4. public static void main(String args[]) {
5. JBT obj = new JBT();
6. obj.method(20);
7. obj.method();
8. }
9. void method(int variable) {
10. variable = 10;
11. System.out.println("Value of Local variable :" + variable);
12. /*add this statement and see the result =>> System.out.println("Value of Instance variable :" +
this.variable); */
13. }
14. void method() {
15. int variable = 40;
16. System.out.println("Value of Local variable :" + variable);
17. /*add this statement and see the result =>> System.out.println("Value of Instance variable :" +
this.variable); */
18. }
19. }

output of the program

As you can see in the example above, the instance variable is hiding, and the value of the local
variable (or Method Parameter) is displayed not instance variable. To solve this problem
use this keyword with a field to point to the instance variable instead of the local variable. Add
this statement System.out.println("Value of Instance variable :" + this.variable);and see the
difference of the output .

this Keyword with Constructor

“this” keyword can be used inside the constructor to call another overloaded constructor in the same
Class. It is called the Explicit Constructor Invocation. This occurs if a Class has two overloaded
constructors, one without argument and another with the argument. Then “this” keyword can be used to
call the constructor with an argument from the constructor without argument. This is required as the
constructor cannot be called explicitly.

class JBT {
JBT() {
this("JBT");

56
System.out.println("Inside Constructor without parameter");
}
JBT(String str) {
System.out.println("Inside Constructor with String parameter as " + str);
}
public static void main(String[] args) {
JBT obj = new JBT();
}
}
Output of the program is:

 this keyword can only be the first statement in Constructor.


 A constructor can have either this or super keyword but not both.

this Keyword with Method


this keyword can also be used inside Methods to call another Method from same Class.

Out put of the program


Inside Method TWO

Inside Method ONE

57
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
Polymorphism is the capability of a method to do different things based on the object that it is acting
upon. In other words, polymorphism allows you define one interface and have multiple
implementations. For example, lets say we have a class Animal that has a method sound (). Since this is
a generic class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had to give a
generic message.

Now let’s say we have two subclasses of Animal class: Horse and Cat that extends Animal class. We
can provide the implementation to the same method like this:

The output of this program:

The horse sound() method overrides the animal class sound method. Let as see the cat class override the
sound method in the animal class.

58
Output of the program: Meaw.
As you can see that although we had the common action for all subclasses sound() but there were
different ways to do the same action. This is a perfect example of polymorphism.

We can perform polymorphism in java by method overloading and method overriding. There are two
types of polymorphism in Java:

1. Static Polymorphism also known as compile-time polymorphism: Polymorphism that is


resolved during compiler time is known as static polymorphism. Method overloading is an
example of compile time polymorphism.
2. Dynamic Polymorphism also known as runtime polymorphism: Dynamic polymorphism is a
process in which a call to an overridden method is resolved at runtime, that’s why it is called
runtime polymorphism.

Declaring a method in sub class which is already present in parent class is known as method overriding.
Overriding is done so that a child class can give its own implementation to a method which is already
provided by the parent class. In this case the method in parent class is called overridden method and the
method in child class is called overriding method.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter list as in the parent class.
3. There must be an IS-A relationship (inheritance).
4. The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
5. The access level cannot be more restrictive than the overridden method’s access level. For
example: if the superclass method is declared public then the overriding method in the sub class
cannot be either private or protected.

59
6. A method declared final cannot be overridden.
7. A method declared static cannot be overridden. Because the static method is bound with class
whereas instance method is bound with an object. Static belongs to the class.
8. Constructors cannot override.
9. A subclass within the same package as the instance’s superclass can override any superclass
method that is not declared private or final.
10. If a method cannot be inherited, then it cannot be overridden.
11. A subclass in a different package can only override the non-final methods declared public or
protected.

Example of method overriding

Output: Bike is running safely.

60
What is abstraction in java?

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
In another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal processing
about the message delivery. Abstraction lets you focus on what the object does instead of how it does it.

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

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:
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.

A class derived from the abstract class must implement all those methods that are declared as abstract in
the parent class. Abstract class cannot be instantiated which means you cannot create the object of it. To
use this class, you need to create another class that extends this this class and provides the implementation
of abstract methods, then you can use the object of that child class to call non-abstract methods of parent
class as well as implemented methods (those that were abstract in parent but implemented in child class).

Since abstract class allows concrete methods as well, it does not provide 100% abstraction. You can say
that it provides partial abstraction. Abstraction is a process where you show only “relevant” data and
“hide” unnecessary details of an object from the user.

Why can’t we create the object of an abstract class?

Because these classes are incomplete, they have abstract methods that have no body so if java allows
you to create object of this class then if someone calls the abstract method using that object then What
would happen? There would be no actual implementation of the method to invoke. Also because an
object is concrete. An abstract class is like a template, so you have to extend it and build on it before
you can use it.

61
A class which is not abstract is referred as Concrete class. If you declare an abstract method in a
class then you must declare the class abstract as well. You can’t have abstract method in a concrete
class. It’s vice versa is not always true: If a class is not having any abstract method then also it can be
marked as abstract. An abstract class must be extended and in a same way abstract method must be
overridden.

Output: overriding abstract method

Output: bike is created


running safely..
gear changed

62
Abstract class which is used for achieving partial abstraction. Unlike abstract class an interface is used
for full abstraction. An interface in java is a blueprint of a class. It has static constants and abstract
methods.
Interface looks like a class but it is not a class. An interface can have methods and variables just like the
class but the methods declared in interface are by default abstract. Also, the variables declared in an
interface are public, static & final by default.
Since methods in interfaces do not have body, they have to be implemented by the class before you can
access them. The class that implements interface must implement all the methods of that interface.
Also, java programming language does not allow you to extend more than one class, however you can
implement more than one interfaces in your class.
Syntax:
Interfaces are declared by specifying a keyword “interface”. E.g.:

A class implements interface but an interface extends another interface. It has to provide the body of all
the methods that are declared in interface or in other words you can say that class has to implement all
the methods of interface. Interface fields are public, static and final by default, and the methods are
public and abstract.
Example of interface

Output: Hello

63
Example two:

Output: implementation of method1

As discussed above, an interface cannot implement another interface. It has to extend the other interface.
See the below example where we have two interfaces Inf1 and Inf2. Inf2 extends Inf1 so if class
implements the Inf2 it has to provide implementation of all the methods of interfaces Inf2 as well as Inf1.

In this program, the class Demo only implements interface Inf2, however it has to provide the
implementation of all the methods of interface Inf1 as well, because interface Inf2 extends Inf1.

64
Output: method2

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as


multiple inheritance.

Why interface variables are public, static and final? Since interface does not have a direct object, the
only way to access them is by using a class/interface. That is why if interface variable exists, it should be
static otherwise it wont be accessible at all to outside world. Now since it is static, it can hold only one
value and any class that extends it can change the value, so to ensure that it holds a constant value, it has
been made final. These are the reasons interface variables are static and final and obviously public.
Why interface methods are public and abstract? Interfaces are meant to define the public API of a
type – and only that, not its implementation. So any method you define in an interface is by definition
public and abstract.

65
Example of multiple inheritance

Output: Hello and Welcome

Key points you should remember about interface:

1) We can’t instantiate an interface in java. That means we cannot create the object of an interface
2) Interface provides full abstraction as none of its methods have body. On the other hand abstract class
provides partial abstraction as it can have abstract and concrete (methods with body) methods both.
3) implement keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it needs to be mentioned as
public.
5) Class that implements any interface must implement all the methods of that interface, else the class
should be declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by default.
9) Interface variables must be initialized at the time of declaration otherwise compiler will throw an
error.
10) Inside any implementation class, you cannot change the variables declared in interface because by
default, they are public, static and final, i.e., by default and final variables cannot be re-initialized.
11) An interface can extend any interface but cannot implement it. Class implements interface and
interface extends interface.
12) A class can implement any number of interfaces.
13) A class cannot implement two interfaces that have methods with same name but different return
type. Variable names conflicts can be resolved by interface name.

66
When to use what?
Consider using abstract classes if any of these statements apply to your situation:
 In java application, there are some related classes that need to share some lines of code then you
can put these lines of code within abstract class and this abstract class should be extended by all
these related classes.
 You can define non-static or non-final field(s) in abstract class, so that via a method you can
access and modify the state of Object to which they belong.
 You can expect that the classes that extend an abstract class have many common methods or
fields, or require access modifiers other than public (such as protected and private).
Consider using interfaces if any of these statements apply to your situation:
 It is total abstraction, all methods declared within an interface must be implemented by the
classes that implements this interface.
 A class can implement more than one interface. It is called multiple inheritance.
 You want to specify the behavior of a particular data type, but not concerned about who
implements its behavior.

Encapsulation simply means binding object state (fields) and behavior (methods) together. If you are
creating class, you are doing encapsulation. The whole idea behind encapsulation is to hide the
implementation details from users. If a data member is private it means it can only be accessed within
the same class. No outside class can access private data member (variable) of other class.
However if we setup public getter and setter methods to update (for example void setSSN(int ssn))and
read (for example int getSSN()) the private data fields then the outside class can access those private
data fields via public methods.
This way data can only be accessed by public methods thus making the private fields and their
implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets see
an example to understand this concept better.
How to implement encapsulation in java:
1) Make the instance variables private so that they cannot be accessed directly from outside the class.
You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.

67
Output:

Advantages of encapsulation

1. It improves maintainability and flexibility and re-usability: for e.g. In the above code the
implementation code of void setEmpName(String name) and String getEmpName() can be
changed at any point of time. Since the implementation is purely hidden for outside classes they
would still be accessing the private field empName using the same methods (setEmpName(String
name) and getEmpName()). Hence the code can be maintained at any point of time without
breaking the classes that uses the code. This improves the re-usability of the underlying class.
2. The fields can be made read-only (If we don’t define setter methods in the class) or write-only
(If we don’t define the getter methods in the class). For e.g. If we have a field(or variable) that
we don’t want to be changed so we simply define the variable as private and instead of set and

68
get both we just need to define the get method for that variable. Since the set method is not
present there is no way an outside class can modify the value of that field.
3. User would not be knowing what is going on behind the scene. They would only be knowing
that to update a field call set method and to read a field call get method but what these set and
get methods are doing is purely hidden from them.

What is the difference between abstraction and encapsulation while they both are hiding the
implementation from user?

We use abstraction when we are not sure about certain implementation. for e.g -> car surely need
fuel but may or may not need ac & wiper features. so we define implementation for only fuel() and
make ac(),wiper()as abstract. i.e., no implementation.

Encapsulation-> provides data protection/hiding.

Technically in encapsulation, the variables or data of a class is hidden from any other class and
can be accessed only through any member function of own class in which they are declared.
 Encapsulation can be achieved by: Declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.

69
An exception is an indication of a problem that occurs during a program’s execution. The name
“exception” implies that the problem occurs infrequently if the “rule” is that a statement normally
executes correctly, then the ”exception to the rule” is that a problem occurs. Exception handling enables
programmers to create applications that can resolve (or handle) exceptions.

Exception handling enables programmers to remove error-handling code from the “main line” of the
program’s execution, improving program clarity and enhancing modifiability. Programmers can decide
to handle any exceptions they choose all exceptions, all exceptions of a certain type or all exceptions of
a group of related types (i.e., exceptions types that are related through an inheritance hierarchy). Such
flexibility reduces the likelihood that errors will be overlooked, thus making programs more robust.

With programming languages that do not support exception handling, programmers often delay writing
error-processing code or sometimes forget to include it. This results in less robust software products. Java
enables programmers to deal with exception handling easily from the inception/ beginning of a project.

Runtime errors occur while a program is running if the environment detects an operation that is
impossible to carry out. For example, if you access an array using an index out of bounds, your program
will get a runtime error with an ArrayIndexOutOfBoundsException.

In Java, runtime errors are caused by exceptions. An exception is an object that represents an error or a
condition that prevents execution from proceeding normally. If the exception is not handled, the program
will terminate abnormally. How can you handle the exception so that the program can continue to run or
else terminate gracefully? Let us see some examples
import java.util.Scanner; import java.util.Scanner;
public class Quotient { public class QuotientWithIf {
public static void main(String[] args) {
1 public static void main(String[] args) {
2
Scanner input = new Scanner(System.in); Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers // Prompt the user to enter two integers
System.out.print("Enter two integers: "); System.out.print("Enter two integers: ");
int number1 = input.nextInt(); int number1 = input.nextInt();
int number2 = input.nextInt(); int number2 = input.nextInt();
System.out.println(number1 + " / " + if (number2 != 0)
number2 + " is " + ( )); System.out.println(number1 + " / " + number2
} + " is " + ( ));
} else
System.out.println("Divisor cannot be zero ");
} }

70
A simple way to fix the error we add an if statement to test the second number in program 2.
In order to demonstrate the concept of exception handling, including how to create, throw, catch, and
handle an exception, we rewrite program 2 in the following form.

The program contains a try block and a catch block. The try block contains the code that is executed in
normal circumstances. The catch block contains the code that is executed when number2 is 0. In this
event the program throws an exception by executing

throw new ArithmeticException("Divisor cannot be zero");

The value thrown, in this case new ArithmeticException("Divisor cannot be zero"), is called an
exception. The execution of a throw statement is called throwing an exception. The exception is an object
created from an exception class. In this case, the exception class is java.lang.ArthmeticException. When
an exception is thrown, the normal execution flow is interrupted. As the name suggests, to “throw an
exception” is to pass the exception from one place to another. The exception is caught by the catch block.

71
The code in the catch block is executed to handle the exception. Afterward, the statement after the catch
block is executed.
The throw statement is analogous to a method call, but instead of calling a method, it calls
a catch block. In this sense, a catch block is like a method definition with a parameter that
matches the type of the value being thrown. Unlike a method, after the catch block is executed, however,
the program control does not return to the throw statement; instead, it executes the next statement after
the catch block.
The identifier ex in the catch–block header
catch (ArithmeticException ex)
acts very much like a parameter in a method. So this parameter is referred to as a catch–block parameter.
The type (e.g., ArithmeticException) preceding ex specifies what kind of exception the catch block can
catch. Once the exception is caught, you can access the thrown value from this parameter in the body of
a catch block.
An exception can occur for many different reasons, below given are some scenarios where exception
occurs.

 A user has entered invalid data.


 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out
of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
Based on these we have three categories of Exceptions you need to understand them to know how
exception handling works in Java,

 Checked exceptions: A checked exception is an exception that occurs at the compile time, these
are also called as compile time exceptions. These exceptions cannot simply be ignored at the time
of compilation, the Programmer should take care of handle these exceptions.

For example, if you use FileReader class in your program to read data from a file, if the file specified in
its constructor doesn't exist, then FileNotFoundException occurs, and compiler prompts the programmer
to handle the exception.

72
Note: Since the methods read and close of FileReader class throws IOException, you can observe
that compiler notifies to handle IOException, along with FileNotFoundException.

 Unchecked exceptions: An Unchecked exception is an exception that occurs at the time of


execution, these are also called as Runtime Exceptions, and these include programming bugs, such
as logic errors or improper use of an API. runtime exceptions are ignored at the time of
compilation.

For example, if you have declared an array of size 5 in your program, and trying to call the 6th element
of the array then an ArrayIndexOutOfBoundsException exception occurs.

 Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation.

There are many predefined exception classes in the Java API.

Exceptions thrown are instances of the classes shown in this diagram, or of subclasses of one of these
classes. The Throwable class is the root of exception classes. All Java exception classes inherit directly

73
or indirectly from Throwable. You can create your own exception classes by extending Exception or a
subclass of Exception.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch block is
referred to as protected code, and the syntax for using try/catch looks like the following:

The try block contains the code that is executed in normal circumstances. The catch block contains the
code that is executed in exceptional circumstances. Exception handling separates error-handling code
from normal programming tasks, thus making programs easier to read and to modify. Every try block
should be immediately followed either by a class block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an exception
occurs in protected code, the catch block or blocks that follows the try is checked. If the type of
exception that occurred is listed in a catch block, the exception is passed to the catch block much
as an argument is passed into a method parameter.
The following is an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword.
The throws keyword appears at the end of a method's signature. The difference between throws and throw
keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke

74
an exception explicitly. You can throw an exception, either a newly instantiated one or an exception that
you just caught, by using the throw keyword.

The finally block:

The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:

Example of finally block

75
Note the following:

 A catch clause cannot exist without a try statement.


 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks

When to use Exception Handling

Be aware, however, that exception handling usually requires more time and resources, because it requires
instantiating a new exception object, rolling back the call stack, and propagating the exception through
the chain of methods invoked to search for the handler.

An exception occurs in a method. If you want the exception to be processed by its caller, you should
create an exception object and throw it. If you can handle the exception in the method where it occurs,
there is no need to throw or use exceptions. In general, common exceptions that may occur in multiple
classes in a project are candidates for exception classes. Simple errors that may occur in individual
methods are best handled locally without throwing exceptions.

When should you use a try-catch block in the code? Use it when you have to deal with unexpected error
conditions. Do not use a try-catch block to deal with simple, expected situations.

76
Introduction

So far, we have covered the basic programming constructs (such as variables, data types, decision, loop,
array and method) and introduced the important concept of Object-Oriented Programming (OOP). As
discussed, OOP permits higher level of abstraction than traditional Procedural-Oriented languages (such
as C and Pascal). The design of the API for Java GUI programming is an excellent example of how the
Object Oriented principle is applied.

GUI stands for Graphical User Interface, a term used not only in java but in all programming languages
that support the development of GUIs. A programs graphical user interface presents an easy–to-use visual
display to the user. It is made up of graphical components (e.g., buttons, labels, windows) through which
the user can interact with the page or application.

A graphical user interface (GUI) presents a user-friendly mechanism for interfacing with an application.
A GUI (pronounced “GOO-ee”) gives an application a distinctive “look” and “feel” providing different
applications with consistent, intuitive user interface components allows users to be somewhat familiar
with an application, so that they can learn it more quickly and use it more productively.

A GUI includes a range of user interface elements- which just means all the elements that display when
you are working in an application. These can include:

 Input control such as buttons, dropdown lists, checkboxes, and text fields.
 Informational elements such as labels, banners, icons, or notification dialogs.
 Navigational elements, including sidebars, breadcrumbs, and menus.

GUIs are built from GUI components. These are sometimes called controls or widgets short for windows
gadgets in other languages. A GUI component is an object with which the user interacts via the mouse,
the keyboard or another form of input, such as voice recognition. If you’re an application developer, you
need to consider not only the tools and programming widgets you will use to create your GUI, but also
aware of the user and how he will interact with the application. Once you have mastered the tools for
creating GUIs, learn the basics of usability to ensure that your application has a look-and-feel that will
make it attractive and useful to its users.

There are current three sets of Java APIs for graphics programming: AWT(Abstract Windowing Toolkit),
Swing and JavaFX.

1. AWT API was introduced in JDK 1.0. Most of the AWT components have become obsolete and
should be replaced by newer Swing components.
2. Swing API, a much more comprehensive set of graphics libraries that enhances the AWT, was
introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC consists of
Swing, Java2D, Accessibility, Internationalization, and Pluggable Look-and-Feel Support APIs.
JFC has been integrated into core Java since JDK 1.2.
3. The latest JavaFX, which was integrated into JDK 8, is meant to replace Swing.

77
Other than AWT/Swing/JavaFX graphics APIs provided in JDK, other organizations/vendors have also
provided graphics APIs that work with Java, such as Eclipse's Standard Widget Toolkit (SWT) (used in
Eclipse), Google Web Toolkit (GWT) (used in Android), 3D Graphics API such as Java bindings for
OpenGL (JOGL) and Java3D.

The Java GUI API

The figure below shows the class hierarchy of the swing GUI classes. The JFrame, JApplet, JDialog,
and JComponent classes and their subclasses are grouped in the javax.swing package. All the other
classes of AWT are grouped in the java.awt package. The Component class is the root for all GUI
components and containers. All Swing GUI components (except JFrame, JApplet, and JDialog) are
subclasses of JComponent, as shown in the Figure below.

Java GUI API contains classes that can be classified into three groups: component classes, container
classes, and helper classes.

The component classes, such as JButton, JLabel, and JTextField, are for creating the user interface.
The container classes, such as JFrame, JPanel, and JApplet, are used to contain other components.
The helper classes, such as Graphics, Color, Font, FontMetrics, and Dimension, are used to support
GUI components.

The component classes


An instance of Component can be displayed on the screen. Component is the root class of all
the user-interface classes including container classes, and JComponent is the root class of all
the lightweight Swing components. Both Component and JComponent are abstract classes. For
Abstract Classes and Interfaces you cannot create instances using the new operator. However, you can
use the constructors of concrete subclasses of JComponent to create JComponent instances. Swing

78
component classes (in package javax.swing) begin with a prefix “J” e.g., JButton, JTextField, Jlabel,
JPanel, JFrame, or JApplet.

There are component class methods commonly used in the program:

Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.

The Container Classes


Container classes are GUI components that are used to contain other GUI components. Window, Panel,
Applet, Frame, and Dialog are the container classes for AWT components. To work with Swing
components, use Container, JFrame, JDialog, JApplet, and JPanel.

GUI of swing Container Classes

Container Classes Description


java.awt.Container is used to group components. Frames, panels, and applets are its subclasses.
javax.swing.JFrame is a window not contained inside another window. It is used to hold other
Swing user-interface components in Java GUI applications.
javax.swing.JPanel is an invisible container that holds user-interface components. Panels can be
nested. You can place panels inside a container that includes a panel. JPanel
is also often used as a canvas to draw graphics.
javax.swing.JApplet is a subclass of Applet. You must extend JApplet to create a Swing-based
Java applet.
javax.swing.JDialog is a popup window or message box generally used as a temporary window to
receive additional information from the user or to provide notification that an
event has occurred.

GUI Helper Classes


The helper classes, such as Graphics, Color, Font, FontMetrics, Dimension, and LayoutManager, are
not subclasses of Component. They are used to describe the properties of GUI components, such as
graphics context, colors, fonts, and dimension.

Helper Classes Description


java.awt.Graphics is an abstract class that provides the methods for drawing strings,
lines, and simple shapes.
java.awt.Color Deals with the colors of GUI components. For example, you can specify
background or foreground colors in components like JFrame and
JPanel, or you can specify colors of lines, shapes, and strings in
drawings.

79
java.awt.Font Specifies fonts for the text and drawings on GUI components.
For example, you can specify the font type (e.g., SansSerif), style
(e.g., bold), and size (e.g., 24 points) for the text on a button
java.awt.FontMetrics is an abstract class used to get the properties of the fonts..
java.awt.Dimension Encapsulates the width and height of a component (in integer
precision) in a single object.
java.awt.LayoutManager Specifies how components are arranged in a container.

The helper classes are in the java.awt package. The Swing components do not replace all the
classes in AWT. The AWT helper classes are still useful in GUI programming.

AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18 packages of 737
classes as of JDK 8). Fortunately, only 2 packages - java.awt and java.awt.event - are commonly-used.

1. The java.awt package contains the core AWT graphics classes:


o GUI Component classes, such as Button, TextField, and Label.
o GUI Container classes, such as Frame and Panel.
o Layout managers, such as FlowLayout, BorderLayout and GridLayout.
o Custom graphics classes, such as Graphics, Color and Font.
2. The java.awt.event package supports event handling:
o Event classes, such as ActionEvent, MouseEvent, KeyEvent and WindowEvent,
o Event Listener Interfaces, such as ActionListener, MouseListener,
MouseMotionListener, keyListener and WindowListener.
o Event Listener Adapter classes, such as MouseAdapter, KeyAdapter, and
WindowAdapter

AWT is rarely used now days because of its platform dependent and heavy-weight nature. AWT
components are considered heavy weight because they are being generated by underlying operating
system (OS). For example if you are instantiating a text box in AWT that means you are actually asking
OS to create a text box for you.

The AWT user-interface components were replaced by a more robust, versatile, and flexible library
known as Swing components.

80
Swing is a part of JFC, Java Foundation Classes. It is a collection of packages for creating full featured
desktop applications. JFC consists of AWT, Swing, Accessibility, Java 2D, and Drag and Drop. Swing
was released in 1997 with JDK 1.2. It is a mature toolkit. In general Swing toolkit is: platform
independent, customizable, extensible, configurable, and lightweight.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc. To distinguish new Swing component classes
from their AWT counterparts, the Swing GUI component classes are named with a prefixed J. Java Swing
components are basic building blocks of a Java Swing application and we will use JFrame, JButton, and
JLabel Components.

Although AWT components are still supported in Java, it is better to learn to how program using Swing
components, because the AWT user-interface components will eventually fade away.

Writing Swing Applications

In summary, to write a Swing application, you have:

1. Use the Swing components with prefix "J" in package javax.swing, e.g., JFrame, JButton,
JTextField, JLabel, etc.
2. A top-level container (typically JFrame) is needed. The JComponents should not be added directly
onto the top-level container. They shall be added onto the content-pane of the top-level container.
You can retrieve a reference to the content-pane by invoking method getContentPane() from the
top-level container.
3. Swing applications uses AWT event-handling classes, e.g., ActionEvent/ActionListener,
MouseListener etc.
4. Run the constructor in the Event Dispatcher Thread (instead of Main thread) for thread safety.

Swing Vs AWT
Some of the difference between Swing and AWT are listed in the table below:

No Java AWT Java Swing


1 AWT components are platform-dependent. Swing components are platform-independent.
2 AWT components are heavyweight. Swing components are lightweight.
3 AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
4 AWT provides less components than Swing. Swing provides more powerful components
such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.
5 AWT doesn't follows MVC (Model View Swing follows MVC.
Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and view.

81
A user interacts with an applications GUI to indicate the tasks that the application should perform. For
example, when you write an e-mail in an e-mail application, clicking the send button tells the application
to send the e-mail to the specified e-mail addresses.
GUI are event driven. When the user interacts with a GUI component, the interaction known as an event
drives the program to perform a task. Events are generated as result of user interaction with the graphical
user interface components. Some common events (user interactions) that might cause an application to
perform a task include clicking a button, typing in a text field, selecting an item from a menu, closing a
window and moving the mouse.
Events can be broadly classified into two categories:

1) Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page etc.
2) Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires,
an operation completion are the example of background events.

The component that creates an event and fires it is called the source object or source component. For
example, a button is the source object for a button-clicking action event. An event is an
instance of an event class. The root class of the event classes is java.util.EventObject.
The hierarchical relationships of some event classes are shown in Figure below.

An event is an object of the EventObject class.

An event object contains whatever properties are pertinent to the event. You can identify
the source object of an event using the getSource() instance method in the EventObject
class. The subclasses of EventObject deal with special types of events, such as action
events, window events, component events, mouse events, and key events. In the table below lists
external user actions, source objects, and event types fired.

82
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.
The code that performs a task in response to an event is called an event handler and the overall process
of responding to event is known as event handling. The AWT’s event –handling classes are kept in
package java.awt.event.
Java uses a delegation-based model for event handling: a source object fires an event, and
an object interested in the event handles it. The latter object is called a listener. For an
object to be a listener for an event on a source object, two things are needed:

1) The listener object must be an instance of the corresponding event-listener interface to


ensure that the listener has the correct method for processing the event. Java provides a
listener interface for every type of event. The listener interface is usually named
XListener for XEvent, with the exception of MouseMotionListener. For example, the
corresponding listener interface for ActionEvent is ActionListener; each listener for
ActionEvent should implement the ActionListener interface. Table below lists event

83
types, the corresponding listener interfaces, and the methods defined in the listener interfaces.
The listener interface contains the method(s), known as the handler(s), for processing
the event.
2) The listener object must be registered by the source object. Registration methods
depend on the event type. For ActionEvent, the method is addActionListener. In
general, the method is named addXListener for XEvent. A source object may fire
several types of events. It maintains, for each event, a list of registered listeners and
notifies them by invoking the handler of the listener object to respond to the event, as
shown in Figure below. You don’t have to know how a source class such as JButton is
implemented in order to use it. Nevertheless, this knowledge will help you to understand the Java
event-driven programming framework).

84
85
Steps involved in event handling

1. The User clicks the button and the event is generated.


2. Now the object of concerned event class is created automatically and information about the source
and the event get populated with in same object.
3. Event object is forwarded to the method of registered listener class.
4. The method is now get executed and returns.

Callback Methods

These are the methods that are provided by API provider and are defined by the application
programmer and invoked by the application developer. Here the callback methods represents an
event method. In response to an event java JRE will fire callback method. All such callback methods
are provided in listener interfaces. If a component wants some listener will listen to its events the source
must register itself to the listener.

Java ActionListener Interface

The Java ActionListener is notified whenever you click on the button or menu item. It is notified against
ActionEvent. The ActionListener interface is found in java.awt.event package. It has only one method:
actionPerformed().
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
public abstract void actionPerformed(ActionEvent e);
Java ActionListener Example: On Button click
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ActionListenerExample {
4. public static void main(String[] args) {
5. Frame f=new Frame("ActionListener Example");
6. final TextField tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. Button b=new Button("Click Here");
9. b.setBounds(50,100,60,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(ActionEvent e){
13. tf.setText("Welcome to Javatpoint.");
14. }
15. });
16. f.add(b);f.add(tf);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. }

86
Java IButton
The JButton class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.
JButton class declaration
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.


Commonly used Methods of Abstract Button class:
Method Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.
Example:
1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example);
5. JButton b=new JButton("Click Here");
6. b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }

Java JLabel

The object of JLabel class is a component for placing text in a container. It is used to display a single line
of read only text. The text can be changed by an application but a user cannot edit it directly. It inherits
JComponent class.
JLabel class declaration

87
public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string for the
title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, Creates a JLabel instance with the specified text, image, and horizontal
int horizontalAlignment) alignment.
Commonly used Methods:
Method Description
String getText() It returns the text string that a label displays.
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X
axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the
X axis.
Example

1. import javax.swing.*;
2. class LabelExample {
3. public static void main(String args[] ) {
4. JFrame f= new JFrame("Label Example");
5. JLabel l1,l2;
6. l1=new JLabel("First Label.");
7. l1.setBounds(50,50, 100,30);
8. l2=new JLabel("Second Label.");
9. l2.setBounds(50,100, 100,30);
10. f.add(l1); f.add(l2);
11. f.setSize(300,300);
12. f.setLayout(null);
13. f.setVisible(true);
14. } }

Java JTextField

The object of a JTextField class is a text component that allows the editing of a single line text. It inherits
JTextComponent class.
JTextField class declaration
public class JTextField extends JTextComponent implements SwingConstants
Commonly used constructors
Constructor Description
JTextField() JTextField(int columns)
JTextField(String text) Creates a new TextField initialized with the specified text.

88
JTextField(String text, int columns) Creates a new TextField initialized with the specified text
and columns.
JTextField(int columns) Creates a new empty TextField with the specified number
of columns.

Commonly used Methods:


Method Description
void addActionListener(ActionListener l) It is used to add the specified action listener to receive
action events from this textfield.
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
void setFont(Font f) It is used to set the current font.
void removeActionListener(ActionListener l) It is used to remove the specified action listener so that
it no longer receives action events from this textfield.
Java JTextField Example:
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){ JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){ c=a+b;
}else if(e.getSource()==b2){ c=a-b; }
String result=String.valueOf(c);

89
tf3.setText(result); }
public static void main(String[] args) {
new TextFieldExample();
}}

Java JTextArea

The object of a JTextArea class is a multi line region that displays text. It allows the editing of multiple
line text. It inherits JTextComponent class.
JTextArea class declaration
public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text
initially.
JTextArea(int row, int column) Creates a text area with the specified number of
rows and columns that displays no text initially.
JTextArea(String s, int row, int column) Creates a text area with the specified number of
rows and columns that displays specified text.
Commonly used Methods:
Method Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int position) It is used to insert the specified text on the specified position.
void append(String s) It is used to append the given text to the end of the document.

Example of JTextArea

import javax.swing.*;
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
l2=new JLabel();
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);

90
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}

Java JList

The object of JList class represents a list of text items. The list of text items can be set up so that the
user can choose either one item or multiple items. It inherits JComponent class.

public class JList extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-
null, model.

Commonly used Methods:

Method Description
Void addListSelectionListener It is used to add a listener to the list, to be notified each time a
(ListSelectionListener listener) change to the selection occurs.
int getSelectedIndex() It is used to return the smallest selected cell index.
ListModel getModel() It is used to return the data model that holds a list of items
displayed by the JList component.
void setListData(Object[] listData) It is used to create a read-only ListModel from an array of
objects.

Java JList Example with actionlistener

1. import javax.swing.*;
2. import java.awt.event.*;

91
3. public class ListExample
4. {
5. ListExample(){
6. JFrame f= new JFrame();
7. final JLabel label = new JLabel();
8. label.setSize(500,100);
9. JButton b=new JButton("Show");
10. b.setBounds(200,150,80,30);
11. final DefaultListModel<String> l1 = new DefaultListModel<>();
12. l1.addElement("C");
13. l1.addElement("C++");
14. l1.addElement("Java");
15. l1.addElement("PHP");
16. final JList<String> list1 = new JList<>(l1);
17. list1.setBounds(100,100, 75,75);
18. DefaultListModel<String> l2 = new DefaultListModel<>();
19. l2.addElement("Turbo C++");
20. l2.addElement("Struts");
21. l2.addElement("Spring");
22. l2.addElement("YII");
23. final JList<String> list2 = new JList<>(l2);
24. list2.setBounds(100,200, 75,75);
25. f.add(list1); f.add(list2); f.add(b); f.add(label);
26. f.setSize(450,450);
27. f.setLayout(null);
28. f.setVisible(true);
29. b.addActionListener(new ActionListener() {
30. public void actionPerformed(ActionEvent e) {
31. String data = "";
32. if (list1.getSelectedIndex() != -1) {
33. data = "Programming language Selected: " + list1.getSelectedValue();
34. label.setText(data);
35. }
36. if(list2.getSelectedIndex() != -1){
37. data += ", FrameWork Selected: ";
38. for(Object frame :list2.getSelectedValues()){
39. data += frame + " ";
40. }
41. }
42. label.setText(data);
43. }
44. });
45. }
46. public static void main(String args[])
47. {
48. new ListExample();
49. }}

92
Java JPanel

The JPanel is a simplest container class. It provides space in which an application can attach any other
component. It inherits the JComponents class.

JPanel class declaration

public class JPanel extends JComponent implements Accessible

Commonly used Constructors:

Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.
JPanel(boolean isDoubleBuffered) It is used to create a new JPanel with FlowLayout and the
specified buffering strategy.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout
manager.

1. import java.awt.*;
2. import javax.swing.*;
3. public class PanelExample {
4. PanelExample()
5. {
6. JFrame f= new JFrame("Panel Example");
7. JPanel panel=new JPanel();
8. panel.setBounds(40,80,200,200);
9. panel.setBackground(Color.gray);
10. JButton b1=new JButton("Button 1");
11. b1.setBounds(50,100,80,30);
12. b1.setBackground(Color.yellow);
13. JButton b2=new JButton("Button 2");
14. b2.setBounds(100,100,80,30);
15. b2.setBackground(Color.green);
16. panel.add(b1); panel.add(b2);
17. f.add(panel);
18. f.setSize(400,400);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public static void main(String args[])
23. {
24. new PanelExample();
25. }
26. }

93
JFrame
JFrame is a top-level window with a title and a border. It is used to organize other components, commonly
referred to as child components.
JFrame is used for the application's main window (with an icon, a title, minimize/maximize/close buttons,
an optional menu-bar and content-pane), as illustrated in the figure below.

Example code

Here in the above code the frame is not displayed until the frame.setVisible(true) method is invoked.
frame.setSize(400, 300) specifies that the frame is 400 pixels wide and 300 pixels
high. If the setSize method is not used, the frame will be sized to display just the title bar.
Since the setSize and setVisible methods are both defined in the Component class, they
are inherited by the JFrame class. Invoking setLocationRelativeTo(null) centers the frame on the
screen. Invoking setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) tells the program to
terminate when the frame is closed. If this statement is not used, the program does not
terminate when the frame is closed.
When you run the MyFrame program, a window will be displayed on the screen

94
Java JMenuBar, JMenu and JMenuItem

The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It
inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong
to the JMenuItem or any of its subclass.
JMenuBar class declaration
public class JMenuBar extends JComponent implements MenuElement, Accessible
JMenu class declaration
public class JMenu extends JMenuItem implements MenuElement, Accessible
JMenuItem class declaration
public class JMenuItem extends AbstractButton implements Accessible, MenuElement
Java JMenuItem and JMenu Example
1. import javax.swing.*;
2. class MenuExample
3. {
4. JMenu menu, submenu;
5. JMenuItem i1, i2, i3, i4, i5;
6. MenuExample(){
7. JFrame f= new JFrame("Menu and MenuItem Example");
8. JMenuBar mb=new JMenuBar();
9. menu=new JMenu("Menu");
10. submenu=new JMenu("Sub Menu");
11. i1=new JMenuItem("Item 1");
12. i2=new JMenuItem("Item 2");
13. i3=new JMenuItem("Item 3");
14. i4=new JMenuItem("Item 4");
15. i5=new JMenuItem("Item 5");
16. menu.add(i1); menu.add(i2); menu.add(i3);
17. submenu.add(i4); submenu.add(i5);
18. menu.add(submenu);
19. mb.add(menu);
20. f.setJMenuBar(mb);
21. f.setSize(400,400);
22. f.setLayout(null);
23. f.setVisible(true);
24. }
25. public static void main(String args[])
26. {
27. new MenuExample();
28. }}

95

You might also like