Java Lesson Notes 2025 Batch
Java Lesson Notes 2025 Batch
JAVA PROGRAMMING
Lesson Notes
Semester – II
Courses:
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
Problem
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
Course
Syllabus, Exam
Arts Science
Attributes Attributes
--------- ----------
---------- ---------
Polymorphism
Shape
Draw()
Dynamic Binding
Linking of a procedure call to the code to be executed in response to the call (run
time)
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
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
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
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 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.
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)
Operators
Separators (),{},[],period, comma, semicolon
Constants
Constants have fixed values that do not change during the execution of a program.
1. A whole number
2. A decimal point mantissa
3. A fractional part
4. An exponent
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
Arrays
Arrays are used to store multiple values of the same type in a single variable.
Declaration of Array in Java
type[] arrayName;
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];
Output
10 20 30 40
50 60 70 80
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; )
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;
Example
public class NestedIfElseExample {
public static void main(String[] args) {
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".
Example
public class SwitchStatementExample {
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
{ à 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
class Addition {
int sum = 0;
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
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 {
}
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.
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
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
Example
// Grandparent class
class Animal {
void eat() {
[Link]("Eating...");
}
// Parent class
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
// Child class
class Labrador extends Dog {
void run() {
[Link]("Running...");
}
}
Hierarchical Inheritance
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
[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
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
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
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.
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
{
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
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 provides five keywords that are used to handle exceptions. The following table
describes each:
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
}
finally block
try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling code
} finally {
// Cleanup code
}
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]());
}
}
}
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
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
Example
[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.
Example
// Define a class that implements Runnable
class Task implements Runnable {
private String taskName;
// 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
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
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
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
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
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
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.
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
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
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.
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.
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!
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
// Creating File
if ([Link]()) {
[Link]("File created: " + [Link]());
}
else {
[Link]("File already exists.");
}
}
// 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
// Writing File
[Link]("Files in Java are seriously good!!");
[Link]();
[Link]("Successfully written.");
}
// 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
[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
if ([Link]()) {
[Link]("The deleted file is : " + [Link]());
}
else {
[Link](
"Failed in deleting the file.");
}
}
}
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
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.
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
-----------------------------------------
|-----------------------------------------|
| |
| [ 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);
[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
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).
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():
// Create Frame
Frame f = new Frame("AWT Panel Example");
[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]);
[Link](l);
[Link](tf);
[Link](b);
---------------------------------------------
| AWT Panel Example |
| |
| ------------------------------ |
Containers in Swing
Swing follows a top-level container → intermediate container → atomic component
structure.
Types:
Modal (blocks other windows)
Non-modal
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.
4. JRadioButton
Used when only one option must be selected.
Multiple radio buttons must be grouped using ButtonGroup.
5. JLabel
Used to display text or images.
Non-editable.
6. JTextField
Single-line editable text box.
Common methods:
getText()
setText()
setEditable(true/false)
7. JTextArea
Multi-line text input area.
Supports line wrapping, scrolling.
Methods:
getSelectedItem()
addItem()
JScrollPane
Example:
JScrollPane sp = new JScrollPane(textArea);
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);
}
}
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());
│ │
└──────────────────────────────────────┘
JDialog Example
[Link](true);
}
}
Output
----------------------------------------------------
| Parent Frame |
----------------------------------------------------
| [ Show Dialog ] |
----------------------------------------------------
After Clicking the Button
---------------- Modal Dialog ----------------------
| Hello from JDialog! |
| |
| [ OK ] |
-----------------------------------------------------
JPanel Example
[Link](new BorderLayout());
[Link](panelTop, [Link]);
[Link](panelBottom, [Link]);
[Link](true);
}
}
Output
---------------------------------------------------------
| JPanel Example |
---------------------------------------------------------
| [ TOP PANEL - CYAN ] |
| Top Panel |
| |
| [ BOTTOM PANEL - LIGHT GRAY ] |
| Bottom Panel |
---------------------------------------------------------
[Link](new FlowLayout());
[Link](button);
[Link](true);
}
}
-------------------------------------------------
| JButton Example |
-------------------------------------------------
| [ Click Me ] |
-------------------------------------------------
After Clicking the Button
+-------------------------+
| Button Clicked! |
+-------------------------+
JToggleButton (button with toggle ON/OFF behavior) Example
import [Link].*;
import [Link].*;
import [Link].*;
[Link](toggle);
[Link](true);
}
}
Output
Initial Window
-------------------------------------------------
| JToggleButton Example |
-------------------------------------------------
| [ OFF ] |
-------------------------------------------------
-------------------------------------------------
| [ ON ] |
-------------------------------------------------
Back to OFF
-------------------------------------------------
| [ OFF ] |
-------------------------------------------------
JCheckBox (independent selection) Example
import [Link].*;
import [Link].*;
import [Link].*;
[Link](cb1);
[Link](cb2);
[Link](btn);
[Link](true);
}
}
Output
Main Window
----------------------------------------------
| JCheckBox Example |
----------------------------------------------
| [ ] Option 1 [ ] Option 2 |
| |
| [ Show Selection ] |
----------------------------------------------
[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
[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 |
----------------------------------------
[Link](true);
}
}
Output
-----------------------------------------------------
| Enter something: [___________TextField__________] |
| Show Text |
-----------------------------------------------------
JTextArea (multi-line text input area) Example
import [Link].*;
import [Link].*;
[Link](scrollPane);
[Link](true);
}
}
Output
|--------------------------------------------------|
| This is a text area where you can type multiple |
| lines of text. |
| |
| (Scrollbars appear when content exceeds size) |
|--------------------------------------------------|
[Link](new BorderLayout());
[Link](new JScrollPane(list), [Link]);
[Link](btn, [Link]);
[Link](true);
}
}
Output
--------------------------
| Red |
| Green |
| Blue |
| Yellow |
| Black |
--------------------------
JComboBox (drop-down list / combo box) Example
import [Link].*;
import [Link].*;
import [Link].*;
[Link](btn);
[Link](true);
}
}
Output
JScrollPane (scrollbars for components like text area, list, panel) Example
[Link](scrollPane);
[Link](true);
}
----------------------------------------------
| 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)
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.
Example:
Flow of EDM
Example Program:
import [Link].*;
import [Link].*;
import [Link].*;
[Link](new ActionListener() {
[Link]("Button Clicked!");
});
[Link](new FlowLayout());
[Link](button);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
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.
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);
x = [Link]();
y = [Link]();
repaint();
}
Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class KeyEventExample extends JFrame implements KeyListener {
JLabel label;
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.
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
---------------------------------------------
| 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 {
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
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
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.
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).
Styling with CSS: Apply Cascading Style Sheets for easy customization, making UIs look
like web pages.
Cross-Platform: Write once, run anywhere on desktops, mobile, and embedded systems.
Integration: Easily use any existing Java library within JavaFX applications.
Scene: The container for all graphical content (nodes) within a Stage.
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.
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];
[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:
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.
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)
Design goals:
Prerequisites
src/
└─ main/
├─ java/
│ └─ [Link]/
│ ├─ [Link] // main @SpringBootApplication
│ ├─ controller/
│ ├─ service/
│ └─ repository/
└─ resources/
├─ [Link]
└─ static/, templates/
[Link] (or [Link])
package [Link];
import [Link];
import [Link];
package [Link];
import [Link];
import [Link];
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello from Spring Boot!";
}
}
Using Gradle
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".
Jython
Jython
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
Example:
print([Link]())
c) Runs on JVM
e) Embeddable
f) No explicit compilation
Jython Architecture
Architecture Components
Installing Jython
Steps
Basics of Jython
[Link]
Run:
jython [Link]
robot = Robot()
[Link](KeyEvent.VK_A)
[Link](KeyEvent.VK_A)
2. Platform
Native runtime JVM
}
}
Advantages of Jython
Limitations of Jython
Industry/Project Scenarios