0% found this document useful (0 votes)
7 views60 pages

Introduction to Java and JavaFX Stages

Java is a high-level, object-oriented programming language known for its platform independence and versatility in application development. The document covers key concepts such as JavaFX's Stage for GUI applications, the origin of Java, challenges faced by developers, and essential features and elements of Java programming. It also discusses Java's API, variables, literals, primitive data types, and the String class.

Uploaded by

bhuttmubii59
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)
7 views60 pages

Introduction to Java and JavaFX Stages

Java is a high-level, object-oriented programming language known for its platform independence and versatility in application development. The document covers key concepts such as JavaFX's Stage for GUI applications, the origin of Java, challenges faced by developers, and essential features and elements of Java programming. It also discusses Java's API, variables, literals, primitive data types, and the String class.

Uploaded by

bhuttmubii59
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

❖INTRODUTION TO JAVA

Java is a high-level, object-oriented programming language developed by Sun


Microsystems in 1995, known for its "write once, run anywhere" principle. This
platform independence is achieved because Java code is compiled into bytecode, which
can then run on any device with a Java Virtual Machine (JVM). Java is used for a wide
range of applications, including mobile, web, and enterprise software, and its syntax is
similar to C-based languages

❖ STAGE FOR JAVA


In JavaFX, a Stage is the top-level container for a graphical user interface (GUI) application. It
functions as the primary window for the application and is analogous to a JFrame in Swing

Here's a breakdown of the role of a Stage in JavaFX:


• Window Representation:
A Stage essentially represents a window on the user's desktop. It provides the
visual frame and controls (like title bar, minimize/maximize buttons, close
button) for the application.
• Container for Scenes:
A Stage holds one or more Scene objects. A Scene is the drawing surface for the
graphical content of your application, and it contains a hierarchical tree of nodes
(e.g., buttons, text fields, images).
• Primary Stage:
Every JavaFX application starts with a primary Stage that is automatically created
by the platform and passed as an argument to the start() method of
your Application class.
• Additional Stages:
You can create additional Stage objects within your application if you need
multiple independent windows.
• Properties and Control:
The Stage class provides methods to control various properties of the window,
such as its title, size (width and height), position, resizability, and more.

1|Page
Example of using a Stage in JavaFX:
Java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MyJavaFXApp extends Application {

@Override
public void start(Stage primaryStage) {
[Link]("My JavaFX Application"); // Set the title of the stage

Label label = new Label("Hello, JavaFX!"); // Create a UI component


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

Scene scene = new Scene(root, 300, 200); // Create a scene with the root node
[Link](scene); // Set the scene on the stage
[Link](); // Display the stage
}

public static void main(String[] args) {


launch(args); // Launch the JavaFX application
}
}

2|Page
❖ ORIGIN IN JAVA
The "origin" in Java can refer to several distinct concepts depending on the context:
1. Origin of the Java Programming Language:
• Java was developed by James Gosling and his team at Sun Microsystems in the
early 1990s as part of the "Green Project."
• It was initially designed for interactive television and other consumer electronic
devices, aiming for platform independence.
• The language was first named "Oak," after an oak tree outside Gosling's office,
but was later renamed "Java" due to trademark issues.
• Java was officially released in 1995, and its focus shifted towards the World Wide
Web.
2. Origin in a 2D Coordinate System (e.g., in graphics or geometry problems):
• When dealing with points in a two-dimensional space, the "origin" refers to the
point with coordinates (0, 0).
• In Java 2D graphics, the origin (0,0) is typically located at the top-left corner of the
drawing area.
• Problems like finding "K Closest Points to Origin" involve calculating the distance
of points from (0,0).
3. [Link] in Java's Annotation Processing API:
• Within the [Link] interface, the
nested [Link] enum represents how a construct in a program (like a
class, method, or field) is declared in the source code.
• This can indicate whether a construct is explicitly declared, implicitly generated,
or originates from other sources.
4. Origin in the Context of Cross-Origin Resource Sharing (CORS):
• In web development with Java (e.g., using Spring), "origin" refers to the domain,
protocol, and port of a web request.
• Cross-Origin Resource Sharing (CORS) is a mechanism that allows or restricts web
applications running at one origin from accessing resources at another origin.
• The @CrossOrigin annotation in Spring is used to configure CORS behavior for
controllers or specific handler methods.
3|Page
❖ CHALENGES OF JAVA
The challenges of Java include its verbose syntax and complex Object-Oriented
Programming (OOP) concepts, which can be difficult for beginners. Other
challenges involve potential performance issues due to the Java Virtual
Machine (JVM) and garbage collection, memory leaks, and difficulties with
multi-threading and concurrency. Additionally, keeping up with the rapidly
evolving ecosystem of frameworks like Spring and dealing with large, complex
codebases are significant hurdles.
Conceptual and learning challenges
• Verbose syntax: Java's syntax can be lengthy and complex, requiring a lot

of boilerplate code, such as the public static void main(String[]


args) statement.
• Object-Oriented Programming (OOP): Grasping and correctly implementing
OOP principles like dependency inversion can be challenging for new
programmers.
• Data Structures and Algorithms: Deep understanding of complex data
structures and algorithms is necessary for efficient code, especially for
interviewers.
Performance and technical challenges
• Performance overhead: The JVM can introduce some performance
overhead compared to lower-level languages. The garbage collection
process can also lead to performance pauses.
• Memory leaks: Incorrect management of object references can lead to
memory leaks, which are a common source of bugs.
• Concurrency and multi-threading: Developing concurrent applications
requires careful handling to avoid issues like deadlocks and to ensure
thread safety.
• Improper transaction management: Errors in managing transactions can
lead to data integrity problems.
Development and ecosystem challenges
• Complex frameworks: The Java ecosystem has many powerful and
complex frameworks (e.g., Spring), which have a steep learning curve for
debugging and customization.
• Keeping up with technology: The language and its surrounding
technologies (like microservices, reactive programming) are constantly
evolving, requiring continuous learning to stay current.
4|Page
❖ FEATURES IN JAVA
1. SIMPLE SYNTAX
Java syntax is very straightforward and very easy to learn. Java removes
complex features like pointers and multiple inheritance, which makes it a
good choice for beginners.
Example: Basic Java Program
// Java program to Demonstrate the Basic Syntax
import [Link].*;
class Geeks {
public static void main(String[] args) {
[Link]("GeeksForGeeks!"); }}
2. OBJECT ORIENTED
Java is a pure object-oriented language. It supports core OOP concepts like,
• Class

• Objects

• Inheritance

• Encapsulation

• Abstraction

• Polymorphism

3. PLATFORM INDEPENDENT
Java is platform-independent because of Java Virtual Machine (JVM).
• When we write Java code, it is first compiled by the compiler and

then converted into bytecode (which is platform-independent).


• This byte code can run on any platform which has JVM installed.

4. Interpreted
Java code is not directly executed by the computer. It is first compiled into
bytecode. This byte code is then understand by the JVM.
5. SCALABLE
6. Portable
7. Secured and Robust
8. Memory Management
9. High Performance
10. Multithreading
11. Rich Standard Library
12. Functional Programming Features
13. Integration with Other Technologies
14. Support for Mobile and Web Application
5|Page
❖ ELEMENTS OF JAVA PROGRAM
A Java program consists of several fundamental elements that work together to create
functional applications. These elements can be categorized as follows:
1. Program Structure:
• Package Declaration:
Organizes related classes and interfaces, preventing naming conflicts and providing a
hierarchical structure for your code.
• Import Statements:
Allow the use of classes and interfaces defined in other packages, including the
standard Java libraries.
• Class Declaration:
The blueprint for creating objects, encapsulating data (variables) and behavior
(methods). Every Java program must have at least one class.
• Main Method:
The entry point for any standalone Java application. Execution begins within this
method.
• Statements and Expressions:
Instructions that perform actions, calculations, or manipulate data within
methods. Statements typically end with a semicolon.
2. Language Elements (Tokens):
• Keywords: Reserved words with predefined meanings in Java
(e.g., public, class, static, void, int).
• Identifiers: Names given to classes, methods, variables, and other program
elements.
• Literals (Constants): Fixed values directly represented in the code
(e.g., 10, "Hello", true).
• Data Types:
Define the type of data a variable can hold (e.g., int, double, boolean, String).
4. Control Flow:
• Control Flow Statements: Dictate the order in which statements are executed
(e.g., if-else, for, while, switch).
6|Page
❖ JAVA API
The term "Java API" refers to the Application Programming Interface for the Java
programming language. It is a collection of pre-defined classes, interfaces, and methods
that developers can use to build applications without needing to understand the
underlying implementation details.
Key aspects of the Java API:
• Standard Library:
The core Java API is an integral part of the Java Development Kit (JDK) and provides
fundamental functionalities. This includes packages like [Link] (for core language
features like String, Object, System), [Link] (for utility classes like collections,
date/time), [Link] (for input/output operations), and [Link] (for networking).
• Pre-built Components:
The API offers a vast array of ready-to-use software components that simplify common
programming tasks. For example, you can use classes in [Link] to manage data
structures like ArrayList or HashMap, or classes in [Link] to read from or write to files.
• Interaction with Platforms and Services:
Java APIs facilitate communication and interaction with various software platforms,
external services, and databases. Examples include:
• JDBC (Java Database Connectivity): An API for connecting to and interacting
with relational databases.
• Java EE (Enterprise Edition) APIs: A set of APIs for building enterprise-level
applications, including web services, messaging, and persistence.
• Third-party APIs: Numerous external libraries and services provide Java APIs
to integrate their functionalities into Java applications (e.g., Google API
Client Library for Java, various web service APIs).

