0% found this document useful (0 votes)
29 views

UNIT I-1 java

Easy
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)
29 views

UNIT I-1 java

Easy
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
You are on page 1/ 48

UNIT I

Introduction: Review of Object Oriented concepts- History of Java-Java buzz words-JVM


architecture- Data types-Variables-Scope and life time of variables -arrays-operators-control
statements- type conversion and casting-simple java program- constructors-methods-Static block-Static
Data- Static Method String and String Buffer Classes.

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

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

UNIT IV
AWT Controls: The AWT class hierarchy- user interface components-Labels-Button- Text
Components - Check Box - Check Box Group - Choice -List Box - Panels – Scroll Pane - Menu -
Scroll Bar. Working with Frame class - Colour - Fonts and layout managers.
Event Handling: Events-Event sources-Event Listeners - Event Delegation Model (EDM) – Handling
Mouse and Keyboard Events - Adapter classes – Inner classes

UNIT V
Swing: Introduction to Swing- Hierarchy of swing components. Containers- Top level containers-
JFrame-JWindow - JDialog - JPanel - JButton - JToggleButton -JCheckBox- JRadio Button- JLabel,
JTextField- JTextArea- JList- JComboBox- JScrollPane.

TextBooks:
1. HerbertSchildt,The CompleteReference,TataMcGraw Hill, New Delhi,7thEdition,2010
2. GaryCornell,CoreJava2VolumeI–Fundamentals,AddisonWesley,1999
References:
1. HeadFirstJava,O‘RiellyPublications,
2. Y.DanielLiang,IntroductiontoJavaProgramming,7thEdition,PearsonEducationIndi a,2010
UNIT I
Introduction: Review of Object-Oriented Concepts

➢ Object-Oriented Programming (OOP) is a programming paradigm based on the concept


of "objects." These objects represent real-world entities and can have attributes (data)
and behaviors (functions or methods).
➢ OOP is widely used in modern programming languages like Java, Python, C++, and
others.
➢ This introduction will review the core concepts of OOP:

1. Class: A class is a blueprint for creating objects. It defines the structure (attributes) and
behavior (methods) that the objects created from the class will have. For example, a class "Car"
might define attributes like color and model, and methods like drive() and brake().

2. Object: An object is an instance of a class. It holds the actual data and methods defined by the
class. Multiple objects can be created from a single class, each with its own unique set of data.
3. Encapsulation: This concept involves bundling the data (attributes) and methods (functions)
that operate on the data into a single unit or class. Encapsulation also ensures that the data
within a class is protected from unauthorized access by hiding its internal details, often
achieved by using access modifiers like private, protected, and public.

4. Inheritance: Inheritance allows a class to inherit attributes and methods from another class.
This promotes code reuse and hierarchical classification. For instance, a "Truck" class can
inherit from a "Vehicle" class, gaining its attributes and methods, while also having unique
features of its own.

5. Polymorphism: Polymorphism enables a single function or method to behave differently based


on the object that invokes it. There are two types:
o Compile-time polymorphism (method overloading): Same method name but different
parameters.
o Run-time polymorphism (method overriding): A subclass can provide a specific
implementation of a method already defined in its superclass.

6. Abstraction: Abstraction hides the complex implementation details of an object and exposes
only the necessary parts. This is typically achieved through abstract classes and interfaces,
allowing users to work with high-level entities without knowing the internal complexities.
These fundamental concepts form the foundation of OOP, allowing for modular, reusable, and
maintainable code, which is especially beneficial in large-scale software development.

History of Java
➢ Java is a high-level, object-oriented programming language initially developed by Sun
Microsystems (now owned by Oracle Corporation) in 1995. The language has undergone
significant evolution since its inception and remains one of the most popular programming
languages in the world today. Here's a brief history of Java:
1. 1991: The Origins - The Green Team
✓ Java was originally developed as part of a project called Green Project led by James
Gosling, along with Mike Sheridan and Patrick Naughton.
✓ The team wanted a platform-independent language that could run on any type of device.
Initially, they called the language Oak, after an oak tree outside Gosling's office.
However, the name was later changed to Java due to a trademark conflict.

2. 1995: The Release of Java 1.0

✓ Java was officially released in 1995. The language was promoted with the tagline
"Write Once, Run Anywhere" (WORA), signifying its ability to run on any device that
had a Java Virtual Machine (JVM). This platform independence was made possible
through the bytecode system, which allowed Java programs to be compiled once and
run anywhere.
✓ Java 1.0 was widely adopted by web developers, as it allowed them to create dynamic
content using Java applets that could run within a web browser.

3. Late 1990s: Java’s Growth

✓ Java gained widespread popularity during the late 1990s due to the rise of the Internet.
It was widely used for creating web applications and applets. Around this time, Sun
Microsystems released various versions of Java, including:
• Java 1.1 (1997): Introduced event handling, JDBC (Java Database
Connectivity), and inner classes.
• Java 2 (1998): This version marked a major upgrade, bringing in the
concept of multiple configurations for different platforms, such as J2SE
(Java 2 Standard Edition), J2EE (Java 2 Enterprise Edition), and J2ME
(Java 2 Micro Edition).
4. 2000s: Enterprise Adoption and J2EE

✓ By the early 2000s, Java had become the standard for enterprise-level applications,
particularly with the introduction of Java 2 Enterprise Edition (J2EE), which
provided a robust platform for developing distributed, scalable, and secure applications.
✓ The adoption of Java for server-side programming allowed for the development of
large-scale web applications and enterprise systems. Java's reliability, security features,
and scalability contributed to its dominance in the industry.
5. 2004: Java 5.0 (J2SE 5.0)

✓ Java 5.0 (also known as J2SE 5.0 or Java 1.5) brought several significant language
improvements, such as:
o Generics
o Enhanced for loop
o Autoboxing/Unboxing
o Enums
o Varargs These additions improved developer productivity and made the language more
expressive.
6. 2006: OpenJDK and the Evolution to Java SE

✓ In 2006, Sun Microsystems announced the OpenJDK project, which made Java's
source code available to the public under the GNU General Public License (GPL).
✓ This step encouraged greater community involvement and innovation.
Around this time, Sun rebranded J2SE and J2EE as Java Standard Edition (Java SE)
and Java Enterprise Edition (Java EE), respectively.
7. 2010: Oracle Acquisition

✓ In 2010, Oracle Corporation acquired Sun Microsystems, including Java. Oracle


continued to develop Java and made several enhancements to the language, tools, and
JVM.
✓ Subsequent releases of Java, such as Java 7 (2011), Java 8 (2014), and Java 9 (2017),
introduced new features like:
o Lambda Expressions (Java 8)
o Stream API (Java 8)
o Modularization (Project Jigsaw) (Java 9)
8. Recent Developments: Java 10 and Beyond

