Java Programming Concepts Overview
Java Programming Concepts Overview
II Java user defined Classes and Objects – Arrays – constructors - Inheritance: Basic concepts -
Types of inheritance - Member access rules - Usage of this and Super key word - Method
Overloading - Method overriding - Abstract classes - Dynamic method dispatch - Usage of
final keyword -Packages: Definition - Access Protection - Importing Packages - Interfaces:
Definition – Implementation – Extending Interfaces
III Exception Handling: try – catch - throw - throws –- finally – Built-in exceptions - Creating
own Exception classes - garbage collection, finalise -Multithreaded Programming: Thread
Class - Runnable interface – Synchronization – Using synchronized methods – Using
synchronized statement - Interthread Communication – Deadlock.
IV The AWT class hierarchy - Swing: Introduction to Swing - Hierarchy of swing components.
Containers - Top level containers - JFrame - JWindow - JDialog - JPanel
- JButton - JToggleButton - JCheckBox - JRadioButton - JLabel,JTextField - JTextArea - JList
- JComboBox – JscrollPane - Event Handling: Events - Event sources - Event Listeners -
Event Delegation Model (EDM) - Handling Mouse and Keyboard Events
V Adapter classes - Inner classes -Java Util Package / Collections Framework:Collection &
Iterator Interface- Enumeration- List and ArrayList- Vector- Comparator
1
UNIT - 1
****************************************************************
Introduction to Java
Java is a class-based, object-oriented programming language that is designed to have as
few implementation dependencies as possible
Java is known for its simplicity, robustness, and security features, making it a popular choice
for enterprise-level applications. Java applications are compiled to byte code that can run on
any Java Virtual Machine. The syntax of Java is similar to C/C++.
Java makes writing, compiling, and debugging programming easy. It helps to create reusable
code and modular programs.
Key Features of Java
1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the bytecode
generated by the compiler. This byte code can run on any platform be it Windows, Linux, or
macOS which means if we compile a program on Windows, then we can run it on Linux and
vice versa
2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes.
The four main concepts of Object-Oriented programming are:
Abstraction
Encapsulation
Inheritance
Polymorphism
3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar with C or C+
+. It eliminates complex features like pointers and multiple inheritances, making it
easier to write, debug, and maintain code.
2
[Link]
Java language is robust which means reliable. It is developed in such a way that
it puts a lot of effort into checking errors as early as possible, that is why the java
compiler is able to detect even those errors that are not easy to detect by another
programming language. The main features of java that make it robust are garbage
collection, exception handling, and memory allocation
5. Security
In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several
security flaws like stack corruption or buffer overflow are impossible to exploit in
Java. Also, java programs run in an environment that is independent of
the os(operating system) environment which makes java programs more secure.
6. Distributed
We can create distributed applications using the java programming language. Remote
Method Invocation and Enterprise Java Beans are used for creating distributed
applications in java. The java programs can be easily distributed on one or more
systems that are connected to each other through an internet connection.
7. Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts of a
program. This feature is particularly useful for applications that require high
performance, such as games and real-time simulations.
8. Portability
java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to
any platform for execution makes java portable
9. High Performance
java uses Just In Time (JIT) compiler where the compiler compiles code on-demand
basis where it only compiles those methods that are called making applications to
execute faster.
3
OOPs Concepts:
Class
Objects
Data Abstraction
Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which
can be accessed and used by creating an instance of that class. It represents the set of
properties or methods that are common to all objects of one type. A class is like a blueprint
for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage
are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An
Object is an instance of a Class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) memory is allocated. An object has an identity, state,
and behavior. Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to know the type
of message accepted and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed,
Bark, Sleep, and Eats.
Object
4
3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the data
to the outside world, hiding the background details or implementation. Consider a real-life
example of a man driving a car. The man only knows that pressing the accelerators will
increase the speed of the car or applying brakes will stop the car, but he does not know about
how on pressing the accelerator the speed is increasing, he does not know about the inner
mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is
what abstraction is.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates. In Encapsulation, the variables or data of
a class are hidden from any other class and can be accessed only through any member
function of their class in which they are declared. As in encapsulation, the data in a class is
hidden from other classes, so it is also known as data-hiding.
Consider a real-life example of encapsulation, in a company, there are different sections like
the accounts section, finance section, sales section, etc. The finance section handles all the
financial transactions and keeps records of all the data related to finance. Similarly, the sales
section handles all the sales-related activities and keeps records of all the sales. Now there
may arise a situation when for some reason an official from the finance section needs all the
data about sales in a particular month. In this case, he is not allowed to directly access the
data of the sales section. He will first have to contact some other officer in the sales section
and then request him to give the particular data. This is what encapsulation is. Here the data
of the sales section and the employees that can manipulate them are wrapped under a single
name “sales section”.
5
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a
class to derive properties and characteristics from another class is called Inheritance. When
we write a class, we inherit properties from other classes. So when we create a class, we do
not need to write all the properties and functions again and again, as these can be inherited
from another class that possesses it. Inheritance allows the user to reuse the code whenever
possible and reduce its redundancy.
6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For
example, A person at the same time can have different characteristics. Like a man at the same
time is a father, a husband, an employee. So the same person posses different behavior in
different situations. This is called polymorphism.
6
7. Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call is decided at
runtime. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. Dynamic Method Binding One of the main
advantages of inheritance is that some derived class D has all the members of its base class B.
Once D is not hiding any of the public members of B, then an object of D can represent B in
any context where a B could be used. This feature is known as subtype polymorphism.
8. Message Passing:
It is a form of communication used in object-oriented programming as well as parallel
programming. Objects communicate with one another by sending and receiving information
to each other. A message for an object is a request for execution of a procedure and therefore
will invoke a function in the receiving object that generates the desired results. Message
passing involves specifying the name of the object, the name of the function, and the
information to be sent.
7
It lets us write generic code: which will work with a range of data, so we don’t have
to write basic stuff over and over again.
Java Buzzwords
The Java programming language can be characterized by the following buzzwords:
1. Simple
2. Object-Oriented
3. Distributed
4. Compiled and Interpreted
5. Robust
6. Secure
7. Architecture-Neutral
8. Portable
9. High Performance
10. Multithreaded
11. Dynamic
1. Simple
Java is designed to be easy for beginners and professional programmers to learn and
use effectively.
It’s simple and easy to learn if you already know the basic concepts of Object-
Oriented Programming.
Java has removed many complicated and rarely-used features, such as explicit
pointers and operator overloading.
2. Object-Oriented
Everything in Java revolves around objects and classes.
Java allows you to model real-world entities (like a car or a bank account) as objects
in your program, making it easier to manage and build complex applications.
Key Object-Oriented Programming (OOP) concepts include:
o Object: An instance of a class.
o Class: A blueprint for creating objects.
o Inheritance: Allows one class to inherit the properties of another.
o Polymorphism: The ability of objects to take on multiple forms.
o Abstraction: Hides the complex details and shows only the essentials.
o Encapsulation: Keeps the data safe by restricting access to it.
8
9
3. Distributed
Java is designed to create distributed applications on networks.
Java applications can access remote objects on the Internet as easily as they can do in
the local system.
Java enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
4. Compiled and Interpreted
Java combines both compiled and interpreted approaches, making it a two-stage
system.
Compiled: Java compiles programs into an intermediate representation called Java
Bytecode.
Interpreted: Bytecode is then interpreted, generating machine code that can be
directly executed by the machine that provides a JVM.
5. Robust
Java provides many features that make programs execute reliably in a variety of
environments.
Java is a strictly typed language that checks code at compile time and runtime.
Java handles memory management with garbage collection and captures serious errors
through exception handling.
6. Secure
Java does not use pointers, which helps prevent unauthorized memory access.
The JVM verifies Java bytecode before execution, ensuring that it adheres to Java’s
security constraints.
Java applications run in a restricted environment (sandbox) that limits their access to
system resources and user data, enhancing security.
7. Architecture-Neutral
Java language and JVM help achieve the goal of “write once; run anywhere, any time,
forever.”
Changes and upgrades in operating systems, processors, and system resources do not
force any changes in Java programs.
8. Portable
Java provides a way to download programs dynamically to various types of platforms
connected to the Internet.
10
Java is portable because of the JVM, which provides a consistent runtime
environment across different platforms.
9. High Performance
Java performance is high because of the use of bytecode.
The bytecode can be easily translated into native machine code.
10. Multithreaded
Multithreaded programs handle multiple tasks simultaneously, which is helpful in
creating interactive, networked programs.
Java run-time system supports multiprocess synchronization for constructing
interactive systems.
11. Dynamic
Java can link in new class libraries, methods, and objects dynamically.
Java programs carry substantial amounts of run-time type information, enabling
dynamic linking in a safe and expedient manner.
How JVM Works – JVM Architecture
What is JVM?
JVM stands for Java Virtual Machine. It is essentially a virtual machine or runtime
environment that allows Java programs to run and operate on multiple devices and operating
systems.
Java programs cannot run on machines that don’t have JVM support. It is an integral part of
the Java Runtime Environment (JRE). JVM features many specifications that work together
to run Java programs. It is platform-dependent by nature, i.e., every operating system has a
different JVM.
JVM Architecture
There are three notions of JVM in Java:
Implementation,
Specification,
Instance.
Implementation: Also known as JRE (Java Runtime Environment).
Specification: A document that describes the requirements for JVM implementation.
Instance: A JVM instance is created whenever you run a java class file.
JVM architecture can be divided into three major subsystems:
ClassLoader
Memory area / Runtime memory
11
Execution engine
ClassLoader:
JVM loads the compiled .class files to run Java applications, and to perform this action; a
JVM relies on its ClassLoader.
Method area
There is only one method area per JVM, and this runtime area is common to all threads. It
stores the structure of each class, such as class name, method data, methods, variables
information, etc.
Heap
The Heap memory area stores the object and its instance variable. Every time you create an
object in Java, it gets moved into the heap. The Heap area denotes a shared memory area.
Stack
Stack (also known as thread stack) is a data area within the JVM memory created for one
execution thread.
JVM stacks stores partial results, local variables, and data for method invocations and returns.
PC register
The PC register stores the address of the Java Virtual Machine instruction address currently
being executed. Each thread is assigned a separate PC register.
Native method stack
It contains all native methods needed for an application. Native methods use languages other
than Java.
12
1. Class Declaration:
Every Java program is built around classes, which act as blueprints for creating
objects.
A class defines the properties (data) and behaviors (methods) of objects.
Example: public class MyClass { ... }
2. Objects:
Objects are instances of classes, representing real-world entities or concepts.
You create objects using the new keyword: MyClass myObject = new MyClass();
3. Methods:
Methods are blocks of code that perform specific actions or operations.
They can take input (parameters) and return output (return type).
Example: public int add(int a, int b) { return a + b; }
4. main Method:
The main method is the entry point for program execution.
It's a special method with the signature: public static void main(String[] args).
The program starts executing from the code within the main method.
5. Packages and Imports:
13
Packages: Organize classes into logical groups, preventing naming conflicts and
improving code organization.
Import Statements: Allow you to use classes from other packages without having to
specify their full names.
Example: import [Link];
6. Comments:
Comments are used to explain the code and are ignored by the compiler.
Single-line comments start with //.
Multi-line comments are enclosed in /* ... */.
7. Basic Syntax:
Statements in Java end with a semicolon (;).
Code blocks are enclosed in curly braces ({ ... }).
Identifiers (names for classes, variables, methods) follow specific rules (e.g., cannot
start with a digit).
8. Object-Oriented Programming (OOP) Concepts:
Java is an object-oriented programming language, meaning it relies heavily on classes
and objects.
Key OOP concepts include:
o Encapsulation: Bundling data and methods that operate on that data within a
class.
o Inheritance: Allowing classes to inherit properties and methods from other
classes.
o Polymorphism: Enabling objects of different classes to be treated as objects
of a common type.
A basic Java program consists of several components that create a functional application. We
can learn about basic Java Syntax using the following program:
// FileName : "[Link]".
public class Geeks {
14
{
Output
Hello World
Syntax of main() Method
Syntax of the main() method is always written as:
1. Public
It is an Access modifier, which specifies from where and who can access the method.
Making the main() method public makes it globally available. It is made public so that JVM
can invoke it from outside the class as it is not present in the current class.
2. Static
It is a keyword that is when associated with a method, making it a class-related method.
The main() method is static so that JVM can invoke it without instantiating the class. This
also saves the unnecessary wastage of memory which would have been used by the object
declared only for calling the main() method by the JVM.
3. Void
It is a keyword and is used to specify that a method doesn’t return anything. As
the main() method doesn’t return anything, its return type is void. As soon as
the main() method terminates, the Java program terminates too. Hence, it doesn’t make any
sense to return from the main() method as JVM can’t do anything with its return value of it.
15
4. main
It is the name of the Java main method. It is the identifier that the JVM looks for as
the starting point of the Java program. It’s not a keyword.
If we change the name while initiating main method, we will get an error.
Example:
5. String[] args
It stores Java command-line arguments and is an array of type [Link] class.
Here, the name of the String array is args but it is not fixed and the user can use any name in
place of it.
JAVA CONSOLE OUTPUT([Link])
[Link] in Java
Java [Link]() is used to print an argument that is passed to it.
Parts of [Link]()
The statement can be broken into 3 parts which can be understood separately:
1. System: It is a final class defined in the [Link] package.
2. out: This is an instance of PrintStream type, which is a public and static member field
of the System class.
3. println(): As all instances of the PrintStream class have a public method println(), we
can invoke the same on out as well. This is an upgraded version of print(). It prints
any argument passed to it and adds a new line to the output. We can assume that
[Link] represents the Standard Output Stream.
16
Below is the implementation of [Link] :
import [Link].*;
class GFG {
public static void main(String[] args)
{
[Link]("Welcome");
[Link]("To");
[Link]("GeeksforGeeks");
}
}
Output
Welcome
To
GeeksforGeeks
17
18
Primitive Data Types
19
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
Java Variables
Variables are the containers for storing the data values or you can also call it a memory
location name for the data. Every variable has a:
Data Type – The kind of data that it can hold. For example, int, string, float, char, etc.
Variable Name – To identify the variable uniquely within the scope.
Value – The data assigned to the variable.
There are three types of variables in Java – Local, Instance, and Static.
Example:
int age = 27; // integer variable having value 27
20
Because in many cases, We have to Cast large datatype values into smaller datatype values
according to the requirement of the operations. We can also convert large datatype values
into smaller datatype values that’s why Type Casting called Narrow Casting.
RequiredDatatype=(TargetType)Variable
Type Conversion is a type conversion that is done by compiler done by a compiler without
the intention of the programmer during the compile time. This Conversion sometimes creates
an error or incorrect answer if the proper resultant data type does not mention at the end of
the multiple expression of the datatype that’s why Type Conversion is less efficient than Type
Casting.
The working mechanism of type conversion is as follows:
double > float > long > int > short > byte
21
Java Operators
Java operators are special symbols that perform operations on variables or values. They can
be classified into several categories based on their functionality
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive and non-
primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or negate a
value.
- , Negates the value.
+ , Indicates a positive value (automatically converts byte, char, or short to int).
++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
-- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
! , Inverts a boolean value.
22
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable.
The general format of the assignment operator is:
variable = value;
4. Relational Operators
Relational Operators are used to check for relations like equality, greater than, and less than.
Relational operators compare values and return boolean results:
== , Equal to.
!= , Not equal to.
< , Less than.
<= , Less than or equal to.
> , Greater than.
>= , Greater than or equal to.
5. Logical Operators
Logical Operators are used to perform “logical AND” and “logical OR” operations,
Conditional operators are:
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three operands
and hence the name Ternary. The general format is ,
condition ? if true : if false
7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a number and
with any of the integer types. They are used when performing update and query operations of
the Binary indexed trees.
& (Bitwise AND) – returns bit-by-bit AND of input values.
| (Bitwise OR) – returns bit-by-bit OR of input values.
^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
~ (Bitwise Complement) – inverts all bits (one’s complement).
8. Shift Operators
Shift Operators are used to shift the bits of a number left or right
23
<< (Left shift) – Shifts bits left, filling 0s (multiplies by a power of two).
>> (Signed right shift) – Shifts bits right, filling 0s (divides by a power of two), with
the leftmost bit depending on the sign.
>>> (Unsigned right shift) – Shifts bits right, filling 0s, with the leftmost bit always
0
9. instanceof operator
The instance of operator is used for type checking. It can be used to test if an object is an
instance of a class, a subclass, or an interface. The general format ,
object instance of class/subclass/interface
Decision-Making statements:
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false.
In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
24
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
2. if-else statement
The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is
evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
25
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if
statements. In other words, we can say that it is the chain of if-else statements that
create a decision tree where the program may enter in the block of code where the
condition is true. We can also define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
26
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside
another if or else-if statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
27
Loop Statements
In Java, we have three types of loops that execute similarly.
1. for loop
2. while loop
3. do-while loop
1. for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
28
Java while loop
The while loop is also used to iterate over the number of statements multiple times
The syntax of the while loop is given below.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
29
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
Jump Statements
Java break statement
As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop.
Example
1. public class Main {
2. public static void main(String[] args) {
3. for(int i = 0; i<= 10; i++) {
4. [Link](i);
30
5. if(i==6) {
6. break;
7. }
8. }
9. }
10. }
31
Static variables
When a variable is declared as static, then a single copy of the variable is created and
shared among all objects at the class level. Static variables are, essentially, global variables.
All instances of the class share the same static variable.
Important points for static variables:
We can create static variables at the class level only.
static block and static variables are executed in the order they are present in a
program.
Static methods
When a method is declared with the static keyword, it is known as the static method.
The most common example of a static method is the main( ) method. As discussed
above, Any static member can be accessed before any objects of its class are created,
and without reference to any object. Methods declared as static have several
restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
32
Methods of Java StringBuffer Class
33
StringBuffer Class
34
UNIT-2
Java user defined Classes and Objects – Arrays – constructors - Inheritance: Basic concepts -
Types of inheritance - Member access rules - Usage of this and Super key word - Method
Overloading - Method overriding - Abstract classes - Dynamic method dispatch - Usage of
final keyword -Packages: Definition - Access Protection - Importing Packages - Interfaces:
Definition – Implementation – Extending Interfaces
Java Class
A Java classes is a blueprint or template used to create object. It serves as a fundamental
building block in Java programming, encapsulating data (fields) and behaviors (methods) into
a single unit.
a Java class defines the structure and behavior of objects, serving as a blueprint for creating
instances of that class.
Properties of Java Classes
A Java class serves as a blueprint for creating objects and doesn’t take up memory.
It comprises variables of various types and methods. You can include data members,
methods, constructors, nested classes, and interfaces within a class.
It acts as a template for organizing and defining the behaviour of objects in your
program.
Syntax of Java Classes
package [Link];
import [Link];
public class MyClass {
private int age;
public MyClass(int age) {
[Link] = age;
}
public void display() {
[Link]("Age: " + age);
}
}
35
This syntax defines a class named MyClass in the [Link] package, with a
private field age, a constructor that initializes age, and a method display() to print the age.
36
The Java file can contain any number of classes but should not have more than one
public class. The file name should be named after the public class followed by the
“.java” extension.
One class should only inherit another single class.
Types of classes
There are two types of classes-
1. Built-in classes
2. User-defined classes
Built-in classes- The built-in classes are those which are pre-defined by the
developers in JDK.
Examples include-
[Link]
[Link]
User-defined classes- So as the name suggests, user-defined classes are the classes
created by the user. We can add our functionality to the classes.
Java Objects
Syntax of an object
The syntax for creating an object in Java is:
ClassName objectName = new ClassName();
Car myCar = new Car();
37
Here, Car is the class name, myCar is the object name, and new Car() instantiates a new
object of the Car class.
Initializing an object
In Java, we can initialize objects in 3 ways-
By reference variable
By method
By constructor
By reference variable– Initialization of an object means storing the data in the object.
Let us understand this with an example-
public class MyClass {
public static void main(String[] args) {
// Initialize the object by reference variable in a single line
MyClass myObject = new MyClass();
// Access methods or fields of the object
[Link]();
}
public void myMethod() {
[Link]("Object initialized successfully!");
}
}
38
Difference Between Java Classes and Object
Arrays in Java
What is an Array in Java?
An array refers to a data structure that contains homogeneous elements. This means
that all the elements in the array are of the same data type. Let's take an example:
1. Dynamic allocation: In arrays, the memory is created dynamically, which reduces the
amount of storage required for the code.
2. Elements stored under a single name: All the elements are stored under one name.
This name is used any time we use an array.
3. Occupies contiguous location: The elements in the arrays are stored at adjacent
positions. This makes it easy for the user to find the locations of its elements.
39
Now that we understand what Java arrays are- let us look at how arrays in Java are
declared and defined.
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
We have now declared a variable that holds an array of strings. To insert values to it,
you can place the values in a comma-separated list, inside curly braces:
Example:
Array Length
To find out how many elements an array has, use the length property:
Example
40
Types of Arrays
There are three types of arrays. We use these types of arrays as per the requirement of
the program. These are:
1. One-dimensional Array
Also known as a linear array, the elements are stored in a single row. For example:
In this example, we have an array of five elements. They are stored in a single line or
adjacent memory locations.
Look at this example in Java code. Here, the five elements are 1, 2, 3, 4, and 5. We
use a for loop to print the elements of the array. The output of this is as follows:
41
2. Two-dimensional Array
Two-dimensional arrays store the data in rows and columns:
In this, the array has two rows and five columns. The index starts from 0,0 in the left-
upper corner to 1,4 in the right lower corner.
In this Java code, we have a two-dimensional array. We have two rows and three
columns. Brackets separate the rows, and the number of elements separates the
columns. For this, we use two for loops: one for rows and one for each element in the
row. When we execute this program, the result will be as follows:
3. Multi-dimensional Array
This is a combination of two or more arrays or nested arrays. We can even use more
than two rows and columns using the following code:
42
Here, we are using three rows and three columns, but we are only using two for loops.
Regardless of how many rows and columns are entered, the number of for loops will
always be two.
The above program will add all the elements defined in my_array[] and produce the
result.
Constructors in Java
In Java, a Constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling the constructor, memory for the
object is allocated in the memory. It is a special type of method that is used to
initialize the object. Every time an object is created using the new() keyword, at least
one constructor is called.
Syntax
public class MyClass {
// Constructor
public MyClass() {
// Initialization code goes here
}
43
Types of Java Constructors
Parameterized Constructor
44
constructor, which takes no arguments, a parameterized constructor allows you to pass
values at the time of object creation to set initial states.
Here’s an example of a parameterized constructor in Java:
// Parameterized constructor
public MyClass(int intValue, String stringValue) {
myInt = intValue;
myString = stringValue;
}
In Java, constructors are similar to methods but without a return type. They can be
overloaded, just like methods, allowing for the creation of multiple constructors with
different parameter lists. Each constructor can serve a distinct purpose, with the
compiler distinguishing them based on the number and types of parameters they
accept. This technique, known as constructor overloading, enables flexibility in
initializing objects based on varying sets of input parameters.
class Dogs {
public Dogs() {
// No initialization parameters
}
45
public Dogs(String breed) {
[Link] = breed;
}
[Link](0);
[Link]("Woof");
// A dog with both name and breed initialized at the time of object creation.
Dogs dog3 = new Dogs("Snoopy", "German Shepherd");
}
}
Output:
Dog is not running
Dog is wagging its tail
A Copy Constructor in Java is used to create an object with the help of another object
of the same Java class.
46
The copy constructor has at least one object of the same class as an argument. The
primary objective of the copy constructor is to create a new object with the same
properties as that of the passed argument.
// Copy constructor
public MyClass(MyClass original) {
[Link] = [Link];
[Link] = [Link];
}
// Parameterized constructor
public MyClass(int intValue, String stringValue) {
[Link] = intValue;
[Link] = stringValue;
}
[Link]("nCopied Object:");
[Link]();
}
}
47
In Java, it is possible to inherit attributes and methods from one class to another. We
group the "inheritance concept" into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
In the example below, the Car class (subclass) inherits the attributes and methods
from the Vehicle class (superclass):
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
[Link]("Tuut, tuut!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar object
[Link]();
// Display the value of the brand attribute (from the Vehicle class) and the value of
the modelName from the Car class
[Link]([Link] + " " + [Link]);
}
}
48
Multiple Inheritance
Hybrid Inheritance
49
1. Single-level inheritance
Single-level inheritance in Java is a fundamental concept where a subclass inherits
from only one superclass. This means that the subclass can acquire the properties and
methods of the superclass, enabling code reuse and the extension of existing
functionality.
2. Multi-level Inheritance
Multilevel inheritance in Java is a feature that allows a class to inherit properties
and behaviours from another class, which in turn inherits from another class, forming
a "chain" of inheritance. This mechanism enables a class to inherit methods and fields
from multiple ancestors but in a direct line, where each class in the chain inherits from
one class directly above it.
3. Hierarchical Inheritance
Hierarchical inheritance in Java occurs when one base class (superclass) is
inherited by multiple subclasses. In this type of inheritance, all the features that are
common in child classes are included in the base class. This way, the code becomes
more manageable and reusable.
50
A graphical illustration of hierarchical inheritance is given below:
4. Multiple Inheritance
Multiple inheritance refers to a feature in object-oriented programming where a
class can inherit properties and methods from more than one parent class. This
concept allows a subclass to inherit behaviours and attributes from multiple base (or
super) classes, creating a rich, multifaceted hierarchy.
An interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types.
Interfaces cannot contain instance fields or constructor methods.
51
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance, such as
hierarchical, multiple, multilevel, or single inheritance. It integrates various
inheritance mechanisms to achieve a specific design or functionality
Modifier Description
52
53
Public Access Modifier
When methods, variables, classes, and so on are declared public, then we can access
them from anywhere. The public access modifier has no scope restriction.
// [Link] file
// public class
public class Animal {
// public variable
public int legCount;
// public method
public void display() {
[Link]("I am an animal.");
[Link]("I have " + legCount + " legs.");
}
}
// [Link]
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();
Output:
I am an animal.
I have 4 legs.
When variables and methods are declared private, they cannot be accessed outside of
the class.
For example,
class Data {
// private variable
private String name;
}
54
public class Main {
public static void main(String[] main){
Output:
The name is Programiz
When methods and data members are declared protected, we can access them within
the same package as well as from subclasses.
For example,
class Animal {
// protected method
protected void display() {
[Link]("I am an animal");
}
}
Output:
I am an animal
Default Access Modifier
If we do not explicitly specify any access modifier for classes, methods, variables, etc,
then by default the default access modifier is considered.
package defaultPackage;
55
class Logger {
void message(){
[Link]("This is a message");
}
}
Access Parent Class Variables: When a child class has a variable with the same
name as its parent class, super helps access the parent’s variable.
Call Parent Class Methods: If a child class overrides a method from its parent, super
allows calling the parent class’s version of the method.
Invoke Parent Class Constructor: super() can be used to call the parent class
constructor from a child class constructor.
Differentiate Between Parent and Child Class Members: It helps when both parent
and child classes have members with the same name.
Improve Code Reusability: By using super, we can reuse parent class functionalities
instead of rewriting code in the child class.
Syntax
super();
[Link]();
[Link];
In this example, the super() call in the Dog constructor invokes the constructor of
the Animal class.
Example 1: Calling Superclass Constructor
class Animal {
class Animal {
Animal() {
[Link]("Animal constructor called");
}
}
56
super(); // Calls the constructor of Animal class
[Link]("Dog constructor called");
}
}
Here, the [Link]() call in the Dog class method sound() invokes
the sound() method of the Animal class.
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
In this example, [Link] is used to access the color field of the Animal class,
which is hidden by the color field in the Dog class.
class Animal {
57
String color = "white";
}
class Dog extends Animal {
String color = "black";
void displayColor() {
[Link]("Dog color: " +// Prints the color of Dog class
[Link]("Animal color: " + super.// Prints the color of Animal class
}
}
public class TestSuper {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Output: Dog color: black
// Animal color: white
}
this keyword:
It is a reserved keyword in Java that is used to refer to the current class object. It is a
reference variable through which the method is called. Other uses of this keyword are:
o We can use it to refer current class instance variable.
o We can use it to invoke the current class method (implicitly).
o We can pass it as an argument in the method and constructor calls.
o We can also use it for returning the current class instance from the method.
this super
The current instance of the class is The current instance of the parent class is
represented by this keyword. represented by the super keyword.
In order to call the default constructor of the In order to call the default constructor of the
current class, we can use this keyword. parent class, we can use the super keyword.
It can be referred to from a static context. It It can't be referred to from a static context. It
means it can be invoked from the static means it cannot be invoked from a static
context. context.
We can use it to access only the current class We can use it to access the data members and
data members and member functions. member functions of the parent class.
58
Java Method Overriding
Method overriding allows us to achieve run-time polymorphism and is used for writing
specific definitions of a subclass method that is already defined in the superclass.
The method is superclass and overridden method in the subclass should have the same
declaration signature such as parameters list, type, and return type.
Usage of Java Method Overriding
Following are the two important usages of method overriding in Java:
Method overriding is used for achieving run-time polymorphism.
Method overriding is used for writing specific definition of a subclass method (this
method is known as the overridden method).
Rules for Method Overriding
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
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 overridding method
in the sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared
public or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should
not throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions
than the overridden method.
Constructors cannot be overridden.
59
Java Method Overriding: Using the super Keyword
Example: Using the super Keyword
class Animal {
public void move()
{
[Link]("Animals can move");
}
}
class Dog extends Animal { public void move()
{
[Link]();
// invokes the super class method
[Link]("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[])
{
Animal b = new Dog();
// Animal reference but Dog object
[Link]();
// runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run
60
Java Method Overloading
In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called
overloaded methods and this feature is called method overloading. For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Here are different ways to perform method overloading:
1. Overloading by changing the number of parameters
class MethodOverloading {
private static void display(int a){
[Link]("Arguments: " + a);
}
61
private static void display(int a){
[Link]("Got Integer data.");
}
Important Points
Two or more methods can have the same name inside the same class if they accept
different arguments. This feature is known as method overloading.
Method overloading is achieved by either:
o changing the number of arguments.
o or changing the data type of arguments.
It is not method overloading if we only change the return type of methods. There must
be differences in the number of parameters.
62
Difference between method overloading and method overriding:
Java Abstraction
Abstract Classes and Methods
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).
63
[Link]("Zzz");
Java Polymorphism
Polymorphism in Java is a core concept of object-oriented programming (OOP) that allows
objects to be treated as instances of their parent class. It facilitates flexibility and the ability to
define methods in multiple forms. Polymorphism is primarily achieved through method
overriding and method overloading.
Usage
Polymorphism is used to perform a single action in different ways. It allows for the
implementation of dynamic method dispatch, where the method to be executed is determined
at runtime. This is beneficial for implementing a cleaner and more maintainable codebase.
Types of Polymorphism
1. Compile-time Polymorphism (Method Overloading): Achieved by defining
multiple methods with the same name but different parameters within the same class.
2. Runtime Polymorphism (Method Overriding): Achieved when a subclass provides
a specific implementation of a method already defined in its superclass.
Examples
Example 1: Method Overloading
64
}
}
In this example, the add method is overloaded with two different parameter lists. The
appropriate method is called based on the arguments passed.
Example 2: Method Overriding
class Animal {
public void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
[Link]("Dog barks");
}
}
public class OverridingExample {
public static void main(String[] args) {
Animal myAnimal = new Dog();
[Link](); // Outputs "Dog barks"
}
}
Here, the Dog class overrides the sound method of the Animal class. The sound method of
the Dog class is invoked at runtime.
final Keyword in Java
The final keyword in Java is a non-access modifier that can be applied to variables, methods,
and classes. It is used to restrict the user from further modifying the entity to which it is
applied. This keyword plays a crucial role in ensuring immutability and preventing
inheritance or method overriding.
Usage:
1. final Variables
A final variable is a constant; once initialized, its value cannot be changed.
65
final int MAX_VALUE = 100;
Initialization of final Variables
A final variable must be initialized when it is declared or within a constructor if it is an
instance variable.
public class FinalInitialization {
final int MAX_VALUE;
public FinalInitialization() {
MAX_VALUE = 100;
}
}
Examples
Example 1: final Variable
public class FinalVariableExample {
public static void main(String[] args) {
final int MAX_VALUE = 100;
[Link]("MAX_VALUE: " + MAX_VALUE);
// MAX_VALUE = 200; // This will cause a compilation error
}
}
2. final Methods
A final method cannot be overridden by subclasses, ensuring that the method's
implementation remains unchanged.
class Parent {
public final void display() {
[Link]("This is a final method.");
}
}
Example 2: final Method
class Parent {
public final void display() {
66
[Link]("This is a final method.");
}
}
3. final Classes
A final class cannot be subclassed, preventing inheritance.
public final class FinalClass {
// Class implementation
}
Example 3: final Class
public final class FinalClass {
public void show() {
[Link]("This is a final class.");
}
}
// class SubClass extends FinalClass { // This will cause a compilation error
// }
67
public class FinalClassExample {
public static void main(String[] args) {
FinalClass obj = new FinalClass();
[Link]();
}
}
Packages in Java
A Java package is a group of similar types of classes, interfaces and sub-packages.
Organise Classes: For organizing the class, interfaces and other components, packages are
used.
o Control Access: It is the package that controls the access of the protected and default
members. Think what would be the use of default and protected access specifiers if
packages were absent?
o Reusability: Java enhances the reusability management of code and does the
promotion of data encapsulation with the help of packages.
Types of Packages
There are two types of packages in Java.
1. Built-in Packages
2. User-defined Packages
[Link]-in Packages
Some of the built-in packages that are used commonly are:
[Link]: It contains those classes that are required for language support, such as classes for
primitive data types and math operations. This package is automatically imported into Java.
68
[Link]: It contains all those classes that are required for the input/output operations.
[Link]: It contains utility classes that are needed for the data structures, such
as Array, List, Map, etc.
[Link]: All those classes that are required for finding applets are found in this package.
[Link]: It contains all those classes that are required for creating components of GUI
(Graphical User Interface).
[Link]: It includes classes that are used for doing tasks in the field of networking.
[Link]-defined Packages
In this section, we will create two Java files in two different packages (or folders). We will
also create three files. One file each for both the folders, and the last file is of the main class.
How to Create a Package?
To create a package in Java, you use the `package` keyword. The package statement must be
the first line in the source file (excluding comments).
Creating a Package:
//File:com/example/[Link]
[Link];
Public class HelloWorld {
public void greet() {
[Link]("Hello from the [Link] package!");
}
}
In this example:
- The `package [Link];` statement defines that the class `HelloWorld` belongs to the
`[Link]` package.
- The folder structure should mirror the package name (`com/example/`).
5. Accessing Classes from Packages
To access a class from a package, the fully qualified name of the class (including the package
name) should be used, or the class should be imported.
Accessing Without Import:
[Link] hello = new [Link]();
[Link]();
6. Importing Packages
Java provides the `import` statement to import classes or entire packages.
1. Importing a Single Class:
import [Link];
69
2. Importing All Classes in a Package:
import [Link].*;
In the second example, all classes within the `[Link]` package will be imported.
7. Sub-packages in Java
Java supports sub-packages, which are simply packages within other packages. There is no
special syntax for sub-packages; they are treated like regular packages, but the hierarchy is
created by adding dots in the package name.
Example:
package [Link];
8. Package Naming Conventions
Java follows certain conventions for naming packages to ensure uniqueness and clarity:
1. Reverse Domain Name: Use your domain name in reverse as the base of your package
names. For example, if your domain is `[Link]`, start your package with
`[Link]`.
2. Lowercase Names: Use lowercase letters to avoid conflicts with class names.
3. Meaningful Names: Use descriptive and meaningful names to reflect the content of the
package.
9. Java Built-in Packages
Java comes with several built-in packages that provide a wide range of functionalities. Some
common built-in packages are:
- [Link]: Provides classes fundamental to the Java language (automatically imported).
- [Link]: Contains utility classes, including collections framework, date, time facilities, and
more.
- [Link]: Contains classes for input/output operations (e.g., file handling).
- [Link]: Contains classes for networking operations.
- [Link]: Contains classes for database access and processing.
Java Interface
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:
Example
// interface
70
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
Relationship Between Class and Interface
A class can extend another class, and similarly, an interface can extend another interface.
However, only a class can implement an interface, and the reverse (an interface implementing
a class) is not allowed.
Notes on Interfaces:
Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object
(interface).
71
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple
interfaces
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
[Link]("Some text..");
}
public void myOtherMethod() {
[Link]("Some other text...");
}
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
[Link]();
[Link]();
}
}
72
UNIT-IV
The AWT class hierarchy - Swing: Introduction to Swing - Hierarchy of swing
components. Containers - Top level containers - JFrame - JWindow - JDialog - JPanel -
JButton - JToggleButton - JCheckBox - JRadioButton - JLabel,JTextField - JTextArea -
JList - JComboBox – JscrollPane - Event Handling: Events - Event sources - Event
Listeners - Event Delegation Model (EDM) - Handling Mouse and Keyboard Events
***************************************************************************
Java AWT
Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User
Interfaces) or Window-Based Applications in Java. Java AWT is part of the Java Foundation
Classes (JFC) that provides a way to build platform-independent graphical applications.
Java AWT Basics
Java AWT (Abstract Window Toolkit) is an API used to create Graphical User Interface
(GUI) or Windows-based Java programs and Java AWT components are platform-dependent,
which means they are shown in accordance with the operating system’s view. AWT is
heavyweight, which means that its components consume resources from the underlying
operating system (OS). The [Link] package contains AWT API classes such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List, and so on.
Why AWT is Platform Independent?
AWT is platform independent even after the AWT components are platform dependent
because of the points mentioned below:
1. JVM (Java Virtual Machine):
As Java Virtual Machine is platform dependent
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through
Abstract API which are platform independent. Abstract API allows Java to isolate platform-
specific details, making code portable across different systems.
3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent.
Because of this, it ensures that AWT functionality remains consistent across different
environments.
73
Java AWT Hierarchy
Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
Containers: AWT provides containers like panels, frames, and dialogues to organize
and group components in the Application.
Layout Managers: Layout Managers are responsible for arranging data in the
containers some of the layout managers are BorderLayout, FlowLayout, etc.
Event Handling: AWT allows the user to handle the events like mouse clicks, key
presses, etc. using event listeners and adapters.
Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert
images and write text in the components of a Java Application.
Types of Containers in Java AWT
There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents a graphical window or
dialog box. The Window class extends the Container class, which means it can
contain other components, such as buttons, labels, and text fields.
2. Panel: Panel is a container class in Java. It is a lightweight container that can be used
for grouping other components together within a window or a frame.
3. Frame: The Frame is the container that contains the title bar and border and can have
menu bars.
4. Dialog: A dialog box is a temporary window an application creates to retrieve user
input.
74
Introduction to Java Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components,
expanded components features, and excellent event handling with drag-and-drop support.
Difference between Java Swing and Java AWT
There are certain points from which Java Swing is different than Java AWT as mentioned
below:
Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java. and is used to create various applications.
Execution Time is more than Swing. Execution Time is less than AWT.
75
depend on any non-Java [O/s based) system classes. Swing components have their
own view supported by Java’s look and feel classes.
Pluggable Look and Feel: This feature enable the user to switch the look and feel of
Swing components without restarting an application. The Swing library supports
components’ look and feels that remain the same across all platforms wherever the
program runs. The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.
76
77
Java JComponent
Intermediate Containers
These containers hold other components and help organize the GUI. They include:
JPanel: A general-purpose container.
JScrollPane: Provides scrollbars for components that exceed the display area.
JSplitPane: Allows dividing the window into resizable panels.
Basic Components
Layout Managers
Layout managers control the arrangement of components within a container:
FlowLayout: Arranges components in a row, wrapping to the next row if necessary
(default for JPanel).
BorderLayout: Arranges components in five regions: North, South, East, West, and
Center (default for JFrame).
78
GridLayout: Arranges components in a grid of rows and columns.
CardLayout: Allows switching between different components in the same space.
GridBagLayout: Provides a flexible grid-based layout with advanced customization
options.
Event Handling
Event handling is the process of responding to user interactions, such as button clicks
or mouse movements. The delegation event model is commonly used, where event
listeners are attached to components to handle specific events.
Model-View-Controller (MVC)
MVC is an architectural pattern for separating the application logic into three
interconnected parts:
Model: Represents the data and business logic.
View: Displays the data to the user.
Controller: Handles user input and updates the model and view.
Swing components are often used in the view part of an MVC architecture, while
event handling mechanisms facilitate the interaction between the controller and the
other parts.
79
user. For example, a button, check-box, radio-button, text-field, etc. These together form the
components in Swing.
Components of Swing in Java
Below are the different components of swing in java:
1. ImageIcon
The ImageIcon component creates an icon sized-image from an image residing at the source
URL.
Example:
ImageIcon homeIcon = new ImageIcon("src/images/[Link]");
This returns an icon of a home button. The string parameter is the path at which the source
image is present.
2. JButton
JButton class is used to create a push-button on the UI. The button can contain some display
text or image. It generates an event when clicked and double-clicked. A JButton can be
implemented in the application by calling one of its constructors.
Example:
JButton okBtn = new JButton("Ok");
This constructor returns a button with text Ok on it.
JButton homeBtn = new JButton(homeIcon);
It returns a button with a homeIcon on it.
JButton btn2 = new JButton(homeIcon, "Home");
It returns a button with the home icon and text Home.
3. JLabel
JLabel class is used to render a read-only text label or images on the UI. It does not generate
any event.
Example:
JLabel textLbl = new JLabel("This is a text label.");
This constructor returns a label with text.
JLabel imgLabel = new JLabel(homeIcon);
It returns a label with a home icon.
4. JTextField
JTextField renders an editable single-line text box. A user can input non-formatted text in the
box. To initialize the text field, call its constructor and pass an optional integer parameter to
80
it. This parameter sets the width of the box measured by the number of columns. It does not
limit the number of characters that can be input in the box.
Example:
JTextField txtBox = new JTextField(20);
It renders a text box of 20 column width.
5. JTextArea
JTextArea class renders a multi-line text box. Similar to the JTextField, a user can input non-
formatted text in the field. The constructor for JTextArea also expects two integer parameters
which define the height and width of the text-area in columns. It does not restrict the number
of characters that the user can input in the text-area.
Example:
JTextArea txtArea = new JTextArea("This text is default text for text area.", 5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20 columns, with
default text initialized in the text-area.
6. JPasswordField
JPasswordField is a subclass of JTextField class. It renders a text-box that masks the user
input text with bullet points. This is used for inserting passwords into the application.
Example:
JPasswordField pwdField = new JPasswordField(15);
var pwdValue = [Link]();
It returns a password field of 15 column width. The getPassword method gets the value
entered by the user.
7. JCheckBox
JCheckBox renders a check-box with a label. The check-box has two states – on/off. When
selected, the state is on and a small tick is displayed in the box.
Example:
CheckBox chkBox = new JCheckBox("Show Help", true);
It returns a checkbox with the label Show Help. Notice the second parameter in the
constructor. It is a boolean value that indicates the default state of the check-box. True means
the check-box is defaulted to on state.
8. JRadioButton
JRadioButton is used to render a group of radio buttons in the UI. A user can select one
choice from the group.
81
Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Easy", true);
JRadioButton rb2 = new JRadioButton("Medium");
JRadioButton rb3 = new JRadioButton("Hard");
[Link](rb1);
[Link](rb2);
[Link](rb3);
The above code creates a button group and three radio button elements. All three elements are
then added to the group. This ensures that only one option out of the available options in the
group can be selected at a time. The default selected option is set to Easy.
9. JList
JList component renders a scrollable list of elements. A user can select a value or multiple
values from the list. This select behavior is defined in the code by the developer.
Example:
DefaultListItem cityList = new DefaultListItem();
[Link]("Mumbai"):
[Link]("London"):
[Link]("New York"):
[Link]("Sydney"):
[Link]("Tokyo"):
JList cities = new JList(cityList);
[Link](ListSelectionModel.SINGLE_SELECTION);
The above code renders a list of cities with 5 items in the list. The selection restriction is set
to SINGLE_SELECTION. If multiple selections is to be allowed, set the behavior to
MULTIPLE_INTERVAL_SELECTION.
10. JComboBox
JComboBox class is used to render a dropdown of the list of options.
Example:
String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo" };
JComboBox cities = new JComboBox(cityList);
[Link](3);
82
The default selected option can be specified through the setSelectedIndex method. The above
code sets Sydney as the default selected option.
11. JFileChooser
JFileChooser class renders a file selection utility. This component lets a user select a file
from the local system.
Example:
JFileChooser fileChooser = new JFileChooser();
JButton fileDialogBtn = new JButton("Select File");
[Link](new ActionListner(){
[Link]();
})
var selectedFile = [Link]();
The above code creates a file chooser dialog and attaches it to the button. The button click
would open the file chooser dialog. The selected file is returned through the getSelectedFile
method.
12. JTabbedPane
JTabbedPane is another very useful component that lets the user switch between tabs in an
application. This is a highly useful utility as it lets the user browse more content without
navigating to different pages.
Example:
JTabbedPane tabbedPane = new JTabbedPane();
[Link]("Tab 1", new JPanel());
[Link]("Tab 2", new JPanel());
The above code creates a two tabbed panel with headings Tab 1 and Tab 2.
13. JSlider
JSlider component displays a slider which the user can drag to change its value. The
constructor takes three arguments – minimum value, maximum value, and initial value.
Example:
JSlider volumeSlider = new JSlider(0, 100, 50);
var volumeLevel = [Link]();
The above code creates a slider from 0 to 100 with an initial value set to 50. The value
selected by the user is returned by the getValue method.
Event Handling in Java
83
An event is a change in the state of an object triggered by some action such as Clicking a
button, Moving the cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java,
the [Link] package provides various event classes to handle these actions.
Classification of Events
Events in Java can be broadly classified into two categories based on how they are generated:
1. Foreground Events: Foreground events are the events that require user interaction to
generate. Examples of these events include Button clicks, Scrolling the scrollbar,
Moving the cursor, etc.
2. Background Events: Events that don’t require interactions of users to generate are
known as background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.
Event Handling Mechanism
Event handling is a mechanism that allows programs to control events and define what should
happen when an event occurs. Java uses the Delegation Event Model to handle events. This
model consists of two main components:
Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
Listeners: Listeners are used for handling the events generated from the source. Each
of these listeners represents interfaces that are responsible for handling events.
84
Registering the Source With Listener
To handle events, the source must be registered with a listener. Java provides specific
methods for registering listeners based on the type of event.
Syntax:
addTypeListener()
For example,
addKeyListener() for KeyEvent
addActionListener() for ActionEvent
Event Classes and Listener Interfaces
Java provides a variety of event classes and corresponding listener interfaces. Below
table demonstrates the most commonly used event classes and their associated
listener interfaces:
85
Event Class Listener Interface Description
86
Each listener interface contains specific methods that must be implemented to handle events.
Below table demonstrates the key methods for each interface:
ActionListener actionPerformed()
AdjustmentListene adjustmentValueChang
r ed()
componentResized()
ComponentListene componentShown()
r componentMoved()
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener itemStateChanged()
keyTyped()
KeyListener keyPressed()
keyReleased()
mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()
87
Listener Interface Methods
MouseMotionListe mouseMoved()
ner mouseDragged()
MouseWheelListen
mouseWheelMoved()
er
TextListener textChanged()
windowActivated()
windowDeactivated()
windowOpened()
WindowListener windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
TextField textField;
88
GFGTop()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
89
public static void main(String[] args)
{
new GFGTop();
}
}
Output:
Explanation:
Firstly extend the class with the applet and implement the respective listener.
Create Text-Field and Button components.
Registered the button component with respective event. i.e. ActionEvent by
addActionListener().
In the end, implement the abstract method.
90
TextField textField;
GFG2()
{
// Component Creation
textField = new TextField();
// setBounds method is used to provide
// position and size of component
[Link](60, 50, 180, 25);
Button button = new Button("click Here");
[Link](100, 120, 80, 30);
Other other = new Other(this);
// Registering component with listener
// Passing other class as reference
[Link](other);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
public static void main(String[] args)
{
new GFG2();
}
}
91
Separate class implementing ActionListener to handle events:
/// import necessary packages
import [Link].*;
// implements the listener interface
class Other implements ActionListener {
GFG2 gfgObj;
Other(GFG1 gfgObj) {
[Link] = gfgObj;
}
92
3. Event Handling By Anonymous Classes
// Java program to demonstrate the
// event handling by the anonymous class
import [Link].*;
import [Link].*;
TextField textField;
GFG3()
{
// Component Creation
textField = new TextField();
93
// add Components
add(textField);
add(button);
94
UNIT- V
Adapter classes - Inner classes -Java Util Package / Collections
Framework:Collection & Iterator Interface- Enumeration- List and ArrayList-
Vector- Comparator
Class Adapter
A class adapter uses inheritance to adapt the interfaces of two different classes. It
extends the class that needs to be adapted and implements the interface expected by
the client class. As a result, it inherits the functionality of the adapter class and makes
it available through the interface required by the client.
public interface Target {
void request();
} public class Adaptee {
95
public void specificRequest() {
// Specific implementation
}
} public class ClassAdapter extends Adaptee implements Target {
public void request() {
specificRequest(); // Reusing adaptee's functionality
}
}
In the example above, the “Target” interface defines the expected interface for the
client class. The “Adaptee class” represents the existing functionality that needs to be
adapted. The ClassAdapter class extends “Adaptee” and implements Target,
providing the necessary adaptation by calling the specific method of the “Adaptee”
within the request() method.
Object Adapter
An object adapter uses composition to adapt the interfaces of two different classes. It holds an
instance of the “adaptee class” and implements the interface expected by the client class. By
doing so, it delegates the method calls from the client to the “adaptee”, effectively adapting
the functionality.
public interface Target {
void request();
} public class Adaptee {
public void specificRequest() {
// Specific implementation
}
} public class ObjectAdapter implements Target {
private Adaptee adaptee; public ObjectAdapter(Adaptee adaptee) {
[Link] = adaptee;
} public void request() {
[Link](); // Delegating to adaptee's functionality
}
}
In this example, the “Target” interface defines the expected interface for the client class,
while the “Adaptee class” represents the existing functionality. The ObjectAdapter class
implements Target and holds an instance of “Adaptee”. By implementing
96
the “request()” method and delegating the call to the “specificRequest()” method of
the adaptee, the object adapter achieves the desired adaptation.
97
public static void main(String[] args) {
Square square = new Square();
Circle circle = new SquareToCircleAdapter(square);
double area = [Link]();
[Link]("Area: " + area);
}
}
In the example above, we create an adapter class called “SquareToCircleAdapter” that
implements the Circle interface. This adapter class takes an instance of the Square class as a
constructor argument. By implementing the “computeArea()” method in the adapter class
and delegating the call to the square’s “calculateArea()” method, we establish compatibility
between the two classes.
Benefits of Adapter Classes
1) Code reusability: Adapter classes enable the reuse of existing classes that have
incompatible interfaces, saving development time and effort.
2) Seamless integration: Adapter classes facilitate the integration of legacy or third-party
code into new systems, even when the interfaces differ.
3) Modularity: Adapter classes allow you to keep existing code intact while adapting it to
new requirements, promoting modular and maintainable codebases.
4) Flexibility: Through adapters, you can extend the functionality of existing classes without
modifying their original implementation.
Inner Classes in Java (Nested Classes)
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data members
and methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
98
Advantage of Java inner classes
There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Difference between nested class and inner class in Java
An inner class is a part of a nested class. Non-static nested classes are known as inner classes.
Types of Nested classes
There are two types of nested classes non-static and static nested classes. The non-
static nested classes are also known as inner classes.
1. Non-static nested class (inner class)
Member inner class
Anonymous inner class
Local inner class
2. Static nested class
Type Description
Static Nested Class A static class was created within the class.
99
Collection Frameworks in Java
The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
What is Collection?
A Collection represents a single unit of objects, i.e., a group.
What is a framework?
A framework provides a ready-made structure of classes and interfaces for building software
applications efficiently. It simplifies adding new features by offering reusable components that
perform similar tasks, eliminating the need to create a framework from scratch for each new
project. This approach enhances object-oriented design, making development quicker, more
consistent, and reliable.
o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It enhances code efficiency and readability by offering various data
structures, including arrays, linked lists, trees, and hash tables, tailored to different
programming needs. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Why Collection Framework?
Before the Collection Framework was introduced in JDK 1.2, Java's approach to collections
was using Arrays, Vectors, and Hash tables lacked a common interface. This meant each type
of collection had its own set of methods, syntax, and constructors, with no standardization or
correlation between them.
This made it difficult for users to remember the diverse functionalities of each collection type
and hindered code consistency and reusability. The disparate nature of these collections
highlighted the need for a unified Collection Framework to simplify and standardize collection
operations in Java.
Advantages of the Java Collection Framework
100
The Java Collections Framework offers significant advantages that enhance development
practices, code quality, and application performance:
1. Reusability: The framework provides a comprehensive set of common classes and
utility methods applicable across various types of collections. This feature promotes code
reusability, sparing developers the need to write duplicate code for common operations.
2. Quality: Leveraging the Java Collections Framework elevates the quality of
programs. The components within the framework have been extensively tested and are widely
used by a vast community of developers, ensuring reliability and stability in your
applications.
3. Speed: Developers often report an increase in development speed when using the
Collections Framework. It allows them to concentrate on the core business logic of their
applications rather than on implementing generic collection functionalities, thus speeding up
the development process.
4. Maintenance: The open-source nature of the Java Collections Framework, coupled
with readily available API documentation, facilitates easier code maintenance. Code written
using the framework can be easily understood and taken over by other developers, ensuring
continuity and ease of maintenance.
5. Reduces Effort to Design New APIs: An additional benefit is the reduced necessity
for API designers and implementers to create new collection mechanisms for each new API.
They can instead rely on the standard collection interfaces provided by the framework,
streamlining the API development process and ensuring consistency across Java applications.
101
Hierarchy of Collection Framework
Let's see the hierarchy of Collection framework. The [Link] package contains all
the classes and interfaces for the Collection framework.
o Class: A class is a blueprint from which individual objects are created. It encapsulates
data for objects through fields (attributes) and defines behavior via methods. Classes
support inheritance, allowing one class to inherit the properties and methods of
another, facilitating code reuse and polymorphism.
o Interface: An interface is a reference type in Java that can contain constants and
abstract methods (methods without a body). Interfaces specify what a class must do
but not how it does it, enforcing a set of methods that the class must implement.
Interfaces are used to achieve abstraction and multiple inheritance in Java.
102
Methods of Collection interface
There are many methods declared in the Collection interface. The Collection interface in Java
provides basic methods to work with groups of objects, such as adding, removing, and iterate
through each element. They are as follows:
103
of elements from the
collection.
104
o 18 o public boolean o It matches two collections.
equals(Object element)
Iterator interface
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
No Method Description
.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection interface
also implement the Iterable interface.
It contains only one abstract method. i.e.,
1. Iterator<T> iterator()
It returns the iterator over the elements of type T.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.
105
Some of the methods of Collection interface are Boolean add (Object obj), Boolean addAll
(Collection c), void clear(), etc. that are implemented by all the subclasses of Collection
interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use:
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.
import [Link].*;
class Main{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Ravi");//Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
106
}
}
Output:
1. Ravi
2. Vijay
3. Ravi
4. Ajay
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, it
is synchronized and contains many methods that are not the part of Collection framework.
Consider the following example.
import [Link].*;
public class Main{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
[Link]("Ayush");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
Basics Of Enumeration
107
What Is Enumeration in Java?
Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named
values separated by commas. These named values are also known as elements or enumerators
or enum instances. Since the values in the enum type are constant, you should always
represent them in UPPERCASE letters.
The following characteristics make enum a ‘special’ class:
enum constants cannot be overridden
enum doesn’t support the creation of objects
enum can’t extend other classes
enum can implement interfaces like classes
Syntax:
In Java, to define an Enum type, the ‘enum’ keyword is used rather than ‘class’ or ‘interface’.
Mentioned below is the syntax.
enum Variable_Name { VALUE_1, VALUE_2, VALUE_3, … }
Why Do We Need Enumeration?
Java supports two types of Data Types:
1. User-Defined Datatypes
2. Inbuilt Data Types- int, float, double, char, etc.
Sometimes inbuilt data types are not sufficient. Let’s suppose that we have data of different
data types required to be stored in a single variable. In such a situation, inbuilt data types
won’t fulfill the need. That’s why there is a requirement for user-defined Data Types, and
enum in Java is one of them.
Examples of Enum in Java:
What Is Enumeration in Java?
Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named
values separated by commas. These named values are also known as elements or enumerators
or enum instances. Since the values in the enum type are constant, you should always
represent them in UPPERCASE letters.
You can use an Enum type when you need a fixed set of pre-defined constant values that are
known at the compile-time itself. Examples can be days of the week, seasons of the year, etc.
The following characteristics make enum a ‘special’ class:
enum constants cannot be overridden
enum doesn’t support the creation of objects
108
enum can’t extend other classes
enum can implement interfaces like classes
Syntax:
In Java, to define an Enum type, the ‘enum’ keyword is used rather than ‘class’ or ‘interface’.
Mentioned below is the syntax.
enum Variable_Name { VALUE_1, VALUE_2, VALUE_3, … }
Want a Top Software Development Job? Start Here!
Full Stack Developer - MERN StackExplore Program
In the example depicted above, TicketCategory is of the enum type with 4 predefined values
which are CRITICAL, HIGH, MEDIUM, and LOW.
Constants in Enum can be referred to in the code later using the ‘dot’ notation operator like
below.
TicketCategory category = [Link];
How To Define Java Enum?
109
Enum in Java can be defined outside or within the class.
Syntax: enum Name{constants}
With the following example, we will learn how to define an enum in Java.
Code:
package definition;
enum Car{
MARUTI,HONDA,TESLA;
}
public classExample{
public static void main(String [] args) {
Carc1= [Link];
[Link](c1);
}
}
Vector Class in Java
The Vector class in Java implements a growable array of objects. Vectors were legacy
classes, but now it is fully compatible with collections. It comes under [Link] package and
implement the List interface.
Key Features of Vector:
It expands as elements are added.
Vector class is synchronized in nature means it is thread-safe by default.
Like an ArrayList, it maintains insertion order.
It allows duplicates and nulls.
It implements List, RandomAccess, Cloneable, and Serializable.
110
Vector Class Declaration
public class Vector<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
Here, E is the type of element.
It extends AbstractList and implements List interfaces.
It implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>,
RandomAccess interfaces.
The directly known subclass is Stack.
We can use all the methods of the List interface as shown below as follows:
Constructors of Vector
1. Vector(): Creates a default vector of the initial capacity is 10.
Vector<E> v = new Vector<E>();
111
3. Vector(int size, int incr): Creates a vector whose initial capacity is specified by size and
increment is specified by incr. It specifies the number of elements to allocate each time a
vector is resized upward.
Vector<E> v = new Vector<E>(int size, int incr);
Method Description
112
Method Description
113
Method Description
lastIndexOf(Object o, int index) Returns the index of the last occurrence of the
114
Method Description
removeIf(Predicate<? super E> Removes all of the elements of this collection that
115
Method Description
removeRange(int fromIndex, Removes from this list all of the elements whose
index is between fromIndex, inclusive, and
int toIndex) toIndex, exclusive.
116
Method Description
117
118