0% found this document useful (0 votes)
2 views123 pages

Java Lesson Notes 2025 Batch

The document provides lesson notes for a Java Programming course, covering fundamental concepts of object-oriented programming, Java history, and key features of the language. It includes details on Java's architecture, core components, data types, variables, arrays, operators, and control statements. Additionally, it outlines the Java Development Kit (JDK), Java Runtime Environment (JRE), and various Java buzzwords that highlight the language's capabilities.

Uploaded by

nithya.n
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views123 pages

Java Lesson Notes 2025 Batch

The document provides lesson notes for a Java Programming course, covering fundamental concepts of object-oriented programming, Java history, and key features of the language. It includes details on Java's architecture, core components, data types, variables, arrays, operators, and control statements. Additionally, it outlines the Java Development Kit (JDK), Java Runtime Environment (JRE), and various Java buzzwords that highlight the language's capabilities.

Uploaded by

nithya.n
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

School of Computational Sciences

JAVA PROGRAMMING

Lesson Notes

Semester – II

Courses:

[Link]. Computer Science

[Link]. Computer Science (AI & DS)


[Link]. Computer Technology

[Link]. Information Technology

Bachelor of Computer Applications


School of Computational Sciences Java Programming

Core – III: Java Programming

Unit I
Introduction: Review of Object-Oriented concepts – History of Java - Java buzzwords - JVM
architecture - Datatypes – Variables - Scope and lifetime of variables – arrays – operators –
control statements – type conversion and casting – Simple Java program – constructors –
methods – Static Block - Static Data – Static Method String and String Buffer Classes.

INTRODUCTION TO JAVA

 Java is a high-level, object-oriented programming language.


 It was developed by James Gosling at Sun Microsystems, released in 1995.
 Java is easy to use and platform-independent language.
 Java applications are compiled into byte codes that can run on any Java Virtual
Machine (JVM), making Java platform-independent.
 It provides secure environment. Everything is treated as an object.

Review of Object-Oriented Concepts

 Object-Oriented Programming provides a way of modularizing programs into Objects.


 Objects are the combination of Data and Methods
Object Oriented Programming

Problem

Object Object Object Object

Fig: Hierarchical structure of a problem

KG College of Arts and Science Page 2


School of Computational Sciences Java Programming

Fig: Object and its associated Methods

Features of OOP

 Emphasis on data
 Programs divided into Objects
 Data is hidden and cannot be accessed by external functions
 Objects communicate with each other
 New data and methods can be added easily
 Follows bottom-up approach
Basic Concepts of OOPs

 Objects
 Basic runtime entities(student, bank account, car, birds)
 Objects takes up space in the memory
Representation of an object

Fig: Representation of object in object-oriented programming


Class

 User defined data type, Object - Variable


 Entire set of data and code of an object
 Any number of objects can be created from a class
 Collection of objects of similar type
 Apple, mango and orange are members of class fruit

KG College of Arts and Science Page 3


School of Computational Sciences Java Programming

 fruit mango creates an object mango belonging to the class fruit


Abstraction

 Act of representing essential features without including details


Encapsulation

 Most important feature of a class


 Wrapping up of data and methods into a single unit
 Insulation of data from direct access by the program is called Data hiding
Inheritance

 Objects of one class acquire the properties of another class.


 Provides reusability
 Deriving a new class from the existing class

Course
Syllabus, Exam

Arts Science
Attributes Attributes
--------- ----------
---------- ---------

[Link] BBA [Link] CS [Link] IT

Polymorphism

 Ability to take more than one form


 ie. An operation may exhibit different behavior in different instances
 Ex. Addition (on numbers it returns sum, on string inputs combines both the string)

Shape
Draw()

Rectangle Triangle Object()


Circle Object()
Object()

Dynamic Binding

KG College of Arts and Science Page 4


School of Computational Sciences Java Programming

 Linking of a procedure call to the code to be executed in response to the call (run
time)
Message Communication

 Process of programming in an Object-oriented language :


 Creating classes that define objects and their behavior
 Creating objects from class definition
 Establishing communication among objects (Syntax → [Link]();
 [Link](rollno);

Fig: Object and Message Communication

Benefits of OOP

 Code reusability
 Saves time
 Security
 Easy to partition a project based on objects
 Data-centered approach
 Easily upgraded from small to large systems
 Software complexity can be easily managed

Applications of OOP

 Real-time systems

KG College of Arts and Science Page 5


School of Computational Sciences Java Programming

 Simulation and modeling


 Object-oriented databases
 Hypertext, hyper media and expertext
 AI and expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
History of JAVA

 Java team members (Green Team), initiated this project to develop a language for
digital devices such as set-top boxes, televisions, etc.
 It was best suited for internet programming.
 Java is a high level, robust, object-oriented and secure programming language.
 Java was developed by Sun Microsystems in the year 1995.
 James Gosling is known as the father of Java.
Java Versions

 JDK Alpha and Beta (1995)


 JDK 1.0 (23rd Jan 1996)
 JDK 1.1 (19th Feb 1997)
 J2SE 1.2 (8th Dec 1998)
 J2SE 1.3 (8th May 2000)
 J2SE 1.4 (6th Feb 2002)
 J2SE 5.0 (30th Sep 2004)
 Java SE 6 (11th Dec 2006)
 Java SE 7 (28th July 2011)
 Java SE 8 (18th Mar 2014)
 Java SE 9 (21st Sep 2017)
 Java SE 10 (20th Mar 2018)
 Java SE 11 (September 2018)
 Java SE 12 (March 2019)
 Java SE 13 (September 2019)
 Java SE 14 (Mar 2020)
 Java SE 15 (September 2020)
 Java SE 16 (Mar 2021)
 Java SE 17 (September 2021)

KG College of Arts and Science Page 6


School of Computational Sciences Java Programming

 Java SE 18 ( March 2022)


 Java SE 19 (September 2022)
 Java SE 20 ( March 2023)
 Java SE 21 (September 2023)
 Java SE 22 ( March 2024)
 Java SE 23 (September 2024)
Java Buzzwords
Java is a popular programming language known for its rich ecosystem and robust community.
Common buzzwords in Java are:
1. Platform Independence
"Write Once, Run Anywhere" (WORA): Java code can run on any device with a
Java Virtual Machine (JVM), making it platform-independent.
2. Object-Oriented
Java is a pure object-oriented language, with features like inheritance, polymorphism,
encapsulation, and abstraction.
3. Robust
Java emphasizes error handling and memory management, reducing issues like
memory leaks through its garbage collection system.
4. Secure
Java provides features like byte code verification, a secure execution environment,
and API-level security for building secure applications.
5. Multithreaded
Java supports multithreading at the language level, enabling efficient execution of
multiple tasks concurrently.
6. High Performance
While not as fast as languages like C++, Java achieves high performance through
Just-In-Time (JIT) compilation and optimized runtime environments.
7. Dynamic
Java supports dynamic linking, runtime type checking, and reflection, allowing it to
adapt to evolving requirements.
8. Portable
Java's bytecode format ensures portability across different platforms without
modification.
9. Distributed
KG College of Arts and Science Page 7
School of Computational Sciences Java Programming

Java includes APIs like RMI (Remote Method Invocation) and tools like Java EE for
building distributed systems.
10. Extensible
Java's modular architecture and large ecosystem of libraries make it highly extensible
for various use cases.
11. Scalable
Java is designed to build applications that can scale from small systems to enterprise-
level architectures.
12. Backward Compatibility
Newer versions of Java maintain backward compatibility with older ones, allowing
legacy systems to integrate with minimal issues.
13. Versatile
Java is used for desktop applications, web development, mobile applications (via
Android), and enterprise systems.
14. Ecosystem
With frameworks like Spring, Hibernate, and tools like Maven and Gradle, Java
boasts a rich ecosystem that facilitates development.

Java Environment

A large number of development tools(JDK)


Hundreds of classes and methods (JSL) à Java Environment

Java Development Kit

Collection of tools used to develop and run Java programs are :

 appletviewer (to view Java applets)


 javac (java compiler)
 java (java interpreter)
 javap(java disassembler)
 javah (for C header files)
 javadoc (To create HTML documents)
 jdb(Java debugger)
Java Standard Library (Application Programming Interface)

KG College of Arts and Science Page 8


School of Computational Sciences Java Programming

JSL of API includes hundreds of classes and methods grouped into several functional
packages. Commonly used packages in Java:
 Language Support Package: To implement basic features of Java
 Utilities Package: To provide utility functions (date and time)
 Input / Output Package: Used for input / output manipulation
 Networking Package: To communicate with other computers via internet
 AWT Package: The Abstract Window Tool Kit package is used to implement
platform-independent GUI
 Applet Package: Allows to create Java Applets

Java Runtime Environment (JRE)

JRE facilitates the execution of programs developed in Java. It includes:


1. Java Virtual Machine (JVM): This program interprets the intermediate Java byte
code and generates the desired output.
2. Runtime class libraries: Core libraries required for execution of Java program
3. User interface toolkits: AWT , Swing
4. Development technologies:
 Java Plug-in (execution of applet on the browser)
 Java Web Start (enables remote-deployment of an application)
JVM Architecture

 JVM (Java Virtual Machine) is an abstract machine.

KG College of Arts and Science Page 9


School of Computational Sciences Java Programming

 Java compiler produces an intermediate code(byte code) for a machine that does not
exist (JVM)
 JVMs are available for many hardware and software platforms. JVM, JRE, and JDK
are platform dependent because the configuration of each OS is different from each
other.

Fig: Compilation and execution process of Java program

Fig: Implementation process of Java programs across various operating systems

Java Tokens

Java program is a collection of tokens, comments and white spaces. Tokens are
smallest individual units. Java tokens are:
 Reserved Keywords(if , switch, for, while, try)
 Identifiers(Used for naming classes, methods, variables Ex: fruits, main, total)
 Literals(constant values)

KG College of Arts and Science Page 10


School of Computational Sciences Java Programming

 Operators
 Separators (),{},[],period, comma, semicolon
Constants
Constants have fixed values that do not change during the execution of a program.

Fig: Hierarchy of java constants

A real number can be expressed in exponential or scientific notation.

Example 314.275 can be written as 3.14275e2 mantissa e exponent

Floating point constant comprise of four parts

1. A whole number
2. A decimal point mantissa
3. A fractional part
4. An exponent

Backslash Character constants


Used in output method. For example ‘\t’ is used to print horizontal tab. These
constants are also known as escape sequences.
Constant Meaning
‘ \b ’ Back space
‘ \f ’ Form feed
‘ \n ’ New line
‘ \r ’ Carriage return
‘ \t ’ Horizontal tab
‘ \’ ’ Single quote
‘ \” ‘ Double quote
‘ \\ ’ Backslash
Data Types
Data types specify the size and type of values that can be stored.

KG College of Arts and Science Page 11


School of Computational Sciences Java Programming

Fig: Data types in java

Variables
Variables are used to store a data value. Variables can take different values at
different times.
Rules for naming a variable:
1. Name must not begin with a digit
2. Uppercase and lower case are distinct
3. It should not be a keyword
4. White space is not allowed
5. Variable names can be of any length
6. May consist of an underscore (_) and dollar character

Scope and lifetime of Variables


 Instance Variables - declared inside a class, created when the objects are instantiated
 Class Variables - declared inside a class(global to a class)
 Local Variables -declared inside methods (or) declared between { and }
Declaration of variables
type variable1,variable2,……………….., variablen;

Arrays
Arrays are used to store multiple values of the same type in a single variable.
Declaration of Array in Java
type[] arrayName;

KG College of Arts and Science Page 12


School of Computational Sciences Java Programming

Example: To store and display array elements

class ArrEx
{
public static void main(String[] args)
{ int[] arr;
arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i + " : " + arr[i]);
}
}

Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Multidimensional Arrays
Arrays with more than one dimension are called Multi-Dimensional Arrays.
public class MultiDimensionalArray {
public static void main(String[] args) {
// Declare a 2D array with 3 rows and 4 columns
int[][] arr = new int[3][4];

KG College of Arts and Science Page 13


School of Computational Sciences Java Programming

// Initialize the array


int value = 10;
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = value;
value += 10;
}
}
// Print the array
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < arr[i].length; j++) {
[Link](arr[i][j] + "\t");
}
[Link]();
}
}
}

Output

10 20 30 40

50 60 70 80

90 100 110 120

Operators
Operators in Java are the symbols used for performing specific operations in Java.
 Arithmetic Operators (+,-,*,/,%)
 Unary Operators (++,--,+)
 Assignment Operator (=)
 Relational Operators(=,!=,<,<=,>,>=)
 Logical Operators(&&,||,!)
 Ternary Operator (condition ? True-st: false-st )
 Bitwise Operators(&,|,^,~)
 Shift Operators ( number shift_op number_of_places_to_shift; a<<1; )

KG College of Arts and Science Page 14


School of Computational Sciences Java Programming

 instance of operator object- instance of class/subclass/interface


Control statements
When a program breaks the sequential flow and jumps to another part, it is called
branching.
Decision making statements

 if statement
 switch statement
 conditional operator statement
if statement
 powerful decision making statement
 two way branching
Simple if Statement