✓ Java has moved to a more rapid release cycle, with a new version released every six
months. Notable versions include:
✓ Java 11 (2018): The first long-term support (LTS) release under Oracle's new cadence.
It included new features like the var keyword for local variables and the removal of
some deprecated features.
✓ Java 17 (2021): Another LTS release, introducing new features such as sealed classes
and pattern matching for switch expressions.
Java Buzzwords
❖ Java, from its inception, has been associated with a series of key "buzzwords" that define its
philosophy and features. These buzzwords highlight the core strengths of the language and
explain why Java is so widely used. Here's a review of the main Java buzzwords:
1. Simple:
Java was designed to be easy to learn and use. It simplified many complex features of
languages like C and C++ by removing explicit pointers, operator overloading, and multiple
inheritance. Java’s syntax is also clean and closely resembles C++, which makes it familiar to
many developers.
2. Object-Oriented:
Everything in Java is based on objects, which makes the language intuitive and flexible for
solving real-world problems. It supports the four fundamental OOP principles—encapsulation,
inheritance, polymorphism, and abstraction.
3. Platform-Independent:
Java achieves platform independence through the Java Virtual Machine (JVM) and bytecode.
When a Java program is compiled, it is transformed into bytecode, which can run on any
system with a JVM, regardless of the underlying hardware or operating system. This concept is
known as Write Once, Run Anywhere (WORA).
4. Secure:
Java places a strong emphasis on security. It provides a security manager that controls access to
resources (like files, network, memory) at runtime. Java’s runtime environment also includes
automatic memory management and strong type-checking, helping prevent common security
vulnerabilities like memory leaks or buffer overflow attacks.
5. Robust:
Java was designed with reliability in mind. It emphasizes strong memory management by
incorporating features like garbage collection and exception handling. Java’s type-checking
mechanism ensures fewer errors, and runtime checks help identify bugs early.
6. Multithreaded:
Java natively supports multithreading, allowing multiple threads to run concurrently within a
program. This makes it easier to develop applications that perform multiple tasks
simultaneously, such as handling multiple user requests in a web server or performing
background operations.
7. Architecture-Neutral:
Java’s bytecode is designed to be neutral with respect to architecture, meaning that it doesn’t
depend on any specific processor or operating system. This allows Java programs to run on any
platform with a compatible JVM.
8. Interpreted:
Java programs are compiled into bytecode, which is interpreted by the JVM. This intermediate
step allows Java to be platform-independent and makes the program execution faster than
traditional interpreted languages while ensuring portability.
9. High Performance:
While Java may not be as fast as languages like C or C++ due to the overhead of bytecode
interpretation, techniques like Just-In-Time (JIT) compilation, where bytecode is compiled
into native machine code at runtime, have significantly improved Java’s performance over
time.
10. Distributed:
Java provides built-in support for developing distributed applications. It comes with libraries
such as Remote Method Invocation (RMI) and supports networking through its extensive
API, which allows Java programs to communicate over the network.
11. Dynamic:
Java is designed to adapt to an evolving environment. It supports dynamic loading of classes,
meaning that new modules can be loaded at runtime without restarting the application. Java
also supports reflection, enabling the inspection and manipulation of classes and objects at
runtime.
12. Portable:
Since Java eliminates many system-dependent features (like pointer arithmetic in C/C++) and
defines platform-independent data types (e.g., the size of int is always 32 bits), it ensures that
Java applications are highly portable across different platforms.

Java Virtual Machine (JVM) Architecture


❖ The Java Virtual Machine (JVM) is the heart of Java’s platform independence.
❖ It provides an execution environment for Java bytecode, which is compiled from Java source
code.
❖ The JVM is responsible for converting the platform-independent bytecode into machine code,
allowing the same Java program to run on different devices and operating systems.

Here’s an overview of the JVM architecture, broken down into key components:

1. ClassLoader
• Role: The ClassLoader is responsible for loading class files into memory during runtime. Java
programs are compiled into .class files containing bytecode, which the ClassLoader brings into
the JVM.
• Functions:
o Loading: It loads classes from different sources like local file systems, remote servers,
or JAR files.
o Linking: This step verifies the bytecode and prepares the class for execution.
o Initialization: This involves assigning default values to static variables and invoking
static blocks.
• Types of Class Loaders:
o Bootstrap ClassLoader: Loads core Java libraries (like java.lang).
o Extension ClassLoader: Loads classes from the Java Extensions directory.
o Application ClassLoader: Loads application-level classes.

2. Runtime Data Areas


❖ These are the memory areas used by the JVM during program execution. They are created
when the JVM starts and destroyed when the JVM shuts down.

• Method Area:
The Method Area stores class-level information, including the runtime constant pool
(constants, method and field data), code for methods, and constructors.
• Heap:
The Heap is the memory area where all Java objects are stored. It’s shared among all threads.
Objects created using new are stored here. Garbage Collection (GC) is responsible for
reclaiming memory from unused objects in the heap.
• Stack:
Each thread in the JVM has its own stack. The stack holds frames, where each frame contains
local variables, method calls, and partial results. The stack grows and shrinks as methods are
invoked and return.
• Program Counter (PC) Register:
Each thread has its own PC register, which keeps track of the current instruction being executed
by that thread. It holds the address of the current instruction in the bytecode.
• Native Method Stack:
This stack holds native (non-Java) methods written in other languages like C or C++. JNI (Java
Native Interface) allows the JVM to invoke such methods.

3. Execution Engine

❖ The Execution Engine is responsible for executing the bytecode loaded by the ClassLoader. It
converts bytecode into machine code and handles the actual execution of instructions.

• Interpreter:
The interpreter executes the bytecode line-by-line. While it's fast to start, interpreting bytecode
can be slow for frequently executed code.
• Just-In-Time (JIT) Compiler:
The JIT compiler improves performance by compiling frequently executed bytecode (hotspots)
into native machine code at runtime. Once compiled, the native code runs faster than
interpreting the bytecode repeatedly.
• Garbage Collector (GC):
The GC is responsible for automatic memory management. It reclaims memory used by objects
that are no longer referenced by the application, ensuring efficient use of the heap memory.
• Java Native Interface (JNI):
JNI provides a way for the JVM to call or be called by native applications and libraries written
in languages like C and C++. This is often used when interfacing with system-level resources.

4. Native Method Libraries


❖ Java’s platform independence is enhanced by native method libraries, which allow the JVM to
interface with underlying system resources.
❖ These libraries are platform-dependent and help execute native methods via the Native Method
Interface.
❖ For example, I/O operations like file handling, which depend on the operating system, are
managed through these libraries.

JVM Execution Flow:

1. Class Loading: When a Java program starts, the ClassLoader loads the necessary class files
into memory.
2. Bytecode Verification: The bytecode verifier ensures that the code adheres to Java's security
constraints and will not harm the JVM or the system it is running on.
3. Execution: The Execution Engine starts interpreting or compiling the bytecode into native
code. During execution, it can switch between interpreting and JIT compilation to optimize
performance.
4. Garbage Collection: The GC periodically frees up memory by reclaiming space from objects
that are no longer in use, ensuring efficient memory management.

Diagram of JVM Architecture:

Class Loader

Method Area
Heap

Stack Program Counter Native Method Stack

Execution Engine
(Interpreter, JIT, GC)

Native Method Libraries

Variables

