UNIT I-1 java
UNIT I-1 java
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
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.
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.
✓ 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.
✓ 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
✓ 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.
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.
• 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.
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.
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 {
Example:
class Example {
}
3. Local Variables:
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
• 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).
• 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.
Key Points
❖ 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.
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};
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:
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:
• 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).
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.
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:
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
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.
Example:
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().
4. Sorting Arrays: Java provides utility methods in the Arrays class for sorting.
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
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.
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:
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);
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).
Example:
int intValue = 100;
long longValue = intValue; // Implicit conversion from int to long
float floatValue = intValue; // Implicit conversion from int to float
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)
Example:
// Boxing
Integer integerValue = Integer.valueOf(100); // from int to Integer
// Unboxing
int intValue = integerValue.intValue(); // from Integer to int
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
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.
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.
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.
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);
}
}
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.
❖ 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.
Syntax
The syntax for a static block is as follows:
static
{
// Code to be executed
}
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.
Syntax
The syntax for declaring static data is as follows:
class ClassName
{
static dataType variableName; // Static variable declaration
}
❖ 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."
2. 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.
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