General Form
if (test expression)
{
Statement-block;
}
Statement – x
If…else statement
if (test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
Statement - x

Example
public class IfStatementExample {
public static void main(String[] args) {
int age = 25;

KG College of Arts and Science Page 15


School of Computational Sciences Java Programming

if (age >= 18) {


[Link]("You are Eligible to Vote.");
} else {
[Link]("You are not Eligible to Vote.");
}
}
}
This program checks if the age variable is greater than or equal to 18 and prints out a
message accordingly.
Output
You are Eligible to Vote.
Nested if… else statements
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

Example
public class NestedIfElseExample {
public static void main(String[] args) {

KG College of Arts and Science Page 16


School of Computational Sciences Java Programming

int age = 25;


boolean isStudent = true;
if (age >= 18) { // Outer condition
if (isStudent) { // Inner condition
[Link]("You are an adult student.");
} else {
[Link]("You are an adult.");
}
} else {
[Link]("You are a minor.");
}
}
}
In this example: The outer condition checks if age is greater than or equal to 18. Since
age is 25, the outer condition is true. The inner condition checks if isStudent is true. Since
isStudent is true, the inner condition is also true. The code inside the inner if block is
executed, printing "You are an adult student." If we change the values of age and is Student,
the output would change accordingly.
For example:
If age is 17 and isStudent is true, the output would be "You are a minor."
If age is 25 and isStudent is false, the output would be "You are an adult."
Output
You are an adult student.
The else if ladder
if (condition1) {
// Statements 1
}
else if (condition2) {
// Statements 2
}
else {
// Else body
}

KG College of Arts and Science Page 17


School of Computational Sciences Java Programming

class ElseIfLadderExample {
public static void main(String[] args) {
int marks = 85;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 80) {
[Link]("Grade B");
} else if (marks >= 70) {
[Link]("Grade C");
} else if (marks >= 60) {
[Link]("Grade D");
} else {
[Link]("Grade F");
}
}
}
This program uses an else-if ladder to determine the grade based on the marks variable.
Output
Grade B
How it Works?
The program checks the marks variable against each condition in sequence. If a
condition is true, the corresponding code block is executed, and the rest of the ladder is
skipped. If none of the conditions are true, the final else block is executed. In this example,
since marks is 85, the output would be "Grade B".

KG College of Arts and Science Page 18


School of Computational Sciences Java Programming

Benefits of Else-If Ladder


Allows for multiple conditions to be checked in sequence. More efficient than using
multiple if statements, as the program exits the ladder as soon as a condition is true. Easy to
read and maintain, especially when the conditions are mutually exclusive.
The switch statement
General form
switch (expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
…….
..…..
default:
default-block
break;
}
statement-x

Example
public class SwitchStatementExample {

KG College of Arts and Science Page 19


School of Computational Sciences Java Programming

public static void main(String[] args) {


int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
[Link]("Day " + day + " is " + dayName);
}
}
This program uses a switch statement to determine the day of the week based on the
day variable.
KG College of Arts and Science Page 20
School of Computational Sciences Java Programming

Output
Day 3 is Wednesday
How it Works?
The day variable is evaluated, and its value is matched against each case. If a match is
found, the code inside that case is executed. The break statement is used to exit the switch
block. If no match is found, the default case is executed. In this example, since day is 3, the
output would be "Day 3 is Wednesday".
Benefits of Switch Statement
 More efficient than using multiple if-else statements for a single variable.
 Easier to read and maintain, especially when there are many cases.
Looping
In looping, Sequence of statements is executed until some conditions are satisfied.
Four steps in the looping process:
1. Setting and initialization of a counter
2. Execution of the statements in the loop
3. Test for a specified condition for executed of the loop
4. Incrementing the counter
While loop statement
The simplest of all the looping structures
Entry-controlled loop
General Form
initialization;
while (test condition)
{
Body of the loop
}
public class WhileLoopExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
[Link](i);
i++;
}
}
KG College of Arts and Science Page 21
School of Computational Sciences Java Programming

}
Output
0
1
2
3
4
do… while loop
Exit – Controlled loop
General Form
Initialization;
do
{
Body of the loop
} while (test condition);
Example
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 0;
do {
[Link](i);
i++;
} while (i < 5);
}
}
Output
0
1
2
3
4
This Java program uses a do-while loop to print numbers from 0 to 4. The loop body
is executed at least once before the condition i < 5 is checked.
Difference between while and do… while loops
KG College of Arts and Science Page 22
School of Computational Sciences Java Programming

While do…while
Executes only if the condition is true Execute at least once even if the test
Entry-controlled loop condition is false
Used for common looping process Exit-controlled loop
Used menu-based programs

for loop statement


The for loop is also entry-controlled loop. It provides more concise loop control
structure.
for( initialization ; test condition ; increment)
{
Body of the loop
}
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
[Link](i);
}
}
}
Output
0
1
2
3
4
Type conversion and casting
Type casting is used to store a value of one type into a variable of another type.
Type variable1=(type)variable2;
Type casting is necessary when a method returns a type different from the one we
require.

Simple Java program


JAVA Programs
KG College of Arts and Science Page 23

Standalone applications Web Applets


School of Computational Sciences Java Programming

Fig: Process of compiling and interpreting Java source code


Standalone application

Standalone application is programs written in Java to carry out certain tasks on a


standalone computer.
Steps involved in executing a standalone application:
1. Compiling source code into bytecode using javac compiler
2. Executing the bytecode program using java interpreter
class SampleProgram
{
public static void main(String args[])
{
[Link](“HELLO”);
}
}
Output
HELLO
Explanation
class SampleProgram à declares a class class is a keyword, SampleProgram is an
identifier

KG College of Arts and Science Page 24


School of Computational Sciences Java Programming

{ à Every class in Java begins with an opening brace “{“ and end with closing brace
“}”
public static void main(String args[]) the entry point of every java program.
Keyword Meaning
public Access specifier , accessible to all other classes
static The method belongs to the entire class and not a part of any objects of the class.
The main method must be declared as static since the interpreter uses this
method before any objects are created.
void The type void states that the main function does not return any value.
All parameters to a method are declared inside a pair of parentheses ().
Output line
Every method must be part of an object. The println() method is a member of our
object which is a static data member of System class. Every Java statement must end with a
semicolon.
Applets
 Applets are small Java programs developed for Internet applications.
 An applet located on a distant computer can be downloaded via internet and executed
on a local computer using java-capable browser.
 Applets can only run within a web browser.
Constructors
 Constructors are special type of methods. It enables an object to initialize itself when
it is created.
 Constructors have the same name as the class itself. They do not specify a return type.
class Rectangle
{
int length, width;
Rectangle(int x, int y)
{
length=x;
width=y;
}
int rectArea()
{
return(length * width);
KG College of Arts and Science Page 25
School of Computational Sciences Java Programming

}
}
class RectangleArea
{
public static void main(String args[])
{
Rectangle rect1=new Rectangle(5,10);
int area1=[Link]();
[Link](“Area1= “+ area1);
}
}
Output
Area1= 50
Methods
The method in Java or Methods of Java is a collection of statements that perform some
specific tasks.
 A Java method can perform some specific tasks without returning anything.
 Java Methods allows us to reuse the code without retyping the code.
 In Java, every method must be part of some class.
 A method is like a function i.e. used to expose the behaviour of an object.
 It is a set of codes that perform a particular task.
Advantage of Method
 Code Reusability
 Code Optimization

Fig: A Method in Java programming

class Addition {
int sum = 0;

KG College of Arts and Science Page 26


School of Computational Sciences Java Programming

public int addTwoInt(int a, int b) {


sum = a + b;
return sum;
}
}
class MethodEx {
public static void main(String[] args) {
Addition add = new Addition();
int s = [Link](10, 20);
[Link]("Sum of two integer values :" + s);
}
}
Output
Sum of two integer values: 30
Explanation
 An Addition object add is created.
 The addTwoInt method is called on add, passing 10 and 20 as arguments.
 The addTwoInt method calculates the sum of 10 and 20, which is 30, and returns it.
 The result is stored in the variable s and printed.
Method Overloading
Method overloading is creating methods that have the same name but different
parameter lists and definitions. Java matches up the method name first and then the number
and type of parameters to decide which one of the definitions to execute. This process is
known as polymorphism.
class Room
{
int length, width;
Room(int x, int y)
{
length=x;
width=y;
}
Room(int x)
{
KG College of Arts and Science Page 27
School of Computational Sciences Java Programming

Length=width=x;
}
int Area()
{
return(length * width);
}
}
class AreaRectSq
{
public static void main(String args[])
{
Room room1=new Room(5,10);
Room room2=new Room(10);
int areaRect=[Link]();
int areaSquare=[Link]();
[Link](“Area of Rectangle = “+ areaRect);
[Link](“Area of Square = “+ areaSquare);
}
}
Output
Area of Rectangle = 50
Area of Square = 100
Rectangle Area
room1 is created with length = 5 and width = 10.
areaRect = [Link]() calculates the area by multiplying length and width, resulting in 5 *
10 = 50.
Square Area
room2 is created with length = width = 10.
areaSquare = [Link]() calculates the area by multiplying length and width, resulting in
10 * 10 = 100.

Static Block

KG College of Arts and Science Page 28


School of Computational Sciences Java Programming

Java supports a special block, called a static block (also called static clause) that can
be used for static initialization of a class. This code inside the static block is executed only
once: the first time the class is loaded into memory.
class SBExample {
static
{
[Link]("Static block can be printed without main method");
}
}
Static Data and Static method
Static keyword is used to define a member that is common to all the objects and
accessed without using a particular object. The data and methods declared with static
keyword are associated with the class itself rather than individual objects. These variables are
referred to as class variables and class methods.
class Test {
static int i;
int j;
static
{
i = 10;
[Link]("static block called ");
}
static int add(int a, int b)
{return a+b;
}
}
class staticExample {

public static void main(String args[])


{
int sum=[Link](10,10);
[Link](Test.i);
[Link](sum);
}
KG College of Arts and Science Page 29
School of Computational Sciences Java Programming

}
Output
static block called
10
20
 When [Link](10, 10) is called in the main method, the Test class is loaded.
 During class loading, the static block is executed, printing "static block called " and
initializing i to 10.
 The add method is then called, returning the sum of 10 and 10, which is 20.
 The values of Test.i (10) and sum (20) are printed.
 So, the static block is executed before the main method uses the Test class.
String and String Buffer Classes
 Though character arrays are used to represent a string , it does not support the range
of operations.
 In Java, Strings are class objects and implemented using two classes (String ,
StrinBuffer)
 Java string is not a character array and is not NULL terminated.
String Declaration:
String stringname;
Stringname=new String(“string”);
Example
String collegename;
collegename=new String(“KGCAS”);
String arrays
String name[]=new String[3];
The name array will hold 3 string constants.
Most commonly used String methods
str2=[Link];
str2=[Link];
str2=[Link](‘x’,’y’)
[Link](str2);
[Link]();
[Link](n);
[Link](str2);
KG College of Arts and Science Page 30
School of Computational Sciences Java Programming

StringBuffer Class
The String class creates strings of fixed length whereas the StringBuffer class creates
strings of flexible length that can be modified in terms of both length and content. Substrings
and characters can be inserted in the middle of a string or appended with another string to the
end.
[Link](n,’x’);
[Link](str2);
[Link](n,str2);
[Link](n);
public class StringBufferExample
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer();
[Link]("Hello");
[Link](" ");
[Link]("world");
String str = [Link]();
[Link](str);
}
}
Output
Hello world
1. A new StringBuffer object s is created.
2. The string "Hello" is appended to s.
3. A space is appended to s.
4. The string "world" is appended to s.
5. The toString() method is called on s, converting it to a String object str.
6. The string "Hello world" is printed.

KG College of Arts and Science Page 31


School of Computational Sciences Java Programming

Unit II
Inheritance: Basic concepts - Types of inheritance - Member access rules - Usage of this and
Super keyword - Method Overloading - Method overriding - Abstract classes - Dynamic method
dispatch - Usage of final keyword. Packages: Definition - Access Protection - Importing
Packages - Interfaces- Definition – Implementation – Extending. Exception Handling: try –catch
- throw - throws –finally – Built–in exceptions - Creating own Exception classes.

INHERITANCE IN JAVA

Inheritance – Basic concepts


The mechanism of deriving a new class from an existing class is called inheritance. The
existing class is known as base class or super class or parent class. The new class is called
subclass or derived class or child class.
Types of inheritance
1. Single Inheritance (Only one super class)
2. Multiple Inheritances (More than one super classes) Java does not support multiple
inheritance. This concept is implemented using interfaces.
3. Hierarchical Inheritance(one super class, many subclasses)
4. Multilevel Inheritance(derived from a derived class)
Defining Subclass
class subclass extends superclass
{
Variables declaration;
Methods declaration;
}
The keyword extends signifies that the properties of the superclass name are extended to
the subclass name. The sub class contains its own variables and methods as well as those of
the superclass.
class Student
{
String name;

KG College of Arts and Science Page 32


School of Computational Sciences Java Programming

String rollno;
Student(String a, String b)
{
name=a;
rollno=b;
}

}
class Test extends Student
{
int java;
int javalab;
Test(String a,String b, int c, int d)
{ super(a,b);
java=c;
javalab=d;
}
void display()
{ [Link]("Name = " +name);
[Link]("Rollno = "+rollno);
[Link]("Java Mark = "+java);
[Link]("Javalab Mark = "+javalab);
}
}
class SingleInheritance
{
public static void main(String args[])
{
Test test1=new Test("Abarna S K","24BIT101",89,90);
[Link]();
}}
Output
Name = Abarna S K
Rollno = 24BIT101
KG College of Arts and Science Page 33
School of Computational Sciences Java Programming