❖ Variable is a named memory location used to store data. Each variable has a specific data type
that determines what kind of values it can hold and what operations can be performed on it.
❖ Variables in Java must be declared before they are used, and they can store different types of
data such as integers, floating-point numbers, characters, and more.
Types of Variables in Java
1. Instance Variables (Non-static Fields):
o Defined within a class but outside of any method, constructor, or block.
o Every instance of the class (object) has its own copy of instance variables.
o These variables are associated with objects, so they are also known as object-level
variables.
o Lifetime: They exist as long as the object exists.
o Default Values: They are assigned default values if not initialized explicitly.
Example:
class Example {

int instanceVar = 10; // Instance variable

2. Static Variables (Class Variables):

• Declared with the static keyword.


• They belong to the class rather than any individual object, meaning all objects share the same
static variable.
• Lifetime: Static variables exist for the entire lifetime of the class.
• Default Values: Like instance variables, static variables also have default values if not
initialized.

Example:

class Example {

static int staticVar = 20; // Static variable

}
3. Local Variables:

• Declared inside a method, constructor, or block.


• They are only accessible within the scope in which they are defined.
• Local variables do not have default values, so they must be initialized before use.
• Lifetime: They exist only during the execution of the method or block in which they are
declared.
Example:
class Example {
void method() {
int localVar = 30; // Local variable
}
}

4. Parameters:

• Variables declared in the method signature are called parameters. They act as inputs to
methods.

Example:
class Example {
void method(int paramVar) { // Parameter variable
System.out.println(paramVar);
}
}
Declaration and Initialization of Variables
❖ Variables in Java are declared by specifying the data type followed by the variable name.
Optionally, the variable can also be initialized with a value.

Syntax:
dataType variableName = value;
Example:
int age = 25; // Declaration and initialization
float price; // Declaration only
price = 99.99f; // Initialization later

What is Declaration and Initialization?


• Declaration of a variable in a computer programming language is a statement used to specify the
variable name and its data type. Declaration tells the compiler about the existence of an entity in
the program and its location. When you declare a variable, you should also initialize it.
• Initialization is the process of assigning a value to the Variable. Every programming language has
its own method of initializing the variable. If the value is not assigned to the Variable, then the
process is only called a Declaration.

Variable Naming Rules

• Variable names must start with a letter (a-z, A-Z), a dollar sign ($), or an underscore (_).
• Subsequent characters can be letters, digits (0-9), underscores, or dollar signs.
• Java is case-sensitive, so age and Age are different variables.
• Keywords cannot be used as variable names (e.g., int class; is invalid).

Scope and Lifetime of Variables

• Instance Variables: Accessible throughout the class in instance methods and exist as long as
the object exists.
• Static Variables: Accessible throughout the class and across objects, existing as long as the
class is loaded into memory.
• Local Variables: Their scope is limited to the block, method, or constructor in which they are
declared, and they exist only during the execution of that block.

Example: Variable Declaration in Java


class Example {
int instanceVar = 10; // Instance variable
static int staticVar = 20; // Static variable
void display() {
int localVar = 30; // Local variable
System.out.println("Instance Variable: " + instanceVar);
System.out.println("Static Variable: " + staticVar);
System.out.println("Local Variable: " + localVar);
}
public static void main(String[] args) {
Example obj = new Example();
obj.display();
}
}
Output:
Instance Variable: 10
Static Variable: 20
Local Variable: 30

Key Points

• Instance Variables: Unique to each object, shared across instance methods.


• Static Variables: Shared across all objects of the class.
• Local Variables: Temporary and exist only during method/block execution.
• Scope: Defines where the variable can be accessed, and its lifetime depends on the type of
variable.
Data Types in Java
❖ In Java, data types specify the type of values that variables can hold. They are divided into two
main categories: Primitive Data Types and Reference Data Types.

1. Primitive Data Types

❖ Primitive data types are the most basic data types that Java provides.
❖ These are predefined by the language and named by a keyword.
❖ They are used to store simple values. There are eight primitive data types in Java:

a. Integer Types
• byte:
o Size: 1 byte (8 bits)
o Range: -128 to 127
o Use case: Useful for saving memory in large arrays.
• short:
o Size: 2 bytes (16 bits)
o Range: -32,768 to 32,767
o Use case: Also used to save memory, like byte, but has a larger range.
• int:
o Size: 4 bytes (32 bits)
o Range: -2^31 to 2^31 - 1 (-2,147,483,648 to 2,147,483,647)
o Use case: Most commonly used for representing integers in Java.
• long:
o Size: 8 bytes (64 bits)
o Range: -2^63 to 2^63 - 1
o Use case: Used when a wider range of integers is needed (e.g., for large calculations).

b. Floating-Point Types
• float:
o Size: 4 bytes (32 bits)
o Range: Approximately ±3.40282347E+38F (7 decimal digits)
o Use case: Useful for saving memory in large arrays of floating-point numbers,
especially when high precision isn't required.
• double:
o Size: 8 bytes (64 bits)
o Range: Approximately ±1.79769313486231570E+308 (15 decimal digits)
o Use case: Default type for decimal values; used when precision is important.

c. Character Type
• char:
o Size: 2 bytes (16 bits)
o Range: 0 to 65,535 (represents Unicode characters)
o Use case: Used to store a single character. It can store any character, including letters,
digits, or special symbols.

d. Boolean Type
• boolean:
o Size: Not precisely defined (typically 1 bit, but implementation-specific)
o Values: true or false
o Use case: Used to represent logical values (i.e., true/false conditions). Often used in
conditional statements and loops.

2. Reference Data Types


❖ Reference data types refer to objects and are created using constructors.
❖ Unlike primitive types, reference types do not store the actual value; they store a reference (or
address) to the value.
❖ They can also point to complex data structures like arrays, classes, and interfaces.

a. Classes:
• A class is a blueprint for creating objects. Objects of a class can store data (attributes) and have
methods (functions).
• Example: String class stores sequences of characters. Example: String name = "Java";
b. Interfaces:
• An interface is a contract that classes can implement. It specifies what methods a class should
implement but not the implementation itself.
• Example: List is an interface that is implemented by classes like ArrayList and LinkedList.
c. Arrays:
• Arrays are objects that store multiple values of the same type in a contiguous memory location.
They can be primitive types or reference types.
• Example: int[] numbers = {1, 2, 3, 4};

Summary Table of Primitive Data Types:

Data Type Size Default Value Range / Values Use Case


byte 1 byte 0 -128 to 127 Small integers, memory-saving
short 2 bytes 0 -32,768 to 32,767 Larger ranges than byte
int 4 bytes 0 -2,147,483,648 to 2,147,483,647 Most common integer type
long 8 bytes 0L -2^63 to 2^63 - 1 Very large integer values
Data Type Size Default Value Range / Values Use Case
float 4 bytes 0.0f ~7 decimal digits precision Floating-point numbers
double 8 bytes 0.0d ~15 decimal digits precision Precise floating-point numbers
char 2 bytes '\u0000' 0 to 65,535 Single characters, Unicode
boolean 1 bit false true, false Logical conditions

Summary of Reference Data Types:


• Class: Template for creating objects.
• Interface: Contract that specifies methods to be implemented.
• Array: A collection of elements of the same type.

Scope and Lifetime of Variables in Java


❖ In Java, the scope of a variable refers to the region of the program where the variable is
accessible, and the lifetime refers to the duration during which the variable exists in memory.
❖ Understanding the scope and lifetime of variables is important to manage data access and
resource usage efficiently.

1. Types of Variable Scope in Java

a. Local Variables
• Definition: A local variable is declared inside a method, constructor, or block.
• Scope: The variable is accessible only within the method, constructor, or block where it is
declared.
• Lifetime: Local variables are created when the method or block is invoked and destroyed when
the method or block is exited.

Example:

java
Copy code
public void exampleMethod() {
int localVar = 10; // Local variable
System.out.println(localVar);
}
In this example, localVar exists only within the exampleMethod and cannot be accessed outside
of it.
b. Instance Variables (Non-Static Fields)
• Definition: Instance variables are declared inside a class but outside any method or constructor.
They are also known as fields.
• Scope: Instance variables are accessible by all methods, constructors, and blocks of the class in
which they are declared. Each object of the class has its own copy of the instance variables.
• Lifetime: The lifetime of instance variables coincides with the lifetime of the object. They are
created when the object is created (instantiated) and destroyed when the object is destroyed
(garbage collected).

Example:

public class MyClass


{
int instanceVar = 5; // Instance variable
public void printValue()
{
System.out.println(instanceVar); // Accessible within the class
}
}

Here, instanceVar is an instance variable, and it will be accessible by all methods within the
class MyClass.
c. Static Variables (Class Variables)

• Definition: Static variables are declared with the static keyword inside a class but outside any
method or constructor.
• Scope: Static variables are accessible by all methods (both static and non-static) and
constructors of the class. Unlike instance variables, static variables are shared among all
instances of the class.
• Lifetime: Static variables are created when the class is first loaded into memory (when it is
used for the first time) and destroyed when the class is unloaded (typically when the JVM shuts
down).

Example:
public class MyClass
{
static int staticVar = 10; // Static variable
public static void main(String[] args)
{
System.out.println(staticVar); // Accessible throughout the class
}
}

In this example, staticVar is a static variable shared by all objects of the class MyClass.

d. Block Variables
• Definition: Block variables are declared inside a block of code, such as a loop or an if
statement.
• Scope: They are accessible only within the block where they are declared.
• Lifetime: Block variables exist only for the duration of the block execution.

Example:

public void exampleMethod()


{
for (int i = 0; i < 5; i++)
{ // `i` is a block variable
System.out.println(i);
}
// `i` is not accessible here
}
2. Lifetime of Variables

• Local Variables: Exist only during the execution of the method, block, or constructor where
they are declared. Memory is allocated when the block is entered and freed when the block is
exited.
• Instance Variables: Exist as long as the object they belong to exists. Memory for instance
variables is allocated when an object is instantiated and freed when the object is destroyed
(garbage collected).
• Static Variables: Exist for the lifetime of the class in which they are declared. Memory for
static variables is allocated when the class is loaded into memory and is freed when the class is
unloaded (usually when the program terminates).

Example: Combining Scopes

public class ScopeExample


{
static int staticVar = 100; // Static variable (class-level)
int instanceVar = 50; // Instance variable (object-level)
public void methodExample()
{
int localVar = 20; // Local variable (method-level)
if (localVar == 20)
{
int blockVar = 10; // Block variable (block-level)
System.out.println("Block variable: " + blockVar);
}
// blockVar is not accessible here
}
public static void main(String[] args)
{
ScopeExample obj = new ScopeExample(); // Object creation
obj.methodExample(); // Method call
System.out.println("Static variable: " + staticVar); // Accessible from static context
System.out.println("Instance variable: " + obj.instanceVar); // Accessible via object
reference
}
}
In this example:
• staticVar is a static variable, accessible throughout the class.
• instanceVar is an instance variable, tied to each object of ScopeExample.
• localVar is a local variable, confined to methodExample().
• blockVar is a block variable, confined to the if block.

Arrays in Java
❖ An array in Java is a collection of elements of the same data type stored in contiguous memory
locations.
❖ Arrays provide a way to store multiple values in a single variable, making it easier to work with
groups of related data.
Key Characteristics of Arrays:
• Fixed Size: The size of the array is specified when it's created and cannot be changed.
• Homogeneous Elements: All elements in an array must be of the same data type (e.g., int[] can
only hold integers).
• Indexing: Elements in the array are accessed by their index, starting from 0.

Types of Arrays
1. Single-Dimensional Arrays
2. Multi-Dimensional Arrays (e.g., 2D Arrays)

1. Single-Dimensional Arrays
❖ A single-dimensional array is the most basic form of an array, where data is stored in a single
row.

Declaration and Initialization:


// Declaration
int[] arr; // Declares an array variable
// Initialization
arr = new int[5]; // Allocates memory for 5 integers
// Declaration and Initialization together
int[] arr = new int[5]; // Array of 5 integers
// Initializing with values
int[] arr = {1, 2, 3, 4, 5}; // Array with 5 elements
Accessing Elements:
Array elements are accessed using their index. Indexes in Java arrays start at 0 and go up to length - 1.
int[] arr = {10, 20, 30, 40, 50};
System.out.println(arr[0]); // Output: 10
System.out.println(arr[4]); // Output: 50

Modifying Elements:
You can modify elements in an array by assigning new values using their index.
arr[2] = 100; // Changes the third element (index 2) to 100
Example:

public class ArrayExample


{
public static void main(String[] args)
{
int[] numbers = {1, 2, 3, 4, 5};
// Accessing elements
System.out.println("First element: " + numbers[0]);
// Changing an element
numbers[2] = 10;
System.out.println("Modified third element: " + numbers[2]);
// Loop through the array
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}

2. Multi-Dimensional Arrays
❖ A multi-dimensional array in Java is essentially an array of arrays.
❖ The most commonly used type is the two-dimensional array, which is like a matrix (rows and
columns).

Declaration and Initialization:

// Declaration
int[][] matrix;
// Initialization
matrix = new int[3][4]; // 3 rows, 4 columns
// Declaration and Initialization together
int[][] matrix = new int[3][4]; // A 2D array with 3 rows and 4 columns
// Initializing with values
int[][] matrix =
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Accessing Elements:
❖ Elements in a two-dimensional array are accessed using two indices: one for the row and one
for the column.

System.out.println(matrix[0][1]); // Accesses the element at row 0, column 1 (Output: 2)

Example:

public class TwoDArrayExample


{
public static void main(String[] args)
{
int[][] matrix =
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing an element
System.out.println("Element at [0][1]: " + matrix[0][1]);
// Loop through the array
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // New line after each row
}
}
}

Common Operations on Arrays:


1. Finding Length of an Array: Use the .length property to get the number of elements in an
array.
int[] arr = {1, 2, 3, 4, 5};
System.out.println("Length: " + arr.length); // Output: 5

2. Traversing Arrays: Arrays can be traversed using loops, such as for, for-each, or while loops.
• For Loop:
for (int i = 0; i < arr.length; i++)
{
System.out.println(arr[i]);
}
• Enhanced For Loop (For-Each Loop):
for (int num : arr)
{
System.out.println(num);
}
3. Copying Arrays: Arrays can be copied using built-in methods like System.arraycopy().

int[] source = {1, 2, 3};


int[] destination = new int[3];
System.arraycopy(source, 0, destination, 0, source.length);

4. Sorting Arrays: Java provides utility methods in the Arrays class for sorting.

int[] arr = {3, 1, 4, 1, 5};


Arrays.sort(arr);

Limitations of Arrays:
• Fixed Size: Once an array's size is defined, it cannot be changed. If you need a dynamically
resizable array, consider using collections like ArrayList.
• Homogeneous: Arrays can only hold elements of the same type. For heterogeneous collections
of objects, you can use Object[] or collections.

Summary:
• Single-Dimensional Arrays: A list of elements of the same type stored in contiguous memory.
• Multi-Dimensional Arrays: Arrays of arrays, useful for representing data in a tabular form.
• Common Operations: Access, modify, traverse, copy, and sort arrays.
• Limitations: Fixed size, homogeneous elements. For more flexibility, Java collections like
ArrayList can be used.

Operators in Java
➢ Operators in Java are symbols that perform operations on variables and values.
➢ Java provides several types of operators for different tasks like arithmetic calculations,
logical decisions, comparisons, and more.
➢ Operators are divided into several categories:

1. Arithmetic Operators
These operators are used to perform basic arithmetic calculations.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (Remainder) a%b
Example:
int a = 10;
int b = 5;
System.out.println(a + b); // Output: 15
System.out.println(a % b); // Output: 0

2. Relational (Comparison) Operators


➢ These operators are used to compare two values. The result is always true or false.
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
Example:
int a = 10;
int b = 20;
System.out.println(a == b); // Output: false
System.out.println(a < b); // Output: true

3. Logical Operators
➢ Logical operators are used to combine multiple conditions (boolean expressions).
Operator Description Example
&& Logical AND a && b
` `
! Logical NOT !a
Example:
boolean a = true;
boolean b = false;
System.out.println(a && b); // Output: false
System.out.println(a || b); // Output: true
System.out.println(!a); // Output: false

4. Assignment Operators
➢ Assignment operators are used to assign values to variables.
Operator Description Example
= Assign a=b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
Example:
int a = 10;
a += 5; // Equivalent to a = a + 5
System.out.println(a); // Output: 15

5. Unary Operators
➢ Unary operators are used with a single operand to perform operations like increment,
decrement, negation, etc.
Operator Description Example
+ Unary plus (positive) +a
- Unary minus (negative) -a
++ Increment (pre/post) ++a, a++
-- Decrement (pre/post) --a, a--
! Logical negation !a
Example:
int a = 10;
System.out.println(++a); // Output: 11 (Pre-increment)
System.out.println(a--); // Output: 11 (Post-decrement)
System.out.println(a); // Output: 10
6. Bitwise Operators
➢ Bitwise operators perform operations on bits (binary digits) of integer types.
Operator Description Example
& Bitwise AND a&b
` ` Bitwise OR
^ Bitwise XOR a^b
~ Bitwise NOT ~a
<< Left shift a << 2
>> Right shift a >> 2
>>> Unsigned right shift a >>> 2
Example:
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
System.out.println(a & b); // Output: 1 (0001 in binary)
System.out.println(a | b); // Output: 7 (0111 in binary)

7. Ternary Operator
➢ The ternary operator is a shorthand for an if-else statement. It takes three operands and
evaluates a condition.
Operator Description Example
?: Ternary (conditional) operator condition ? expr1 : expr2
Example:
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
System.out.println(max); // Output: 20

8. Instanceof Operator
➢ The instanceof operator checks if an object is an instance of a specific class or interface.

Example:
String s = "Hello";
System.out.println(s instanceof String); // Output: true
Summary of Java Operators:
• Arithmetic Operators: Perform basic mathematical operations like addition and
multiplication.
• Relational Operators: Compare two values and return a boolean result.
• Logical Operators: Combine boolean expressions to form complex conditions.
• Assignment Operators: Assign values to variables.
• Unary Operators: Operate on a single operand, often used for incrementing or negating
values.
• Bitwise Operators: Perform bit-level operations on integer types.
• Ternary Operator: A concise way to make decisions (if-else).
• Instanceof Operator: Checks if an object is an instance of a class.

Control Statements in Java


➢ Control statements in Java allow developers to control the flow of execution based on certain
conditions, loops, or jumps.
➢ These statements help create logical decisions, repeat certain code blocks, or exit from loops
and methods when necessary.

Types of Control Statements:


1. Decision-Making Statements
o if
o if-else
o if-else-if
o switch
2. Looping Statements
o for
o while
o do-while
o Enhanced for (for-each)
3. Jump Statements
o break
o continue
o return

1. Decision-Making Statements

a. if Statement
The if statement executes a block of code if the given condition is true.
if (condition)
{
// Code to execute if condition is true
}

Example:
int number = 10;
if (number > 5)
{
System.out.println("Number is greater than 5.");
}

b. if-else Statement
The if-else statement provides an alternative block of code to execute if the condition is false.
if (condition)
{
// Code if condition is true
} else
{
// Code if condition is false
}
Example:
int number = 10;
if (number > 15)
{
System.out.println("Number is greater than 15.");
} else
{
System.out.println("Number is not greater than 15.");
}

c. if-else-if Ladder
This statement is used to check multiple conditions one after another.
if (condition1)
{
// Code if condition1 is true
} else if (condition2)
{
// Code if condition2 is true
} else
{
// Code if none of the conditions are true
}
Example:
int score = 85;
if (score >= 90)
{
System.out.println("A");
} else if (score >= 80)
{
System.out.println("B");
} else if (score >= 70)
{
System.out.println("C");
} else
{
System.out.println("Fail");
}
d. switch Statement
The switch statement is used to select one of many code blocks to execute based on the value of
a variable.
switch (variable)
{
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
// More cases...
default:
// Default code if no case matches
}

Example:
int day = 2;
switch (day)
{
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
2. Looping Statements

a. for Loop
The for loop is used to execute a block of code a specific number of times.
for (initialization; condition; update)
{
// Code to execute in each iteration
}

Example:

for (int i = 0; i < 5; i++)


{
System.out.println("Iteration: " + i);
}
b. while Loop
The while loop continues to execute a block of code as long as the specified condition is true.

while (condition)
{
// Code to execute while condition is true
}

Example:
int i = 0;
while (i < 5)
{
System.out.println("i: " + i);
i++;
}
c. do-while Loop
The do-while loop is similar to the while loop, except that it guarantees that the loop will
execute at least once, even if the condition is false.
do
{
// Code to execute
} while (condition);
Example:
int i = 0;
do
{
System.out.println("i: " + i);
i++;
} while (i < 5);

d. Enhanced for Loop (for-each)


The enhanced for loop (for-each) is used to iterate over arrays or collections.
for (type variable : array)
{
// Code to execute for each element
}
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers)
{
System.out.println(number);
}

3. Jump Statements

a. break Statement
The break statement is used to exit a loop or switch statement immediately.
Example (in a loop):
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit the loop when i is 5
}
System.out.println(i);
}