7|Page
❖ VARIABLES AND LITERALS IN JAVA
In Java, variables and literals are fundamental concepts for storing and
representing data.
Variables
Variables are named memory locations used to store data during the
execution of a program. They have a specific data type, which determines
the kind of values they can hold (e.g., integers, floating-point numbers,
characters, or objects).
• Declaration: Before using a variable, it must be declared, specifying its
data type and a unique name (identifier).
Java
int age; // Declares an integer variable named 'age'
String name; // Declares a String variable named 'name'
• Initialization: Variables can be assigned a value during declaration or
later in the code.
Java
int age = 30; // Declares and initializes 'age'
name = "Alice"; // Assigns a value to 'name' later
• Types:

Variables can be of primitive types (like int, double, boolean, char)


or reference types (like String, arrays, or custom classes).
• final keyword:
The final keyword can be used to declare a variable as a constant,
meaning its value cannot be changed after initialization.
Java
final double PI = 3.14159; // Declares a constant PI

8|Page
❖ LITERALS
Literals are fixed, constant values that are directly represented in the source
code. They are used to initialize variables or to represent constant values in
expressions.
• Integer Literals: Represent whole numbers. They can be expressed in
decimal, binary (prefix 0b), octal (prefix 0), or hexadecimal (prefix 0x).
Java
int decimal = 10;
int binary = 0b1010; // 10 in decimal
int octal = 012; // 10 in decimal
int hexadecimal = 0xA; // 10 in decimal
• Floating-Point Literals: Represent numbers with fractional parts. They
can be float (suffix f or F) or double (default).
Java
double price = 9.99;
float temperature = 25.5f;
• Character Literals: Represent single characters enclosed in single
quotes. Escape sequences are used for special characters (e.g., \n for
newline).
Java
char initial = 'J';
char newline = '\n';
• String Literals: Represent sequences of characters enclosed in double
quotes.
Java
String message = "Hello, Java!";
• Boolean Literals: Represent truth values: true or false.
Java
boolean isActive = true;
• Null Literal: Represents the absence of a value for reference types.
Java
String emptyString = null;

9|Page
❖ PRIMITIVE DATA TYPES
Java defines eight primitive data types, which are fundamental building
blocks for storing simple values. These types are:
• byte:

An 8-bit signed two's complement integer. It has a minimum value of -


128 and a maximum value of 127.
• short:
A 16-bit signed two's complement integer. It has a minimum value of -
32,768 and a maximum value of 32,767.
• int:
A 32-bit signed two's complement integer. It is the most commonly
used integer type.
• long:
A 64-bit signed two's complement integer. Used when int is not large
enough to hold the desired value.
• float:
A single-precision 32-bit floating-point number. Used for decimal
numbers where precision is less critical.
• double:
A double-precision 64-bit floating-point number. Used for decimal
numbers requiring higher precision.
• char:
A 16-bit Unicode character. Used to store individual characters.
• boolean:
Represents one of two possible values: true or false. Used for
logical conditions.
These primitive types are distinct from non-primitive (or reference) types
like String or custom objects, as they store the actual value directly in
memory and do not have associated methods.

10 | P a g e
String Class in Java
••

The String class in Java is used to create and manipulate sequences of
characters. It is one of the most commonly used classes in Java. Objects of
the String class are immutable, which means they cannot be changed once
created
Key Features of the String Class
1. Immutable
Immutable means that once a String object is created, its value cannot be
changed.
Example:
public class Main {
public static void main(String[] args) {
String text = "hello";
[Link](0) = 'H'; // compile-time error
}
}
Explanation: The line [Link](0) = 'H'; causes a compile-time error
because charAt(0) returns a read-only char, not a variable. String is
immutable in Java, you cannot modify its characters directly.
2. Thread-Safe
String in Java is thread-safe because it is immutable, allowing safe access by
multiple threads without synchronization.
3. Supports Various Utility Methods
String is a predefined final class in Java present in [Link] package. It
provides various methods to create, manipulate, and compare strings, like
length(), charAt(), concat(), equals(), etc.
import [Link].*;

class GFG {
public static void main (String[] args) {
String str = "hello geeks";
[Link]("Length of String-> "+[Link]());
[Link]("Changed String ->"+[Link]());
}
}
Output
Length of String-> 11
Changed String ->HELLO GEEKS
11 | P a g e
➢ JAVA VARIABLES
••
In •Java, variables are containers used to store data in memory. Variables
define how data is stored, accessed, and manipulated.
A variable in Java has three components,
• Data Type: Defines the kind of data stored (e.g., int, String, float).

• Variable Name: A unique identifier following Java naming rules.

• Value: The actual data assigned to the variable.

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

// Declaring and initializing variables

// Integer variable
int age = 25;

// String variable
String name = "GeeksforGeeks";

// Double variable
double salary = 50000.50;

// Displaying the values of variables


[Link]("Age: " + age);
[Link]("Name: " + name);
[Link]("Salary: " + salary);
}
}
Output
Age: 25
Name: GeeksforGeeks
Salary: 50000.5
How to Declare Java Variables?
The image below demonstrates how we can declare a variable in Java:
Variable Declaration
From the image, it can be easily perceived that while declaring a variable, we
need to take care of two things that are data type of the variable and name.
TYPE NAME
INT COUNT
12 | P a g e
➢ CONSTANTS
In Java, a constant is a variable whose value, once initialized, cannot be changed during
the program's execution. Java does not have a dedicated constant keyword like some
other languages. Instead, constants are achieved using the final keyword.
Here's how to declare and use constants in Java: using the final keyword.
The final keyword is used to declare a variable as a constant. Once a final variable is
assigned a value, it cannot be reassigned.
Java
final int MAX_VALUE = 100;
final String GREETING = "Hello, World!";
• Combining with static (for class-level constants):
To make a constant accessible directly through the class name without needing an
object instance, and to ensure there's only one copy of the constant for the entire class,
it's common practice to combine final with the static keyword.
Java
public class MyConstants {
public static final double PI = 3.14159;
public static final int DEFAULT_TIMEOUT = 5000;
}
You would then access these constants
like [Link] or MyConstants.DEFAULT_TIMEOUT. naming convention.
While not enforced by the compiler, the conventional naming for constants in Java is to
use all uppercase letters with underscores to separate words
(e.g., MAX_VALUE, DEFAULT_TIMEOUT). This enhances readability and clearly
distinguishes constants from regular variables.

13 | P a g e
Q:-Scope of Variables & Blocks
In Java, the scope of variables refers to the part of the program where the
variable is accessible and can be used. It is determined by where the variable is
declared, and it plays a crucial role in organizing and managing memory and
ensuring data integrity. Java provides various scopes based on where variables
are declared and the blocks in which they reside.

Types of Variable Scopes in Java

1. Local Scope (Local Variables)