Java Mark = 89
Javalab Mark = 90
The subclass constructor uses the keyword super to invoke the constructor method of the
superclass.
Conditions to be followed while using super keyword:
1. Super may only be used within a subclass constructor method.
2. The call to superclass constructor must appear as the first statement within the
subclass constructor.
3. The parameters in the super call must match the order and type of the instance
variable declared in the superclass.
Multilevel Inheritance

SuperClass

SubClass1

SubClass2

Deriving a class from a derived class.


class SuperClass
{
…………..
….……….
}
class SubClass1 extends SuperClass
{
…………..
….……….
}
class SubClass2 extends SubClass1
{
…………..
….……….
}

Example
// Grandparent class
class Animal {
void eat() {
[Link]("Eating...");
}

KG College of Arts and Science Page 34


School of Computational Sciences Java Programming

// Parent class
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}

// Child class
class Labrador extends Dog {
void run() {
[Link]("Running...");
}
}

public class MultilevelInheritance {


public static void main(String[] args) {
Labrador labrador = new Labrador();
[Link](); // Inherited from Animal
[Link](); // Inherited from Dog
[Link](); // Defined in Labrador
}
}
Output
Eating...
Barking...
Running...

Hierarchical Inheritance

Deriving more than one subclasses from one Super Class.

Hierarchical inheritance is a type of inheritance in Java where one superclass is inherited


by multiple subclasses. In other words, a single parent class has multiple child classes that
inherit its properties and behavior.
Example
class UGDegree {

KG College of Arts and Science Page 35


School of Computational Sciences Java Programming

void display() {
[Link]("Degree");
}
}
class Arts extends UGDegree {
void artsdisplay() {
[Link]("Arts Stream");
}
}
class Science extends UGDegree {
void sciencedisplay() {
[Link]("Science Stream");
}
}
class HierInheritance {
public static void main(String args[]) {
Arts art = new Arts();
[Link]();
[Link]();
[Link]();
Science sc = new Science();
[Link]();
[Link]();
}
}

Output
Degree
Arts Stream
Degree
Science Stream
Multiple Inheritance
 Deriving one class from more than one Super class.
 Java does not directly implement Multiple Inheritance.
KG College of Arts and Science Page 36
School of Computational Sciences Java Programming

 This concept is implemented using a secondary inheritance path in the form of


interfaces.
 Multiple inheritance is not supported in java.
 Java supports multiple inheritance through interfaces, where a class can implement
multiple interfaces.

Member Access Rules


Access modifier
public, protected, friendly, private protected, private
1. Use “public” if the field is to be visible everywhere.
2. Use “protected” if the field is to be visible everywhere in the current package and also
subclasses in other packages.
3. Use “default” if the field is to be visible everywhere in the current package only.
4. Use private protected if the field is to be visible only in subclasses, regardless of
packages.
5. Use “private” if the field is not to be visible anywhere except in its own class.
Usage of this and Super keyword
“super” keyword is used to access methods of the parent class while “this” is used to
access methods of the current class.
“this” keyword is a reserved keyword in java. It is used to refer current class’s instance as
well as static members.
Example program using super and this keywords:
class Super
{
int x;
Super (int x)
{this.x=x;
}
void display()
{

KG College of Arts and Science Page 37


School of Computational Sciences Java Programming

[Link](“Super x = “ +x);
}
}
class Sub extends Super
{
int y;
Sub(int x, int y)
{
Super(x);
this.y=y;
}
void display()
{
[Link](“Super x= “ +x);
[Link](“Sub y=” + y);
}
}
class OverrideTest
{
public static void main(String args[])
{
Sub s1=new Sub(100,200);
[Link]();
}
}
Output
Super x = 100
Sub y = 200
The Sub class overrides the display() method of the Super class. When [Link]() is
called, it invokes the display() method of the Sub class, which prints the values of x and y.
Note: if you want to call the display() method of the Super class from the Sub class, you
can use the super keyword like this: [Link]();.
Method Overloading

KG College of Arts and Science Page 38


School of Computational Sciences Java Programming

Method overloading is used when objects required to perform similar tasks but using
different input parameters. When a function with same name is called, Java matches up the
method name first and then the number and type of parameters to decide which one of the
definitions to execute. This process is known as polymorphism.
Giving same name for many functions with different parameters lists and different
types is called polymorphism.
class Area {
int area(int l, int b) {
return (l * b);
}
int area(int a) {
return (a * a);
}
double area(float r) {
return (3.14 * r * r);
}
}
class PolyEx {
public static void main(String args[]) {
Area a = new Area();
[Link]("Area of rectangle = " + [Link](4, 5));
[Link]("Area of square = " + [Link](5));
[Link]("Area of Circle = " + [Link](1.5f));
}
}
Output
Area of rectangle = 20
Area of square = 25
Area of Circle = 7.065
Method overriding
If an object need to respond to the same method but have different behavior when that
method is called, the super class method should be overridden by defining a method with
same name arguments and return type in the sub class. For example, display method is

KG College of Arts and Science Page 39


School of Computational Sciences Java Programming

defined in both super class and sub class but when it is invoked the sub class method is
executed instead of super class method. This concept is known as overriding.
Abstract classes
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. A class that is declared with the abstract keyword is known as an
abstract class in Java. ‘abstract’ keyword indicates that a method must always be redefined in
a subclass. It makes overriding compulsory. It can have abstract and non-abstract methods.
Syntax
abstract class Shape
{
………………………..
………………………..
abstract void draw();
…………………………
…………………………
}
Dynamic method dispatch

Dynamic method
dispatch is a mechanism in Java where the method to be invoked is determined at runtime,
rather than at compile time. This allows for more flexibility and polymorphism in
programming.
 A superclass reference variable is used to refer to a subclass object.
 When a method is invoked on the superclass reference variable, the actual
method to be invoked is determined at runtime, based on the type of object
being referred to.
 If the subclass has overridden the method, the subclass's implementation is
invoked. Otherwise, the superclass's implementation is invoked.
Example

KG College of Arts and Science Page 40


School of Computational Sciences Java Programming

class Super
{
public void method()
{
[Link](“Method of Super class”);
}
}
class Sub extends Super
{
public void method()
{
[Link](“Method of Sub class”);
}
}
class dyn_dis
{
public static void main(String args[])
{
Super A=new Sub();
[Link]();
}
}
Output
Method of Sub class
Usage of final keyword
The ‘final’ keyword is used to prevent the subclasses from overriding the members of
the superclass.
final int mark=100;
final void result();
The class that cannot be subclassed is called a final class.
final class Super
{
…..
….
KG College of Arts and Science Page 41
School of Computational Sciences Java Programming

}
Packages Definition
Packages are a way of grouping a variety of classes and interfaces together.
Benefits
1. The classes contained in the packages of other programs can be easily reused.
2. Two classes in different packages can have the same name,
3. Packages provide a way to hide classes,
4. Packages also provide a way for separating design from coding.
Java Packages are classified into two types.
1. Java API packages (Built-in packages)
2. user defined packages
The accessibility of the members of a class or interface depends on its access
specifies. The following table provides information about the visibility of both data members
and methods.

 Anything declared public can be accessed from any where


 Anything accessed private cannot be accessed from outside of its class
 In the default, it is visible to sub-class as well as to other classes in the same package
 Anything declared as protected, this is allow an element to be seen outside your
current package, but also allow to sub class in other packages access.
Access protection of Packages
In Java, access protection of packages is achieved through access modifiers. Here's a
brief overview:
Access Modifiers
public: Accessible from anywhere
protected: Accessible within the same package and subclasses
default (no modifier): Accessible within the same package
private: Accessible only within the same class
Package-Level Access

KG College of Arts and Science Page 42


School of Computational Sciences Java Programming

To protect packages, you can use the default access modifier (no modifier) for classes,
methods, and variables. This way, they will only be accessible within the same package.
Importing Packages

import [Link];
import [Link];
import [Link].*;
Creating own packages

1. Declare the package at the beginning of the file using the form package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing as the [Link] file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
package package1;
public class ClassA
{
public void displayA()
{
[Link](“Class A”);
}
}
Save this file as [Link] under package1 subdirectory. Compile the file.
[Link] file will be stored in the same subdirectory.
import [Link];
class PackageTest1
{

KG College of Arts and Science Page 43


School of Computational Sciences Java Programming

public static void main(String args[])


{
ClassA objectA=new ClassA();
[Link]();
}
}
Save this file as [Link]
package package2;
public class ClassB
{
protected int m=10;
public void display()
{
[Link](“Class B”);
[Link](“m=” +m);
}
}
Save this file as [Link] in the package2 subdirectory.

import [Link];
import package2.*;
class packageTest2
{
public static void main(String args[])
{
ClassA objectA=new ClassA();
ClassB objectB=new ClassB();
[Link]();
[Link]();
}
}
Output
Class A
Class B
KG College of Arts and Science Page 44
School of Computational Sciences Java Programming

m = 10
Interfaces- Definition
An interface is a kind of class. Interfaces define only abstract methods and final fields.
(ie no method definition , constant variables).
General Form
interface InterfaceName
{
Variables declaration;
Methods declaration;
}
Declaring variable
static final type VariableName=value;
Method Declation
return-type methodName1(parameter_list);
Implementation Extending
Interfaces are used as “superclasses” whose properties are inherited by classes it is
therefore necessary to create a class that inherits the given interface.
class classname implements interfacename
{
Body of classname
}
Here the class classname “implements” the interface interfacename. A more general form of
implementation may look like this:
class classname extends superclass
implements interface1, interface2……
{
body of classname
}
// [Link]
interface Area { // Interface defined
final static float pi = 3.14F;
float compute(float x, float y);
}
class Rectangle implements Area { // Interface implemented
KG College of Arts and Science Page 45
School of Computational Sciences Java Programming

public float compute(float x, float y) {


return (x * y);
}
}
class Circle implements Area { // Another implementation
public float compute(float x, float y) {
// The second argument 'y' is ignored for Circle as area calculation
// only depends on 'x' (radius) for pi*x*x
return (pi * x * x);
}
}
class InterfaceTest {
public static void main(String args[]) {
Rectangle rect = new Rectangle();
Circle cir = new Circle();

Area area; // Interface object

area = rect; // area refers to rect object


[Link]("Area of Rectangle = " + [Link](10, 20));

area = cir; // area refers to cir object


[Link]("Area of Circle = " + [Link](10, 0));
}
}
Output
Area of Rectangle = 200.0
Area of Circle = 314.0
Exception Handling
 The Exception Handling in Java is one of the powerful mechanisms to handle the
runtime errors.

KG College of Arts and Science Page 46


School of Computational Sciences Java Programming

Programming with Java Primer

Class A D
Interface A
Extension
Implementation
Class B E
Class B Implementation

Extension
Extension
Class C
Interface C

(a) (b)

Interface A

Implementation

B Class C Class
(c)

Java Exception Keywords

Java provides five keywords that are used to handle exceptions. The following table
describes each:

KG College of Arts and Science Page 47


School of Computational Sciences Java Programming

S.N Keyword Description


o
The "try" keyword is used to specify a block where we should place an
1. try exception code. It means we can't use try block alone. The try block must
be followed by either catch or finally.
The "catch" block is used to handle the exception. It must be
2. catch preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.
The "finally" block is used to execute the necessary code of the
3. finally
program. It is executed whether an exception is handled or not.
The "finally" block is used to execute the necessary code of the
4. finally
program. It is executed whether an exception is handled or not.

try –catch
The try block contains the code that may throw an exception, and the catch block is
used to handle the exception if it occurs.
try catch block
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
}

Multiple catch block


try {
// Code that may throw an exception
} catch (IOException e) {
// Handle IOException
} catch (NumberFormatException e) {
// Handle NumberFormatException
} catch (Exception e) {
// Handle any other exceptions
}

KG College of Arts and Science Page 48


School of Computational Sciences Java Programming

finally block
try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling code
} finally {
// Cleanup code
}

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("try catch example");
}
}
Output
try catch example
Built–in exceptions
1. Arithmetic exception
2. ArrayIndexOutOfBounds Exception
3. ClassNotFoundException
4. FileNotFoundException
5. IOException
6. InterruptedException
7. NoSuchMethodException
8. NullPointerException
9. NumberFormatException
10. StringIndexOutOfBoundsException
// Java program to demonstrate
// ArithmeticException
KG College of Arts and Science Page 49
School of Computational Sciences Java Programming