b. continue Statement
The continue statement skips the current iteration of a loop and continues with the next
iteration.
Example:
for (int i = 0; i < 5; i++)
{
if (i == 2)
{
continue; // Skip the rest of the loop body when i is 2
}
System.out.println(i);
}
c. return Statement
The return statement exits from the current method and can return a value if needed.
Example:
public int add(int a, int b)
{
return a + b; // Return the sum of a and b
}
Summary:
• Decision-Making Statements: Control the flow based on conditions (if, if-else, switch).
• Looping Statements: Repeat code based on conditions (for, while, do-while).
• Jump Statements: Interrupt normal flow by jumping to another point (break, continue, return).

Type Conversion and Casting in Java


❖ In Java, type conversion refers to converting one data type to another. There are two types of
type conversion: implicit and explicit (or casting).
❖ Understanding type conversion is essential for effective data handling and manipulation in
Java.

1. Implicit Type Conversion (Widening Conversion)


✓ Implicit conversion, also known as widening conversion, occurs when the Java compiler
automatically converts a smaller data type to a larger data type without any explicit instruction
from the programmer.
✓ This typically happens when assigning a value of a smaller data type to a variable of a larger
data type.

Examples of Implicit Conversion:


byte → short → int → long → float → double

Example:
int intValue = 100;
long longValue = intValue; // Implicit conversion from int to long
float floatValue = intValue; // Implicit conversion from int to float