2. Instance Scope (Instance Variables)
3. Static Scope (Class Variables)
4. Block Scope
1 Local Scope (Local Variables)
• Definition: Variables declared inside a method, constructor, or block.
• Lifetime: Exist only during the execution of the method or block in which they are
declared.
• Default Value: No default value; local variables must be initialized before use.
• Accessibility: Accessible only within the block or method where declared.
2. Instance Scope (Instance Variables)
• Definition: Variables declared within a class but outside any method, constructor,
or block.
• Lifetime: Exist as long as the object exists. Each object of the class has its own
copy of instance variables.
• Default Value: Initialized to default values (e.g., 0 for integers, null for objects).
3. Static Scope (Class Variables)
• Definition: Variables declared with the static keyword inside a class but outside
any method, constructor, or block.
4. Block Scope
• Definition: Variables declared inside any block of code (inside {}), including loops,
conditional statements, and methods.
14 | P a g e
Q:- JAVA COMMENTS
In Java, comments are non-executable statements that explain code and
improve readability. They are ignored by the compiler and do not affect
program execution.
• Enhance code readability and maintainability.
• Useful for debugging and documenting logic.
Java supports three main types of comments:
1. Single-Line Comments
Single-line comments are used to comment on one line of code.
Syntax:
// Comments here( Text in this line only is considered as comment )
// Java program to show single line comments
class GFG{
public static void main(String args[]) {
// Single line comment here
[Link]("Single Line Comment Above");
}}
2. Multi-Line Comments
Multi-line comments are used to describe complex code or methods, as
writing multiple single-line comments can be tedious.
/*
Comment starts
continues
continues...
Comment ends
*/
3. Documentation Comments
Documentation comments are used to generate external documentation
using Javadoc. They are generally used in professional projects to describe
classes, methods, and parameters.

15 | P a g e
Q:-DECISION MAKING STATEMENTS
Decision-making in programming is similar to real-life decision-making. We often
want certain blocks of code to execute only when specific conditions are met. In
Java, this is achieved using decision-making statements that control the flow of
execution.
In Java, the following decision-making statements are available:

The if statement is the simplest decision-making statement. It executes a block of code