class ArithmeticException_Demo {
public static void main(String[] args) {
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
[Link]("Result = " + c);
} catch (ArithmeticException e) {
[Link]("Can't divide a number by 0");
}
}
}
Output
Can't divide a number by 0
Creating own exception classes
// A Class that represents user-defined exception
class MyException extends Exception {
public MyException(String m) {
super(m);
}
}
// A Class that uses the above MyException
public class setText {
public static void main(String args[]) {
try {
// Throw an object of user-defined exception
throw new MyException("This is a custom exception");
}
catch (MyException ex) {
[Link]("Caught"); // Catch and print message
[Link]([Link]());
}
}
}

KG College of Arts and Science Page 50


School of Computational Sciences Java Programming

Unit III
Multithreaded Programming: Thread Class - Runnable interface - Synchronization – Using
synchronized methods – Using synchronized statement - Interthread Communication –
Deadlock. I/O Streams: Concepts of streams - Stream classes - Byte and Character stream -
Reading console Input and Writing Console output - File Handling.

MULTITHREADED PROGRAMMING

 Multithreading is a conceptual programming paradigm where a program is divided


into two or more subprograms, which can be implemented at the same time in
parallel.
 A thread is similar to a program that has a single flow of control.
 A program that contains multiple flows of control is known as multithreaded program.
 The ability of a language to support multithreads is referred to as concurrency.
 Since threads in Java are subprograms of a main application program and share the
same memory space, they are known as lightweight threads or light weight processes.

Single-threaded program

 A single-threaded program in Java is a program that executes all its tasks sequentially,
one after the other, using a single thread of execution.
 This means that the program performs one task at a time, and each task must complete
before the next one starts.

Characteristics

 Only one thread of execution


 Tasks are executed sequentially
 No concurrent execution of tasks

Example

KG College of Arts and Science Page 51


School of Computational Sciences Java Programming

public class SingleThreadedExample {


public static void main(String[] args) {
[Link]("Task 1 started");
// simulate some work
try {
[Link](2000);
} catch (InterruptedException e) {
[Link]().interrupt();
}
[Link]("Task 1 completed");

[Link]("Task 2 started");
// simulate some work
try {
[Link](2000);
} catch (InterruptedException e) {
[Link]().interrupt();
}
[Link]("Task 2 completed");
}
}
Output
Task 1 started
Task 1 completed
Task 2 started
Task 2 completed
Multi-threaded program
A multi-threaded program in Java is a program that executes multiple threads of
execution concurrently, improving responsiveness, system utilization, and throughput.

KG College of Arts and Science Page 52


School of Computational Sciences Java Programming

Example
// Define a class that implements Runnable
class Task implements Runnable {
private String taskName;

public Task(String taskName) {


[Link] = taskName;
}
@Override
public void run() {
[Link](taskName + " started");
// simulate some work
try {
[Link](2000);
} catch (InterruptedException e) {
[Link]().interrupt();
}
[Link](taskName + " completed");
}
}

KG College of Arts and Science Page 53


School of Computational Sciences Java Programming

public class MultiThreadedExample {


public static void main(String[] args) {
// Create threads
Thread thread1 = new Thread(new Task("Task 1"));
Thread thread2 = new Thread(new Task("Task 2"));

// Start threads
[Link]();
[Link]();
}
}
Output
Task 1 started
Task 1 completed
Task 2 started
Task 2 completed
Thread Class
 Threads are implemented in the form of objects that contain a method called run().
 The run() method is the heart and soul of any thread.
public void run ( )
{
..................
. . . . . . . . . . . (statements for implementing thread)
............
}
A thread can be created in two ways:
1. By creating a thread class : Define a class that extends Thread class and override its
run() method with the code required by the thread.
2. By converting a class to a thread : Define a class that implements Runnable interface.
Declaring the Class
The Thread class can be extended as follows:
class MyThread extends Thread
{
.........
KG College of Arts and Science Page 54
School of Computational Sciences Java Programming

.........
.........
}
Implementing the run() Method
The `run()` method has been inherited by the class `MyThread`. We have to override
this method in order to implement the code to be executed by our thread. The basic
implementation of `run()` will look like this:
public void run()
{
.......... // Thread code here
..........
}
Starting new Thread

MyThread aThread=new MyThread()


[Link]();
Example
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link](“\t From Thread A : I = “ + i);
}
[Link](“Exit from A”);
}
}
class B extends Thread
{
public void run()
{
for(int j=11;j<=15;j++)
{
KG College of Arts and Science Page 55
School of Computational Sciences Java Programming

[Link](“\t From Thread B : J = “ + j);


}
[Link](“Exit from B”);
}
}
class C extends Thread
{
public void run()
{
for(int k=21;k<=5;k++)
{
[Link](“\t From Thread C : K = “ + k);
}
[Link](“Exit from C”);
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
Output
From Thread A : I = 1
From Thread B : J = 11
From Thread A : I = 2
From Thread B : J = 12
From Thread A : I = 3
From Thread B : J = 13
From Thread A : I = 4
From Thread B : J = 14
KG College of Arts and Science Page 56
School of Computational Sciences Java Programming

From Thread A : I = 5
From Thread B : J = 15
Exit from B
Exit from A
Exit from C
Runnable interface
The Runnable interface declares the run() method that is required for implementing
threads in our programs. To do this, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run() method.
3. Create a thread by defining an object that is instantiated from this "runnable" class as
the target of the thread.
4. Call the thread's start() method to run the thread.
class X implements Runnable // Step 1
{
public void run ( ) // Step 2
{
for(int i = 1; i<=10; i++)
{
[Link]("\tThreadX : " +i);
}
[Link]("End of ThreadX");
}
}
class RunnableTest
{
public static void main(String args[ ])
{
X runnable = new X( );
Thread threadX = new Thread(runnable); // Step 3
[Link]( ); // Step 4
[Link]("End of main Thread");
}
}
KG College of Arts and Science Page 57
School of Computational Sciences Java Programming

Output
End of main Thread
ThreadX : 1
ThreadX : 2
ThreadX : 3
ThreadX : 4
ThreadX : 5
ThreadX : 6
ThreadX : 7
ThreadX : 8
ThreadX : 9
ThreadX : 10
End of ThreadX
Life Cycle of Thread
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

State Transition Diagram

KG College of Arts and Science Page 58


School of Computational Sciences Java Programming

1. Newborn State
When we create a thread object, the thread is born and is said to be in newborn state.
The thread is not yet scheduled for running. At this state, we can do only one of the following
things with it:
 Schedule it for running using start() method.
 Kill it using stop() method.
New born state

Stop
Start

Runnable state Dead state

2. Runnable State

The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution. If all threads have equal priority, then they are given time slots for
execution in round robin fashion, i.e., first-come, first-serve manner. The thread that
relinquishes control joins the queue at the end and again waits for its turn. This process of
assigning time to threads is known as time-slicing.

Yield

Running thread

Runnable thread

3. Running State

KG College of Arts and Science Page 59


School of Computational Sciences Java Programming

Running means that the processor has given its time to the thread for its execution.
The thread runs until it relinquishes control on its own or it is preempted by a higher priority
thread. A running thread may relinquish its control in one of the following situations.
i. It has been suspended using suspend() method. A suspended thread can be revived by
using the resume() method. This approach is useful when we want to suspend a thread
for some time due to certain reason, but do not want to kill it.

Suspend

Resume

Running Runnable Suspended

ii. It has been made to sleep. We can put a thread to sleep for a specified time period
using the method sleep(time) where time is in milliseconds. This means that the
thread is out of the queue during this time period. The thread re-enters the runnable
state as soon as this time period is elapsed.
iii. It has been told to wait until some event occurs. This is done using the wait() method.
The thread can be scheduled to run again using the notify() method.

Wait

notify

Running Runnable waiting

4. Blocked State

A thread is said to be blocked when it is prevented from entering into the runnable
state and subsequently the running state. This happens when the thread is suspended,
sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered
"not runnable" but not dead and therefore fully qualified to run again.
5. Dead State
Every thread has a life cycle. A running thread ends its life when it has completed
executing its run() method. It is a natural death. However, we can kill it by sending the stop
message to it at any state thus causing a premature death to it. A thread can be killed as soon
as it is born, or while it is running, or even when it is in "not runnable" (blocked) condition.

KG College of Arts and Science Page 60


School of Computational Sciences Java Programming

A thread can also be temporarily suspended or blocked from entering into the
runnable and subsequently running state by using either of the following thread methods:
sleep( ) // blocked for a specified time
suspend( ) // blocked until further orders
wait( ) // blocked until certain condition occurs
Synchronization
synchronized void update ( )
{
............
. . . . . . . . . . . . // code here is synchronized
............
}
When we declare a method synchronized, Java creates a "monitor" and hands it over
to the thread that calls the method first time. As long as the thread holds the monitor, no other
thread can enter the synchronized section of code. A monitor is like a key and the thread that
holds the key can only open the lock.
Using synchronized methods
Thread A
synchronized method2( )
{
synchronized method1( )
{
........
}
}
Thread B
synchronized method1( )
{
synchronized method2( )
{
........
}
}
Using synchronized statement
KG College of Arts and Science Page 61
School of Computational Sciences Java Programming

To avoid polling, Java uses three methods, namely, wait(), notify(), and notifyAll().
All these methods belong to object class as final so that all classes have them. They must be
used within a synchronized block only.
 wait(): It tells the calling thread to give up the lock and go to sleep until some other
thread enters the same monitor and calls notify().
 notify(): It wakes up one single thread called wait() on the same object. It should be
noted that calling notify() does not give up a lock on a resource.
 notifyAll(): It wakes up all the threads called wait() on the same object.
Interthread Communication
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed. It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()
1. wait() method
The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this object, or a
specified amount of time has elapsed. The current thread must own this object's monitor, so it
must be called from the synchronized method only otherwise it will throw exception.
2. notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation.
Syntax:
public final void notify()
3. notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
Deadlock

KG College of Arts and Science Page 62


School of Computational Sciences Java Programming

Deadlock occurs in Java when multiple threads block each other while waiting for
locks held by one another. To prevent deadlocks, we can use the synchronized keyword to
make methods or blocks thread-safe which means only one thread can have the lock of the
synchronized method and use it, other threads have to wait till the lock releases other one
acquires the lock.
I/O Streams
Concepts of streams
 Streams are the sequence of data that are read from the source and written to the
destination.
 An input stream is used to read data from the source.
 An output stream is used to write data to the destination.

Stream classes

Depending upon the data a stream holds, it can be classified into:

 Byte Stream
 Character Stream
Byte Stream
Byte stream is used to read and write a single byte (8 bits) of data. All byte stream
classes are derived from base abstract classes called InputStream and OutputStream.
Java InputStream Class
The InputStream class of the [Link] package is an abstract superclass that represents
an input stream of bytes. Since InputStream is an abstract class, it is not useful by itself.
However, its subclasses can be used to read data.

Java OutputStream Class

KG College of Arts and Science Page 63


School of Computational Sciences Java Programming

The OutputStream class of the [Link] package is an abstract superclass that represents
an output stream of bytes.
Since OutputStream is an abstract class, it is not useful by itself. However, its
subclasses can be used to write data.
Character Stream
Character stream is used to read and write a single character of data. All the character
stream classes are derived from base abstract classes Reader and Writer.
Reader Class
The OutputStream class of the [Link] package is an abstract superclass that represents
an output stream of bytes. Since OutputStream is an abstract class, it is not useful by itself.
However, its subclasses can be used to write data.

Fig: Character input stream reader classes


Writer Class
The Writer class of the [Link] package is an abstract superclass that represents a
stream of characters. Since Writer is an abstract class, it is not useful by itself. However, its
subclasses can be used to write data.

Fig: Character input stream writer classes

Reading console Input and Writing Console output

KG College of Arts and Science Page 64


School of Computational Sciences Java Programming

1. Using Buffered Reader Class

Buffered Reader Class is the classical method to take input, Introduced in JDK 1.0.
This method is used by wrapping the [Link] (standard input stream) in an
InputStreamReader which is wrapped in a BufferedReader, we can read input from the user
in the command line.
 The input is buffered for efficient reading.
 The wrapping code is hard to remember.
2. Using Scanner Class

Scanner Class is probably the most preferred method to take input, Introduced in JDK
1.5. The main purpose of the Scanner class is to parse primitive types and strings using
regular expressions; however, it is also can be used to read input from the user in the
command line. Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from
the tokenized input.
 Regular expressions can be used to find tokens.
 The reading methods are not synchronized.
File Handling
File Handling is an integral part of any programming language as file handling
enables us to store the output of any particular program in a file and allows us to perform
certain operations on it. File handling means reading and writing data to a file.
Example
// Importing File Class
import [Link];
class NewFile
{
public static void main(String[] args)
{
// File name specified
File obj = new File("[Link]");
[Link]("File Created!");
}
}
Output
File Created!

KG College of Arts and Science Page 65


School of Computational Sciences Java Programming

File Operations
The following are the several operations that can be performed on a file in Java:
 Create a File
 Read from a File
 Write to a File
 Delete a File
1. Create a File
In order to create a file in Java, you can use the createNewFile() method.
If the file is successfully created, it will return a Boolean value true and false if the
file already exists.
// Creating File using Java Program

// Import the File class


import [Link];
import [Link];

public class CreateFile


{
public static void main(String[] args)
{
// Creating the File also
// Handling Exception
try {
File Obj = new File("[Link]");

// Creating File
if ([Link]()) {
[Link]("File created: " + [Link]());
}
else {
[Link]("File already exists.");
}
}

KG College of Arts and Science Page 66


School of Computational Sciences Java Programming

// Exception Thrown
catch (IOException e) {
[Link]("An error has occurred.");
[Link]();
}
}
}
2. Write to a File
We use the FileWriter class along with its write() method in order to write some text to the
file.
Example:
// Writing Files using Java Program

// Import the FileWriter class


import [Link];
import [Link];

public class WriteFile


{
public static void main(String[] args)
{
// Writing Text File also
// Exception Handling
try {

FileWriter Writer = new FileWriter("[Link]");

// Writing File
[Link]("Files in Java are seriously good!!");
[Link]();

[Link]("Successfully written.");
}

KG College of Arts and Science Page 67


School of Computational Sciences Java Programming

// Exception Thrown
catch (IOException e) {
[Link]("An error has occurred.");
[Link]();
}
}
}
3. Read from a File
We will use the Scanner class in order to read contents from a file.
// Reading File using Java Program

// Import the File class


import [Link];
import [Link];
import [Link];

public class ReadFile


{
public static void main(String[] args)
{
// Reading File also
// Handling Exception
try {
File Obj = new File("[Link]");
Scanner Reader = new Scanner(Obj);

// Traversing File Data


while ([Link]()) {
String data = [Link]();
[Link](data);
}

[Link]();
}
KG College of Arts and Science Page 68
School of Computational Sciences Java Programming

// Exception Cases
catch (FileNotFoundException e) {
[Link]("An error has occurred.");
[Link]();
}
}
}
4. Delete a File
We use the delete() method in order to delete a file.

// Deleting File using Java Program


import [Link];

public class DeleteFile


{
public static void main(String[] args)
{
File Obj = new File("[Link]");

// Deleting File
if ([Link]()) {
[Link]("The deleted file is : " + [Link]());
}
else {
[Link](
"Failed in deleting the file.");
}
}
}

KG College of Arts and Science Page 69


School of Computational Sciences Java Programming

Unit IV
AWT: Overview of AWT - 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 - Adapter classes - Inner
classes.

OVERVIEW OF AWT

 Java Abstract Window Toolkit (AWT) is an Application Programming


Interface(API) to develop Graphical User Interface (GUI) or windows-based
applications in Java.
 Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).

AWT Controls