2. Explicit Type Conversion (Narrowing Conversion or Casting)


✓ Explicit conversion, also known as narrowing conversion or casting, occurs when a larger data
type is converted into a smaller data type.
✓ This requires an explicit cast operator because it can lead to data loss.

Syntax for Casting:


targetType variableName = (targetType) value;

Examples of Explicit Conversion:


• double → float → long → int → short → byte

Example:
double doubleValue = 9.78;
int intValue = (int) doubleValue; // Explicit conversion from double to int
System.out.println(intValue); // Output: 9 (decimal part is truncated)

float floatValue = (float) doubleValue; // Explicit conversion from double to float


3. Type Conversion Between Primitive and Wrapper Classes
❖ Java provides wrapper classes for each primitive data type, and you can convert between
primitive types and their corresponding wrapper classes using methods provided in these
classes.

Example of Boxing and Unboxing:


• Boxing: Converting a primitive type to its corresponding wrapper class.
• Unboxing: Converting a wrapper class back to its corresponding primitive type.

Example:
// Boxing
Integer integerValue = Integer.valueOf(100); // from int to Integer
// Unboxing
int intValue = integerValue.intValue(); // from Integer to int

4. Type Conversion with Strings


❖ Converting strings to numeric types (and vice versa) is common. To convert a string to a
numeric type, use the wrapper class methods.

Example:
String numberString = "123";
int number = Integer.parseInt(numberString); // String to int
double doubleNumber = Double.parseDouble("123.45"); // String to double
System.out.println(number); // Output: 123
System.out.println(doubleNumber); // Output: 123.45
// Converting numeric to string
String strFromInt = Integer.toString(number); // int to String
String strFromDouble = Double.toString(doubleNumber); // double to String

5. Type Conversion in Expressions


❖ When performing operations with mixed data types, Java applies implicit conversion to avoid
loss of data.
❖ The result type of an expression is determined by the largest data type in the expression.

Example:
int intValue = 10;
double doubleValue = 5.5;
double result = intValue + doubleValue; // int is promoted to double
System.out.println(result); // Output: 15.5

Summary
• Implicit Conversion: Automatic widening conversion from a smaller to a larger data type. No
data loss occurs.
• Explicit Conversion (Casting): Narrowing conversion from a larger to a smaller data type,
which requires a cast and may result in data loss.
• Wrapper Classes: Boxing and unboxing for converting between primitive types and their
corresponding object types.
• String Conversion: Converting between strings and numeric types using wrapper class
methods.
• Mixed Expressions: Java applies implicit conversion to the largest data type involved in the
expression.

Simple java program