only if a given condition is true.
class Geeks { TEST

public static void main(String args[]) { EXPRESSION

int i = 10;
BODY OF IF FALS
E
if (i < 15)
[Link]("Condition is True"); } }}
Output STATEMNT JUST
BELOW IF
Condition is True
Note: If curly braces {} are omitted, only the next line after if is considered part of the
block.
if Statement Execution Flow
The below diagram demonstrates the flow chart of an "if Statement execution flow" in
programming.
16 | P a g e
❖JAVA IF-ELSE STATEMENT
The if-else statement allows you to execute one block if the condition is true and
another block if it is false.
import [Link].*;
class Geeks {
public static void main(String args[]) {
int i = 10;
if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15"); }}
Output
i is smaller than 15
if-else Statement Execution flow
The below diagram demonstrates the flow chart of an "if-else Statement execution
flow" in programming

17 | P a g e
❖JAVA NESTED-IF STATEMENT
A nested-if is an if statement inside another if statement. It is useful when a second
condition depends on the first.
class Geeks {
public static void main(String args[]) {
int i = 10;
// Outer if statement
if (i < 15) {
[Link]("i is smaller than 15");
// Nested if statement
if (i == 10) {
[Link]("i is exactly 10"); } }}
Output
i is smaller than 15
i is exactly 10
❖ NESTED-IF STATEMENT EXECUTION FLOW
The below diagram demonstrates the flow chart of an "nested-if Statement
execution flow" in programming.

18 | P a g e
Q:-JAVA IF-ELSE-IF LADDER
The if-else-if ladder allows multiple independent conditions to be checked in order. As
soon as one condition is true, its block executes, and the rest are skipped.
import [Link].*;
class Geeks {
public static void main(String args[]) {
int i = 20;
if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present"); }}
Output
i is 20
❖ IF-ELSE-IF LADDER EXECUTION FLOW
The below diagram demonstrates the flow chart of an "if-else-if ladder execution flow"
in programming

19 | P a g e
Q:-JAVA SWITCH CASE
The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
import [Link].*;
class Geeks {
public static void main(String[] args) {
int num = 20;
switch (num) {
case 5: [Link]("It is 5");
break;
case 10: [Link]("It is 10");
break;
case 15: [Link]("It is 15");
break; case 20:
[Link]("It is 20"); break;
default: [Link]("Not present"); }}}
Output
It is 20
switch Statements Execution Flow
The below diagram demonstrates the flow chart of a "switch Statements execution
flow" in programming.

20 | P a g e
Q:-CONDITIONAL OPERATOR (? :)
The ternary operator in Java is a conditional operator that provides a shorthand way to
write simple if-else statements
Syntax:
condition ? expression_if_true : expression_if_false;
class Geeks {
public static void main(String args[]) {
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Maximum is " + max);}}
Output
Maximum is 20
Explanation: This program uses the ternary operator ( ? : ) to find the maximum of two
numbers. It checks the condition a > b; if true, it assigns a to the variable max,
otherwise it assigns b. Finally, it prints the maximum value.

❖IF-ELSE VS SWITCH-CASE
The table below demonstrates the difference between if-else and switch-case.

Features if-else switch-case

Use Case Suitable for condition-based checks Best for exact value matching

More readable and efficient for


More readable for a few conditions
Readability many cases

Slower for many checks due to Faster and optimized for


Performance multiple conditions handling many cases

Supports ranges and complex Only supports exact matches of


Flexibility conditions values

21 | P a g e
Q:-LOOPING STATEMENTS
Looping statements in Java, also known as iteration statements, allow for
the repeated execution of a block of code based on a specified
condition. This helps in reducing code redundancy and enhancing
efficiency when performing repetitive tasks. Java offers three primary types
of loops: for, while, and do-while
1. for loop
The for loop is used when we know the number of iterations (we know how many times we
want to repeat a task). The for statement includes the initialization, condition, and
increment/decrement in one line.
Example: The below Java program demonstrates a for loop that prints numbers from 0 to 10
in a single line.
// Java program to demonstrates the working of for loop
import [Link].*; Class Geeks {
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
[Link](i + " "); } }}
Output
0 1 2 3 4 5 6 7 8 9 10
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed}
2. WHILE LOOP
A while loop is used when we want to check the condition before executing the loop
Example: The below Java program demonstrates a while loop that prints numbers from
0 to 10 in a single line.
// Java program to demonstrates
// the working of while loop
import [Link].*;
class Geeks {
public static void main(String[] args) {
int i = 0;
while (i <= 10) {
[Link](i + " ");
i++; } }}
Output
0 1 2 3 4 5 6 7 8 9 10
Syntax:
while (condition) {
// code to be executed}
22 | P a g e
3. do-while Loop
The do-while loop ensures that the code block executes at least once before checking
the condition.
Example: The below Java program demonstrates a do-while loop that prints numbers
from 0 to 10 in a single line.
// Java program to demonstrates
// the working of do-while loop
import [Link].*;
class Geeks {
public static void main(String[] args) {
int i = 0; do {
[Link](i + " "); i++;
} while (i <= 10) } }
Output
0 1 2 3 4 5 6 7 8 9 10
Syntax:
do {
// code to be executed
} while (condition);

❖ Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
ExampleGet your own Java Server
// Outer loop
for (int i = 1; i <= 2; i++) {
[Link]("Outer: " + i); // Executes 2 times

// Inner loop
for (int j = 1; j <= 3; j++) {
[Link](" Inner: " + j); // Executes 6 times (2 * 3)
}
}

23 | P a g e
In Java, jump statements are used to alter the normal flow of program execution when
certain conditions are met. They can be used to terminate a loop, skip an iteration, or
exit from a method or block of code.
Continue Statement
The continue statement pushes the next repetition of the loop to take place, skipping
any code between itself and the conditional expression that controls the loop.
import [Link].*;
class GFG { public static void main(String[] args) {
for (int i = 0; i < 5; i++) { if (i == 2){
[Link](); // using continue keyword
// to skip the current iteration continue; }
[Link](i); } }}
Output
0134
Break statement
1. Using Break Statement to exit a loop:
In Java, the break statement is used to terminate the execution of the nearest looping
statement or switch statement. The break statement is widely used with the switch
statement, for loop, while loop, and do-while loop.
When a break statement is executed inside a loop, the loop is terminated, and the
control reaches the statement that follows the loop. here is an example:
import [Link].*;
class GFG {
public static void main(String[] args) {
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 4) break;
[Link](i); } }}
Output
0123
24 | P a g e
Q:-OBJECT-ORIENTED 00PS
Before Object-Oriented Programming (OOPs), most programs used a procedural
approach, where the focus was on writing step-by-step functions. This made it harder
to manage and reuse code in large applications.
To overcome these limitations, Object-Oriented Programming was introduced. Java is
built around OOPs, which helps in organizing code using classes and objects.
Key Features of OOP in Java:
• Structures code into logical units (classes and objects)
• Keeps related data and methods together (encapsulation)
• Makes code modular, reusable and scalable
• Prevents unauthorized access to data
• Follows the DRY (Don’t Repeat Yourself) principle
1. Class
A Class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
Using classes, you can create multiple objects with the same behavior instead of
writing their code multiple times. In general, class declarations can include these
components in order:
• Modifiers: A class can be public or have default access (Refer to this for details).
• Class name: The class name should begin with the initial letter capitalized by
convention.
• Body: The class body is surrounded by braces, { }.

1. CLASS
A Class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
Using classes, you can create multiple objects with the same behavior instead of
writing their code multiple times. In general, class declarations can include these
components in order:
• Modifiers: A class can be public or have default access (Refer to this for details).
• Class name: The class name should begin with the initial letter capitalized by
convention.
25 | P a g e
3. ABSTRACTION
• Abstraction in Java is the process of hiding the implementation details
and only showing the essential details or features to the user. It allows
to focus on what an object does rather than how it does it. The
unnecessary details are not displayed to the user.
• Note: In Java, abstraction is achieved by interfaces and abstract classes.
We can achieve 100% abstraction using interfaces.
4. ENCAPSULATION
Encapsulation is defined as the process of wrapping data and the methods into a single
unit, typically a class. It is the mechanism that binds together the code and the data. It
manipulates. Another way to think about encapsulation is that it is a protective shield
that prevents the data from being accessed by the code outside this shield.
• Technically, in encapsulation, the variables or the data in a class is hidden from
any other class and can be accessed only through any member function of the
class in which they are declared.
• In encapsulation, the data in a class is hidden from other classes, which is similar
to what data-hiding does. So, the terms "encapsulation" and "data-hiding" are
used interchangeably.
• Encapsulation can be achieved by declaring all the variables in a class as private
and writing public methods in the class to set and get the values of the variables.

• 5. INHERITANCE
• Inheritance is an important pillar of OOP (Object Oriented
Programming). It is the mechanism in Java by which one class is allowed
to inherit the features (fields and methods) of another class. We are
achieving inheritance by using extends keyword. Inheritance is also
known as "is-a" relationship.
• Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

6. POLYMORPHISM
The word polymorphism means having many forms, and it comes from the Greek
words poly (many) and morph (forms), this means one entity can take many forms. In
Java, polymorphism allows the same method or object to behave differently based on
the context, specially on the project's actual runtime class.

26 | P a g e
Q:- CLASSES AND OBJECTS
In Java, classes and objects form the foundation of Object-Oriented
Programming (OOP). They help model real-world entities and organize code
in a structured way.
• A class is a blueprint used to create objects that share common

properties and behavior.


• An object is an instance of a class. It represents a specific entity

created from the class template.


CLASS
A class is a blueprint that defines data and behavior for objects. It groups
related fields and methods in a single unit. Memory for its members is
allocated only when an object is created.
• Acts as a template to create objects with shared structure.

• Does not occupy memory for fields until instantiation.

Can contain fields, methods, constructors, nested classes


and interfaces.
OBJECTS
An object is an instance of a class created to access its data and operations.
Each object holds its own state.
• State: Values stored in fields.

• Behavior: Actions defined through methods.

• Identity: Distinguishes one object from another.

Objects mirror real-world items such as customer, product or circle. Non-


primitive objects are stored on the heap while their references remain on the
stack.

Object Instantiation
Creating an object is known as instantiation. All instances of a class share
structure and behavior while storing different state values.

27 | P a g e
Q:- MODIFIERS
Modifiers in Java are keywords used to define the scope, behavior, and properties of
classes, methods, and variables. They are of two types:
A. Access Modifiers
1. public – Accessible from anywhere.
2. private – Accessible only within the same class.
3. protected – Accessible within the same package and subclasses.
4. default (no keyword) – Accessible only within the same package.
B. Non-Access Modifiers
1. static – Belongs to the class, not objects.
2. final – Value cannot be changed; methods cannot be overridden; classes cannot
be inherited.
3. abstract – Used for abstract classes and methods.
4. synchronized – Used for thread safety.
5. transient – Excluded from serialization.
6. volatile – Value is stored in main memory.
7. strictfp – Ensures consistent floating-point calculations.

Q:- JAVA USES CALL BY VALUE FOR ALL METHOD


CALLS.
• For primitive data types, a copy of the value is passed; changes inside the method
do not affect the original variable.
• For objects, a copy of the reference is passed; the method can modify the object's
data, but not the reference itself.

28 | P a g e
Q:- CONSTRUCTORS
A constructor is a special method used to initialize objects.
Characteristics:
• Has the same name as the class.
• No return type, not even void.
• Automatically invoked when an object is created.
• Used to initialize variables and allocate resources.
Example:
class A {
A() {
[Link]("Constructor called"); }}

Q:- OVERLOADED CONSTRUCTORS


Constructor overloading means having more than one constructor in a class, each
with a different parameter list.
It provides multiple ways to initialize objects.
Example:
class Student {
Student() {}
Student(String name) {}
Student(String name, int age) {}}

Q:- OVERLOADED OPERATORS


Java does not support operator overloading, except for the ’+’ operator, which is
overloaded for String concatenation.
Example:
String s = "Hello" + " World";

29 | P a g e
Q:- STATIC CLASS MEMBERS
Static members belong to the class, not to individual objects.
Static Variables
• Shared by all objects.
• Memory allocated only once.
Static Methods
• Can be called without creating an object.
• Cannot access non-static members directly.
• Cannot use this or super.
Static Block
Executed once when the class is loaded.
Example:
class Counter {
static int count = 0;
Counter() { count++; }

static void show() {


[Link](count);
}
}

30 | P a g e
Q:-BASICS OF INHERITANCE
Inheritance in Java is a fundamental concept of Object-Oriented Programming (OOP)
that allows a class to acquire the properties (fields) and behaviors (methods) of
another class. This promotes code reusability and establishes a hierarchical relationship
between classes.
Key Concepts:
• Superclass (Parent Class): The class whose features are inherited.
• Subclass (Child Class): The class that inherits features from the superclass.
• extends Keyword: Used to establish the inheritance relationship. A
subclass extends a superclass.
In this example:
• The Car class inherits brand, speed, and accelerate() from Vehicle.
• It also adds its own numberOfDoors field and honk() method
Benefits of Inheritance:
• Code Reusability: Avoids writing the same code multiple times.
• Polymorphism: Enables objects of different classes to be treated as objects of a
common superclass.
• Maintainability: Changes in the superclass can propagate to subclasses,
simplifying updates.
• Organization: Creates a clear and logical structure for your code.

31 | P a g e
INHERITING AND OVERRIDING SUPERCLASS METHODS
INHERITING SUPERCLASS METHODS
Definition:
When a subclass is created using the extends keyword, it automatically inherits all non-
private methods of the superclass.
Access Rules:
Public and Protected methods are inherited and accessible in the subclass.
Private methods are not inherited directly but can be accessed indirectly through
public/protected methods in the superclass.
Default (Package-Private) methods are inherited only if the subclass is in the same
package as the superclass.
Usage:
Subclasses can directly call inherited methods unless overridden.
Q:-OVERRIDING SUPERCLASS METHODS
Method overriding occurs when a subclass provides a specific implementation of a
method that is already defined in its superclass.
Rules for Overriding
• Method Signature:
The overridden method in the subclass must have the same name, return type, and
parameter list as the method in the superclass.
• Access Modifier:
The access level of the overridden method in the subclass cannot be more restrictive
than the superclass method.
Example: If a superclass method is protected, the subclass method cannot be private.
• Annotations:
It is good practice to use the @Override annotation for clarity and to avoid mistakes.
Exception Handling:
The overriding method cannot throw new or broader checked exceptions than the
overridden method.
• final Methods:
Methods declared as final in the superclass cannot be overridden.
• Static and Private Methods:
Static methods cannot be overridden but can be re-declared (method hiding).
Private methods are not visible to the subclass and hence cannot be overridden.

32 | P a g e
Q:-CALLING SUPERCLASS CONSTRUCTOR
In Java, a subclass constructor can explicitly call a superclass constructor using
the super() keyword. This is essential for ensuring that the superclass's initialization
logic is executed when a subclass object is created.
Key points for calling a superclass constructor:
• super() keyword: Use super() to invoke the superclass's constructor. If the
superclass has a no-argument constructor, you can use super() without any
arguments. If the superclass has parameterized constructors, you must provide
the corresponding arguments within the super() call.
CODE class Animal {
String name;
Animal(String name) {
[Link] = name;
[Link]("Animal constructor called for: " + name); } }
class Dog extends Animal {
Dog(String name) {
super(name); // Calls the Animal(String name) constructor
[Link]("Dog constructor called for: " + name); } }
• FIRST STATEMENT: The call to super() must be the very first
statement within the subclass constructor. Java enforces this rule to
ensure that the superclass is fully initialized before the subclass
performs any of its own initialization.
class Cat extends Animal {
int age;
Cat(String name, int age) {
// [Link] = age; // This would cause a compilation error as
super() must be first
super(name);
[Link] = age;
[Link]("Cat constructor called for: " + name + ",
age: " + age);
}
}
• NO-ARGUMENT CONSTRUCTOR REQUIREMENT: If the superclass
does not have a no-argument constructor and the subclass does not
explicitly call another superclass constructor using super(), a
compilation error will occur. The subclass must explicitly call one of
the available superclass constructors.
33 | P a g e
Q:- POLYMORPHISM
Polymorphism in Java is a core concept of Object-Oriented Programming (OOP) that
allows objects to take on "many forms." It enables a single interface to be used for
multiple underlying data types or implementations, promoting code reusability,
flexibility, and scalability. The term "polymorphism" originates from Greek words
"poly" (many) and "morphs" (forms).
There are two main types of polymorphism in Java:
• Compile-time Polymorphism (Static Polymorphism):
o Achieved through method overloading.
o Method overloading involves defining multiple methods within the same
class that have the same name but different parameter lists (different
number of arguments, different data types of arguments, or different order
of argument types).
o The Java compiler determines which overloaded method to call at compile
time based on the method signature (name and parameter list).
class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}
• Runtime Polymorphism (Dynamic Polymorphism):
o Achieved through method overriding.

o Method overriding occurs when a subclass provides a specific


implementation for a method that is already defined in its
superclass.
o The decision of which overridden method to call is made at
runtime, based on the actual type of the object being referred to by
a superclass reference variable. This is also known as Dynamic
Method Dispatch.
o This relies on upcasting, where a subclass object is referred to by
a superclass reference variable.
34 | P a g e
Q:-ABSTRACT CLASS
An abstract class in Java is a class declared using the abstract keyword. It serves as a
blueprint for other classes and cannot be instantiated directly, meaning you cannot
create an object of an abstract class. Abstract classes are primarily intended to be
subclassed.
Here are key characteristics of abstract classes in Java:
• Declaration: An abstract class is declared using the abstract keyword before
the class keyword.
Java
abstract class ClassName {
// ...
}
• Abstract Methods: An abstract class can contain abstract methods. An abstract
method is declared without an implementation (without a method body) and
ends with a semicolon. Any class that extends an abstract class must provide
implementations for all of its abstract methods, unless the subclass itself is also
declared as abstract.
Java
abstract void methodName(); // Abstract method declaration
• Concrete Methods:
Abstract classes can also contain concrete methods, which are methods with full
implementations. These methods provide default behavior that can be inherited and
used by subclasses.
• Constructors and Fields:
Abstract classes can have constructors, fields (variables), and static and final methods,
just like regular classes.
• Inheritance:
Abstract classes are extended by other classes using the extends keyword. Subclasses
inherit both the abstract and concrete methods, and must implement the abstract
ones.

35 | P a g e
Q:-INTRODUCTION TO FINAL CLASS IN JAVA
As the name suggests, the Final Class in Java uses the final keyword for its declaration.
The final keyword in Java restricts the user; similarly, the final class means that the
class cannot be extended. We can only create a final class if it is complete, which
means it cannot be an abstract class. All wrapper classes in Java are final classes, such
as String, Integer, etc. Any subclass cannot inherit final class,
If we try to inherit a final class, the compiler throws an error during compilation.
How to Create Final Classes?
We can use Java's final keyword to create a final class. The class's definition should be
complete and not abstract.
Syntax:
final class className
{
// Body of class
}
where final is the keyword used to declare the final class and className is the name of
the class we are defining.

36 | P a g e
Q:-ARRAY INTRODUCTIOM
An array is a collection of items of the same variable type that are stored at contiguous
memory locations. It is one of the most popular and simple data structures used in
programming.
Basic terminologies of Array
• Array Element: Elements are items stored in an array.
• Array Index: Elements are accessed by their indexes

Q:-PASSING ARRAY ASARGUMENT


o pass an array as an argument to a method in Java, you declare the method parameter
to be of the array type and then pass the name of the array variable when calling the
method.
1. Declaring a method that accepts an array:
When defining the method, specify the array type in the parameter list. For example, to
accept an integer array, you would use int[] arrayName. Java
public class ArrayExample {
// Method to print elements of an integer array
public static void printArray(int[] arr) {
[Link]("Array elements: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " "); }
[Link]();}
// Method to modify elements of an integer array
public static void doubleArrayElements(int[] arr) {
for (int i = 0; i < [Link]; i++) {
arr[i] = arr[i] * 2; } }
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Passing the 'numbers' array to the printArray method
printArray(numbers); // Output: Array elements: 10 20 30 40 50
// Passing the 'numbers' array to the doubleArrayElements method
doubleArrayElements(numbers);
// Printing the array again to see the changes
printArray(numbers); // Output: Array elements: 20 40 60 80 100 }
}
37 | P a g e
Q:-RETURNING AEEY FROM METHODS
To return an array from a method in Java, the method's return type must be declared as
an array of the desired data type.
Here are the steps to return an array from a method:
• Declare the method with an array return type:
Specify the data type of the array in the method signature, followed by square
brackets []. For instance, int[], String[], double[].
Java
public int[] getNumbers() {
// Method body }
• Create and populate the array within the method:
Inside the method, create an array using the new keyword and populate it with the
necessary elements.
Java
public int[] getNumbers() {
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
// ... populate the array
return numbers;
}
return the array.
Use the return statement followed by the name of the array to send it back to the
calling code.
Java
public int[] getNumbers() {
int[] numbers = {1, 2, 3, 4, 5}; // Shortcut for creating and populating
return numbers;
}

38 | P a g e
Q:-ARRAY OF OBJECTS
In Java, an array of objects is simply an array whose elements are references to
instances of a class.
Here’s everything you need to know, with examples.
1. Declaring an Array of Objects
You declare it just like a normal array, but with a class type:
ClassName[] arr;
Example:
Student[] students;
2. Creating the Array (this only allocates space for references)
students = new Student[3];
At this point, the array contains null references:
[ null, null, null ]
3. Creating Objects for Each Slot
You must instantiate each object individually:
students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 22);
students[2] = new Student("Carol", 19);
Complete Example
class Student {
String name;
int age;
Student(String name, int age) {
[Link] = name;
[Link] = age; }}

public class Main {


public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 22);
students[2] = new Student("Carol", 19);
for (Student s : students) {
[Link]([Link] + " - " + [Link]); } }}

Output:
Alice - 20
Bob - 22
Carol - 19
39 | P a g e
Q:-2D ARRAY
In Java, a 2D array, also known as a multi-dimensional array, is essentially an array of
arrays. It provides a structured way to store data in a grid-like format, similar to rows and
columns in a spreadsheet or a matrix.
Declaration and Initialization:
You can declare a 2D array by specifying the data type followed by two sets of square
brackets and the array name:
Java
int[][] twoDArray;
String[][] names;
To initialize a 2D array, you can specify its dimensions (number of rows and columns) using
the new keyword:
Java
int[][] matrix = new int[3][4]; // A 3x4 integer matrix
Alternatively, you can initialize a 2D array with values directly using an initializer list:
Java
int[][] numbers = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
Accessing Elements:
Elements in a 2D array are accessed using two
indices: arrayName[rowIndex][columnIndex]. Both row and column indices start from 0.
Java
int value = numbers[1][2]; // Accesses the element at row 1, column 2 (which is 6 in the
example above)
Iterating Through a 2D Array:
You can iterate through a 2D array using nested loops, commonly for loops or enhanced for-
each loops:
Using Nested for loops:
Java
for (int i = 0; i < [Link]; i++) { // Iterates through rows
for (int j = 0; j < numbers[i].length; j++) { // Iterates through columns in the current row
[Link](numbers[i][j] + " "); }
[Link](); // New line after each row}
Using Nested Enhanced for-each loops:
Java
for (int[] row : numbers) { // Iterates through each row (which is itself an array)
for (int element : row) { // Iterates through each element in the current row
[Link](element + " ");
}
[Link]();
}
40 | P a g e
Q:-Array with three or more dimensions
In Java, arrays with three or more dimensions are essentially arrays of arrays, providing
a way to organize data hierarchically. These arrays can be thought of as grids, cubes, or
even higher-dimensional data structures. Below is a detailed discussion of
multidimensional arrays with three or more dimensions in Java:
• Definition and Syntax
A three-dimensional array in Java is an array where each element is a two-dimensional
array. It can be declared and initialized as follows:
int[][][] array3D = new int[3][4][5];
Here:
• 3 represents the number of 2D arrays.
• 4 is the number of rows in each 2D array.
• 5 is the number of columns in each 2D array.
For higher dimensions, the same principle applies:
int[][][][] array4D = new int[2][3][4][5];
Initialization
You can initialize a multidimensional array either at the time of declaration or later
USING NESTED LOOPS.
At Declaration:
int[][][] array3D = { {
{1, 2, 3},
{4, 5, 6} }, {
{7, 8, 9},
{10, 11, 12}}};
Using Loops:
int[][][] array3D = new int[2][3][4];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
array3D[i][j][k] = i + j + k; } }}
Accessing Elements
You can access elements using multiple indices, one for each dimension:
int value = array3D[0][1][2]; // Accesses the element in the 1st 2D array, 2nd row, 3rd
column
You can also modify elements directly:
array3D[0][1][2] = 42;