 The [Link] package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
 Java AWT calls the native platform (operating systems) subroutine for
creating API components like TextField, CheckBox, button, etc.

For example, an AWT GUI with components like TextField, label and button will
have different look and feel for the different platforms like Windows, MAC OS, and Unix.
The reason for this is the platforms have different view for their native components and AWT
directly calls the native subroutine that creates those components.

The AWT Class Hierarchy

User interface components


KG College of Arts and Science Page 70
School of Computational Sciences Java Programming

Button, text fields, scroll bars, etc. are called components. To place every component on a
screen, we need to add them to a container. The Container is a component in AWT that can
contain another components like buttons, textfields, labels etc.
There are four types of containers in Java AWT:

1. Window

2. Panel

3. Frame

4. Dialog

1. Window

The window is the container that has no borders and menu bars. Frame, dialog or another
window need to be used for creating a window. Often used internally for creating other top-
level components. It is not commonly used in applications because it lacks standard window
decorations.
2. Panel

The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container used to group and organize other components. It cannot exist on its own, it must be
added inside another container such as a Frame. Panel is used for creating sections in a UI
(like placing buttons, labels, text fields together). It uses FlowLayout as the default layout
manager.
3. Frame

The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.
4. Dialog

Dialog is a pop-up window used to show messages, warnings, confirmations, or custom


forms. It is always associated with a parent Frame. It can be modal (blocks other windows
until closed) or non-modal. Dialog control is used for tasks like input boxes or alerts.
To create simple AWT example, you need a frame. There are two ways to create a GUI
using Frame in AWT.

1. By extending Frame class (inheritance)

KG College of Arts and Science Page 71


School of Computational Sciences Java Programming

2. By creating the object of Frame class (association)


Example1
// importing Java AWT class
import [Link].*;
// extending Frame class to our class AWTExample1
public class AWTExample1 extends Frame {
// initializing using constructor
AWTExample1() {
// creating a button
Button b = new Button("Demo Button!!");
// setting button position on screen
[Link](30,100,80,30);

// adding button into frame


add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
}
Output

-----------------------------------------

| This is our basic AWT example |

KG College of Arts and Science Page 72


School of Computational Sciences Java Programming

|-----------------------------------------|

| |

| [ Demo Button!! ] |

| |

| |

| |

-------------------------------------------

Example2
// importing Java AWT class
import [Link].*;
// class AWTExample2 directly creates instance of Frame class
class AWTExample2 {
// initializing using constructor
AWTExample2() {
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// setting position of above components in the frame
[Link](20, 80, 80, 30);
[Link](20, 100, 80, 30);
[Link](100, 100, 80, 30);
// adding components into frame
[Link](b);

KG College of Arts and Science Page 73


School of Computational Sciences Java Programming

[Link](l);
[Link](t);
// frame size 300 width and 300 height
[Link](400,300);
// setting the title of frame
[Link]("Employee info");
// no layout
[Link](null);
// setting visibility of frame
[Link](true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample2 awt_obj = new AWTExample2();
}
}
Output
---------------------------------------------------
| Employee info |
|---------------------------------------------------|
| |
| Employee id: |
| [__________] [ Submit ] |
| |
| |
| |
-----------------------------------------------------
Labels

KG College of Arts and Science Page 74


School of Computational Sciences Java Programming

There are three types of Java AWT Label Class


1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified alignment
Button
AWT Button is a control component with a label that generates an event when clicked on.
Button Class is used for creating a labeled button that is platform-independent.

Java AWT Button Class Constructors


There are two types of Button class constructors as mentioned below:

1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.

2. Button(String str):
Creates a Button with String str as a label. For example if str=”Click Here” button with
show click here as the value.

Text Components
TextField Class constructors
There are TextField class constructors are mentioned below:
1. TextField():
Constructs a TextField component.
2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.
3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).
4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given number of columns
(col).

KG College of Arts and Science Page 75


School of Computational Sciences Java Programming

Check Box
Checkbox Class Constructors
There are certain constructors in the AWT Checkbox class as mentioned below:
1. Checkbox():
Creates a checkbox with no label.
2. Checkbox(String str):
Creates a checkbox with a str label.
[Link](String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the mentioned group.
Check Box Group
CheckboxGroup Class is used to group together a set of Checkbox.
Choice
The object of the Choice class is used to show a popup menu of choices.
AWT Choice Class constructor
Choice(): It creates a new choice menu.
List Box
The List of class constructors is defined below:
[Link]():
Creates a new list.
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.
Scrollbar
Syntax of AWT Scrollbar:
public class Scrollbar extends Component implements Adjustable, Accessible
Scrollbar Class Constructors
There are three constructor classes in Java mentioned below:
1. Scrollbar():

KG College of Arts and Science Page 76


School of Computational Sciences Java Programming

It Creates a new vertical Scrollbar in the Application.


2. Scrollbar(int orientation):
Creates a new vertical Scrollbar with the given orientation.
3. Scrollbar(int orientation, int value, int visible, int mini, int maxi):
Creates a new scrollbar with the orientation mentioned with value as the default value and
[mini, maxi] as the lower and higher limit.
MenuItem & Menu
MenuItem class adds a simple labeled menu item on the menu. The MenuItem class allows
you to create individual items that can be added to menus. And Menu is a component used to
create a dropdown menu that can contain a list of MenuItem components.
Syntax of Java AWT MenuItem
public class MenuItem extends MenuComponent implements Accessible
Syntax of Java AWT Menu
public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT PopupMenu is a component that is used for dynamically popping up a menu
that appears when the user right-clicks or performs any other action on a component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer, Accessible
Panel
Java AWT Panel is a container class used to hold and organize graphical components in a
Java Application.
Syntax of Java AWT Panel:
public class Panel extends Container implements Accessible
Example
import [Link].*;

public class PanelExample {


public static void main(String[] args) {

// Create Frame
Frame f = new Frame("AWT Panel Example");

KG College of Arts and Science Page 77


School of Computational Sciences Java Programming

[Link](400, 300);
[Link](null); // Using no layout to manually set positions

// Create Panel
Panel p = new Panel();
[Link](50, 50, 300, 150);
[Link]([Link]);

// Add components to Panel


Label l = new Label("Enter Name:");
TextField tf = new TextField(15);
Button b = new Button("Submit");

[Link](l);
[Link](tf);
[Link](b);

// Add Panel to Frame


[Link](p);

// Make frame visible


[Link](true);
}
}

---------------------------------------------
| AWT Panel Example |
| |
| ------------------------------ |

KG College of Arts and Science Page 78


School of Computational Sciences Java Programming

| | Enter Name: [________] [Submit] | |


| ------------------------------ |
| |
---------------------------------------------
|
SWING
Swing is a part of Java Foundation Classes (JFC) and provides a rich set of components
for developing graphical user interfaces (GUI). Unlike AWT, Swing components are
lightweight, platform-independent, and offer a pluggable look-and-feel.
Swing classes are primarily found in the package:
[Link].*
Introduction to Swing
Swing was introduced to overcome various limitations of AWT:
 AWT components are heavyweight, relying on native OS components.
 Swing provides lightweight components written entirely in Java.
 Swing offers a richer set of widgets such as tables, trees, tabbed panes, sliders, color
choosers, etc.

Key Features of Swing


1. Lightweight Components
Do not depend on native GUI components.
2. Pluggable Look-and-Feel
Components can adopt different UI styles at runtime.
3. MVC Architecture
Uses Model–View–Controller internally.
4. High Flexibility
Rich set of components for complex interfaces.
5. Double Buffering
Ensures smooth graphics.
6. Customizable and Configurable
Developers can easily extend and modify components.

KG College of Arts and Science Page 79


School of Computational Sciences Java Programming

Hierarchy of Swing Components


Swing is built on top of AWT, so the component hierarchy begins from [Link].
Object
└── Component (AWT)
└── Container (AWT)
└── JComponent (Swing base class)
├── JPanel
├── JLabel
├── JButton
├── JToggleButton
├── JCheckBox
├── JRadioButton
├── JTextField
├── JTextArea
├── JList
├── JComboBox
├── JScrollPane
└── many more...
└── Window (AWT)
├── Frame → JFrame
└── Dialog → JDialog
└── JWindow
 JComponent is the root class for almost all Swing controls
 Top-level containers do NOT inherit from JComponent (JFrame, JDialog,
JWindow)

Containers in Swing
Swing follows a top-level container → intermediate container → atomic component
structure.

Two Major Categories of Containers


(A) Top-Level Containers
These are the containers that exist independently:
 JFrame
 JWindow
 JDialog

They serve as roots for component trees.


(B) Intermediate Containers
Used for grouping components:
 JPanel
 JScrollPane
 JTabbedPane (not in this list but commonly used)

KG College of Arts and Science Page 80


School of Computational Sciences Java Programming

(C) Atomic Components (Controls/Widgets)


JButton, JLabel, JTextField, JComboBox, JList, etc.
Top-Level Containers
1. JFrame
A JFrame is the most commonly used Swing top-level container.
Features
 Contains a title bar, borders, maximize/minimize/close buttons.
 Provides a content pane to hold UI components.
 Used to create primary application windows.

[Link] Method Use


1. setTitle(String) Set window title
2. setSize(int,int) Set frame size
3. setDefaultCloseOperation() Define close behaviour
4. getContentPane() Returns content area
Example:
JFrame frame = new JFrame("My Window");
[Link](400,300);
[Link](true);
2. JWindow
 A borderless, title-less top-level container.
 Used for splash screens, tooltips, custom pop-ups.
 Does not have minimize/maximize buttons.

JWindow win = new JWindow();


[Link](200,100);
[Link](true);
3. JDialog
A pop-up window that is usually used for:
 messages
 confirmation boxes
 custom dialog forms

KG College of Arts and Science Page 81


School of Computational Sciences Java Programming

Types:
 Modal (blocks other windows)
 Non-modal

JDialog d = new JDialog(frame, "Warning", true);


Intermediate Container
1. JPanel
 A lightweight container that groups components.
 Uses FlowLayout by default.
 Frequently used for UI layout organization.

JPanel p = new JPanel();


[Link](new JButton("OK"));

Swing Components (Controls)


1. JButton
 Represents a push button.
 Generates ActionEvent when clicked.

Common methods
 setText()
 addActionListener()
 setEnabled()

Example:
JButton b = new JButton("Submit");
2. JToggleButton
 A button with ON/OFF toggle behavior.
 Parent class for JCheckBox and JRadioButton.

JToggleButton t = new JToggleButton("Start");


3. JCheckBox
 Allows independent selection (true/false)
 Generates ItemEvent

JCheckBox cb = new JCheckBox("I agree");

4. JRadioButton
 Used when only one option must be selected.
 Multiple radio buttons must be grouped using ButtonGroup.

KG College of Arts and Science Page 82


School of Computational Sciences Java Programming

ButtonGroup bg = new ButtonGroup();


[Link](rb1);
[Link](rb2);

5. JLabel
 Used to display text or images.
 Non-editable.

JLabel l = new JLabel("Enter Name:");

6. JTextField
 Single-line editable text box.

Common methods:
 getText()
 setText()
 setEditable(true/false)

JTextField tf = new JTextField(20);

7. JTextArea
 Multi-line text input area.
 Supports line wrapping, scrolling.

JTextArea ta = new JTextArea(5, 30);


8. JList
 Displays a list of items.
 Can enable single or multiple selection.

JList list = new JList(dataArray);


Selection Modes:
 SINGLE_SELECTION
 MULTIPLE_INTERVAL_SELECTION
9. JComboBox
 Drop-down list.
 Allows selecting one item at a time.

JComboBox cb = new JComboBox(items);

Methods:
 getSelectedItem()
 addItem()
 JScrollPane

KG College of Arts and Science Page 83


School of Computational Sciences Java Programming

Provides scrollbars for components like:


 JTextArea
 JList
 JTable
 JPanel

Example:
JScrollPane sp = new JScrollPane(textArea);

[Link] Component Type Purpose


1. JFrame Top-level Main window with title bar
2. JWindow Top-level Borderless window
3. JDialog Top-level Modal/Non-modal dialog
4. JPanel Container Group UI elements
5. JButton Component Push button
6. JToggleButton Component Toggle button
7. JCheckBox Component Independent selection
8. Mutually exclusive selection (via
JRadioButton Component
ButtonGroup)
9. JLabel Component Display text/image
10. JTextField Component Single-line text input
11. JTextArea Component Multi-line text input
12. JList Component List of items
13. JComboBox Component Drop-down list
14. JScrollPane Container Adds scrollbars

JFrame Example
import [Link].*;
public class JFrameExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame Example");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello, this is a JFrame window!",
[Link]);
[Link](label);
[Link](true);
}
}

