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

JavaFX Application Structure

Best best

Uploaded by

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

JavaFX Application Structure

Best best

Uploaded by

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

JavaFX Application Structure

Designing GUI Applications using JavaFx: Basic structure of JavaFx


application

Fast answer

Basic Structure of a JavaFX Application


JavaFX is used to create Graphical User Interface (GUI) applications in Java.
Every JavaFX application follows a basic structure consisting of:

1. Importing JavaFX packages

2. Extending the Application class

3. Overriding the start() method

4. Creating a Stage and Scene

5. Adding GUI components (controls/layouts)

6. Launching the application

Basic JavaFX Program

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

public class HelloJavaFX extends Application {

@Override
public void start(Stage primaryStage) {

// Create a label
Label label = new Label("Welcome to JavaFX");

// Create layout pane


StackPane root = new StackPane();
[Link]().add(label);

// Create scene
Scene scene = new Scene(root, 400, 300);

// Set stage title


[Link]("JavaFX Application");

// Add scene to stage


[Link](scene);

// Display the stage


[Link]();
}

// Main method

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/63
public static void main(String[] args) {
launch(args);
}
}

Explanation of Components

1. Import Statements

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

These import the required JavaFX classes.

Application → Base class for JavaFX applications

Stage → Main window


Scene → Container for GUI elements

2. Extending the Application Class

Java
public class HelloJavaFX extends Application

Every JavaFX program must extend the Application class.

3. The start() Method

Java
public void start(Stage primaryStage)

This is the entry point of a JavaFX GUI application.

primaryStage represents the main window.

4. Stage

Java
[Link]("JavaFX Application");

A Stage is the top-level container (window).

Functions:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/63
Set title

Set scene

Show window

5. Scene

Java
Scene scene = new Scene(root, 400, 300);

A Scene contains all GUI components.

Width = 400

Height = 300

6. Layout Pane

Java
StackPane root = new StackPane();

Layout panes organize controls in the window.

Common layouts:

StackPane

VBox

HBox

GridPane

BorderPane

7. Controls

Java
Label label = new Label("Welcome to JavaFX");

Controls are GUI elements such as:

Label
Button

TextField
CheckBox

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/63
RadioButton

8. Showing the Window

Java
[Link]();

Displays the GUI window.

JavaFX Application Life Cycle


The life cycle includes three main methods:

1. init() → Initializes the application

2. start() → Starts the GUI


3. stop() → Terminates the application

Structure Diagram
Application
|
|--> Stage (Window)
|
|--> Scene
|
|--> Layout Pane
|
|--> Controls

Advantages of JavaFX
Rich GUI controls
CSS styling support
Animation and multimedia support

Cross-platform compatibility
Modern UI design

Summary
A JavaFX application mainly contains:

Component Purpose

Application Class Base class


Stage Main window

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/63
Component Purpose

Scene Holds GUI content


Layout Pane Arranges controls
Controls GUI elements
launch() Starts application

Layout Panes

Layout Panes in JavaFX


Layout panes in JavaFX are used to arrange GUI components (controls) inside a window in a proper
way.
Examples of controls:

Button
Label
TextField

CheckBox

Instead of placing components manually, layout panes automatically manage their positions.

Common Layout Panes in JavaFX


Layout Pane Purpose

VBox Arranges components vertically


HBox Arranges components horizontally
BorderPane Arranges components in top, bottom, left, right, center
GridPane Arranges components in rows and columns
StackPane Places components on top of each other

FlowPane Arranges components in flow style


AnchorPane Anchors components to edges

1. VBox (Vertical Box)


VBox arranges controls in vertical order.