41 | P a g e
Applications

Multidimensional arrays are useful in scenarios requiring complex data representation, such as:

• 3D graphics: Representing points in 3D space.


• Game development: Representing game boards or maps in 3D space.
• Data science: Handling higher-dimensional data like tensors.
Jagged Multidimensional Arrays
Java supports “jagged arrays,” where arrays at each level can have different sizes:
int[][][] jaggedArray = { {
{1, 2},
{3, 4, 5} },{
{6, 7, 8, 9} }};
Accessing and iterating over these requires checking the size at each level dynamically.
Example Code

Here’s an example that creates a 3D array, fills it, and prints its contents:
public class ThreeDArrayExample {
public static void main(String[] args) {
int[][][] array3D = new int[2][3][4];
// Filling the array
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < array3D[i].length; j++) {
for (int k = 0; k < array3D[i][j].length; k++) {
array3D[i][j][k] = i + j + k; } } }
// Printing the array
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < array3D[i].length; j++) {
for (int k = 0; k < array3D[i][j].length; k++) {
[Link](array3D[i][j][k] + ” “);
}
[Link]();
}
[Link]();
}
}
}

42 | P a g e
Q:-STRING CLASS
The String class in Java represents character strings and is a fundamental part of Java
programming. Here's a summary of its key characteristics:
1. Immutability:
• String objects are immutable, meaning their value cannot be changed after they
are created. Any operation that appears to modify a string, such as concatenation
or substring extraction, actually creates a new String object.
2. Object, Not Primitive:
• In Java, String is a class, and string variables hold references to String objects,
unlike primitive types like int or char.
3. String Pool:
• String literals (e.g., "Hello") are stored in a special area of the heap called the
"string pool." If a string literal with the same value already exists in the pool, a
new object is not created; instead, the existing reference is returned, optimizing
memory usage.
• Creating a string using new String("...") always creates a new object in the heap,
regardless of whether the content already exists in the string pool.
4. Methods for Manipulation:
• The String class provides a rich set of methods for various operations, including:
o Comparison: equals(), equalsIgnoreCase(), compareTo()
o Concatenation: concat(), or using the + operator
o Substring Extraction: substring()
o Searching: indexOf(), lastIndexOf()
o Case Conversion: toLowerCase(), toUpperCase()
o Length: length()
o Splitting: split()
5. StringBuilder and StringBuffer:
• For scenarios requiring mutable strings (where frequent modifications are
needed), StringBuilder and StringBuffer classes are used.