KG College of Arts and Science Page 84


School of Computational Sciences Java Programming

Output
-----------------------------------------------------
| JFrame Example |
-----------------------------------------------------
| |
| Hello, this is a JFrame window! |
| |
| |
-----------------------------------------------------

Jwindow Example
JWindow (borderless, undecorated window — e.g. splash screen) Example
import [Link].*;
import [Link].*;
public class JWindowExample {
public static void main(String[] args) {
JWindow window = new JWindow();
[Link](300, 150);
[Link](new BorderLayout());

JLabel label = new JLabel("This is a JWindow (no title bar)",


[Link]);
[Link](label, [Link]);

[Link](null); // center on screen


[Link](true);

// Automatically close after 3 seconds


try {
[Link](3000);
} catch (InterruptedException e) {}
[Link]();
}
}
Output
┌──────────────────────────────────────┐
│ │
│ This is a JWindow (no title bar) │

KG College of Arts and Science Page 85


School of Computational Sciences Java Programming

│ │
└──────────────────────────────────────┘

JDialog Example

JDialog (modal/non-modal dialog window) Example


import [Link].*;
import [Link].*;
import [Link].*;
public class JDialogExample {
public static void main(String[] args) {
JFrame parent = new JFrame("Parent Frame");
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new FlowLayout());
JButton btnShow = new JButton("Show Dialog");
[Link](btnShow);
[Link](e -> {
JDialog dialog = new JDialog(parent, "Modal Dialog", true);
[Link](200, 120);
[Link](new FlowLayout());
[Link](new JLabel("Hello from JDialog!"));
JButton ok = new JButton("OK");
[Link](ok);
[Link](ev -> [Link]());
[Link](parent);
[Link](true);
});

[Link](true);
}
}

Output
----------------------------------------------------

KG College of Arts and Science Page 86


School of Computational Sciences Java Programming

| Parent Frame |
----------------------------------------------------
| [ Show Dialog ] |
----------------------------------------------------
After Clicking the Button
---------------- Modal Dialog ----------------------
| Hello from JDialog! |
| |
| [ OK ] |
-----------------------------------------------------

JPanel Example

JPanel (container for organizing components) Example


import [Link].*;
import [Link].*;

public class JPanelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JPanel Example");
[Link](400, 200);
[Link](JFrame.EXIT_ON_CLOSE);

JPanel panelTop = new JPanel();


[Link]([Link]);
[Link](new JLabel("Top Panel"));

JPanel panelBottom = new JPanel();


[Link](Color.LIGHT_GRAY);
[Link](new JLabel("Bottom Panel"));

[Link](new BorderLayout());
[Link](panelTop, [Link]);
[Link](panelBottom, [Link]);

[Link](true);
}

KG College of Arts and Science Page 87


School of Computational Sciences Java Programming

}
Output
---------------------------------------------------------
| JPanel Example |
---------------------------------------------------------
| [ TOP PANEL - CYAN ] |
| Top Panel |
| |
| [ BOTTOM PANEL - LIGHT GRAY ] |
| Bottom Panel |
---------------------------------------------------------

JButton (push button) Example


import [Link].*;
import [Link].*;

public class JButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JButton Example");
[Link](300, 150);
[Link](JFrame.EXIT_ON_CLOSE);

JButton button = new JButton("Click Me");


[Link](e -> [Link](frame, "Button
Clicked!"));

[Link](new FlowLayout());
[Link](button);
[Link](true);
}
}

-------------------------------------------------
| JButton Example |
-------------------------------------------------
| [ Click Me ] |
-------------------------------------------------
After Clicking the Button
+-------------------------+
| Button Clicked! |

KG College of Arts and Science Page 88


School of Computational Sciences Java Programming

+-------------------------+
JToggleButton (button with toggle ON/OFF behavior) Example
import [Link].*;
import [Link].*;
import [Link].*;

public class JToggleButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JToggleButton Example");
[Link](300, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new FlowLayout());

JToggleButton toggle = new JToggleButton("OFF");


[Link](e -> {
if ([Link]()) {
[Link]("ON");
} else {
[Link]("OFF");
}
});

[Link](toggle);
[Link](true);
}
}

Output
Initial Window
-------------------------------------------------
| JToggleButton Example |
-------------------------------------------------
| [ OFF ] |
-------------------------------------------------

After Clicking Once

KG College of Arts and Science Page 89


School of Computational Sciences Java Programming

-------------------------------------------------
| [ ON ] |
-------------------------------------------------
Back to OFF
-------------------------------------------------
| [ OFF ] |
-------------------------------------------------
JCheckBox (independent selection) Example
import [Link].*;
import [Link].*;
import [Link].*;

public class JCheckBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JCheckBox Example");
[Link](300, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new FlowLayout());

JCheckBox cb1 = new JCheckBox("Option 1");


JCheckBox cb2 = new JCheckBox("Option 2");

JButton btn = new JButton("Show Selection");


[Link](e -> {
String msg = "Selected: ";
if ([Link]()) msg += "Option 1 ";
if ([Link]()) msg += "Option 2 ";
[Link](frame, msg);
});

[Link](cb1);
[Link](cb2);
[Link](btn);
[Link](true);
}
}

KG College of Arts and Science Page 90


School of Computational Sciences Java Programming

Output
Main Window
----------------------------------------------
| JCheckBox Example |
----------------------------------------------
| [ ] Option 1 [ ] Option 2 |
| |
| [ Show Selection ] |
----------------------------------------------

If User Selects Option 1 and Clicks Button


+----------------------------------+
| Selected: Option 1 |
+----------------------------------+
Both Selected
+----------------------------------+
| Selected: Option 1 Option 2 |
+----------------------------------+
JRadioButton (mutually exclusive selection — using ButtonGroup) Example
import [Link].*;
import [Link].*;
import [Link].*;

public class JRadioButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JRadioButton Example");
[Link](300, 180);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new FlowLayout());

JRadioButton rb1 = new JRadioButton("Male");


JRadioButton rb2 = new JRadioButton("Female");
JRadioButton rb3 = new JRadioButton("Other");

ButtonGroup group = new ButtonGroup();


[Link](rb1);
[Link](rb2);
[Link](rb3);

JButton btn = new JButton("Submit");


KG College of Arts and Science Page 91
School of Computational Sciences Java Programming

[Link](e -> {
String selection = "None";
if ([Link]()) selection = "Male";
else if ([Link]()) selection = "Female";
else if ([Link]()) selection = "Other";
[Link](frame, "Selected: " + selection);
});

[Link](rb1);
[Link](rb2);
[Link](rb3);
[Link](btn);

[Link](true);
}
}
Output
Male (○)
Female (○)
Other (○)

[ Submit ]

Selected: Male
Selected: Female
Selected: Other
Selected: None

JLabel (display text or image — non-editable) Example


import [Link].*;
import [Link].*;

public class JLabelExample {


public static void main(String[] args) {
KG College of Arts and Science Page 92
School of Computational Sciences Java Programming

JFrame frame = new JFrame("JLabel Example");


[Link](300, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new FlowLayout());

JLabel label1 = new JLabel("Simple Text Label");


JLabel label2 = new JLabel("Label with Icon", new ImageIcon("path/to/[Link]"),
[Link]);

[Link](label1);
[Link](label2);

[Link](true);
}
}
(Note: for the icon example, replace "path/to/[Link]" with an actual image file path.)
Output
----------------------------------------
| Simple Text Label |
| [Image] Label with Icon |
----------------------------------------

JTextField (single-line text input) Example


import [Link].*;
import [Link].*;
import [Link].*;

public class JTextFieldExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JTextField Example");
[Link](350, 120);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new FlowLayout());

KG College of Arts and Science Page 93


School of Computational Sciences Java Programming

JTextField tf = new JTextField(20);


JButton btn = new JButton("Show Text");
[Link](e -> {
String text = [Link]();
[Link](frame, "You entered: " + text);
});

[Link](new JLabel("Enter something: "));


[Link](tf);
[Link](btn);

[Link](true);
}
}
Output
-----------------------------------------------------
| Enter something: [___________TextField__________] |
| Show Text |
-----------------------------------------------------
JTextArea (multi-line text input area) Example
import [Link].*;
import [Link].*;

public class JTextAreaExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JTextArea Example");
[Link](400, 250);
[Link](JFrame.EXIT_ON_CLOSE);

JTextArea textArea = new JTextArea(8, 30);


[Link](true);
[Link](true);

JScrollPane scrollPane = new JScrollPane(textArea);

KG College of Arts and Science Page 94


School of Computational Sciences Java Programming

[Link](scrollPane);
[Link](true);
}
}
Output
|--------------------------------------------------|
| This is a text area where you can type multiple |
| lines of text. |
| |
| (Scrollbars appear when content exceeds size) |
|--------------------------------------------------|

JList (list of items, single or multiple selection) Example


import [Link].*;
import [Link].*;
import [Link].*;

public class JListExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JList Example");
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);

String[] data = { "Red", "Green", "Blue", "Yellow", "Black" };


JList<String> list = new JList<>(data);
[Link](ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

JButton btn = new JButton("Show Selection");


[Link](e -> {
[Link]<String> selected = [Link]();
[Link](frame, "Selected: " + selected);
});

[Link](new BorderLayout());
[Link](new JScrollPane(list), [Link]);
[Link](btn, [Link]);

KG College of Arts and Science Page 95


School of Computational Sciences Java Programming

[Link](true);
}
}

Output
--------------------------
| Red |
| Green |
| Blue |
| Yellow |
| Black |
--------------------------
JComboBox (drop-down list / combo box) Example
import [Link].*;
import [Link].*;
import [Link].*;

public class JComboBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JComboBox Example");
[Link](300, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new FlowLayout());

String[] items = { "Apple", "Banana", "Cherry", "Date" };


JComboBox<String> combo = new JComboBox<>(items);

JButton btn = new JButton("Select");


[Link](e -> {
String sel = (String) [Link]();
[Link](frame, "You selected: " + sel);
});

[Link](new JLabel("Choose fruit:"));


[Link](combo);

KG College of Arts and Science Page 96


School of Computational Sciences Java Programming

[Link](btn);

[Link](true);
}
}

Output

You selected: Apple

JScrollPane (scrollbars for components like text area, list, panel) Example

Here’s an example combining JTextArea with JScrollPane — similar to the earlier


JTextArea example, but demonstrating scrollbars explicitly:
import [Link].*;
import [Link].*;

public class JScrollPaneExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JScrollPane Example");
[Link](400, 250);
[Link](JFrame.EXIT_ON_CLOSE);

JTextArea textArea = new JTextArea(5, 30);


[Link](true);
[Link](true);

JScrollPane scrollPane = new JScrollPane(


textArea,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
);

[Link](scrollPane);
[Link](true);
}

KG College of Arts and Science Page 97


School of Computational Sciences Java Programming

----------------------------------------------
| JScrollPane Example |
|----------------------------------------------|
| __________________________________________ |
|| ||
| | (A large JTextArea box appears here) ||
|| ||
| | It has vertical and horizontal ||
| | scrollbars that appear when needed. ||
| |__________________________________________| |
| |
----------------------------------------------

EVENT HANDLING