Example

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/63
Java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class VBoxExample extends Application {

@Override
public void start(Stage stage) {

Button b1 = new Button("Button 1");


Button b2 = new Button("Button 2");
Button b3 = new Button("Button 3");

VBox root = new VBox(10);

[Link]().addAll(b1, b2, b3);

Scene scene = new Scene(root, 300, 200);

[Link]("VBox Example");
[Link](scene);
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Output Arrangement
Button 1
Button 2
Button 3

2. HBox (Horizontal Box)


HBox arranges controls horizontally.

Example

Java
HBox root = new HBox(10);

[Link]().addAll(b1, b2, b3);

Output Arrangement
Button1 Button2 Button3

3. BorderPane

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/63
BorderPane divides the window into 5 regions:

Top
Bottom

Left

Right
Center

Example

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

public class BorderPaneExample extends Application {

@Override
public void start(Stage stage) {

BorderPane root = new BorderPane();

[Link](new Button("Top"));
[Link](new Button("Bottom"));
[Link](new Button("Left"));
[Link](new Button("Right"));
[Link](new Button("Center"));

Scene scene = new Scene(root, 400, 300);

[Link](scene);
[Link]("BorderPane Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Structure
Top
Left Center Right
Bottom

4. GridPane
GridPane arranges controls in rows and columns like a table.

Example

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/63
Java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class GridPaneExample extends Application {

@Override
public void start(Stage stage) {

GridPane grid = new GridPane();

[Link](10);
[Link](10);

[Link](new Label("Name:"), 0, 0);


[Link](new TextField(), 1, 0);

[Link](new Label("Password:"), 0, 1);


[Link](new TextField(), 1, 1);

Scene scene = new Scene(grid, 300, 200);

[Link](scene);
[Link]("GridPane Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Structure
Name: [TextField]
Password: [TextField]

5. StackPane
StackPane places components on top of each other.

Example

Java
StackPane root = new StackPane();

[Link]().addAll(
new Button("Button"),
new Label("Label")
);

The controls overlap one another.

6. FlowPane
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/63
FlowPane arranges components like text flow.

If space is not available, controls move to the next line.

Example

Java
FlowPane root = new FlowPane();

[Link]().addAll(
new Button("One"),
new Button("Two"),
new Button("Three")
);

7. AnchorPane
AnchorPane anchors controls to window edges.

Example

Java
Button btn = new Button("Submit");

AnchorPane root = new AnchorPane();

[Link](btn, 20.0);
[Link](btn, 30.0);

[Link]().add(btn);

Advantages of Layout Panes


Automatic arrangement of controls

Easy GUI design

Responsive interface
Better screen management

Reduces manual coding

Comparison of Layout Panes


Layout Arrangement

VBox Vertical

HBox Horizontal
BorderPane Five regions

GridPane Rows and columns


StackPane Overlapping

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/63
Layout Arrangement

FlowPane Flow style


AnchorPane Fixed anchors

Conclusion
Layout panes are very important in JavaFX because they help organize GUI components properly.
Different layout panes are used for different types of user interfaces.

UI Components

UI Components in JavaFX
UI Components are the graphical elements used to interact with the user in a JavaFX application.

They are also called Controls.

Examples:

Button
Label

TextField

CheckBox
RadioButton

JavaFX provides many built-in UI components for designing GUI applications.

Common UI Components in JavaFX


Component Purpose
Label Displays text

Button Performs an action when clicked


TextField Accepts single-line input

PasswordField Accepts hidden password

TextArea Accepts multi-line text


CheckBox Selects multiple options

RadioButton Selects one option from many


ComboBox Drop-down list

ListView Displays list items

TableView Displays tabular data


MenuBar Creates menus

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/63
Component Purpose

ImageView Displays images

1. Label
A Label is used to display text.

Example

Java
Label label = new Label("Welcome to JavaFX");

Complete Program

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

public class LabelExample extends Application {

@Override
public void start(Stage stage) {

Label label = new Label("Hello JavaFX");

StackPane root = new StackPane(label);

Scene scene = new Scene(root, 300, 200);

[Link](scene);
[Link]("Label Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

2. Button
A Button performs an action when clicked.

Example

Java
Button btn = new Button("Click Me");

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/63
Button with Event

Java
[Link](e -> {
[Link]("Button Clicked");
});

3. TextField
A TextField accepts single-line input.

Example

Java
TextField tf = new TextField();

Get Text

Java
String name = [Link]();

4. PasswordField
A PasswordField hides typed characters.

Example

Java
PasswordField pf = new PasswordField();

5. TextArea
A TextArea accepts multi-line text.

Example

Java
TextArea ta = new TextArea();

Used for:

Comments
Notes

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/63
Messages

6. CheckBox
A CheckBox allows multiple selections.

Example

Java
CheckBox c1 = new CheckBox("Java");
CheckBox c2 = new CheckBox("Python");

User can select both options.

7. RadioButton
A RadioButton allows only one selection from a group.

Example

Java
RadioButton r1 = new RadioButton("Male");
RadioButton r2 = new RadioButton("Female");

ToggleGroup tg = new ToggleGroup();

[Link](tg);
[Link](tg);

8. ComboBox
A ComboBox provides a drop-down list.

Example

Java
ComboBox<String> cb = new ComboBox<>();

[Link]().addAll("Java", "Python", "C++");

9. ListView
A ListView displays a list of items.

Example
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/63
Java
ListView<String> list = new ListView<>();

[Link]().addAll("Apple", "Banana", "Mango");

10. TableView
A TableView displays data in table form.

Example

Java
TableView table = new TableView();

Used for:

Student records
Employee data
Database display

11. MenuBar
A MenuBar creates menus in applications.

Example

Java
MenuBar mb = new MenuBar();

Menu file = new Menu("File");

MenuItem open = new MenuItem("Open");

[Link]().add(open);

[Link]().add(file);

12. ImageView
ImageView displays images.

Example

Java
Image img = new Image("file:[Link]");

ImageView iv = new ImageView(img);

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/63
Example Program Using Multiple Components

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

public class UIComponentsDemo extends Application {

@Override
public void start(Stage stage) {

Label label = new Label("Enter Name");

TextField tf = new TextField();

Button btn = new Button("Submit");

[Link](e -> {
[Link]("Hello " + [Link]());
});

VBox root = new VBox(10);

[Link]().addAll(label, tf, btn);

Scene scene = new Scene(root, 300, 200);

[Link]("UI Components");

[Link](scene);

[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Advantages of JavaFX UI Components


Easy to use
Rich GUI design
Event handling support

Modern appearance
Cross-platform support

Conclusion
UI components are the main building blocks of JavaFX GUI applications. They help users interact with the
application through buttons, text fields, menus, lists, and other controls.

Color and Font classes

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/63
Color and Font Classes in JavaFX
JavaFX provides Color and Font classes to improve the appearance of GUI applications.

Color class → Used to set colors


Font class → Used to set font style, size, and family

These classes are available in the [Link] and [Link] packages.

1. Color Class in JavaFX


The Color class is used to apply colors to:

Text

Background
Shapes
Buttons

Labels

Import Statement

Java
import [Link];

Common Predefined Colors


JavaFX provides many predefined colors.
Examples:

Java
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

Example: Setting Text Color

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

public class ColorExample extends Application {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/63
@Override
public void start(Stage stage) {

Label label = new Label("Welcome to JavaFX");

// Set text color


[Link]([Link]);

StackPane root = new StackPane(label);

Scene scene = new Scene(root, 300, 200);

[Link](scene);
[Link]("Color Example");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Creating Custom Colors


Custom colors can be created using RGB values.

Syntax

Java
[Link](red, green, blue)

Values range from 0 to 255.

Example

Java
[Link]([Link](255, 0, 0));

This creates red color.

Setting Background Color

Java
[Link]("-fx-background-color: lightblue;");

2. Font Class in JavaFX


The Font class is used to change:

Font family
Font size

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/63
Font style

Import Statement

Java
import [Link];
import [Link];

Creating Font

Syntax

Java
[Link]("Arial", 20)

"Arial" → Font family


20 → Font size

Example: Setting Font

Java
Label label = new Label("JavaFX Font");

[Link]([Link]("Arial", 25));

Font Styles
JavaFX supports:

Bold
Italic
Regular

Example: Bold Font

Java
[Link]([Link]("Verdana", [Link], 20));

Complete Example of Color and Font

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

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/63
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class FontColorDemo extends Application {

@Override
public void start(Stage stage) {

Label label = new Label("JavaFX Demo");

// Set text color


[Link]([Link]);

// Set font
[Link]([Link]("Arial", [Link], 30));

StackPane root = new StackPane(label);

[Link]("-fx-background-color: lightyellow;");

Scene scene = new Scene(root, 400, 250);

[Link]("Color and Font Demo");

[Link](scene);

[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Output Features
The program displays:

Green colored text


Bold Arial font

Font size 30
Light yellow background

Advantages of Color and Font Classes


Feature Benefit
Color Class Makes GUI attractive

Font Class Improves readability


Different Styles Better user interface
Customization Professional design

Important Methods
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/63
Color Methods
Method Purpose

[Link] Predefined color


[Link]() Custom RGB color

Font Methods
Method Purpose
[Link]() Creates font
setFont() Applies font

setTextFill() Sets text color

Conclusion
The Color and Font classes are important in JavaFX for designing attractive GUI applications. They help
improve the appearance, readability, and user experience of the application.

Event
Handling

Event Handling in JavaFX


Event Handling is the process of responding to user actions in a JavaFX application.
Examples of events:

Button click

Mouse click
Keyboard press
Mouse movement

JavaFX uses Event Handler objects to handle these events.

Need of Event Handling


Event handling is used to:

Perform actions when user clicks a button

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/63
Read user input
Control GUI behavior

Make applications interactive

Event Handling Process


User Action → Event Generated → Event Handler Executes

Example:

Button Click → ActionEvent → Code Executes

Important Classes for Event Handling


Class / Interface Purpose
Event Base event class

ActionEvent Handles button actions


EventHandler Interface for handling events

Syntax of Event Handling

Java
[Link](e -> {
// Code to execute
});

setOnAction() → Registers event handler

e → Event object

Example 1: Button Click Event

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

public class EventExample extends Application {

@Override
public void start(Stage stage) {

Button btn = new Button("Click Me");

// Event Handling
[Link](e -> {
[Link]("Button Clicked");

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/63
});

StackPane root = new StackPane(btn);

Scene scene = new Scene(root, 300, 200);

[Link](scene);
[Link]("Event Handling");
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Working of Above Program


1. User clicks button

2. ActionEvent is generated
3. Event handler executes
4. Message prints on console

Example 2: Change Label Text on Button Click

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

public class LabelEventDemo extends Application {

@Override
public void start(Stage stage) {

Label label = new Label("Welcome");

Button btn = new Button("Change Text");

[Link](e -> {
[Link]("Button Clicked");
});

VBox root = new VBox(10);

[Link]().addAll(label, btn);

Scene scene = new Scene(root, 300, 200);

[Link](scene);

[Link]("Event Demo");

[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/63
Mouse Events
Mouse events occur when user interacts using mouse.
Examples:

Mouse click
Mouse move

Mouse enter

Example: Mouse Click Event

Java
[Link](e -> {
[Link]("Mouse Clicked");
});

Keyboard Events
Keyboard events occur when user presses keys.
Examples:

Key pressed

Key released

Example: Key Event

Java
[Link](e -> {
[Link]("Key Pressed");
});

Types of Event Handling Methods


Method Purpose
setOnAction() Handles button action
setOnMouseClicked() Handles mouse click
setOnKeyPressed() Handles key press

setOnMouseEntered() Mouse enters component

Event Handler Using Separate Class


Instead of lambda expression, separate class can also be used.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/63
Example

Java
import [Link];
import [Link];

class MyHandler implements EventHandler<ActionEvent> {

@Override
public void handle(ActionEvent e) {
[Link]("Button Clicked");
}
}

Use:

Java
[Link](new MyHandler());

Advantages of Event Handling


Makes GUI interactive
Improves user experience
Responds to user actions
Supports dynamic applications

Event Handling Flow Diagram


User Action

Event Generated

Event Handler

Code Executes

Important Points
Events are generated by user actions.
Event handlers contain code to respond to events.
setOnAction() is commonly used for buttons.
Lambda expressions make code shorter and easier.

Conclusion
Event handling is one of the most important features of JavaFX. It allows GUI applications to respond to
user actions like button clicks, mouse events, and keyboard events, making the application interactive
and user-friendly.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/63
I/O Management and Generics:, File class, Writing, reading and Random
Access files, Purpose of Generics, Defining Generic classes and methods,
Generics with Collections like ArrayList, HashMap, etc

Dilip Sir, here is the simple GTU-style detailed answer.

I/O Management and Generics in Java

1. I/O Management in Java


I/O means Input and Output.
In Java, I/O is used to:

Take input from file

Write output into file


Read data from file
Store data permanently

Java provides many classes for file handling in:

Java
[Link] package

2. File Class
File class is used to represent a file or folder path.
It does not read or write data directly.
It is used to create, delete, check, and get information about files.

Import Statement

Java
import [Link];

Example

Java
import [Link];

public class FileDemo {


public static void main(String[] args) {

File f = new File("[Link]");

[Link]("File name: " + [Link]());

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/63
[Link]("Path: " + [Link]());
[Link]("Exists: " + [Link]());
[Link]("Can read: " + [Link]());
[Link]("Can write: " + [Link]());
}
}

Common Methods of File Class


Method Use
exists() Checks file exists or not
createNewFile() Creates new file
delete() Deletes file
getName() Returns file name
getPath() Returns file path
length() Returns file size

canRead() Checks readable or not


canWrite() Checks writable or not

3. Writing Data into File


To write data into file, Java provides FileWriter.

Example

Java
import [Link];
import [Link];

public class WriteFileDemo {


public static void main(String[] args) {

try {
FileWriter fw = new FileWriter("[Link]");

[Link]("Name: Dilip\n");
[Link]("Subject: OOP in Java\n");

[Link]();

[Link]("Data written successfully.");


}
catch (IOException e) {
[Link]("File writing error.");
}
}
}

Explanation

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/63
FileWriter opens file for writing.
write() writes data into file.
close() closes the file.
try-catch handles file errors.

4. Reading Data from File


To read data from file, Java provides FileReader.

Example

Java
import [Link];
import [Link];

public class ReadFileDemo {


public static void main(String[] args) {

try {
FileReader fr = new FileReader("[Link]");

int ch;

while ((ch = [Link]()) != -1) {


[Link]((char) ch);
}

[Link]();
}
catch (IOException e) {
[Link]("File reading error.");
}
}
}

Explanation
FileReader opens file for reading.
read() reads one character at a time.
-1 means end of file.
close() closes the file.

5. Random Access File


RandomAccessFile is used to read and write data at any position in a file.
It can move file pointer using seek() method.

Import Statement
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/63
Java
import [Link];

Modes
Mode Meaning

"r" Read only


"rw" Read and write

Example

Java
import [Link];

public class RandomAccessDemo {


public static void main(String[] args) {

try {
RandomAccessFile raf = new RandomAccessFile("[Link]", "rw");

[Link]("Hello Java");

[Link](0);

String data = [Link]();

[Link](data);

[Link]();
}
catch (Exception e) {
[Link]("Error occurred.");
}
}
}

Important Methods
Method Use
seek(position) Moves file pointer
read() Reads data
write() Writes data

readUTF() Reads string


writeUTF() Writes string
length() Gives file size

6. Generics in Java
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/63
Generics allow us to write code that can work with any data type.
It provides type safety.

Without Generics

Java
ArrayList list = new ArrayList();

[Link]("Java");
[Link](10);

Here different types of data can be added, so error may occur.

With Generics

Java
ArrayList<String> list = new ArrayList<String>();

[Link]("Java");
[Link]("Python");

Now only String data can be added.

7. Purpose of Generics
Generics are used to:

Provide type safety


Avoid type casting
Reduce runtime errors

Make code reusable


Work with different data types

8. Generic Class
A generic class can work with different data types.

Syntax

Java
class ClassName<T> {
T variable;
}

Here, T is a type parameter.


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/63
Example

Java
class Box<T> {

T value;

void setValue(T value) {


[Link] = value;
}

T getValue() {
return value;
}
}

public class GenericClassDemo {


public static void main(String[] args) {

Box<Integer> b1 = new Box<Integer>();


[Link](100);
[Link]([Link]());

Box<String> b2 = new Box<String>();


[Link]("Java");
[Link]([Link]());
}
}

9. Generic Method
A generic method can accept any type of data.

Syntax

Java
<T> void methodName(T value) {
// code
}

Example

Java
public class GenericMethodDemo {

public static <T> void display(T value) {


[Link](value);
}

public static void main(String[] args) {

display(10);
display("Java");
display(25.5);
}
}

10. Generics with ArrayList


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 30/63
ArrayList is used to store dynamic data.

Example

Java
import [Link];

public class ArrayListGenericDemo {


public static void main(String[] args) {

ArrayList<String> names = new ArrayList<String>();

[Link]("Dilip");
[Link]("Rahul");
[Link]("Amit");

for (String name : names) {


[Link](name);
}
}
}

Benefit
Only String values can be stored in this list.

11. Generics with HashMap


HashMap stores data in key-value pair.

Example

Java
import [Link];

public class HashMapGenericDemo {


public static void main(String[] args) {

HashMap<Integer, String> students = new HashMap<Integer, String>();

[Link](1, "Dilip");
[Link](2, "Rahul");
[Link](3, "Amit");

[Link]([Link](1));
}
}

Explanation
Integer is key type.
String is value type.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 31/63
put() adds data.
get() gets data.

Conclusion
I/O management is used to read and write data in files. Java provides classes like File, FileReader,
FileWriter,and RandomAccessFile. Generics are used to make Java programs type-safe, reusable, and
easy to maintain. Generics are commonly used with collections like ArrayList and HashMap.

Data types (byte, short, int,


long, float, double, char, boolean, String, Arrays), variables, keywords, literal,
operators, operator precedence and associativity, type conversion

Java Data Types, Variables, Keywords, Literals, Operators and


Type Conversion

1. Data Types in Java


Data type specifies:

What type of value variable can store


Memory size
Range of values

Java data types are divided into:

1. Primitive Data Types


2. Non-Primitive Data Types

Primitive Data Types


Data Type Size Example
byte 1 byte 10
short 2 bytes 200

int 4 bytes 5000


long 8 bytes 100000L
float 4 bytes 12.5f
double 8 bytes 25.75
char 2 bytes 'A'
boolean 1 bit true

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 32/63
1. byte
byte stores small integer values.

Example

Java
byte b = 100;
[Link](b);

Range:

-128 to 127

2. short
short stores larger integer values than byte.

Example

Java
short s = 2000;
[Link](s);

3. int
int is most commonly used integer type.

Example

Java
int num = 50000;
[Link](num);

4. long
long stores very large integer values.

Example

Java
long mobile = 9876543210L;
[Link](mobile);

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 33/63
L is written at end.

5. float
float stores decimal numbers.

Example

Java
float marks = 85.5f;
[Link](marks);

f is required.

6. double
double stores large decimal values.

Example

Java
double pi = 3.14159;
[Link](pi);

7. char
char stores single character.

Example

Java
char grade = 'A';
[Link](grade);

Character must be inside single quotes.

8. boolean
boolean stores only:

true
false

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 34/63
Example

Java
boolean result = true;
[Link](result);

9. String
String stores group of characters.
It is a non-primitive data type.

Example

Java
String name = "Dilip";
[Link](name);

String uses double quotes.

10. Arrays
Array stores multiple values of same type.

Example

Java
int arr[] = {10, 20, 30, 40};

[Link](arr[0]);

Output:

10

2. Variables in Java
Variable is a named memory location used to store data.

Syntax

Java
datatype variableName = value;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 35/63
Example

Java
int age = 20;

Types of Variables
Variable Type Description
Local Variable Declared inside method
Instance Variable Declared inside class
Static Variable Shared by all objects

Example

Java
class Student {

int roll = 10; // instance variable

static String college = "GTU"; // static variable

void display() {

int marks = 90; // local variable

[Link](roll);
[Link](college);
[Link](marks);
}
}

3. Keywords in Java
Keywords are reserved words with special meaning.
Keywords cannot be used as variable names.

Common Keywords
Keyword Use
class Declares class
int Integer type
if Conditional statement
for Loop
public Access modifier
static Common memory

void No return value

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 36/63
Keyword Use
return Returns value
new Creates object

Example

Java
public class Demo {
}

Here:

public

class

are keywords.

4. Literals in Java
Literal is a fixed value written directly in program.

Types of Literals
Literal Type Example
Integer Literal 10
Floating Literal 12.5

Character Literal 'A'


String Literal "Java"
Boolean Literal true

Example

Java
int x = 10;

char ch = 'A';

String s = "Java";

Here:

10

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 37/63
'A'

"Java"

are literals.

5. Operators in Java
Operators perform operations on data.

Types of Operators
Operator Type Example

Arithmetic +-*/%
Relational > < == !=
Logical && || !
Assignment = += -=
Unary ++ --
Bitwise &|^
Ternary ?:

Arithmetic Operators
Operator Meaning
+ Addition

- Subtraction
* Multiplication
/ Division
% Modulus

Example

Java
int a = 10;
int b = 3;

[Link](a + b);
[Link](a % b);

Relational Operators

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 38/63
Used for comparison.

Operator Meaning
> Greater than
< Less than
== Equal

!= Not equal

Logical Operators
Operator Meaning

&& AND
|| OR
! NOT

Unary Operators
Operator Meaning
++ Increment
-- Decrement

6. Operator Precedence
Operator precedence decides which operator executes first.

Example

Java
int x = 5 + 3 * 2;

First multiplication occurs:

5 + 6 = 11

Output:

11

Common Precedence Order


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 39/63
Priority Operators
Highest ()
Next ++ --
Next */%
Next +-

Lowest =

7. Associativity
Associativity decides evaluation direction when operators have same precedence.

Associativity Direction
Left to Right +-*/
Right to Left =

Example

Java
int x = 10 - 5 + 2;

Left to right:

10 - 5 = 5
5 + 2 = 7

Output:

8. Type Conversion
Type conversion changes one data type into another.
Two types:

1. Implicit Conversion
2. Explicit Conversion

1. Implicit Conversion (Widening)


Smaller type converts automatically into larger type.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 40/63
Example

Java
int x = 10;

double y = x;

[Link](y);

Output:

10.0

2. Explicit Conversion (Casting)


Larger type converts into smaller type manually.

Example

Java
double d = 25.75;

int x = (int)d;

[Link](x);

Output:

25

Decimal part is removed.

Type Conversion Diagram


byte → short → int → long → float → double

Conclusion
Java provides different data types to store various kinds of data. Variables are used to store values in
memory. Operators perform calculations and comparisons. Operator precedence and associativity
control expression evaluation. Type conversion allows conversion between different data types.

Conditional and looping statements: simple if, if-else statement, else-if ladder,
switch-case statement, for loop, while loop, do-while loop, Enhanced for Loop
(for-each loop), break, continue, labelled break, labelled continue

Conditional and Looping Statements in Java


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 41/63
Conditional and looping statements control the flow of program execution.
They help to:

Make decisions
Repeat statements

Control loops

1. Conditional Statements
Conditional statements are used to execute code based on conditions.
Types:

1. simple if
2. if-else
3. else-if ladder
4. switch-case

1. Simple if Statement
if statement executes code only when condition is true.

Syntax

Java
if(condition) {
// code
}

Example

Java
public class IfDemo {
public static void main(String[] args) {

int age = 20;

if(age >= 18) {


[Link]("Eligible for voting");
}
}
}

Output

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 42/63
Eligible for voting

2. if-else Statement
if-else executes one block if condition is true and another block if false.

Syntax

Java
if(condition) {
// true block
}
else {
// false block
}

Example

Java
public class IfElseDemo {
public static void main(String[] args) {

int num = 5;

if(num % 2 == 0) {
[Link]("Even Number");
}
else {
[Link]("Odd Number");
}
}
}

Output
Odd Number

3. else-if Ladder
Used when multiple conditions are checked.

Syntax

Java
if(condition1) {

}
else if(condition2) {

}
else {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 43/63
}

Example

Java
public class ElseIfDemo {
public static void main(String[] args) {

int marks = 75;

if(marks >= 90) {


[Link]("Grade A");
}
else if(marks >= 70) {
[Link]("Grade B");
}
else if(marks >= 50) {
[Link]("Grade C");
}
else {
[Link]("Fail");
}
}
}

Output
Grade B

4. switch-case Statement
switch is used to select one option from many choices.

Syntax

Java
switch(expression) {

case value:
// code
break;

default:
// code
}

Example

Java
public class SwitchDemo {
public static void main(String[] args) {

int day = 2;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 44/63
switch(day) {

case 1:
[Link]("Monday");
break;

case 2:
[Link]("Tuesday");
break;

case 3:
[Link]("Wednesday");
break;

default:
[Link]("Invalid Day");
}
}
}

Output
Tuesday

Importance of break in switch


break stops execution after matching case.
Without break, execution continues to next cases.

2. Looping Statements
Loops are used to repeat code multiple times.
Types:

1. for loop
2. while loop

3. do-while loop
4. Enhanced for loop

1. for Loop
for loop is used when number of repetitions is known.

Syntax

Java
for(initialization; condition; increment/decrement) {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 45/63
// code
}

Example

Java
public class ForDemo {
public static void main(String[] args) {

for(int i = 1; i <= 5; i++) {


[Link](i);
}
}
}

Output
1
2
3
4
5

2. while Loop
while loop checks condition first.

Syntax

Java
while(condition) {

// code
}

Example

Java
public class WhileDemo {
public static void main(String[] args) {

int i = 1;

while(i <= 5) {
[Link](i);
i++;
}
}
}

3. do-while Loop

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 46/63
do-while executes at least one time.

Syntax

Java
do {

// code

} while(condition);

Example

Java
public class DoWhileDemo {
public static void main(String[] args) {

int i = 1;

do {
[Link](i);
i++;
} while(i <= 5);
}
}

Difference Between while and do-while


while do-while
Condition checked first Condition checked last
May execute zero times Executes at least one time

4. Enhanced for Loop (for-each Loop)


Used to traverse arrays and collections easily.

Syntax

Java
for(datatype variable : array) {

// code
}

Example

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 47/63
Java
public class ForEachDemo {
public static void main(String[] args) {

int arr[] = {10, 20, 30, 40};

for(int x : arr) {
[Link](x);
}
}
}

Output
10
20
30
40

3. break Statement
break immediately terminates loop or switch.

Example

Java
for(int i = 1; i <= 10; i++) {

if(i == 5) {
break;
}

[Link](i);
}

Output
1
2
3
4

4. continue Statement
continue skips current iteration and moves to next iteration.

Example

Java
for(int i = 1; i <= 5; i++) {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 48/63
if(i == 3) {
continue;
}

[Link](i);
}

Output
1
2
4
5

5. Labelled break
Used to terminate outer loop from inner loop.

Example

Java
public class LabelBreakDemo {
public static void main(String[] args) {

outer:

for(int i = 1; i <= 3; i++) {

for(int j = 1; j <= 3; j++) {

if(i == 2 && j == 2) {
break outer;
}

[Link](i + " " + j);


}
}
}
}

6. Labelled continue
Used to skip iteration of outer loop.

Example

Java
public class LabelContinueDemo {
public static void main(String[] args) {

outer:

for(int i = 1; i <= 3; i++) {

for(int j = 1; j <= 3; j++) {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 49/63
if(j == 2) {
continue outer;
}

[Link](i + " " + j);


}
}
}
}

Comparison of Loops
Loop Condition Check Minimum Execution
for Beginning 0
while Beginning 0
do-while End 1

Conclusion
Conditional statements are used for decision making, while looping statements are used for repeating
code execution. Java provides different control statements like if, switch, for, while, do-while, break, and
continue to control program flow effectively.

Basics of Object Oriented Programming: Data Encapsulation by defining


classes, data members, member functions, Data Abstraction, access specifiers,
static data member and static member function, defining constructors, objects and
references, this keyword, returning and passing objects, array of objects, static
block, instance block, inner class
Show moreShow less

Basics of Object Oriented Programming (OOP) in Java


Object Oriented Programming (OOP) is a programming method based on:

Objects
Classes
Data security
Reusability

Java is a pure object-oriented programming language.

Main Features of OOP


1. Class

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 50/63
2. Object
3. Encapsulation
4. Abstraction
5. Inheritance
6. Polymorphism

1. Class
A class is a blueprint or template used to create objects.
It contains:

Data members (variables)


Member functions (methods)

Syntax

Java
class ClassName {

// data members

// methods
}

Example

Java
class Student {

int rollNo;
String name;

void display() {
[Link](rollNo + " " + name);
}
}

2. Object
Object is an instance of class.
It occupies memory and can access class members.

Syntax

Java

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 51/63
ClassName objectName = new ClassName();

Example

Java
Student s1 = new Student();

[Link] = 101;
[Link] = "Dilip";

[Link]();

3. Data Encapsulation
Encapsulation means wrapping:

Data members

Member methods

into a single unit (class).


It also hides data from outside world.

Example

Java
class Employee {

private int salary;

public void setSalary(int s) {


salary = s;
}

public int getSalary() {


return salary;
}
}

Advantages
Data security
Controlled access
Better maintenance

4. Data Abstraction
Abstraction means hiding implementation details and showing only necessary information.
Example:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 52/63
ATM machine
Mobile phone

User uses functions without knowing internal working.

Achieved By
Abstract class
Interface

5. Access Specifiers
Access specifiers control visibility of members.

Access Specifier Accessibility


private Inside class only
default Same package
protected Same package + subclass
public Everywhere

Example

Java
class Demo {

private int x = 10;

public void show() {


[Link](x);
}
}

6. Static Data Member


Static variable belongs to class, not object.
Only one copy is shared among all objects.

Example

Java
class Student {

int roll;
static String college = "GTU";
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 53/63
7. Static Member Function
Static method belongs to class.
It can access only static members directly.

Example

Java
class Test {

static void message() {


[Link]("Static Method");
}
}

Call using class name:

Java
[Link]();

8. Constructor
Constructor is special method used to initialize objects.
Rules:

Constructor name must be same as class name


No return type

Types of Constructors
1. Default constructor

2. Parameterized constructor

Default Constructor

Java
class Demo {

Demo() {
[Link]("Default Constructor");
}
}

Parameterized Constructor

Java

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 54/63
class Student {

int id;

Student(int x) {
id = x;
}
}

9. References in Java
Object variable stores reference of object.

Example

Java
Student s1 = new Student();

Here:

s1 is reference variable.

10. this Keyword


this refers to current object.
Used to:

Access current object variables


Resolve variable name conflict
Call constructors

Example

Java
class Student {

int id;

Student(int id) {
[Link] = id;
}

void display() {
[Link](id);
}
}

11. Returning Objects


Method can return object.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 55/63
Example

Java
class Test {

int x = 10;

Test create() {
return this;
}
}

12. Passing Objects as Arguments


Objects can be passed to methods.

Example

Java
class Test {

int x = 10;

void display(Test t) {
[Link](t.x);
}
}

13. Array of Objects


Array can store multiple objects.

Example

Java
class Student {

int id;

Student(int id) {
[Link] = id;
}

void display() {
[Link](id);
}

public static void main(String[] args) {

Student arr[] = new Student[3];

arr[0] = new Student(101);


arr[1] = new Student(102);
arr[2] = new Student(103);

for(Student s : arr) {
[Link]();
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 56/63
}
}

14. Static Block


Static block executes only once when class loads.
Used to initialize static data.

Example

Java
class Demo {

static {

[Link]("Static Block Executed");


}

public static void main(String[] args) {

[Link]("Main Method");
}
}

Output
Static Block Executed
Main Method

15. Instance Block


Instance block executes whenever object is created.

Example

Java
class Demo {

[Link]("Instance Block");
}

Demo() {
[Link]("Constructor");
}

public static void main(String[] args) {

Demo d = new Demo();


}
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 57/63
Output
Instance Block
Constructor

16. Inner Class


Class defined inside another class is called inner class.

Example

Java
class Outer {

class Inner {

void display() {
[Link]("Inner Class");
}
}

public static void main(String[] args) {

Outer o = new Outer();

[Link] i = [Link] Inner();

[Link]();
}
}

Advantages of OOP
Code reusability
Data security

Easy maintenance
Better program structure
Real-world modeling

Conclusion
OOP is a powerful programming approach used in Java. Concepts like classes, objects, encapsulation,
abstraction, constructors, static members, and inner classes help in developing secure, reusable, and
organized programs.

method overloading, method


overriding, dynamic binding

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 58/63
Method Overloading, Method Overriding and Dynamic Binding in
Java
These are important concepts of Object Oriented Programming (OOP) in Java.
They help achieve:

Polymorphism
Flexibility
Code reusability

1. Method Overloading
Method overloading means:

Same method name


Different parameter list

It is an example of compile-time polymorphism.

Rules of Method Overloading


Methods must differ by:

Number of parameters
OR
Type of parameters
OR

Order of parameters

Changing only return type is not overloading.

Example of Method Overloading

Java
class Addition {

int add(int a, int b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}

double add(double a, double b) {


return a + b;
}

public static void main(String[] args) {


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 59/63
Addition obj = new Addition();

[Link]([Link](10, 20));

[Link]([Link](10, 20, 30));

[Link]([Link](5.5, 2.5));
}
}

Output
30
60
8.0

Advantages of Method Overloading


Improves readability
Same method performs different tasks
Reduces code duplication

2. Method Overriding
Method overriding means:

Parent class and child class have same method


Same name
Same parameters

Child class provides new implementation.

It is an example of runtime polymorphism.

Rules of Method Overriding


Inheritance is required
Method name must be same
Parameters must be same
Return type should be same or compatible

Example of Method Overriding

Java
class Animal {

void sound() {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 60/63
[Link]("Animal makes sound");
}
}

class Dog extends Animal {

@Override
void sound() {
[Link]("Dog barks");
}

public static void main(String[] args) {

Dog d = new Dog();

[Link]();
}
}

Output
Dog barks

Another Example

Java
class Vehicle {

void run() {
[Link]("Vehicle is running");
}
}

class Bike extends Vehicle {

void run() {
[Link]("Bike is running");
}

public static void main(String[] args) {

Vehicle v = new Bike();

[Link]();
}
}

Output
Bike is running

Advantages of Method Overriding


Provides specific implementation
Achieves runtime polymorphism
Improves flexibility

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 61/63
3. Dynamic Binding
Dynamic binding means method call is resolved at runtime.
It is also called:

Late binding
Runtime binding

Java decides which overridden method to call during execution.

Example of Dynamic Binding

Java
class Parent {

void display() {
[Link]("Parent class method");
}
}

class Child extends Parent {

void display() {
[Link]("Child class method");
}

public static void main(String[] args) {

Parent p = new Child();

[Link]();
}
}

Output
Child class method

Explanation

Java
Parent p = new Child();

Reference type = Parent


Object type = Child

At runtime, Java calls child class method.


This is called dynamic binding.

Difference Between Overloading and Overriding

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 62/63
Method Overloading Method Overriding
Same class usually Requires inheritance
Different parameters Same parameters
Compile-time polymorphism Runtime polymorphism
Faster execution Slightly slower
No inheritance needed Inheritance required

Compile-Time vs Runtime Polymorphism


Type Achieved By
Compile-time Method overloading

Runtime Method overriding

Important Points
Overloading increases method flexibility.
Overriding changes parent class behavior.
Dynamic binding occurs in overridden methods.
@Override annotation improves readability.

Conclusion
Method overloading allows multiple methods with same name but different parameters. Method
overriding allows child class to provide its own implementation of parent class method. Dynamic binding
helps Java decide method execution at runtime, which supports runtime polymorphism.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 63/63

You might also like