❖ Here's a simple Java program that demonstrates basic concepts such as defining a class, using
methods, and printing output to the console.
❖ This program calculates the sum of two integers input by the user.

Example: Simple Java Program to Calculate the Sum of Two Numbers


import java.util.Scanner; // Import the Scanner class for user input
public class SimpleCalculator
{ // Define a class named SimpleCalculator
// Method to add two numbers
public static int add(int num1, int num2)
{
return num1 + num2; // Return the sum of the two numbers
}
// Main method - entry point of the program
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in); // Create a Scanner object for input
// Prompt user for input
System.out.print("Enter the first number: ");
int firstNumber = scanner.nextInt(); // Read the first number
System.out.print("Enter the second number: ");
int secondNumber = scanner.nextInt(); // Read the second number
// Calculate the sum using the add method
int sum = add(firstNumber, secondNumber);
// Print the result
System.out.println("The sum of " + firstNumber + " and " + secondNumber + " is: " + sum);
scanner.close(); // Close the scanner
}
}

Explanation:
1. Import Statement:
o import java.util.Scanner; imports the Scanner class, which is used for obtaining input
from the user.
2. Class Definition:
o public class SimpleCalculator defines a public class named SimpleCalculator.
3. Method:
o The add method takes two integer parameters and returns their sum.
4. Main Method:
o The main method is the entry point of the program. It creates an instance of the Scanner
class to read user input.
oIt prompts the user to enter two integers, calls the add method to calculate the sum, and
then prints the result.
5. Output:
o The program outputs the sum of the two numbers entered by the user.

How to Run the Program:


1. Save the Code: Save the code in a file named SimpleCalculator.java.
2. Compile the Program: Open a terminal or command prompt, navigate to the directory where
the file is saved, and run:
javac SimpleCalculator.java

Run the Program: After successful compilation, run the program with:
java SimpleCalculator

1. Input: Follow the prompts to enter two numbers, and the program will display their sum.
This simple program showcases basic Java syntax, user input handling, method definition, and output.

Constructors in Java
❖ Constructors are special methods in Java that are called when an object of a class is created.
❖ They initialize the new object and can set initial values for the object's attributes.
❖ Constructors have the same name as the class and do not have a return type.

Key Features of Constructors:


1. Same Name as Class: The name of the constructor must be the same as the name of the class.
2. No Return Type: Constructors do not have a return type, not even void.
3. Invoked Automatically: Constructors are called automatically when an object is created.
4. Can Be Overloaded: You can have multiple constructors in a class with different parameter
lists (constructor overloading).
5. Default Constructor: If no constructor is defined in a class, Java provides a default constructor
that initializes member variables to their default values.
Types of Constructors:

1. Default Constructor: A constructor that does not take any parameters. It initializes object
attributes to default values.
2. Parameterized Constructor: A constructor that takes parameters to initialize the object with
specific values.