Event Handling in Java AWT is a mechanism that allows handling user interactions like
mouse clicks, key presses, button clicks, and window closing events. It follows the Event
Delegation Model, where events are sent to listener objects that handle them.
Events
An event is an object that represents a state change in a component due to:
 User actions (mouse click, key press, button click)
 Component state changes (window opened/closed, resizing)
 System-generated actions (timer event, focus gained, item selected)

Examples of common AWT events:

 ActionEvent – button click


 MouseEvent – mouse pressed, released, moved
 KeyEvent – key press or release
 WindowEvent – window opened/closed/activated
 ItemEvent – checkbox/radio button selected

KG College of Arts and Science Page 98


School of Computational Sciences Java Programming

Event Sources
An event source is an object that generates events. An event source must be a component
that user interacts with or register listeners or fire events when the user performs actions.

Common event sources:

 Button, MenuItem → generate ActionEvents


 TextField → ActionEvent & TextEvent
 Checkbox, Choice, List → ItemEvent
 Window → WindowEvent
 Mouse actions → MouseEvent

Example:

Button b = new Button("Submit");

In this example b is the event source.


Event Listeners
 An event listener is an interface that receives and handles events generated by the
source.
 A listener must be registered with a source, contains abstract methods and executes
automatically when event occurs
[Link] Listener Interface Event Type Handled
1. ActionListener button click, menu select
2. MouseListener mouse pressed/released/clicked/entered/exited
3. MouseMotionListener mouse dragged/moved
4. KeyListener key pressed/released/typed
5. ItemListener item selected/deselected
6. WindowListener window opened/closed
7. FocusListener focus gained/lost
Event Delegation Model (EDM)
The Event Delegation Model (EDM) is Java’s mechanism for handling events in GUI
programming (AWT/Swing). It was introduced in Java 1.1 to replace the older, inefficient
event-handling model.

EDM has two main participants:

KG College of Arts and Science Page 99


School of Computational Sciences Java Programming

1. Event Source – component generating event(e.g., Button, TextField, Window).


2. Event Listener – object receiving and handling event

Flow of EDM

1. Event Source generates an event.


2. The event is an object (e.g., ActionEvent).
3. Event is delivered to registered listeners.
4. Listener executes the corresponding method.

Example Program:

import [Link].*;

import [Link].*;

import [Link].*;

public class EventDelegationExample {

public static void main(String[] args) {

JFrame frame = new JFrame("Event Delegation Model");

JButton button = new JButton("Click Me");

// Adding ActionListener to the button

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]("Button Clicked!");

});

[Link](new FlowLayout());

[Link](button);

[Link](300, 200);

[Link](JFrame.EXIT_ON_CLOSE);

[Link](true);

KG College of Arts and Science Page 100


School of Computational Sciences Java Programming

Advantages of EDM
1. Better Performance: Reduces unnecessary event processing.
2. More Maintainable: Separates event handling from event generation.
3. Reusability: A single listener can handle events for multiple components.

Handling Mouse Events


 Mouse events are generated when the user interacts with the mouse. Java provides the
MouseListener and MouseMotionListener interfaces to handle mouse events.

MouseListener Methods
void mouseClicked(MouseEvent e);
void mousePressed(MouseEvent e);
void mouseReleased(MouseEvent e);
void mouseEntered(MouseEvent e);
void mouseExited(MouseEvent e);

MouseMotionListener Methods
void mouseDragged(MouseEvent e);
void mouseMoved(MouseEvent e);

Example: Display mouse coordinates


import [Link].*;
import [Link].*;

class MouseDemo extends Frame implements MouseListener, MouseMotionListener {


int x = 0, y = 0;
MouseDemo() {
addMouseListener(this);
addMouseMotionListener(this);
setSize(400,300);
setVisible(true);
}
public void mouseMoved(MouseEvent e) {

KG College of Arts and Science Page 101


School of Computational Sciences Java Programming

x = [Link]();
y = [Link]();
repaint();
}

public void paint(Graphics g) {


[Link]("Mouse at: " + x + "," + y, 50, 50);
}
// Empty implementations
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}

public static void main(String[] s) {


new MouseDemo();
}
}
Handling Keyboard Events
 Keyboard events occur when user types keys.
Listener interface:
KeyListener
void keyPressed(KeyEvent e);
void keyReleased(KeyEvent e);
void keyTyped(KeyEvent e);

Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class KeyEventExample extends JFrame implements KeyListener {
JLabel label;

KG College of Arts and Science Page 102


School of Computational Sciences Java Programming

public KeyEventExample() {
label = new JLabel("Press a Key");
[Link](new Font("Arial", [Link], 16));
add(label);

addKeyListener(this);
setSize(400, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setFocusable(true); // Important to receive key events
}
// KeyListener methods
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]([Link]()));
}
public void keyReleased(KeyEvent e) {
[Link]("Key Released: " + [Link]([Link]()));
}
public void keyTyped(KeyEvent e) {
[Link]("Key Typed: " + [Link]());
}
public static void main(String[] args) {
new KeyEventExample();
}
}
Adapter Classes
An Adapter Class is a class that provides empty implementations of all methods of an
interface. When a listener interface contains many abstract methods, implementing all
becomes inconvenient. To solve this, Java provides Adapter Classes, which give default
empty implementations. Instead of implementing all methods of an interface, you can extend
an adapter class and override only the methods you need.

Common Adapter Classes


KG College of Arts and Science Page 103
School of Computational Sciences Java Programming

[Link] Listener Interface Adapter Class


1. MouseListener MouseAdapter
2. MouseMotionListener MouseMotionAdapter
3. KeyListener KeyAdapter
4. WindowListener WindowAdapter
5. FocusListener FocusAdapter

a) Example: Using MouseAdapter


 Instead of implementing all methods of MouseListener, we extend MouseAdapter and
override only the methods we need.

import [Link].*;
import [Link].*;
import [Link].*;
public class MouseAdapterExample extends JFrame {
JLabel label;
public MouseAdapterExample() {
label = new JLabel("Click Anywhere");
[Link](new Font("Arial", [Link], 16));
add(label);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at: " + [Link]());
}
});
setSize(400, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
Output

KG College of Arts and Science Page 104


School of Computational Sciences Java Programming

---------------------------------------------
| MouseAdapter Example |
|---------------------------------------------|
| Click Anywhere |
| |
| |
---------------------------------------------
b) b)Example using WindowAdapter

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

---------------------------------------------------
| WindowAdapter Example |
|---------------------------------------------------|
| Close the window to exit. |
| |
---------------------------------------------------
Inner Classes
 An Inner Class is a class defined within another class. It helps in logically grouping
classes and increasing encapsulation.
AWT/Swing programs often use inner classes for event handling because:
 Easy access to outer class variables
 More readable code
 Avoids global listener classes
Types of inner classes used:
 Member Inner Class
 Anonymous Inner Class ← most common
 Local Inner Class
a) Example: Using a Member Inner Class
class Outer {

KG College of Arts and Science Page 105


School of Computational Sciences Java Programming

class Inner {
void show() {
[Link]("Hello from Inner Class!");
}
}
public static void main(String[] args) {
Outer outer = new Outer();
[Link] inner = [Link] Inner();
[Link]();
}
}
Output
Hello from Inner Class!
b) Example: Using an Anonymous Inner Class
 Anonymous inner classes are commonly used in event handling, especially with
adapter classes.
import [Link].*;
import [Link].*;
import [Link].*;
public class AnonymousInnerClassExample extends JFrame {
JButton button;
public AnonymousInnerClassExample() {
button = new JButton("Click Me");
// Using Anonymous Inner Class for ActionListener
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked!");
}
});
add(button);
setSize(300, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
KG College of Arts and Science Page 106
School of Computational Sciences Java Programming

public static void main(String[] args) {


new AnonymousInnerClassExample();
}
}
-----------------------------------------
| AnonymousInnerClassExample |
|-----------------------------------------|
| [ Click Me ] |
| |
-----------------------------------------

KG College of Arts and Science Page 107


School of Computational Sciences Java Programming

Unit V
JavaFX: Introduction to JavaFX, Setting the Scene, Hello World- Spring Boot:
Fundamentals of Spring Boot-Spring vs Spring Boot-Spring Boot Architecture-
Develop Spring Boot Application step by step-Run Spring Boot Application. Introduction to
Jython-Basics of Jython.

JavaFX

JavaFX

JavaFX is a modern, open-source platform for building rich client applications (desktop,
mobile, embedded) with visually appealing, hardware-accelerated UIs using Java, known for
its CSS styling, FXML support, and separation of UI from logic, succeeding the older Swing
framework for new projects. Developers use tools like Scene Builder to design interfaces,
integrating Java libraries and web assets for interactive experiences across devices.

Introduction to JavaFX

 JavaFX is a software platform is used to build rich GUI (Graphical User Interface)
applications, including desktop applications, web-capable apps (via WebView),
multimedia apps, etc.
 Compared to earlier UI toolkits or technologies (e.g. older Java applets, or web-based
UI toolkits), JavaFX aims to provide a more modern, flexible, hardware-accelerated,
cross-platform rich-client UI framework.
 It supports UI controls, charts, media (audio/video), shapes, animations, CSS-based
styling, 2D/3D graphics, and more.
Key Components / Architecture

[Link] Module / Part Role / Purpose

KG College of Arts and Science Page 108


School of Computational Sciences Java Programming

Core APIs — properties, bindings, collections, events,


1. [Link]
foundational stuff.
2. [Link] Scene graph, geometry, animation, graphics infrastructure.
3. [Link] UI controls (buttons, labels, tables, charts, controls) + skins.
4. [Link] API for FXML — described UI layout in XML.
WebView — embedding web content (HTML/JS) inside
5. [Link]
JavaFX applications.
Integration / interoperability layer for mixing JavaFX and older
6. [Link]
Swing components (for backward compatibility) when needed.

Advantages of JavaFX

 Cross-platform: As long as Java runs, JavaFX apps can run. JavaFX is independent of
platform-specific UI toolkits.
 Rich GUI capabilities: Advanced UI controls, 2D/3D graphics, media support,
animations — good for building modern, polished user interfaces.
 Declarative UI & design tools: JavaFX supports declarative UI via FXML, and UI
design via visual tools like a Scene Builder (drag-and-drop).
 CSS styling for UI: Just like web technologies, you can use CSS to style the UI —
making styling and theming easier and familiar.
 Media & Web integration: Embedding video, audio, web content, etc — making it
suitable for multimedia apps.

Prerequisites for Using JavaFX

 Basic understanding of Java (classes, types, basic syntax) helps.


 Familiarity with UI design concepts helps; knowledge of CSS (for styling) is a plus,
since JavaFX supports CSS styling.
 An IDE: While you can use any text editor, the book focuses on using NetBeans IDE
because of its built-in support for JavaFX and a “Palette” of UI components/snippets.

Key Features & Benefits

 Modern UI: Offers rich graphics, animations, 2D/3D rendering, and visual effects.

 Declarative UI (FXML): Use FXML for UI design, separating it from Java code (MVC
pattern).

KG College of Arts and Science Page 109


School of Computational Sciences Java Programming

 Styling with CSS: Apply Cascading Style Sheets for easy customization, making UIs look
like web pages.

 Hardware Acceleration: Leverages GPU for smooth, high-performance UIs.

 Cross-Platform: Write once, run anywhere on desktops, mobile, and embedded systems.

 Integration: Easily use any existing Java library within JavaFX applications.

 Tools: Features Scene Builder for visual UI design.


Core Concepts

 Stage: The top-level window for an application.

 Scene: The container for all graphical content (nodes) within a Stage.

 Scene Graph: A hierarchical tree of Nodes (buttons, text fields, images).

Modern Development
 JavaFX is now an OpenJFX project under OpenJDK.

 It's actively maintained, with LTS (Long Term Support) releases like versions 21 and 25,
requiring newer JDKs (e.g., JDK 21+ for JavaFX 21).

 Build systems (Maven/Gradle) download modules from Maven Central for easy setup.
Setting the Scene
Setting the Scene refers not just to the conceptual “scene” / GUI, but also to how to
structure the project within an IDE (specifically NetBeans), and how to manage files, UI
elements, etc.

Major points

 When you open NetBeans, you see a set of explorers typically tabs named Projects,
Files, and Services. These help you navigate your project code, assets (images, CSS,
FXML), configuration files which is especially useful as projects grow and
accumulate multiple files.
 On the right side is the Palette, a panel containing reusable UI code
snippets/components (buttons, layouts, controls, etc.). This makes it easier to build UI
quickly without writing everything from scratch.

 Layout management (e.g. using layout containers) becomes important when building
non-trivial UIs: JavaFX provides layout panes.

KG College of Arts and Science Page 110


School of Computational Sciences Java Programming

Setting the Scene includes both the logical UI scene structure (layouts, nodes) and the
practical project / file organization in the IDE — both are essential to building maintainable
JavaFX applications.

Hello World
Typical HelloWorld Example (in JavaFX)

package helloworld;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class HelloWorld extends Application {


public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
[Link]("Hello World!");
Button btn = new Button();
[Link]("Say 'Hello World'");
[Link](new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
[Link]("Hello World!");
}
});
StackPane root = new StackPane();
KG College of Arts and Science Page 111
School of Computational Sciences Java Programming