43 | P a g e
Q:-DIFFERENCE BETWEEN STRING AND STRING BUFFER CLASS
The String and StringBuffer classes in Java both handle sequences of characters but
have significant differences in their functionality, mutability, and performance
characteristics. Understanding these differences helps in choosing the right class for a
given use case.
Key Differences Between String and StringBuffer

Aspect String StringBuffer

Immutable: Any
Mutable: Modifications are made
Mutability modification creates a new
in the same object.
object.

Slower for repeated


Faster for repeated modifications
Performance modifications due to object
due to in-place changes.
creation overhead.

Thread-safe (synchronized
Thread-Safety Not thread-safe.
methods).

Best for frequently modified text,


Best for fixed or
Usage Scenario especially in multi-threaded
infrequently modified text.
environments.

Provides methods like Provides methods like append(),


Methods for
concat(), but these return insert(), replace(), etc., that
Modification
new strings. modify the object directly.

May lead to higher memory


More memory-efficient for
Memory Usage usage due to multiple
frequent modifications.
objects.

Slower for multiple changes Faster for multiple changes due to


Speed
due to immutability. mutability.

44 | P a g e
Q:-STRING TOKENIZER
StringTokenizer class in Java is used to break a string into tokens based on delimiters. A
StringTokenizer object internally maintains a current position within the string to be
tokenized. Some operations advance this current position past the characters
processed.
• A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.
• It provides the first step in the parsing process often called lexer or scanner.
• It implements the Enumeration interface.
• To perform Java String Tokenization, we need to specify an input string and a set
of delimiters.
• A delimiter is a character or set of characters that separate tokens in the string.
Note: StringTokenizer is a legacy class, and the split() method is preferred for modern
applications.
Example: Below is a simple example that explains the use
of Java StringTokenizer to split a space-separated string into tokens:
// Demonstration of Java StringTokenizer
import [Link];
public class Geeks {
public static void main(String[] args) {
// Input string
String s = "Hello Geeks how are you";
// Create a StringTokenizer object
// with space as the delimiter
StringTokenizer st = new StringTokenizer(s, " ");
// Tokenize the string and print each token
while ([Link]()) {
[Link]([Link]()); } }}