Example of Constructors
Here’s an example demonstrating both default and parameterized constructors:
class Student
{
// Attributes
String name;
int age;
// Default Constructor
public Student()
{
name = "Unknown";
age = 0;
}
// Parameterized Constructor
public Student(String name, int age)
{
this.name = name; // 'this' refers to the current object
this.age = age;
}
// Method to display student details
public void display()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main
{
public static void main(String[] args)
{
// Creating an object using the default constructor
Student student1 = new Student();
System.out.println("Student 1 Details:");
student1.display(); // Output: Name: Unknown, Age: 0
// Creating an object using the parameterized constructor
Student student2 = new Student("Alice", 20);
System.out.println("\nStudent 2 Details:");
student2.display(); // Output: Name: Alice, Age: 20
}
}
Explanation of the Example:
1. Class Definition:
o The Student class has two attributes: name and age.
2. Default Constructor:
o public Student() initializes the name to "Unknown" and age to 0.
3. Parameterized Constructor:
o public Student(String name, int age) initializes the attributes with values passed as
parameters. The this keyword differentiates between the instance variables and
parameters with the same name.
4. Method to Display Details:
o The display() method prints the values of the name and age attributes.
5. Main Method:
o An object of Student is created using both the default and parameterized constructors,
and their details are displayed.
Key Points:
• Constructor Overloading: You can have multiple constructors with different parameters, as
shown in the example with both a default and a parameterized constructor.
• The this Keyword: Used in constructors to refer to the current object's attributes when the
parameter names are the same as the attributes.
• Object Initialization: Constructors are primarily used to set the initial state of an object during
its creation.
Summary
• Constructors are special methods for initializing objects.
• They can be default (no parameters) or parameterized (with parameters).
• Constructors do not have a return type and are invoked automatically when an object is created.
• You can overload constructors to create multiple ways of initializing an object.

Methods in Java
❖ Methods in Java are blocks of code that perform specific tasks.
❖ They allow for code reusability, better organization, and separation of functionality.
❖ A method can take inputs (parameters), perform operations, and may return a result.
❖ Understanding methods is fundamental to Java programming.
Key Features of Methods
1. Method Declaration: A method must be declared before it can be used. It consists of the
method signature, which includes the method name and parameters, followed by the method
body.
2. Return Type: Methods can return a value of a specific type or can be declared as void if they
do not return anything.
3. Parameters: Methods can accept parameters, which are values passed to the method when it is
called.
4. Method Overloading: You can have multiple methods in the same class with the same name
but different parameter lists (different types or number of parameters).

Method Syntax
❖ The general syntax for declaring a method in Java is:
accessModifier returnType methodName(parameterType parameterName1, parameterType
parameterName2, ...)
{
// Method body
}
Example of Methods
❖ Here’s an example demonstrating method declaration, parameters, return values, and method
overloading:
class Calculator
{
// Method to add two numbers (returns an int)
public int add(int a, int b)
{
return a + b; // Return the sum
}
// Method to add three numbers (overloaded method)
public int add(int a, int b, int c)
{
return a + b + c; // Return the sum of three numbers
}
// Method to multiply two numbers (returns a double)
public double multiply(double a, double b) {
return a * b; // Return the product
}
// Method to display results
public void displayResult(String operation, double result)
{
System.out.println("The result of " + operation + " is: " + result);
}
}
public class Main
{
public static void main(String[] args)
{
Calculator calculator = new Calculator(); // Create a Calculator object
// Call the add method with two parameters
int sum1 = calculator.add(10, 20);
calculator.displayResult("addition of 10 and 20", sum1);
// Call the add method with three parameters
int sum2 = calculator.add(10, 20, 30);
calculator.displayResult("addition of 10, 20, and 30", sum2);
// Call the multiply method
double product = calculator.multiply(5.5, 4.5);
calculator.displayResult("multiplication of 5.5 and 4.5", product);
}
}

Explanation of the Example:

1. Class Definition:
o The Calculator class contains methods that perform different arithmetic operations.
2. Method Declarations:
o public int add(int a, int b): This method adds two integers and returns the result.
o public int add(int a, int b, int c): This overloaded method adds three integers.
o public double multiply(double a, double b): This method multiplies two doubles and
returns the result.
o public void displayResult(String operation, double result): This method displays the
result of an operation but does not return a value.
3. Method Calls:
o In the main method, a Calculator object is created.
o The add method is called with two and three parameters, demonstrating method
overloading.
o The multiply method is called to demonstrate another operation.
o The displayResult method is used to print the results.
Key Points
• Access Modifiers: Methods can have access modifiers (like public, private, etc.) that define
their visibility.
• Return Type: Indicates the type of value the method will return. If it does not return a value, it
should be declared as void.
• Method Overloading: Allows multiple methods with the same name but different parameters,
improving code readability and organization.
• Method Parameters: Can be of any type (primitive or object) and can be passed by value (for
primitives) or by reference (for objects).
Summary
• Methods are essential for code organization and reusability in Java.
• They can take parameters and return values, facilitating various operations.
• Understanding method overloading and proper declaration is crucial for effective Java
programming.

Static Blocks in Java

❖ A static block in Java is a block of code that initializes static variables when the class is
loaded.
❖ Static blocks are executed only once when the class is loaded into memory, making them ideal
for initializing static fields that require complex initialization.

Key Features of Static Blocks


1. Executed Once: Static blocks are executed when the class is first loaded, before any instance
of the class is created or any static methods are called.
2. Initialization: They are typically used to initialize static variables or perform other one-time
setup tasks for the class.
3. Multiple Static Blocks: You can have multiple static blocks in a class. They will execute in the
order they are defined in the code.
4. Access to Static Members: Static blocks can access static variables and methods directly.

Syntax
The syntax for a static block is as follows:
static
{
// Code to be executed
}

Example of Static Block


Here’s a simple example that demonstrates the use of a static block in a Java class:
class Example {
// Static variable
static int staticVariable;
// Static block to initialize static variables
static {
staticVariable = 10; // Initialize static variable
System.out.println("Static block executed. Static variable initialized to " + staticVariable);
}
// Instance variable
int instanceVariable;
// Constructor
public Example(int value) {
instanceVariable = value; // Initialize instance variable
System.out.println("Constructor executed. Instance variable initialized to " + instanceVariable);
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Creating first object...");
Example example1 = new Example(20); // This will call the constructor and initialize the
instance variable
System.out.println("\nCreating second object...");
Example example2 = new Example(30); // This will call the constructor again
}
}
Explanation of the Example:

1. Class Definition:
o The Example class has a static variable staticVariable and an instance variable
instanceVariable.
2. Static Block:
o The static block initializes staticVariable to 10 and prints a message indicating that the
static block has been executed.
3. Constructor:
o The constructor initializes instanceVariable with the value passed when creating an
object and prints a message.
4. Main Method:
o In the main method, two objects of the Example class are created. When the class is first
loaded, the static block executes only once, followed by the constructor for each object
created.
Output
When you run the program, the output will be:
Static block executed. Static variable initialized to 10
Creating first object...
Constructor executed. Instance variable initialized to 20
Creating second object...
Constructor executed. Instance variable initialized to 30

Key Points
• Execution Order: The static block executes before any objects of the class are created and
before any static methods are invoked. In the example, the static block executes before the
constructors.
• Usage: Static blocks are often used for complex initialization of static variables, loading
configuration data, or setting up resources that are needed by static methods.
• Multiple Static Blocks: If multiple static blocks are present, they execute in the order they
appear in the class.
Summary
• Static blocks are a powerful feature in Java for initializing static variables and performing one-
time setup tasks for a class.
• They execute only once when the class is loaded, providing a clear and efficient way to manage
static initialization.

Static Data in Java


❖ Static data refers to variables or fields that are shared among all instances of a class.
❖ These variables are declared with the static keyword and belong to the class itself rather than to
any particular instance.
❖ Static data is initialized when the class is loaded and is shared by all instances of that class,
making it useful for defining class-wide properties or counters.
Key Features of Static Data
1. Class-Level Variable: Static variables are associated with the class rather than any specific
object. All instances of the class share the same static variable.
2. Memory Management: Static variables are stored in the static memory area. They are created
when the class is loaded and destroyed when the class is unloaded.
3. Access: Static data can be accessed directly using the class name, which is often considered a
good practice for readability. They can also be accessed via instance references, though this is
less common.
4. Initialization: Static data can be initialized using a static block or directly when declared.

Syntax
The syntax for declaring static data is as follows:
class ClassName
{
static dataType variableName; // Static variable declaration
}

Example of Static Data


Here’s an example that demonstrates the use of static data in a Java class:
class Counter {
// Static variable to keep track of the number of instances
static int count = 0;
// Constructor
public Counter() {
count++; // Increment count every time a new object is created
}
// Static method to get the current count
public static int getCount() {
return count; // Return the number of instances created
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Initial count: " + Counter.getCount()); // Output: 0
// Create instances of Counter
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

// Display the current count


System.out.println("Current count after creating objects: " + Counter.getCount()); // Output: 3
}
}

Explanation of the Example:


1. Class Definition:
o The Counter class contains a static variable count to keep track of how many instances
of the class have been created.
2. Constructor:
o Each time a Counter object is instantiated, the constructor increments the static variable
count.
3. Static Method:
o The getCount static method returns the value of count, allowing access to the number of
instances created.
4. Main Method:
o In the main method, we first print the initial count (which is 0), create three instances of
the Counter class, and then print the updated count, which should reflect the number of
instances created.
Output
When you run the program, the output will be:
Initial count: 0
Current count after creating objects: 3
Key Points
• Shared State: Static data is shared across all instances of a class, making it useful for tracking
common properties.
• Accessing Static Data: It is generally best practice to access static data through the class name,
e.g., Counter.getCount(), rather than through instances, e.g., c1.getCount().
• Lifetime: The lifetime of static data extends for the duration of the program, making it
available until the class is unloaded or the program terminates.
Summary
• Static data provides a mechanism for sharing data across all instances of a class in Java.
• It can be used for counting instances, holding configuration values, or managing shared
resources.
• Understanding static data is crucial for effective class design and memory management in Java
applications.

Static Methods in String and StringBuffer Classes in Java

❖ In Java, String and StringBuffer are two important classes used for handling strings, but they
have different characteristics and use cases.
❖ Both classes have several static methods that provide functionality for string manipulation.
❖ Here’s an overview of the String and StringBuffer classes, focusing on their static methods.
1. String Class
❖ The String class in Java is used to represent immutable sequences of characters. Once a String
object is created, it cannot be changed.
❖ This immutability makes the String class inherently thread-safe.
Common Static Methods of the String Class
• String.valueOf(): Converts various types of values (like int, float, char, etc.) to their string
representation.
String str = String.valueOf(100); // "100"
• String.format(): Creates a formatted string using the specified format string and arguments.

String formatted = String.format("Hello, %s! You have %d new messages.", "Alice", 5);
// "Hello, Alice! You have 5 new messages."

• String.join(): Joins multiple strings with a specified delimiter.

String result = String.join(", ", "Apple", "Banana", "Cherry");


// "Apple, Banana, Cherry"

• String.copyValueOf(): Creates a new string from the character array.

char[] chars = {'H', 'e', 'l', 'l', 'o'};


String str = String.copyValueOf(chars); // "Hello"

2. StringBuffer Class

❖ The StringBuffer class is used for mutable sequences of characters.


❖ Unlike String, the StringBuffer object can be modified after it is created, making it suitable for
scenarios where string manipulation is required.

Common Static Methods of the StringBuffer Class

• StringBuffer.append(): Appends the specified string to the end of the current StringBuffer
object.
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // "Hello World"
• StringBuffer.insert(): Inserts a string into the StringBuffer at a specified index.

StringBuffer sb = new StringBuffer("Hello");


sb.insert(5, " World"); // "Hello World"

• StringBuffer.reverse(): Reverses the contents of the StringBuffer.

StringBuffer sb = new StringBuffer("Hello");


sb.reverse(); // "olleH"

• StringBuffer.delete(): Deletes a substring from the StringBuffer.

StringBuffer sb = new StringBuffer("Hello World");


sb.delete(5, 11); // "Hello"
Example of Using String and StringBuffer Classes
Here’s an example that demonstrates the use of static methods in the String and StringBuffer classes:
public class Main {
public static void main(String[] args) {
// Using String class static methods
String name = "Alice";
int age = 30;
// String.format example
String greeting = String.format("Hello, %s! You are %d years old.", name, age);
System.out.println(greeting); // Output: Hello, Alice! You are 30 years old.
// String.join example
String fruits = String.join(", ", "Apple", "Banana", "Cherry");
System.out.println(fruits); // Output: Apple, Banana, Cherry
// Using StringBuffer
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" World");
System.out.println(sb.toString()); // Output: Hello World
sb.insert(5, ",");
System.out.println(sb.toString()); // Output: Hello, World
sb.reverse();
System.out.println(sb.toString()); // Output: dlroW ,olleH
}
}