[Link]().add(btn);
[Link](new Scene(root, 300, 250));
[Link]();
}
}
Explanation:
 The main class extends [Link].
 The core is the start(Stage primaryStage) method — where you build the UI.
 The “Stage” is like the top-level window (the “stage” or “frame”).
 Inside the stage, you create a “Scene” object. The scene is the container for all UI
elements (nodes) — the root of a scene graph.
 In this example, we use a StackPane as the root layout container. Layout containers
manage positioning of child UI nodes.
 We add a Button to the scene. We attach an event handler to respond to button clicks
(here, printing “Hello World!” to console). Shows how JavaFX handles user events —
e.g. mouse clicks.
 Finally, call [Link]() to display the stage (window).

Validation:

Stage → Scene → Root Node → UI Controls + Event Handlers.

 Layouts: How to use layout containers (HBox, VBox, FlowPane, GridPane, TilePane,
etc), nest them, arrange UI elements, build complex interfaces.
 Drawing Shapes, Graphics: Using shapes, drawing primitives, custom drawing —
good for graphics-rich or custom UIs.
 Coloring & Gradients: Styling shapes, backgrounds — managing visual design.
 Images / Media: Loading images, embedding media (audio/video), leveraging
JavaFX’s media support for richer applications.
 Effects & Transformations: Visual effects like blur, glow, shadows; transformations
like rotate, scale, translate — useful for animations / dynamic UIs.
 Animation: Support for animations — helpful for interactive or dynamic UI.
 Events & Event Handling: Handling user interactions — mouse events, keyboard
events, UI events.

KG College of Arts and Science Page 112


School of Computational Sciences Java Programming

 Custom Nodes / Subclassing: Creating custom UI components (subclassing existing


nodes), enabling reusability and encapsulation of complex UI components.
 Web Content / WebView Integration: Embedding web content inside JavaFX
applications (useful for hybrid apps).
 Styling with CSS: Using CSS files to style UI elements — makes UI look consistent
and easier to maintain.
 Packaging & Deployment: How to package and deploy JavaFX applications (as a
proper application rather than just run from IDE).
 Swing Interoperability: If needed, integrating JavaFX components into older Java
Swing applications — good for migrating or mixing UI toolkits.

Spring Boot
Spring Boot
Spring Boot is an opinionated framework built on top of the Spring Framework that
makes it easy to create stand-alone, production-grade Spring applications that you can
“just run.” It reduces boilerplate configuration by providing sensible defaults (auto-
configuration), starter dependency sets, and embedded servers (Tomcat/Jetty/Undertow)

Fundamentals of Spring Boot


 Spring Boot simplifies the development of Java applications by providing a
framework with built-in configurations.
 Spring Boot is a Java framework that makes it easier to create and run Java
applications.
 It simplifies the configuration and setup process, allowing developers to focus more
on writing code for their applications.
 Spring Boot is an open-source Java framework used to create a Micro Service. Spring
boot is developed by Pivotal Team, and it provides a faster way to set up and an
easier, configure, and run both simple and web-based applications. It is a combination
of Spring Framework and Embedded Servers. The main goal of Spring Boot is to
reduce development, unit test, and integration test time and in Spring Boot, there is no
requirement for XML configuration.

Design goals:

KG College of Arts and Science Page 113


School of Computational Sciences Java Programming

 Rapid application development (minimal configuration).


 Provide production-ready features (metrics, health checks, externalized
configuration).
 Make it easy to package apps as executable jars (fat jars) that include an embedded
server.

Spring vs Spring Boot

 Spring Framework: a comprehensive, modular programming model for Java (IoC


container, AOP, JDBC/JPA support, MVC, Security, etc.). Using plain Spring often
requires explicit configuration (XML or JavaConfig) and wiring of many modules.
 Spring Boot: sits on top of Spring. It automates configuration, provides starter
POMs/Gradle BOMs for common dependency sets, and includes embedded servlet
containers so you can run applications without deploying to an external app server.
Use Boot when you want quicker setup and faster prototyping or micro services.

Spring Spring Boot


Configuratio Explicit Auto-configuration
n
Deployment External container Embedded
Purpose Framework opinionated runtime + tooling for building

Spring Boot Architecture


Spring Boot is not a monolithic new framework — it leverages Spring modules and
provides opinionated layers:

1. Application layer (your code): controllers, services, repositories.


2. Spring Boot layer: @SpringBootApplication entry, auto-configuration classes,
starter dependencies.
3. Spring Framework layer: core IoC/DI, Spring MVC, Spring Data, Security, etc.
4. Third-party libraries & embedded server: Tomcat/Jetty/Undertow, Jackson,
Hibernate, etc.

KG College of Arts and Science Page 114


School of Computational Sciences Java Programming

Core architectural features:

 Auto-Configuration: Spring Boot inspects classpath and application properties, then


configures beans automatically (via @EnableAutoConfiguration /
@SpringBootApplication).

 Starters: curated dependency descriptors like spring-boot-starter-web, spring-


boot-starter-data-jpa that pull sensible libraries and versions.
 Embedded Server: package your app with an embedded servlet container; run as
java -jar [Link].

 Externalized Configuration: load properties from


[Link]/[Link], environment variables, command line
args.
 Actuator (optional): exposes production endpoints (health, metrics, info).

Develop a Spring Boot application — step by step

Prerequisites

 JDK (11+ recommended; check project requirements).


 Maven or Gradle.

KG College of Arts and Science Page 115


School of Computational Sciences Java Programming

 An IDE (IntelliJ, Eclipse, VS Code) — Spring tooling optional.

Step 1 — Initialize project (Spring Initializer)

 Use [Link] or the IDE's Spring Starter wizard. Choose:


o Project: Maven/Gradle
o Language: Java (or Kotlin/Groovy)
o Spring Boot version (choose a stable release)
o Dependencies: e.g., Spring Web for REST apps, Spring Data JPA for DB, H2
for in-memory DB, etc.
 Generate and unzip the project into your workspace.

Step 2 — Project structure (typical Spring Boot Maven layout)

src/
└─ main/
├─ java/
│ └─ [Link]/
│ ├─ [Link] // main @SpringBootApplication
│ ├─ controller/
│ ├─ service/
│ └─ repository/
└─ resources/
├─ [Link]
└─ static/, templates/
[Link] (or [Link])

Step 3 — Main class (entry point)

Create the main class with @SpringBootApplication:

package [Link];

import [Link];
import [Link];

@SpringBootApplication // combines @Configuration, @EnableAutoConfiguration,


@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}

KG College of Arts and Science Page 116


School of Computational Sciences Java Programming

Explanation: @SpringBootApplication triggers component scanning and auto-configuration.

Step 4 — Add a simple REST controller (example)

package [Link];
import [Link];
import [Link];

@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello from Spring Boot!";
}
}

Step 5 — Build and run

Using Maven (from project root):

 Run in dev: mvn spring-boot:run


 Package: mvn clean package → produces target/[Link]
 Run jar: java -jar target/[Link]

Using Gradle

 ./gradlew bootRun to run


 ./gradlew bootJar to create executable jar

When running, embedded server listens (default) on port 8080; visit


[Link]

Running & debugging Spring Boot applications

 Run in IDE: Run [Link]() as a Java application.


 Profiles: Use --[Link]=dev or set in [Link] to switch config.
 Logging: Spring Boot uses Logback by default; configure via [Link]
or logback config.

KG College of Arts and Science Page 117


School of Computational Sciences Java Programming

 Devtools: add spring-boot-devtools dependency for automatic restart and live reload
in development.

Debug mode: pass JVM debug options or run with spring-boot:run -Dspring-
[Link]="-
agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005".

Creating the first Spring Boot application — concise checklist

1. Go to [Link], choose dependencies (e.g., Spring Web).


2. Import into IDE.
3. Create @SpringBootApplication main class (auto-generated by Initializr usually).
4. Add controller/service/repository classes.
5. Configure [Link] (port, datasource, logging).
6. Run with mvn spring-boot:run (or bootRun) and test endpoints.

Useful Spring Boot features to mention

 Starters (spring-boot-starter-web, spring-boot-starter-data-jpa, etc.).


 Auto-configuration ([Link]/@Configuration classes driven by
@ConditionalOn*).
 Actuator: health, metrics, info endpoints (add spring-boot-starter-actuator).
 Externalized configuration: [Link]/[Link], environment
variables.
 Packaging: produces executable jars/war with embedded servlet container.

Short sample [Link] (example)


[Link]=8080
[Link]=demo-app
[Link]=jdbc:h2:mem:testdb
[Link]=[Link]
[Link]=sa
[Link]=
[Link]-auto=update

KG College of Arts and Science Page 118


School of Computational Sciences Java Programming

Jython

Jython

 Jython is an implementation of the Python programming language written in Java.


 It allows Python code to run on the Java Virtual Machine (JVM).
 Formerly known as JPython.
 Jython is fully compatible with Java, meaning:
o Python programs can import and use Java classes.
o Java programs can run embedded Jython code.
 Latest stable version (as of 2023): Jython 2.7.x (compatible with Python 2.7 syntax).

Introduction to Jython
Key Goals of Jython
 Combine Python’s simplicity with Java’s power.
 Enable scripting of Java applications using Python code.
 Provide seamless two-way integration:
 Python → Java classes
 Java → Python scripts
Features of Jython
a) Python Language Support

 Supports most Python 2.7 standard libraries.


 Dynamic typing, interpreted execution, interactive mode.

b) Direct Java Integration

 Python code can:


o Create Java objects
o Call Java methods
o Use Java interfaces and inherit Java classes

Example:

from [Link] import Date


d = Date()

KG College of Arts and Science Page 119


School of Computational Sciences Java Programming

print([Link]())

c) Runs on JVM

 Jython scripts compile into Java bytecode.


 Can be executed anywhere Java runs (Windows, Linux, macOS).

d) Compile to Bytecode or Run as Script

 Jython can generate .class files for deployment.

e) Embeddable

 Can be embedded inside Java applications similar to JavaScript or Groovy.

f) No explicit compilation

 Like Python, you write and run code instantly.


 Jython internally compiles to bytecode at runtime.

Jython Architecture

Jython bridges Python syntax and the Java runtime environment.

Architecture Components

1. Python Interpreter Engine


o Parses and interprets Python code.
2. Java Integration Layer
o Maps Python objects to Java objects.
o Converts types between Python and Java.
3. JVM Backend
o Executes compiled bytecode.
4. Standard Libraries
o Python standard library (except modules requiring C extensions).
o Java library access.

Installing Jython

Steps

KG College of Arts and Science Page 120


School of Computational Sciences Java Programming

1. Download installer from official site: [Link].


2. Run:
3. java -jar [Link]
4. Select:
o “Full installation”
o Destination folder
5. Add Jython to PATH:
6. export PATH=$PATH:/install/path/jython/bin

Basics of Jython

a) Syntax Similar to Python

 Variables, loops, functions follow Python 2.7 rules.


 Indentation-based blocks.

b) Using Java Packages

Jython uses Java packages exactly like Python modules.

Importing a Java package

from [Link] import System


[Link]("Hello from Java!")
Importing a Java class and using it
from [Link] import ArrayList
list = ArrayList()
[Link]("India")
[Link]("Python")
print(list)
Writing Jython Programs
Simple Jython Program

[Link]

print("Hello from Jython!")

Run:

KG College of Arts and Science Page 121


School of Computational Sciences Java Programming

jython [Link]

Using Java classes inside Jython

from [Link] import Robot


from [Link] import KeyEvent

robot = Robot()
[Link](KeyEvent.VK_A)
[Link](KeyEvent.VK_A)

Differences between Python and Jython

[Link] Feature Python (CPython) Jython


1. Interpreter C-based (CPython)
Java-based

2. Platform
Native runtime JVM

3. Speed Slower for general ops but


Faster for Python ops
faster for Java ops
4. Modules Supports all Python Cannot use C-based modules
modules like NumPy
5. Java
No Full Java integration
Integration
6.
Bytecode CPython bytecode Java bytecode

Jython Scripting in Java


Running a Jython script from Java
import [Link];

public class Test {


public static void main(String[] args) {
PythonInterpreter py = new PythonInterpreter();
[Link]("print 'Hello from Jython inside Java'");

KG College of Arts and Science Page 122


School of Computational Sciences Java Programming

}
}

Advantages of Jython

 Easy scripting for Java applications.


 Access to both Python and Java libraries.
 Great for:
o Testing Java apps
o Automation
o Scripting inside Java-based systems
 No need to recompile Java code.
 Highly portable (runs anywhere JVM runs).

Limitations of Jython

 Does not support Python 3 syntax.


 Many Python libraries written in C (NumPy, SciPy, Pandas) are not supported.
 Slightly slower than CPython in some operations.
 Development pace is slow.

Use Cases of Jython

Industry/Project Scenarios

 Scripting inside Java desktop apps (Swing, JavaFX).


 Automating Java servers.
 Writing plugins for Java applications.
 Using Python for JVM-based data analysis workflows.
 Teaching Python through Java infrastructure setups.

KG College of Arts and Science Page 123

You might also like