45 | P a g e
Q:----STATIC IMPORT AND PACKAGE CLASS
In Java, static import and package class are distinct concepts related to how classes and
their members are organized and accessed.
• STATIC IMPORT
Static import is a feature introduced in Java 5 that allows you to import static members
(fields and methods) of a class directly, without needing to qualify them with the class
name. This can lead to more concise and readable code, especially when frequently
using static members from a particular class.
• Syntax:
Importing a specific static member.
Java
import static [Link];
Importing all static members of a class:
Java
import static [Link].*;
PACKAGE CLASS
A package in Java is a mechanism for organizing related classes and interfaces into a
hierarchical structure. It provides a way to manage the namespace and prevent naming
conflicts between classes. A "package class" refers to a class that resides within a
specific package.
Key aspects of packages:
• Organization:
Packages help organize code into logical units, making it easier to manage large
projects.
• Namespace Management:
They prevent naming collisions by providing unique namespaces for classes. For
example, two different packages can have a class named MyClass without conflict.
• Access Control:
Packages play a role in Java's access control mechanisms, with package-
private (default) access allowing members to be accessible only within the same
package.
Syntax:
• Declaring a class within a package.
Java
package [Link];
public class MyUtilityClass {
// Class members }
• Importing a class from another package.
Java import [Link]; // Importing a specific class
import [Link].*; // Importing all classes from a package
46 | P a g e
Q----- EXCEPTION HANDLING
In Java, exception handling is a mechanism to handle runtime errors, allowing the
normal flow of a program to continue. Exceptions are events that occur during program
execution that disrupt the normal flow of instructions.
• BASIC TRY-CATCH EXAMPLE
• The try block contains code that might throw an exception,
• The catch block handles the exception if it occurs.
class Geeks{
public static void main(String[] args) {
int n = 10;
int m = 0;
try {
int ans = n / m;
[Link]("Answer: " + ans);
} catch (ArithmeticException e){
[Link]("Error: Division by 0!"); } }}
Output
Error: Division by 0!
Finally Block
The finally block always executed whether an exception is thrown or not. The finally is
used for closing resources like db connections, open files and network connections, It is
used after a try-catch block to execute code that must run.
class FinallyExample {
public static void main(String[] args){
int[] numbers = { 1, 2, 3 };
try {
// This will throw ArrayIndexOutOfBoundsException
[Link](numbers[5]); }
catch (ArrayIndexOutOfBoundsException e){

[Link]("Exception caught: " + e); }


finally{
[Link]("This block always executes."); }
[Link]("Program continues..."); }}

Output
Exception caught: [Link]: Index 5 out of bounds
for length 3
This block always executes.
Program continues...
47 | P a g e
TYPES OF JAVA EXCEPTIONS
Java defines several types of exceptions that relate to its various class libraries. Java
also allows users to define their it's exceptions.
1. Built-in Exception
Built-in Exception are pre-defined exception classes provided by Java to handle
common errors during program execution. There are two type of built-in exception in
java.
• Checked Exception: These exceptions are checked at compile time, forcing the
programmer to handle them explicitly.
• Unchecked Exception: These exceptions are checked at runtime and do not
require explicit handling at compile time.
2. User-Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain situation.
In such cases, users can also create exceptions, which are called "user-defined
Exceptions".
Methods to Print the Exception Information
printStackTrace(): Prints the full stack trace of the exception, including the name,
message and location of the error.
toString(): Prints exception information in the format of the Name of the exception.
getMessage() : Prints the description of the exception
❖ NESTED TRY-CATCH

In Java, you can place one try-catch block inside another to handle
exceptions at multiple levels.
public class NestedTryExample {
public static void main(String[] args) { try {
[Link]("Outer try block"); try {
int a = 10 / 0; // This causes ArithmeticException
} catch (ArithmeticException e) {
[Link]("Inner catch: " + e); }
String str = null;
[Link]([Link]()); // This causes
NullPointerException
} catch (NullPointerException e) {
[Link]("Outer catch: " + e); } }}

48 | P a g e
Q------How Does JVM Handle an Exception?
When an Exception occurs, the JVM creates an exception object containing the error
name, description and program state. Creating the exception object and handling it in
the run-time system is called throwing an exception. There might be a list of the
methods that had been called to get to the method where an exception occurred. This
ordered list of methods is called call stack. Now the following procedure will happen:
• The run-time system searches the call stack for an exception handler
• It starts searching from the method where the exception occurred and proceeds
backward through the call stack.
• If a handler is found, the exception is passed to it.
• If no handler is found, the default exception handler terminates the program and
prints the stack trace.
Exception in thread "abc" Name of Exception : Description
// Call Stack
Look at the below diagram to understand the flow of the call stack:
Illustration:
class Geeks{
public static void main(String args[])
{
// Taking an empty string
String s = null;

// Getting length of a string


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

49 | P a g e
Q:-----MULTITHREADING
Multithreading in Java is a feature that enables a program to run multiple
threads simultaneously, allowing tasks to execute in parallel and utilize the
CPU more efficiently. A thread is a lightweight, independent unit of
execution inside a program (process).
• A process can have multiple threads.

• Each thread runs independently but shares the same memory.

Q----THREADS IN JAVA
In Java, a thread represents a single, independent path of execution
within a program. It is the smallest unit of execution that can be managed
by the Java Virtual Machine (JVM). Java's support for threads allows for
multithreading, enabling multiple tasks to run concurrently within the
same program, sharing the same memory space. This concurrency can
enhance application performance and responsiveness.
Creating Threads in Java:
There are two primary ways to create a thread in Java: Extending the
Thread class.
Java
class MyThread extends Thread {
public void run() {
// Code to be executed in the new thread
[Link]("MyThread is running.");} }

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread();
[Link](); // Starts the new thread and
calls its run() method
}
}

50 | P a g e
Q:--------THREADS CREATION
In Java, threads can be created and managed using two primary approaches: extending
the Thread class or implementing the Runnable interface.
1. Extending the Thread Class:
This method involves creating a new class that inherits from the [Link] class.
• Step 1: Create a Subclass: Define a new class that extends Thread.
• Step 2: Override the run() Method: Implement the run() method within your
subclass. This method contains the code that the thread will execute
concurrently.
• Step 3: Instantiate and Start: Create an object of your custom thread class and call
its start() method. The start() method initiates a new thread of execution and calls
the run() method internally.
Java
class MyThread extends Thread {
public void run() {
[Link]("Thread created by extending Thread class."); }}
public class ThreadExample1 {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link](); // Starts the new thread and executes its run() method }}

IMPLEMENTING THE RUNNABLE INTERFACE:


This method involves creating a class that implements [Link]. This is
generally preferred as it allows your class to inherit from other classes while still
providing thread functionality.
• Step 1: Implement Runnable: Define a new class that implements Runnable.
• Step 2: Override the run() Method: Implement the run() method in your class,
containing the code for concurrent execution.
• Step 3: Create Thread Object and Start: Instantiate
your Runnable implementation, then create a Thread object by passing
your Runnable instance to its constructor. Finally, call the start() method on
the Thread object.

51 | P a g e
The Java Thread Lifecycle describes the various states a thread can be in from its
creation to its termination. Understanding these states is crucial for effective
multithreaded programming. The six main states, as defined by the [Link] enum,
are:
• NEW:
• A thread is in the NEW state when it has been created (an instance
of Thread or a class implementing Runnable is created) but
the start() method has not yet been invoked.
• The thread is alive but not yet eligible to be run by the scheduler.
• RUNNABLE:
• Once start() is called on a new thread, it transitions to the RUNNABLE state.
• In this state, the thread is eligible to be run by the Java Virtual Machine
(JVM) scheduler. It may be actively executing on a CPU or waiting for its turn
to be scheduled.
• A thread enters the BLOCKED state when it attempts to acquire a monitor
lock (e.g., by entering a synchronized block or method) but the lock is
already held by another thread.
• The thread will remain blocked until the lock is released and it can acquire it.
• WAITING:
• A thread enters the WAITING state when it calls one of
the [Link]() methods (without a timeout), [Link]() (without a
timeout), or [Link]().
• TIMED_WAITING:
• Similar to WAITING, but with a specified timeout. A thread enters this state
when it calls [Link](long millis), [Link](long
timeout), [Link](long millis), [Link](),
or [Link]().
• TERMINATED:
• A thread enters the TERMINATED state when its run() method completes
execution or when it terminates due to an uncaught exception.

52 | P a g e
Q:---THREAD SYNCHRONIZATION
Thread synchronization in Java is a mechanism used to control access to
shared resources by multiple threads in a concurrent environment. Its
primary purpose is to prevent data inconsistency and race conditions that
can arise when multiple threads attempt to modify the same shared data
simultaneously.
Key Concepts:
• Race Condition:

Occurs when multiple threads access and manipulate shared data


concurrently, and the final outcome depends on the unpredictable
order of execution of these threads.
• Critical Section:
A block of code or a shared resource that must only be accessed by
one thread at a time to maintain data integrity.
Monitor:

Every Java object has an associated monitor, which acts as a lock. A
thread can acquire this lock to enter a critical section and release it
upon exit.
Methods of Synchronization in Java:
• synchronized Keyword:
o Synchronized Method: When a method is declared synchronized,
only one thread can execute that method on a given object at a
time. The lock is acquired on the object instance (this).
o Synchronized Block: A synchronized block allows for finer-
grained control by specifying a specific object (or class for static
methods) to lock on.
Java
// Synchronized method
public synchronized void incrementCounter() {
// critical section
}

// Synchronized block
public void updateResource() {
synchronized (this) { // or any other object
// critical section
}
}

53 | P a g e
Q:----Applet INTRODUCTION
Java Applets was once a very popular feature of web applications. Java
Applets were small programs written in Java that ran inside a web browser.
Learning about Applet helps us understand how Java has evolved and how it
handles graphics.
Note: [Link] package has been deprecated in Java 9 and later versions,
as applets are no longer widely used on the web.
❖ CREATING HELLO WORLD APPLET
Let’s begin with the HelloWorld applet :
import [Link];
import [Link];
// HelloWorld class extends Applet
public class HelloWorld extends Applet {
// Overriding paint() method
@Override public void paint(Graphics g) {
[Link]("Hello World", 20, 20); }

Q:--APPLET CLASS
For Creating any applet in Java, we use the [Link] class. It has four
Methods in its Life Cycle of Java Applet. The applet can be executed using the applet
viewer utility provided by JDK. A Java Applet was created using the Applet class, i.e.,
part of the [Link] package.
The Applet class provides a standard interface between applets and their environment.
The Applet class is the superclass of an applet that is embedded in a Web page or
viewed by the Java Applet Viewer.
In Java, there are two types of Applet
1-Java Applets based on the AWT(Abstract Window Toolkit) packages by extending its
Applet class
2- Java Applets is based on the Swing package by extending its JApplet Class in it.
Now We See The Life Cycle of an Applet and its Methods-
How to run an Applet?
There are two ways to execute a Java Applet:
• By using an HTML file
• By using the appletviewer tool

54 | P a g e
Q:---APPLET LIFE CYCLE
The applet life cycle in Java describes the sequence of states an applet
goes through from its creation to its destruction. This cycle is managed by
the browser or applet viewer, which automatically invokes specific methods
at appropriate times.
The key methods defining the applet life cycle are:
• init():
• This method is called only once when the applet is first loaded
into memory.
It is used for initialization tasks, such as setting up the user

interface, initializing variables, or loading resources.
• start():
• Called after init(), and also whenever the applet becomes active
again (e.g., when the user navigates back to the page containing
the applet).
Used to start or resume the applet's execution, such as starting

threads or animations.
• paint(Graphics g):
• This method is responsible for drawing the applet's visual content
on the screen.
• It is called whenever the applet needs to be repainted, such as
when it is first displayed, resized, or uncovered.
The Graphics object provides methods for drawing shapes, text,

and images.
• stop():
• Called when the applet is no longer active (e.g., when the user
navigates away from the page or minimizes the browser window).
Used to pause or suspend the applet's operations, such as

stopping threads or releasing temporary resources.
• destroy():
• This method is called only once when the applet is about to be
removed from memory (e.g., when the browser is closed or the
applet's page is completely unloaded).
• Used for final cleanup, such as releasing resources and
performing any necessary finalization.

55 | P a g e
Q:----GRAPHICS IN APPLET AWT
In AWT (Abstract Window Toolkit) in Java, graphics are handled primarily
through the [Link] class. This abstract class provides a set of
methods for drawing various shapes, text, and images onto GUI components
like Frame, Panel, or Canvas.
Key Concepts:
• Graphics Context:
The Graphics object represents a drawing surface, also known as a graphics
context. It encapsulates information about the drawing environment, such as the
current color, font, and clipping region.
• Painting:
Drawing operations in AWT are typically performed within a
component's paint(Graphics g) or update(Graphics g) method. These methods
are automatically invoked by the AWT system when a component needs to be
rendered or re-rendered. The Graphics object is passed as an argument to these
methods, allowing you to draw on the component.
• Drawing Methods:
The Graphics class offers numerous methods for drawing:
• Shapes: drawLine(), drawRect(), fillRect(), drawOval(), fillOval(), drawA
rc(), fillArc(), drawPolygon(), fillPolygon(), drawRoundRect(), fillRound
Rect(), draw3DRect(), fill3DRect().
• Text: drawString(), drawChars(), drawBytes().
• Images: drawImage().
• Managing Drawing Attributes:
• Color: setColor(Color c) sets the current drawing color.
• Font: setFont(Font font) sets the current font for text rendering.
• Clipping: setClip() and clipRect() define the area within which drawing
operations are visible.
• Translation: translate(int x, int y) changes the origin of the graphics
context, shifting subsequent drawing coordinates.

56 | P a g e
❖ EXAMPLE OF DRAWING IN AWT:
Java
import [Link].*;
import [Link].*;

public class MyDrawingApp extends Frame {

public MyDrawingApp() {
setTitle("AWT Graphics Example");
setSize(400, 300);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
setVisible(true);
}

@Override
public void paint(Graphics g) {
// Set color to blue
[Link]([Link]);
// Draw a filled rectangle
[Link](50, 50, 100, 70);

// Set color to red


[Link]([Link]);
// Draw a string
[Link]("Hello AWT Graphics!", 60, 150);

// Set color to green


[Link]([Link]);
// Draw an oval
[Link](200, 50, 80, 80);
}
public static void main(String[] args) {
new MyDrawingApp();}
}
57 | P a g e
Q:---EVENT HANDLING An event is a change in the state of an object
triggered by some action such as Clicking a button, Moving the cursor,
Pressing a key on the keyboard, Scrolling a page, etc. In Java,
the [Link] package provides various event classes to handle these
actions.
An event is a change in the state of an object triggered by some action such as
Clicking a button, Moving the cursor, Pressing a key on the keyboard,
Scrolling a page, etc. In Java, the [Link] package provides various
event classes to handle these actions.
Events in Java can be broadly classified into two categories based on how
they are generated:
1. Foreground Events: Foreground events are the events that require
user interaction to generate. Examples of these events include Button
clicks, Scrolling the scrollbar, Moving the cursor, etc.
2. Background Events: Events that don't require interactions of users to
generate are known as background events. Examples of these events
are operating system failures/interrupts, operation completion, etc.
EVENT HANDLING MECHANISM
Event handling is a mechanism that allows programs to control events and
define what should happen when an event occurs. Java uses the Delegation
Event Model to handle events. This model consists of two main components:
• Source: Events are generated from the source. There are various

sources like buttons, checkboxes, list, menu-item, choice, scrollbar,


text components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated from

the source. Each of these listeners represents interfaces that are


responsible for handling events.

58 | P a g e
Q:--- File Class
The File class in Java is used to represent the path of a file or folder. It helps
in creating, deleting, and checking details of files or directories, but not in
reading or writing data. It acts as an abstract representation of file and
directory names in the system.
• Can retrieve parent directories using the getParent() method.

• A File object is created by passing a file or directory name to its

constructor.
• File systems may impose access permissions (read, write, execute).

• File objects are immutable. Once created, their pathname cannot

change.
How to Create a File Object
A File object is created by passing in a string that represents the name
of a file, a String or another File object.
Syntax
File file = new File("path_to_file"
Q----BYTE STREAM
In Java, a byte stream is a sequence of data that handles input and output
operations of raw binary data in units of 8-bit bytes. These streams are
fundamental for low-level I/O operations and are particularly suitable for
handling binary files such as images, audio, video, and executable
files. Common Byte Stream Classes:
Key Characteristics:
• Byte-oriented: Byte streams read and write data one byte (8 bits) at a
time.
• Raw Data Handling: They are designed for processing raw binary data,
where character encoding is not a primary concern.
• Abstract Base Classes: All byte stream classes in Java are built upon
two abstract base classes:
o InputStream: Used for reading bytes from an input source.

o OutputStream: Used for writing bytes to an output destination.

59 | P a g e
Q--- RANDOM ACCESS FILE
Introduction
The Java RandomAccessFile class file behaves like a large array of bytes stored in the
file [Link] of this class support both reading and writing to a random access
file
Class declaration
Following is the declaration for [Link] class
public class RandomAccessFile extends Object implements DataOutput, DataInput,
Closeable

CLASS CONSTRUCTORS
[Link]. Constructor & Description

RandomAccessFile(File file, String mode)


1 This creates a random access file stream to read from, and optionally to
write to, the file specified by the File argument.

RandomAccessFile(File file, String mode)


2 This creates a random access file stream to read from, and optionally to
write to, a file with the specified name.

Q:--CHARACTER STREAM
In Java, characters are stored using Unicode conventions. Character stream
automatically allows us to read/write data character by character. For
example, FileReader and FileWriter are character streams used to read from
the source and write to the destination.
Byte Stream
A byte stream in Java is a stream that handles input and output of raw 8-bit
binary data. It is mainly used for reading and writing non-text data such as
images, audio, video or any binary file. For example, FileInputStream is used
to read from the source and FileOutputStream to write to the destination.

60 | P a g e

You might also like