Explanation of the Example


1. String Class:
o The String.format() method is used to create a formatted string that includes the name
and age.
o The String.join() method combines multiple strings into one with a specified delimiter.
2. StringBuffer Class:
o A StringBuffer object is created and the append() method is used to add strings.
o The insert() method adds a comma into the StringBuffer.
o Finally, the reverse() method reverses the entire string in the StringBuffer.
Key Points
• Immutability vs. Mutability: String is immutable (cannot be changed), while StringBuffer is
mutable (can be changed).
• Performance: StringBuffer is generally more efficient for operations that involve many string
manipulations, as it does not create new objects each time a modification is made.
• Thread Safety: StringBuffer is synchronized, making it thread-safe for use in multi-threaded
environments.
Summary
• The String class provides several useful static methods for manipulating and formatting strings,
while the StringBuffer class offers mutable strings with methods for dynamic manipulation.
• Choosing between String and StringBuffer depends on whether you need immutability (use
String) or mutability (use StringBuffer).
MCQ:
1. What is the main principle of Object-Oriented Programming (OOP)?
a) Structured programming b) Code reusability c) Procedural programming d) Both b and c
2. Who is the creator of Java?
a) James Gosling b) Dennis Ritchie c) Bjarne Stroustrup d) Guido van Rossum
3. Which of the following is NOT a Java buzzword?
a) Object-oriented b) Platform-independent c) Slow d) Multithreaded
4. Which component of the JVM is responsible for converting bytecode to machine code?
a) Class loader b) Interpreter c) Just-in-time compiler (JIT) d) Garbage collector
5. Which of the following is NOT a primitive data type in Java?
a) int b) float c) String d) double
6. What is the correct way to declare a variable in Java?
a) int 1x = 10; b) float x = 2.5; c) char c = 'z'; d) Both b and c
7. What is the scope of a local variable?
a) Entire program b) Entire class c) Method where it is declared d) Block where it is declared
8. How do you declare an array in Java?
a) int[] arr = new int[5]; b) int arr[] = new int(5); c) array int arr[5]; d) int arr(5);
9. Which of the following operators is used to compare two values?
a) = b) == c) += d) &
10. Which control statement is used to exit a loop immediately?
a) continue b) break c) return d) exit
11. Which of the following is NOT a Java buzzword?
a) Platform-independent b) Object-oriented c) Pointers d) Multithreaded
12. What does "platform-independent" mean in the context of Java?
a) Java programs can run on any platform without modification.
b) Java supports all types of hardware.
c) Java requires different versions for different platforms.
d) Java applications cannot be ported to new platforms.
13. Which buzzword refers to Java’s ability to manage multiple tasks at once?
a) Portable b) Robust c) Multithreaded d) Distributed
14. What is the role of the Class Loader in the JVM?
a) It executes Java bytecode. b) It loads classes during runtime.
c) It manages memory. d) It compiles Java code to bytecode.
15. Which of the following components in the JVM is responsible for garbage collection?
a) Class Loader b) Execution Engine c) Memory Manager d) Garbage Collector
16. What does the JVM convert Java bytecode into?
a) C code b) Machine code c) Assembly code d) Source code
17. Which part of the JVM is responsible for the interpretation and execution of bytecode?
a) Class Loader b) JIT Compiler c) Execution Engine d) Garbage Collector
18. Which of the following is a valid primitive data type in Java?
a) String b) Object c) int d) ArrayList
19. Which data type would you use to store a character in Java?
a) Boolean b) char c) String d) byte
20. What is the default value of a boolean variable in Java?
a) true b) false c) null d) 0
21. What is the size of an int data type in Java?
a) 8 bits b) 16 bits c) 32 bits d) 64 bits
22. Which of the following statements is true about static variables?
a) They are associated with instances of a class. b) They are shared by all instances of a class.
c) They are local to a method. d) They cannot be accessed by class methods.
23. Where is the scope of a local variable in Java?
a) Throughout the entire program b) Within the method it is declared
c) Within the class it is declared d) Across multiple classes
24. Which of the following is the correct way to declare an array in Java?
a) int[] arr = new int(5); b) int[] arr = new int[5];
c) int[] arr = {1, 2, 3}; d) Both b and c
25. What is the index of the first element in an array in Java?
a) 0 b) 1 c) -1 d) Depends on the array size
26. What will be the output of the following code?
int[] arr = {1, 2, 3, 4};
System.out.println(arr[2]);
a) 1 b) 2 c) 3 d) 4
27. Which statement about arrays in Java is true?
a) Arrays can hold multiple types of data. b) Array size can be changed after initialization.
c) Arrays are objects in Java. d) Arrays are always initialized with null values.
28. Which operator is used to increment the value of a variable by 1?
a) + b) += c) ++ d) --
29. What is the output of the following code?
int a = 10, b = 5;
int c = a % b;
System.out.println(c);
a) 5 b) 2 c) 0 d) 10
30. Which of the following is NOT a relational operator in Java?
a) == b) != c) <= d) &&
31. The conditional (?:) operator in Java is also known as the:
a) Arithmetic operator b) Ternary operator c) Unary operator d) Logical operator
32. Which control statement is used to exit a loop immediately?
a) continue b) break c) return d) exit
33. Which control statement is used to skip the current iteration and move to the next iteration of
a loop?
a) continue b) break c) return d) switch
34. What will the following code print?
int x = 10;
if (x > 0) {
System.out.println("Positive");
} else {
System.out.println("Negative");
}
a) Positive b) Negative c) Error d) No output
35. What is typecasting in Java?
a) Converting an object to a different class. b) Converting one data type to another explicitly.
c) Automatically converting a smaller data type to a larger one. d) Creating a new data type.
36. What is a constructor in Java?
a) A method that must have the same name as the class b) A method that returns the class object
c) A method that returns a value d) A special method used to initialize objects
37. Which of the following is true about constructors?
a) They have a return type. b) They are inherited.
c) They can be overloaded. d) They can be called manually.
38. Which statement about methods is true?
a) All methods must return a value. b) Methods can have multiple return statements.
c) Methods cannot be called from constructors. d) Methods cannot be overloaded.
39. When is a static block executed?
a) When an object is created. b) When a class is loaded into memory.
c) When a method is called. d) During compilation.
40. Which keyword is used to declare a static variable?
a) final b) abstract c) private d) static
5 MARK QUESTIONS:

1. Explain the concept of Object-Oriented Programming (OOP) and list its four fundamental
principles.
2. Define any five Java buzzwords and explain their significance.
3. Describe the architecture of the Java Virtual Machine (JVM).
4. Explain different data types in Java with examples.
5. Differentiate between instance variables and static variables in Java.
6. What is the scope and lifetime of variables in Java?
7. Explain arrays in Java and how they are declared and initialized.
8. Describe the differences between break and continue statements in Java with examples.
9. Explain type conversion and casting in Java.

10 MARK QUESTIONS

1. Discuss in detail the four main concepts of Object-Oriented Programming (OOP) with real-
world examples.
2. Trace the history of Java from its development to its current version, highlighting key
milestones.
3. Describe the Java buzzwords with examples. How do these characteristics make Java a
powerful and versatile programming language?
4. Explain the architecture and working of the Java Virtual Machine (JVM) with a detailed
diagram.
5. What are data types in Java? Discuss both primitive and reference data types in detail with
examples.
6. Write a simple Java program demonstrating the use of constructors, methods, and instance
variables. Explain the output of the program.
7. Explain the differences between static data, static methods, and static blocks in Java with
examples.
8. Discuss the differences between String and StringBuffer classes in Java.
9. Write a detailed explanation of control flow statements in Java (if, else, switch, for, while,
do-while) with examples.
10. Explain the concept of type conversion and casting in Java with an example program that
demonstrates both implicit and explicit casting.

UNIT I COMPLETED

You might also like