0% found this document useful (0 votes)
10 views142 pages

Java Programming Notes

The document provides an introduction to Java, highlighting its key features such as simplicity, object-oriented nature, platform independence, and security. It covers the basic structure of a Java program, the workings of Java, object-oriented concepts, and the history of Java's development from its inception to modern versions. Additionally, it discusses Java's architecture, data types, and variable types, making it a comprehensive guide for beginners in Java programming.

Uploaded by

smckap20
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)
10 views142 pages

Java Programming Notes

The document provides an introduction to Java, highlighting its key features such as simplicity, object-oriented nature, platform independence, and security. It covers the basic structure of a Java program, the workings of Java, object-oriented concepts, and the history of Java's development from its inception to modern versions. Additionally, it discusses Java's architecture, data types, and variable types, making it a comprehensive guide for beginners in Java programming.

Uploaded by

smckap20
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

JAVA PROGRAMMING

UNIT-I
UNIT – I

Introduction in java:

What is Java?

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


by Sun Microsystems (now owned by Oracle). It is known for its slogan:

“Write Once, Run Anywhere” (WORA)

This means Java programs can run on any device that has a Java Virtual Machine (JVM).

Key Features of Java

✔Simple

Easy to learn if you know C/C++, but with fewer complex features.

✔Object-Oriented

Everything in Java is based on objects (classes, inheritance, objects, etc.).

✔Platform Independent

Java code is compiled into bytecode, which runs on the JVM — making it portable.

✔Secure

Java provides strong security features (bytecode verification, sandboxing, etc.).

✔Robust

Handles errors well and has automatic garbage collection.

✔Multithreaded

Supports multiple tasks running at the same time.

Basic Structure of a Java Program

public class Main {


public static void main(String[] args) {

SVCAS
1
JAVA PROGRAMMING
UNIT-I
[Link]("Hello, World!");
}
}

Explanation:

 public class Main → defines a class named Main


 main() method → entry point of every Java program
 [Link]() → prints text to the screen

How Java Works

1. You write Java code (.java file)


2. The Java Compiler (javac) converts it to bytecode (.class file)
3. The Java Virtual Machine (JVM) executes the bytecode

Where Java Is Used

 Android app development


 Web servers & backend (Spring, Hibernate)
 Desktop applications
 Big data (Hadoop)
 Cloud & enterprise systems
 Games and embedded systems

*****************

Review of Object-Oriented Concepts in Java

Java is a fully object-oriented programming language (except for primitive types). It is


built around four main principles of Object-Oriented Programming (OOP):

1. Class

A class is a blueprint or template from which objects are created.

class Car {
String color;
void drive() {
[Link]("Car is driving");
}
}

SVCAS
2
JAVA PROGRAMMING
UNIT-I
2. Object

An object is an instance of a class. It represents real-world entities.

Car myCar = new Car();


[Link] = "Red";
[Link]();

3. Encapsulation

Encapsulation means bundling data and methods inside a class and restricting direct
access using access modifiers like private.

class BankAccount {
private double balance;

public void deposit(double amount) {


balance += amount;
}

public double getBalance() {


return balance;
}
}

 Protects data
 Controls access
 Improves security

4. Inheritance

Inheritance allows one class to acquire properties and methods of another class using
extends.

class Animal {
void eat() {
[Link]("Eating...");
}
}

class Dog extends Animal {


void bark() {
[Link]("Barking...");
}
}

SVCAS
3
JAVA PROGRAMMING
UNIT-I
 Promotes code reusability
 Helps build class hierarchies

5. Polymorphism

Polymorphism means many forms — the same method name behaves differently based
on the object.

 Compile-time Polymorphism (Method Overloading)

class MathUtil {
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}

 Runtime Polymorphism (Method Overriding)

class Animal {
void sound() { [Link]("Animal makes a sound"); }
}

class Cat extends Animal {


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

6. Abstraction

Abstraction hides unnecessary details and shows only essential features.

 Using Abstract Class

abstract class Shape {


abstract void draw();
}
class Circle extends Shape {
void draw() { [Link]("Drawing Circle"); }
}

 Using Interface

interface Movable {
void move();
}

SVCAS
4
JAVA PROGRAMMING
UNIT-I
class Robot implements Movable {
public void move() {
[Link]("Robot moves");
}
}
7. Additional OOP Concepts in Java

✔Constructors

Used to create objects and assign initial values.

✔Overloading & Overriding

Enhances flexibility and readability.

✔Super Keyword

Refers to the parent class.

✔This Keyword

Refers to the current object.

******************

History of Java

1. Origin at Sun Microsystems (1991–1995)

 Java was developed by James Gosling, along with Mike Sheridan and Patrick Naughton,
at Sun Microsystems.
 The project originally started as "The Green Project" in 1991.

🔹Why was Java created?

The team wanted a programming language for:

 Consumer electronic devices


 Platform-independent systems
 Secure and reliable applications

🔹 “Oak” – the first name

SVCAS
5
JAVA PROGRAMMING
UNIT-I
 The first version of Java was called Oak, named after a tree outside James Gosling’s
office.
 Later, the name was changed to Java (after Java coffee) because Oak was already
trademarked.

2. Official Release of Java (1995)

 In 1995, Java was officially released.


 It introduced a revolutionary concept:

🔹 “Write Once, Run Anywhere” (WORA)

 Java programs could run on any device using the Java Virtual Machine (JVM).

This made Java ideal for:

 Internet applications
 Cross-platform software

3. Java 1.0 to Java 1.4 (1996–2002)

Java 1.0 (1996):

 First stable version


 Introduced Applets for web browsers

Java 1.2 (1998):

 Major update called Java 2


 Introduced Swing, Collections Framework

Java 1.4 (2002):

 Added exception chaining, NIO package

4. Java 5 to Java 8 (2004–2014)

Java 5 (2004):

Introduced major features like:

 Generics
 Enhanced for-loop
 Annotations
 Autoboxing
 Enums

SVCAS
6
JAVA PROGRAMMING
UNIT-I
Java 6 (2006)

 Performance improvements
 Scripting support

Java 7 (2011)

 try-with-resources
 String in switch

Java 8 (2014)

One of the biggest updates:

 Lambda expressions
 Streams API
 Functional programming features

5. Oracle Acquires Sun Microsystems (2010)

 In 2010, Oracle acquired Sun Microsystems and became the owner of Java.
 Oracle continued the development and distribution of Java.

6. Modern Java (Java 9 to Present)

Java now follows a time-based, six-month release cycle.

Key recent features:

 Java 9 (2017): Module System (Project Jigsaw)


 Java 11 (2018): LTS version, removed JavaFX
 Java 17 (2021): LTS, sealed classes, pattern matching
 Java 21 (2023): Latest LTS with virtual threads (Project Loom)

These versions focus on:

 Better performance
 Better memory use
 Modern programming features

Why Java Became Popular

 Platform independence
 Strong security
 Reliability and stability
 Large community

SVCAS
7
JAVA PROGRAMMING
UNIT-I
 Widely used in enterprise and Android development

*****************

Java Buzzwords

 Java is often described using 12 key buzzwords.


 These explain why Java is powerful, secure, and widely used.

1. Simple:

Java is easy to learn because:

 It removes complex features like pointers, multiple inheritance.


 Syntax is clean and similar to C/C++.

[Link]-Oriented:

 Everything in Java is based on objects and classes.


 Supports OOP concepts: encapsulation, inheritance, polymorphism, and abstraction.

[Link]:

Java supports distributed computing through:

 Remote Method Invocation (RMI)


 Web Services : This allows Java programs on different computers to communicate
easily.

4. Robust:

Java focuses on:

 Strong memory management


 Exception handling
 Garbage collection
All these make Java reliable.

[Link]:

Java provides high security using:

 Bytecode verification
 No pointer manipulation

SVCAS
8
JAVA PROGRAMMING
UNIT-I
 Java Security Manager
Thus, it’s widely used for network-based applications.

[Link] Independent

 Java uses bytecode and JVM, allowing programs to run on any platform.

This is known as:

 “Write Once, Run Anywhere” (WORA)

[Link]

 Java programs do not depend on hardware-specific features.


 Sizes of primitive data types are fixed—this makes the code portable across
systems.

[Link] Performance

Java is faster than traditional interpreted languages because:

 It uses Just-In-Time (JIT) compiler.


 Optimized code execution on JVM.
 Though not as fast as C/C++, it’s efficient.

[Link]

 Java supports multiple tasks running simultaneously.


 Multithreading is built into the language using the Thread class and Runnable interface.

[Link]

 Java can load classes at runtime.


 It supports dynamic linking and runtime polymorphism.

[Link] Neutral

 Java bytecode is not specific to a particular processor.


 Any system with a JVM can run Java bytecode.

[Link]

 Java bytecode is interpreted by the JVM.


 This gives portability and flexibility.

***************

SVCAS
9
JAVA PROGRAMMING
UNIT-I
JVM Architecture (Java Virtual Machine Architecture)

 The JVM (Java Virtual Machine) is the engine that runs Java programs.
 It converts bytecode → machine code and manages program execution.

JVM architecture is divided into three main parts:

1. Class Loader Subsystem

The Class Loader loads .class files (bytecode) into memory.

Responsibilities:

 Loading → Finds and loads class files


 Linking
o Verify – checks bytecode for errors
o Prepare – allocates memory for static variables
o Resolve – replaces symbolic references with real references
 Initialization → Executes static blocks/initializations

Types of Class Loaders:

 Bootstrap Class Loader (loads core Java classes like [Link].*)


 Extension Class Loader
 Application/Classpath Class Loader

2. Runtime Data Areas (Memory Model)

These are memory areas used during program execution.

a) Method Area

 Stores class-level data


 Static variables, method code, constant pool
 Shared among all threads

b) Heap Area

 Stores objects, instance variables, arrays


 Shared by all threads
 Garbage collected

SVCAS
10
JAVA PROGRAMMING
UNIT-I
c) Stack Area

Each thread has its own Java Stack containing:

 Method frames
 Local variables
 Operand stack
 Return values

d) PC (Program Counter) Register

 Keeps track of the current instruction of each thread

e) Native Method Stack

 Stores native (C/C++) method calls


 Used for JNI (Java Native Interface)

3. Execution Engine

The Execution Engine runs the bytecode.

Components:

a) Interpreter

 Reads and executes bytecode line-by-line


 Slow, but immediate execution

b) JIT Compiler (Just-In-Time)

 Converts frequently used bytecode to native machine code


 Makes the program faster

c) Garbage Collector (GC)

 Removes unused objects from the heap


 Automatic memory management

d) HotSpot Compiler

 Optimizes code during runtime

SVCAS
11
JAVA PROGRAMMING
UNIT-I
4. Native Method Interface (JNI)

 Allows Java code to call non-Java (C/C++) code


 Enables platform-specific features

5. Native Method Libraries

 The actual native libraries (like .dll, .so) used by JNI

JVM Architecture Diagram

***************

Datatypes in Java

 A datatype specifies the type of data a variable can store.

Java has two categories of datatypes:

1. Primitive Datatypes
2. Non-Primitive (Reference) Datatypes

SVCAS
12
JAVA PROGRAMMING
UNIT-I

1. Primitive Datatypes:

 There are 8 primitive datatypes in Java.


 They store simple values like numbers, characters, and booleans.

Numeric Type

INTEGER:

 Integer are whole number without decimal point.

Java supports four types of integer:

1. Byte:

 Size: 1 byte (8 bits)


 Range: -128 to 127
 Used to save memory in large arrays.

byte age = 21;

SVCAS
13
JAVA PROGRAMMING
UNIT-I
2. Short:

 Size: 2 bytes
 Range: -32,768 to 32,767

short marks = 30000;

3. Int:

 Size: 4 bytes
 Range: -2,147,483,648 to 2,147,483,647

int salary = 50000;

4. Long:

 Size: 8 bytes
 Used for large integer values
 Must end with L

long population = 7800000000L;

FLOATING POINT :

 The floating point type can hold whole number followed by fractional part.

Java has two main floating-point types:

5. Float:

 Size: 4 bytes
 Used for decimal numbers
 Must end with f

float temperature = 36.6f;

6. Double:

 Size: 8 bytes
 Default datatype for decimal values
 More precise than float

double price = 999.99;

SVCAS
14
JAVA PROGRAMMING
UNIT-I
Non-Numeric Type:

7. char

 Size: 2 bytes (supports Unicode)


 Stores a single character in ' '

char grade = 'A';

8. boolean

 Stores true or false

boolean isJavaEasy = true;

2. Non-Primitive Datatypes (Reference Types)

These do not store actual data — they store addresses (references) to memory.

Examples:

 String
 Array
 Class
 Interface
 Object

Example:

String name = "Java";


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

Key features:

✔Can be of variable size


✔Created using new keyword (except String)
✔Support methods for operations

******************

Variables in Java
 A variable in Java is a name given to a memory location that stores a value.
 The value stored can change during program execution.

SVCAS
15
JAVA PROGRAMMING
UNIT-I
Example:

int age = 20;

Types of Variables in Java


Java has 3 main types of variables:

1. Local Variables

 Declared inside a method, constructor, or block


 Accessible only within that block
 Must be initialized before use (Java does NOT provide default values)

void display() {
int x = 10; // local variable
[Link](x);
}

2. Instance Variables (Non-static variables)

 Declared inside a class but outside methods


 Each object has its own copy
 Known as object-level variables
 JVM provides default values if not initialized

class Student {
int marks; // instance variable
}

3. Static Variables (Class variables)

 Declared with the keyword static


 Shared by all objects of the class
 Memory allocated only once
 Used for constants or common values

class Student {
static String schoolName = "ABC School"; // static variable
}

Declaring Variables in Java

SYNTAX:

SVCAS
16
JAVA PROGRAMMING
UNIT-I
datatype variableName = value;

Examples:

int number = 100;


double price = 99.99;
char grade = 'A';

Rules for Naming Variables (Identifiers)

✔Must start with a letter, $, or _


✔Cannot start with a number
✔Cannot use Java keywords (int, class, etc.)
✔Case-sensitive (age and Age are different)
✔Should be meaningful

Valid:

 age, studentName, _count, $price

Invalid:

 1age
 class
 student-name

Default Values for Variables


Variable Type Default Value
byte, short, int, long 0
float, double 0.0
Char '\u0000'
Boolean False
object reference Null

🔹 Note: Local variables do NOT have default values.

Examples of All Variable Types


class Demo {
static int a = 100; // static variable
int b = 50; // instance variable

SVCAS
17
JAVA PROGRAMMING
UNIT-I
void show() {
int c = 20; // local variable
[Link](a + b + c);
}
}

**************

Scope and Lifetime of Variables in Java

 A variable’s scope means where it can be accessed,


and its lifetime means how long it exists in memory.

Java has three main types of variables:

1. Local Variables
2. Instance Variables
3. Static (Class) Variables

Let’s understand their scope + lifetime:

1. Local Variables

✔Scope:

 Only inside the method, block, or constructor where they are declared.
 Cannot be accessed outside that method/block.

void test() {
int x = 10; // local variable
[Link](x);
}
// x is NOT accessible here

✔Lifetime:

 Created when the method is called


 Destroyed when the method ends
 Stored in stack memory

✔Notes:

 No default values → must be initialized before use.

SVCAS
18
JAVA PROGRAMMING
UNIT-I
2. Instance Variables (Non-static variables)

✔Scope:

 Inside the class, but outside methods.


 Accessible by all non-static methods using objects.

class Demo {
int age = 20; // instance variable
}

✔Lifetime:

 Created when an object is created (new keyword)


 Destroyed when the object is destroyed (garbage collection)
 Stored in heap memory

✔Notes:

 Have default values if not initialized.

[Link] Variables (Class variables)


✔Scope:

 Belong to the class, not to objects.


 Accessible using:
o class name → [Link]
o object reference → [Link]

class Demo {
static int count = 0; // static variable
}

✔Lifetime:

 Created when the class is loaded into JVM


 Destroyed when the JVM shuts down
 Stored in method area of JVM

✔Notes:

 Shared by all objects of the class.

SVCAS
19
JAVA PROGRAMMING
UNIT-I
***************

Arrays in Java

 An array in Java is a collection of elements of the same data type, stored in contiguous
memory locations.
 It allows you to store multiple values in a single variable.

Example:

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

Characteristics of Arrays

 Stores same type of data (int, float, String, etc.)


 Fixed size (cannot grow or shrink)
 Elements are stored in indexes starting from 0
 Fast access using index

Types of Arrays in Java

Java supports two main types:

1. One-Dimensional Array
2. Multi-Dimensional Array
(mostly 2-D arrays)

1. One-Dimensional Array

✔Declaration

int[] arr;

✔Creation

arr = new int[5]; // array of size 5

✔Initialization

arr[0] = 10;

SVCAS
20
JAVA PROGRAMMING
UNIT-I
arr[1] = 20;

✔Combined form

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

✔Accessing elements

[Link](arr[2]); // Output: 30

✔Traversing using loop

for (int i = 0; i < [Link]; i++) {


[Link](arr[i]);
}

2. Two-Dimensional Array (Matrix)

✔Declaration

int[][] matrix;

✔Creation

matrix = new int[2][3]; // 2 rows, 3 columns

✔Initialization

matrix[0][0] = 1;
matrix[1][2] = 6;

✔Combined form

int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};

✔Printing 2D array

SVCAS
21
JAVA PROGRAMMING
UNIT-I
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}

Array Length

 Use .length to get array size.

int[] a = {2, 4, 6, 8};


[Link]([Link]); // Output: 4

Default Values in Arrays

 If you create an array using new, Java gives default values.

Data Type Default Value


int, byte, short 0
float, double 0.0
boolean false
Char '\u0000'
Object/ String Null

Arrays of Objects
String[] names = new String[3];
names[0] = "John";

Advantages of Arrays

 Easy to access elements using index.


 Good for storing fixed-size collections.
 Faster access.

Limitations of Arrays

 Fixed size.
 Cannot store different data types.
 Inserting/deleting is difficult.

SVCAS
22
JAVA PROGRAMMING
UNIT-I
*****************

Operators in Java

 Operators are symbols that perform operations on variables and values.


Example: +, -, *, /, >, <, ==, etc.
 Java operators are grouped into 7 major categories:

[Link] Operators

 Used for mathematical operations.

Operator Meaning Example


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (remainder) a%b

Example:

int a = 10, b = 3;
[Link](a % b); // Output: 1

[Link] Operators

 Operate on one operand.

Operator Meaning
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical NOT

Example:

int x = 5;
[Link](++x); // 6
[Link](x--); // 6 then x becomes 5

SVCAS
23
JAVA PROGRAMMING
UNIT-I
[Link] Operators

 Used to assign values.

Operator Meaning
= Assign
+= Add & assign
-= Subtract & assign
*= Multiply & assign
/= Divide & assign
%= Modulus & assign

Example:

int a = 10;
a += 5; // a = 15

[Link] (Comparison) Operators

 Used to compare two values → returns true / false.

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater or equal
<= Less or equal

Example:

[Link](10 > 5); // true

5. Logical Operators

 Used to combine conditions.

Operator Meaning
&& Logical AND
`
! Logical NOT

Example:

SVCAS
24
JAVA PROGRAMMING
UNIT-I
int age = 20;
[Link](age > 18 && age < 30); // true

6. Bitwise Operators

 Operate on bits (0s and 1s).

Operator Meaning
& Bitwise AND
` `
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Right shift
>>> Zero-fill right shift

Example:

[Link](5 & 3); // 1

[Link] Operator

 The only operator in Java that takes three operands.

SYNTAX:

condition ? value_if_true : value_if_false

Example:

int a = 10, b = 20;


int max = (a > b) ? a : b;

8. Instance of Operator

 Checks whether an object belongs to a particular class.

String s = "Hello";
[Link](s instanceof String); // true

SVCAS
25
JAVA PROGRAMMING
UNIT-I
Operator Precedence (High to Low)

1. ()
2. ++, --
3. *, /, %
4. +, -
5. <, >, <=, >=
6. ==, !=
7. &&
8. ||
9. =, +=, -=, etc.

*************

Control Statements in Java

 Control statements are used to change the normal flow of program execution.
 They decide which instructions execute and how many times.

Java control statements are divided into 3 categories:

1. Decision-Making Statements
2. Looping Statements
3. Jump Statements

1. Decision-Making Statements

 Used to execute different statements based on conditions.

a) if Statement

 Executes block if condition is true.

int age = 18;


if(age >= 18){
[Link]("You are an adult.");
}

b) if-else Statement

 Executes one block if condition is true, another if false.

if(age >= 18){


[Link]("Adult");

SVCAS
26
JAVA PROGRAMMING
UNIT-I
} else {
[Link]("Minor");
}

c) else-if Ladder

 Check multiple conditions sequentially.

if(score >= 90){


[Link]("A Grade");
} else if(score >= 75){
[Link]("B Grade");
} else {
[Link]("C Grade");
}

d) switch Statement

 Selects a block based on value of variable.

int day = 3;
switch(day){
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}

[Link] Statements

 Used to repeat a block of code multiple times.

a) for Loop

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


[Link](i);
}

b) while Loop

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

SVCAS
27
JAVA PROGRAMMING
UNIT-I
c) do-while Loop

 Executes at least once.

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

3. Jump Statements

 Used to change normal flow immediately.

Statement Purpose
Break Exit a loop or switch
continue Skip current iteration of loop
Return Exit from a method and optionally return a value

Example

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


if(i == 3) continue; // skip 3
if(i == 5) break; // exit loop at 5
[Link](i);
}

Output:

1
2
4

[Link] Control Statements

 You can nest loops inside loops


 Or if-else inside loops
 Useful for patterns, multi-level decisions.

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


for(int j=1; j<=i; j++){
[Link]("* ");
}
[Link]();

SVCAS
28
JAVA PROGRAMMING
UNIT-I
}

Output:

*
**
***

*************

Type Conversion and Casting in Java

In Java, type conversion is the process of converting one data type into another.
It is also called typecasting.

There are two types of type conversion:

1. Implicit Type Conversion (Widening)


2. Explicit Type Conversion (Narrowing / Casting)

[Link] Type Conversion (Widening)

 Automatically done by Java.


 Converts a smaller datatype → larger datatype.
 No data loss.

Widening Conversion Order:

byte → short → int → long → float → double


char → int → long → float → double

Example:

int x = 100;
double y = x; // int automatically converted to double
[Link](y); // 100.0

Notes:

 Happens automatically.
 Safe operation.

SVCAS
29
JAVA PROGRAMMING
UNIT-I
2. Explicit Type Conversion (Narrowing / Casting)

 Done manually by the programmer.


 Converts a larger datatype → smaller datatype.
 Might cause data loss.

SYNTAX:

datatype variable = (datatype) value;

Example:

double d = 9.78;
int i = (int) d; // double explicitly converted to int
[Link](i); // Output: 9

Notes:

 Fractional part is truncated, not rounded.


 Must use parentheses for explicit casting.

[Link] Between Compatible Types

From → To Example
int → byte byte b = (byte) 130; → overflow may occur
double → float float f = (float) 3.14;
char → int int x = (int) 'A'; → 65
int → char char c = (char) 65; → 'A'

4. Casting Between Objects (Reference Types)

 Upcasting: Subclass → Superclass (safe, implicit)


 Downcasting: Superclass → Subclass (explicit, may throw ClassCastException)

Example:

class Animal {}
class Dog extends Animal {}

Animal a = new Dog(); // Upcasting (implicit)


Dog d = (Dog) a; // Downcasting (explicit)

SVCAS
30
JAVA PROGRAMMING
UNIT-I
5. Type Conversion Rules

1. Widening → Automatic, safe


2. Narrowing → Explicit, may lose data
3. Arithmetic operations promote smaller types to larger type

Example:

int a = 10;
float b = 5.5f;
float result = a + b; // int promoted to float

6. Quick Table: Size of Primitive Types

Type Size
byte 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
float 4 bytes
double 8 bytes
char 2 bytes

***************

simple java program

Program: Hello World in Java


// This is a simple Java program
public class HelloWorld {

public static void main(String[] args) {


// Print message to the console
[Link]("Hello, World!");
}
}

🔶 Explanation

Part Description
public class HelloWorld Defines a class named HelloWorld. Every Java program

SVCAS
31
JAVA PROGRAMMING
UNIT-I
must have at least one class.
public static void main(String[] The main method. Java starts execution from here.
args)
[Link]("Hello, Prints text to the console. println adds a new line after
World!"); printing.
// This is a comment Single-line comment. Ignored by Java compiler.

🔶 Steps to Run the Program

1. Write the code in a file named [Link] (class name = file name).
2. Compile using:
3. javac [Link]
o This generates [Link] (bytecode).
4. Run using:
5. java HelloWorld
o Output:
6. Hello, World!

🔶 Modifying the Program

You can print your own message:

[Link]("Welcome to Java Programming!");

****************

Constructors in Java

 A constructor is a special method used to initialize objects of a class.


 It is automatically called when an object is created.

🔶 Features of Constructors

1. Name: Must be the same as the class name.


2. No return type: Not even void.
3. Called automatically: When new keyword is used.
4. Can be overloaded: Multiple constructors with different parameters are allowed.
5. Cannot be inherited.

SVCAS
32
JAVA PROGRAMMING
UNIT-I
🔶 Types of Constructors

1. Default Constructor (No-arg constructor)

 Takes no parameters.
 Java provides a default constructor if no constructor is defined.

class Student {
int id;
String name;

// Default constructor
Student() {
id = 0;
name = "Unknown";
}

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

public class Demo {


public static void main(String[] args) {
Student s = new Student(); // Calls default constructor
[Link](); // Output: 0 Unknown
}
}

2. Parameterized Constructor

 Takes arguments to initialize objects with specific values.

class Student {
int id;
String name;

// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
}

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

SVCAS
33
JAVA PROGRAMMING
UNIT-I
}

public class Demo {


public static void main(String[] args) {
Student s = new Student(101, "Alice"); // Calls parameterized constructor
[Link](); // Output: 101 Alice
}
}

[Link] Overloading

 A class can have multiple constructors with different parameters.

class Student {
int id;
String name;

Student() { // Default
id = 0; name = "Unknown";
}

Student(int i) { // One parameter


id = i; name = "Unknown";
}

Student(int i, String n) { // Two parameters


id = i; name = n;
}

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

public class Demo {


public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student(102);
Student s3 = new Student(103, "Bob");

[Link](); // 0 Unknown
[Link](); // 102 Unknown
[Link](); // 103 Bob
}
}

SVCAS
34
JAVA PROGRAMMING
UNIT-I
*****************

Methods in Java

 A method is a block of code that performs a specific task.


 It helps to reuse code and make programs organized.

🔶 Structure of a Method
modifier returnType methodName(parameters) {
// body of method
// statements
return value; // if returnType is not void
}

Parts:

Part Description

modifier Access specifier (public, private, protected)

returnType Type of value the method returns (int, double, String, void)

methodName Name of the method

parameters Input values (optional)

body Code to execute

return Returns value (if not void)

🔶 Example of a Simple Method


public class Demo {

// Method with no parameters and no return value


void greet() {
[Link]("Hello, Java!");
}

public static void main(String[] args) {


Demo obj = new Demo();
[Link](); // Call the method

SVCAS
35
JAVA PROGRAMMING
UNIT-I
}
}

Output:

Hello, Jav
🔶 Types of Methods

1. Based on Parameters and Return Type

Type Description Example


No parameter, no return value Just performs an action void greet()
With parameter, no return value Takes input but returns nothing void display(int x)
No parameter, with return value Returns a value but takes no input int getNumber()
With parameter and return value Takes input and returns a value int sum(int a, int b)

Example: Method with Parameters and Return Value

public class Demo {

// Method to add two numbers


int sum(int a, int b) {
return a + b;
}

public static void main(String[] args) {


Demo obj = new Demo();
int result = [Link](10, 20); // Call method with arguments
[Link]("Sum: " + result); // Output: Sum: 30
}
}

🔶 Method Overloading

 Multiple methods with the same name but different parameters.


 Allows flexibility in method usage.

class Demo {

void show() {
[Link]("No parameters");
}

void show(int x) {

SVCAS
36
JAVA PROGRAMMING
UNIT-I
[Link]("Integer: " + x);
}

void show(String s) {
[Link]("String: " + s);
}

public static void main(String[] args) {


Demo obj = new Demo();
[Link]();
[Link](10);
[Link]("Hello");
}
}

Output:

No parameters
Integer: 10
String: Hello

🔶 Calling a Method

1. Non-static method → Using object of class


2. Static method → Using class name or directly inside main

🔶 Advantages of Methods

 Code reusability
 Improves readability and organization
 Easier to debug and maintain

🔶 Key Points

Feature Description
Access public, private, protected
Return type void if no value returned, otherwise data type
Parameters Optional
Call Use object (non-static) or class (static)
Overloading Same name, different parameters

****************

SVCAS
37
JAVA PROGRAMMING
UNIT-I
Static Block in Java

 A static block (also called static initialization block) is a block of code that is executed
only once when the class is loaded into memory.
 It is mainly used to initialize static variables or perform startup tasks.

SYNTAX

class ClassName {
static {
// code to execute when class is loaded
}
}

🔹 Key Features

Feature Description
Executed When class is loaded into JVM (before main method)
Number of Executions Only once, regardless of number of objects
Purpose Initialize static variables, perform setup
Access Can access static members of the class only

🔹 Example 1: Basic Static Block


class Demo {
static int data;

// Static block
static {
data = 50;
[Link]("Static block executed");
}

public static void main(String[] args) {


[Link]("Main method executed");
[Link]("Data: " + data);
}
}

Output:

Static block executed


Main method executed
Data: 50

SVCAS
38
JAVA PROGRAMMING
UNIT-I
Explanation:

1. JVM loads Demo class → executes static block first.


2. Then executes main() method.

🔹 Example 2: Multiple Static Blocks


class Demo {
static {
[Link]("Static block 1");
}

static {
[Link]("Static block 2");
}

public static void main(String[] args) {


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

Output:

Static block 1
Static block 2
Main method

Note: Static blocks execute in the order they appear in the class.

🔹 Example 3: Static Block with Static Variables


class Demo {
static int count;

static {
count = 100; // initialize static variable
}

public static void main(String[] args) {


[Link]("Count: " + count); // Output: 100
}
}

**************

SVCAS
39
JAVA PROGRAMMING
UNIT-I
Static Data in Java

 In Java, static data refers to class-level variables that are shared among all objects of a
class.
 They are also called class variables.

🔹 Key Features
Feature Description
Declared with static keyword
Memory allocation Only once, at class loading time
Shared By all objects of the class
Access Can be accessed using class name or object reference
Purpose To store data common to all objects (e.g., school name, count)

SYNTAX
class ClassName {
static dataType variableName;
}

🔹 Example 1: Static Variable

class Student {
static String schoolName = "ABC School"; // static variable
String name; // instance variable

Student(String n) {
name = n;
}

void display() {
[Link](name + " studies in " + schoolName);
}
}

public class Demo {


public static void main(String[] args) {
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");

[Link](); // Alice studies in ABC School


[Link](); // Bob studies in ABC School

// Accessing static variable using class name

SVCAS
40
JAVA PROGRAMMING
UNIT-I
[Link]([Link]);
}
}

🔹 Example 2: Static Counter

class Student {
static int count = 0; // static variable
String name;

Student(String n) {
name = n;
count++; // increment count for each object
}

void display() {
[Link](name + " is student number " + count);
}
}

public class Demo {


public static void main(String[] args) {
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
Student s3 = new Student("Charlie");

[Link]("Total students: " + [Link]);


}
}

Output:

Total students: 3

Explanation:

 count is shared across all objects.


 Each time a new object is created, count is incremented.

🔹 Accessing Static Data

1. Using Class Name (Recommended)

[Link];

SVCAS
41
JAVA PROGRAMMING
UNIT-I
2. Using Object Reference (Works, but not recommended)

[Link];

🔹 Key Points

 Static variables exist only once in memory.


 Useful for shared/common data among all objects.
 Can be used inside static methods.
 Can be initialized in static block if needed.

****************

Static Methods, String, and StringBuffer classes in Java:

1. Static Methods in Java

 A static method belongs to the class, not to an object.

Key Points:

Feature Description
Belongs to Class
Access Using [Link]() or inside class directly
Object required? ❌ Not required
Can access Only static variables/methods of class
Can be called Without creating an object

SYNTAX

class Demo {
static void greet() {
[Link]("Hello, Java!");
}

public static void main(String[] args) {


[Link](); // call static method using class name
}
}

SVCAS
42
JAVA PROGRAMMING
UNIT-I
Output:

Hello, Java!

Notes:

 Static methods cannot access instance variables directly.


 Often used for utility methods like [Link](), [Link](), etc.

2. String Class in Java

String is an immutable class in Java ([Link]).

 Immutable → Once created, the value cannot be changed.

Creating Strings

1. Using string literal (stored in String Pool)

String s1 = "Hello";

2. Using new keyword

String s2 = new String("World");

Common Methods of String Class

Method Description Example


length() Returns string length "Hello".length() → 5
charAt(int index) Returns char at index "Hello".charAt(1) → 'e'
concat(String s) Concatenates strings "Hello".concat(" World") → "Hello
World"
equals(String s) Compares content "abc".equals("abc") → true
substring(int start, int Returns substring "Hello".substring(1,4) → "ell"
end)
toUpperCase() Converts to "hello".toUpperCase() → "HELLO"
uppercase
toLowerCase() Converts to "HELLO".toLowerCase() → "hello"
lowercase

Example

SVCAS
43
JAVA PROGRAMMING
UNIT-I
String str = "Hello";
[Link]([Link]()); // 5
[Link]([Link]()); // HELLO

Note: String objects are immutable, so methods return a new string.

3. StringBuffer Class in Java

StringBuffer is a mutable class ([Link]).

 Mutable → Can change content without creating a new object.


 Thread-safe (synchronized).

Creating StringBuffer

StringBuffer sb = new StringBuffer("Hello");

Common Methods of StringBuffer

Method Description Example


append(String s) Add string at end [Link](" World") → "Hello World"
insert(int index, String s) Insert at index [Link](5, " Java") → "Hello Java"
replace(int start, int end, String s) Replace substring [Link](0,5,"Hi") → "Hi Java"
delete(int start, int end) Delete substring [Link](0,3)
reverse() Reverse string "Hello".reverse() → "olleH"
length() Length of string [Link]()

Example

StringBuffer sb = new StringBuffer("Hello");


[Link](" Java");
[Link](sb); // Hello Java
[Link]();
[Link](sb); // avaJ olleH

🔹 Key Differences: String vs StringBuffer

Feature String StringBuffer


Mutability Immutable Mutable

SVCAS
44
JAVA PROGRAMMING
UNIT-I
Methods Many read-only Many modify-in-place
Thread-safe No Yes
Performance Slower for modifications Faster for modifications
Memory New object on modification Same object modified

*********************

SVCAS
45
JAVA PROGRAMMING
UNIT-II

UNIT-II

Inheritance: Basic concepts

Inheritance in Java

Inheritance is a mechanism in Java by which one class acquires the properties and behaviors
(fields and methods) of another class.

 Helps in code reusability


 Establishes a parent-child relationship between classes

🔶 Basic Terminology

Term Description
Superclass / Parent class The class whose properties are inherited
Subclass / Child class The class that inherits from the superclass
extends keyword Used to indicate inheritance
super keyword Refers to the superclass object, used to access parent members

🔶 Types of Inheritance in Java

1. Single Inheritance – One class inherits another class


2. Multilevel Inheritance – A class inherits a class, which itself inherits another class
3. Hierarchical Inheritance – Multiple classes inherit the same parent class
4. Multiple Inheritance (Not in Java via classes) – Achieved using interfaces

Note: Java does not support multiple inheritance with classes to avoid ambiguity (diamond
problem).

🔶 Syntax of Inheritance

class Superclass {
// members of superclass
}

class Subclass extends Superclass {


// members of subclass
}

🔶 Using super Keyword

 Access parent class members


 Call parent class constructor

SVCAS
45
JAVA PROGRAMMING
UNIT-II

class Animal {
String color = "White";
}

class Dog extends Animal {


String color = "Black";

void printColor() {
[Link](color); // Dog color
[Link]([Link]); // Animal color
}
}

public class Demo {


public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}

Output:

Black
White

🔶 Advantages of Inheritance

 Code Reusability – reuse existing class members


 Method Overriding – child class can modify parent method behavior
 Extensibility – easy to add new features
 Organized Structure – forms a hierarchy

***************

Inheritance Types in Java

 Inheritance allows a class to acquire properties and methods of another class.

Java supports several types of inheritance:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (via Interfaces)

SVCAS
46
JAVA PROGRAMMING
UNIT-II

Note: Java does not support multiple inheritance using classes to avoid ambiguity (diamond
problem).

1. Single Inheritance

 Definition: One child class inherits from one parent class.


 Keyword: extends

Example:
class Animal {
void eat() { [Link]("Animal eats"); }
}

class Dog extends Animal {


void bark() { [Link]("Dog barks"); }
}

public class Demo {


public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited from Animal
[Link](); // own method
}
}

Output:

Animal eats
Dog barks

Diagram:

Animal

|
Dog

2. Multilevel Inheritance

 Definition: A class inherits from another class, which itself inherits from a parent class.
 Forms a chain of inheritance.

Example:
class Animal {
void eat() { [Link]("Animal eats"); }
}

SVCAS
47
JAVA PROGRAMMING
UNIT-II

class Dog extends Animal {


void bark() { [Link]("Dog barks"); }
}

class Puppy extends Dog {


void weep() { [Link]("Puppy weeps"); }
}

public class Demo {


public static void main(String[] args) {
Puppy p = new Puppy();
[Link](); // Animal
[Link](); // Dog
[Link](); // Puppy
}
}

Diagram:

Animal

|
Dog

|
Puppy

3. Hierarchical Inheritance

 Definition: Multiple classes inherit from the same parent class.

Example:
class Animal {
void eat() { [Link]("Animal eats"); }
}

class Dog extends Animal {


void bark() { [Link]("Dog barks"); }
}

class Cat extends Animal {


void meow() { [Link]("Cat meows"); }
}

public class Demo {

SVCAS
48
JAVA PROGRAMMING
UNIT-II

public static void main(String[] args) {


Dog d = new Dog();
Cat c = new Cat();

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

Diagram:

Animal
/ \
Dog Cat

[Link] Inheritance (via Interfaces)

 Definition: A class can implement multiple interfaces to achieve multiple inheritance.


 Reason: Java classes cannot extend multiple classes.

Example:
interface Animal {
void eat();
}

interface Pet {
void play();
}

class Dog implements Animal, Pet {


public void eat() { [Link]("Dog eats"); }
public void play() { [Link]("Dog plays"); }
}

public class Demo {


public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}

SVCAS
49
JAVA PROGRAMMING
UNIT-II

Diagram:

Animal Pet
\ /
\ /
Dog

🔶 Summary Table of Inheritance Types

Type Description Example

Single One child inherits one parent class Dog extends Animal

Multilevel Chain of inheritance class Puppy extends Dog extends Animal

Hierarchical Multiple children from same parent Dog & Cat extend Animal

Multiple One class implements multiple interfaces class Dog implements Animal, Pet

******************

Member Access Rules in Java


In Java, member access rules define how class members (variables and methods) can be
accessed from other classes, packages, or subclasses.

These are controlled using access modifiers.

🔶 Access Modifiers in Java

Modifier Class Package Subclass World (any class)


Private ✅ ❌ ❌ ❌
default (no modifier) ✅ ✅ ❌ ❌
protected ✅ ✅ ✅ ❌
Public ✅ ✅ ✅ ✅

Explanation:

1. private → Accessible only within the same class.


2. default (no modifier) → Accessible within the same package.
3. protected → Accessible within same package + subclasses.
4. public → Accessible from everywhere.

SVCAS
50
JAVA PROGRAMMING
UNIT-II

🔶 Member Access Table (Summary)

Access Modifier Same Class Same Package Subclass (different package) World
Private ✅ ❌ ❌ ❌
Default ✅ ✅ ❌ ❌
Protected ✅ ✅ ✅ ❌
Public ✅ ✅ ✅ ✅

🔶 Example of Member Access

// File: Package1/[Link]
package Package1;

public class Parent {


private int privateVar = 1;
int defaultVar = 2; // default access
protected int protectedVar = 3;
public int publicVar = 4;

void display() {
[Link](privateVar);
[Link](defaultVar);
[Link](protectedVar);
[Link](publicVar);
}
}
// File: Package1/[Link]
package Package1;

public class Child extends Parent {


void testAccess() {
// privateVar → ❌Not accessible
[Link](defaultVar); // ✅accessible (same package)
[Link](protectedVar); // ✅accessible (same package)
[Link](publicVar); // ✅accessible
}
}
// File: Package2/[Link]
package Package2;
import [Link];

public class Test {


public static void main(String[] args) {
Parent p = new Parent();

SVCAS
51
JAVA PROGRAMMING
UNIT-II

// [Link] → ❌Not accessible


// [Link] → ❌Not accessible (different package)
// [Link] → ❌Not accessible (not subclass)
[Link]([Link]); // ✅Accessible
}
}

🔶 Key Points

1. private → Only within class


2. default → Only within same package
3. protected → Same package + subclasses
4. public → Everywhere
5. protected members of parent class are accessible in subclass even in different package
using inheritance

🔶 Quick Tips

 Use private for encapsulation.


 Use protected when you want subclasses to access members.
 Use public for API-like methods accessible everywhere.
 Avoid default unless you want package-level access.

*******************

Usage of this and Super key word:

1. This Keyword in Java

 The this keyword refers to the current object of the class.


 It is mainly used to avoid ambiguity between instance variables and parameters, and to
call constructors or methods of the same class.

Uses of this

1. Access instance variables


2. class Demo {
3. int x;
4. Demo(int x) {
5. this.x = x; // refers to instance variable x
6. }
7. void display() {
8. [Link]("x = " + this.x);
9. }
10. public static void main(String[] args) {
11. Demo obj = new Demo(10);

SVCAS
52
JAVA PROGRAMMING
UNIT-II

12. [Link](); // Output: x = 10


13. }
14. }
15. Call another constructor in the same class (Constructor Chaining)
16. class Demo {
17. int x, y;
18.
19. Demo() {
20. this(10, 20); // calls parameterized constructor
21. }
22.
23. Demo(int x, int y) {
24. this.x = x;
25. this.y = y;
26. }
27.
28. void display() {
29. [Link](x + " " + y);
30. }
31.
32. public static void main(String[] args) {
33. Demo obj = new Demo();
34. [Link](); // Output: 10 20
35. }
36. }
37. Pass current object as argument
38. class Demo {
39. void show(Demo obj) {
40. [Link]("Object received");
41. }
42. void display() {
43. show(this); // pass current object
44. }
45. public static void main(String[] args) {
46. Demo obj = new Demo();
47. [Link](); // Output: Object received
48. }
49. }

2. Super Keyword In Java

 The super keyword refers to the parent (superclass) object.


 It is mainly used to access superclass members or call superclass constructor.

SVCAS
53
JAVA PROGRAMMING
UNIT-II

Uses of super

1. Access parent class variables


2. class Parent {
3. int x = 10;
4. }
5.
6. class Child extends Parent {
7. int x = 20;
8. void show() {
9. [Link](x); // Child's x
10. [Link](super.x); // Parent's x
11. }
12. public static void main(String[] args) {
13. Child c = new Child();
14. [Link]();
15. }
16. }

Output:

20
10

🔶 Difference Between this and super

Feature This Super


Refers to Current object Parent object
Usage Access current class members Access parent class members
Constructor call Calls another constructor in same class Calls parent class constructor
Passing object Can pass current object Can pass parent object

🔶 Key Points

 this → Resolves ambiguity, calls constructors, passes current object


 super → Access parent members and constructors
 this() and super() must be first statement in constructor if used

*******************

Method Overloading in Java

 Method Overloading is a feature in Java where two or more methods in the same
class have the same name but different parameters.

SVCAS
54
JAVA PROGRAMMING
UNIT-II

 It is an example of compile-time polymorphism.

🔶 Key Points

1. Methods must have the same name.


2. Parameter lists must be different:
o Different number of parameters or
o Different types of parameters or
o Different sequence of parameters
3. Return type may or may not be different, but return type alone cannot distinguish
overloaded methods.
4. Overloading happens within the same class (can also happen via inheritance).

🔶 SYNTAX

returnType methodName(parameterList) {
// method body
}

Example: Two methods with the same name but different parameters.

🔶 Example 1: Different Number of Parameters

class Demo {

void sum(int a, int b) {


[Link]("Sum of two numbers: " + (a + b));
}

void sum(int a, int b, int c) {


[Link]("Sum of three numbers: " + (a + b + c));
}

public static void main(String[] args) {


Demo obj = new Demo();
[Link](10, 20); // calls first method
[Link](10, 20, 30); // calls second method
}
}

Output:

Sum of two numbers: 30


Sum of three numbers: 60

SVCAS
55
JAVA PROGRAMMING
UNIT-II

🔶 Example 2: Different Types of Parameters

class Demo {

void display(int a) {
[Link]("Integer: " + a);
}

void display(String s) {
[Link]("String: " + s);
}

public static void main(String[] args) {


Demo obj = new Demo();
[Link](100); // calls first method
[Link]("Hello"); // calls second method
}
}

Output:

Integer: 100
String: Hello

🔶 Rules for Method Overloading

1. Must be in the same class.


2. Method names must be the same.
3. Parameter list must be different (number, type, or order).
4. Return type alone cannot distinguish overloaded methods.

🔶 Advantages

 Improves readability of code


 Provides flexibility to call the same method with different data
 Helps in compile-time polymorphism

*****************

Method Overriding in Java


 Method Overriding occurs when a subclass provides its own implementation of a method
that is already defined in its superclass.
 It is an example of runtime polymorphism (dynamic polymorphism).

SVCAS
56
JAVA PROGRAMMING
UNIT-II

🔶 Key Points

1. Same method name, same parameter list, and same return type (or compatible return
type).
2. Must be in subclass and superclass.
3. Access level of the overriding method cannot be more restrictive than the overridden
method.
4. Only inherited methods can be overridden (cannot override private or final methods).
5. super keyword can be used to call parent class method.

🔶 SYNTAX

class Parent {
returnType methodName(parameters) {
// parent class method
}
}

class Child extends Parent {


@Override
returnType methodName(parameters) {
// child class method
}
}

@Override annotation is optional but recommended. It tells the compiler that you intend to
override a method.

🔶 Example 1: Basic Method Overriding

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

class Child extends Parent {


@Override
void show() {
[Link]("Child method");
}
}

public class Demo {


public static void main(String[] args) {
Parent p = new Parent();

SVCAS
57
JAVA PROGRAMMING
UNIT-II

[Link](); // Parent method

Child c = new Child();


[Link](); // Child method

Parent pc = new Child();


[Link](); // Child method (runtime polymorphism)
}
}

Output:

Parent method
Child method
Child method

🔶 Rules for Method Overriding

Rule Description
Method signature Must be same (name + parameters)
Return type Must be same or covariant (compatible)
Access modifier Cannot be more restrictive than parent
final / static / private Cannot be overridden
Exception Subclass can throw same or narrower checked exceptions

🔶 Difference Between Overloading and Overriding

Feature Overloading Overriding


Parameters Must differ Must be same
Return type Can differ Must be same (or covariant)
Occurrence Same class Parent-child class
Compile / Runtime Compile-time polymorphism Runtime polymorphism
Keyword Optional @Override recommended

🔶 Advantages

 Enables runtime polymorphism


 Allows dynamic method behavior based on object type
 Enhances code reusability

***************

SVCAS
58
JAVA PROGRAMMING
UNIT-II

Abstract Classes in Java

An abstract class in Java is a class that cannot be instantiated and may contain abstract
methods (methods without a body) as well as concrete methods (methods with a body).

 Used to provide a base class that defines common behavior for subclasses.
 Achieves partial abstraction.

🔶 Key Points

1. Declared using the abstract keyword.


2. Can have abstract methods and regular methods.
3. Cannot be instantiated: you cannot create objects of an abstract class.
4. Subclasses must implement all abstract methods of the abstract class (unless the subclass
is also abstract).
5. Can have constructors, static methods, and instance variables.

🔶 SYNTAX

abstract class Parent {


int x; // instance variable

// abstract method (no body)


abstract void display();

// concrete method
void show() {
[Link]("This is a concrete method in abstract class");
}
}

🔶 Example 1: Basic Abstract Class

abstract class Animal {


// Abstract method
abstract void sound();

// Concrete method
void eat() {
[Link]("Animal eats");
}
}

class Dog extends Animal {


@Override
void sound() {

SVCAS
59
JAVA PROGRAMMING
UNIT-II

[Link]("Dog barks");
}
}

public class Demo {


public static void main(String[] args) {
// Animal a = new Animal(); // ❌Not allowed
Dog d = new Dog();
[Link](); // Dog barks
[Link](); // Animal eats
}
}

Output:

Dog barks
Animal eats

🔶 Example 2: Abstract Class with Constructor

abstract class Shape {


int x, y;

Shape(int x, int y) {
this.x = x;
this.y = y;
}

abstract void area(); // abstract method


}

class Rectangle extends Shape {


int width, height;

Rectangle(int x, int y, int w, int h) {


super(x, y); // call abstract class constructor
width = w;
height = h;

@Override
void area() {
[Link]("Rectangle area: " + (width * height));
}
}

public class Demo {

SVCAS
60
JAVA PROGRAMMING
UNIT-II

public static void main(String[] args) {


Rectangle r = new Rectangle(0, 0, 10, 20);
[Link](); // Rectangle area: 200
}
}

🔶 Rules for Abstract Classes

Rule Description
Object creation Cannot create object of abstract class
Abstract methods Must be implemented in subclass
Constructor Can have constructors, called by subclass
Access modifiers Can have public, protected, private members
Variables Can have instance and static variables

🔶 Advantages

 Supports code reusability


 Provides partial abstraction
 Can define common behavior for subclasses
 Can contain constructors and member variables

**************

Dynamic method dispatch - Usage of final keyword

1. Dynamic Method Dispatch in Java

 Dynamic Method Dispatch (DMD) is the process by which a call to an overridden


method is resolved at runtime, rather than at compile time.
 It is the mechanism behind runtime polymorphism.

Key Points

1. Occurs when a superclass reference points to a subclass object.


2. The overridden method of the subclass is called at runtime, not the superclass method.
3. Allows flexible and dynamic behavior.

Example: Dynamic Method Dispatch


class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

SVCAS
61
JAVA PROGRAMMING
UNIT-II

class Dog extends Animal {


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

class Cat extends Animal {


@Override
void sound() {
[Link]("Cat meows");
}
}

public class Demo {


public static void main(String[] args) {
Animal a; // superclass reference

a = new Dog(); // reference points to Dog object


[Link](); // Dog barks

a = new Cat(); // reference points to Cat object


[Link](); // Cat meows
}
}

Output:

Dog barks
Cat meows

Explanation:

 Although the reference type is Animal, the subclass method is called because Java
resolves overridden methods at runtime.

2. Usage of final Keyword in Java

 The final keyword in Java is used to restrict modification.

It can be applied to:

1. Variables → value cannot be changed


2. Methods → cannot be overridden by subclasses
3. Classes → cannot be subclassed

SVCAS
62
JAVA PROGRAMMING
UNIT-II

Examples

2.1 Final Variable


class Demo {
final int x = 10;

void show() {
// x = 20; // ❌Error: cannot assign a value to final variable
[Link](x);
}

public static void main(String[] args) {


Demo d = new Demo();
[Link](); // 10
}
}

2.2 Final Method


class Parent {
final void display() {
[Link]("Final method in parent");
}
}

class Child extends Parent {


// void display() { } // ❌Error: cannot override final method
}

2.3 Final Class


final class Parent {
void show() {
[Link]("Final class method");
}
}

// class Child extends Parent { } // ❌Error: cannot inherit from final class

************************

Packages: Definition-Access Protection – Importing Packages.

Packages in Java

A package in Java is a collection of related classes, interfaces, and sub-packages.

SVCAS
63
JAVA PROGRAMMING
UNIT-II

It is used to:

 Organize code into namespaces


 Avoid name conflicts
 Provide access protection

1. Definition

 Syntax to define a package:

package package_name;

 Example:

package mypackage;
public class Demo {
public void display() {
[Link]("Hello from mypackage");
}
}

 Note: Package declaration must be the first line in the source file.

2. Access Protection in Packages

Java provides access modifiers to control visibility of classes, methods, and variables
across packages:

Access Same Same Subclass (different World (any


Modifier Class Package package) class)
private ✅ ❌ ❌ ❌
default ✅ ✅ ❌ ❌
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅

Rules for packages:

1. Only public classes are accessible outside the package.


2. Classes with default access are visible only within the same package.
3. Use protected to allow subclasses in other packages to access members.

3. Importing Packages

Java allows classes from one package to be used in another package using the import statement.

SVCAS
64
JAVA PROGRAMMING
UNIT-II

SYNTAX
import package_name.class_name; // Import a single class
import package_name.*; // Import all classes in a package

Example: Using a Package

File: mypackage/[Link]
package mypackage;
public class Demo {
public void display() {
[Link]("Hello from Demo class");
}
}

File: [Link]

import [Link]; // importing Demo class


public class Test {
public static void main(String[] args) {
Demo d = new Demo();
[Link](); // Output: Hello from Demo class
}
}

 You can also import all classes in mypackage:

import mypackage.*;

4. Types of Packages in Java

1. Built-in Packages – Java provides pre-defined packages like:


o [Link] (String, Math, Object)
o [Link] (ArrayList, Scanner)
o [Link] (File, InputStream)
o [Link] (Connection, ResultSet)
2. User-defined Packages – Packages created by programmers to organize classes.

5. Key Points

 Package declaration must be first line.


 Class accessibility outside the package depends on access modifiers.
 Use import to use classes from other packages.
 [Link] is automatically imported, no need to write import [Link].*.

*****************

SVCAS
65
JAVA PROGRAMMING
UNIT-II

Interfaces: Definition–Implementation–Extending Interfaces

1. Definition of Interface in Java

An interface in Java is a reference type, similar to a class, that can contain:

 Abstract methods (methods without a body)


 Default methods (methods with a body, Java 8+)
 Static methods
 Constants (public static final variables)

Key Points:

 Interface provides 100% abstraction (before Java 8).


 A class implements an interface to provide method definitions.
 Multiple inheritance is achieved via interfaces (since a class can implement multiple
interfaces).

SYNTAX:

interface InterfaceName {
// abstract methods
void method1();
void method2();
// constant variable
int MAX = 100; // public static final by default
}

2. Implementation of Interfaces

A class implements an interface using the implements keyword.

Rules:

1. The class must provide definitions for all abstract methods of the interface.
2. If it does not implement all methods, the class must be declared abstract.

Example:

interface Animal {
void eat();
void sleep();
}
class Dog implements Animal {
@Override
public void eat() {

SVCAS
66
JAVA PROGRAMMING
UNIT-II

[Link]("Dog eats");
}
@Override
public void sleep() {
[Link]("Dog sleeps");
}
}
public class Demo {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Dog eats
[Link](); // Dog sleeps
}
}

Output:

Dog eats
Dog sleeps

3. Extending Interfaces

 An interface can inherit another interface using the extends keyword.


 A child interface can add more abstract methods.
 Multiple inheritance is allowed (an interface can extend multiple interfaces).

Example: Single Interface Inheritance

interface Animal {
void eat();
}
interface Pet extends Animal {
void play();
}
class Dog implements Pet {
@Override
public void eat() {
[Link]("Dog eats");
}
@Override
public void play() {
[Link]("Dog plays");
}
}

public class Demo {

SVCAS
67
JAVA PROGRAMMING
UNIT-II

public static void main(String[] args) {


Dog d = new Dog();
[Link](); // Dog eats
[Link](); // Dog plays
}
}

Output:

Dog eats
Dog plays

Example: Multiple Interface Inheritance

interface Animal {
void eat();
}
interface Pet {
void play();
}
interface Domestic extends Animal, Pet {
void groom();
}
class Dog implements Domestic {
public void eat() {
[Link]("Dog eats");
}
public void play() {
[Link]("Dog plays");
}
public void groom() {
[Link]("Dog is groomed");
}
}
public class Demo {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
[Link]();
}
}

Output:

Dog eats

SVCAS
68
JAVA PROGRAMMING
UNIT-II

Dog plays
Dog is groomed

4. Key Points About Interfaces

1. All methods in an interface are public abstract by default.


2. All variables are public static final by default.
3. Cannot instantiate an interface directly.
4. A class can implement multiple interfaces → achieves multiple inheritance.
5. From Java 8 onwards:
o default methods and static methods are allowed in interfaces.

************

Exception Handling: try – catch- throw - throws – finally – Built-


inexceptions - Creating own Exception classes.
1. What is Exception Handling?

Exception handling is a mechanism in Java to handle runtime errors, so the normal flow of
the application can be maintained.

 Exception: An event that occurs during the execution of a program that disrupts the
normal flow.
 Error vs Exception: Errors are serious problems (like OutOfMemoryError) and
generally not handled in code. Exceptions are conditions that programs can anticipate and
handle.

2. Keywords in Exception Handling

a) try

 The try block contains code that might throw an exception.

SYNTAX:

try {
// code that might throw an exception
}

b) catch

 The catch block handles the exception thrown in the try block.

SYNTAX:

SVCAS
69
JAVA PROGRAMMING
UNIT-II

try {
int a = 10 / 0; // may throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
}

You can also have multiple catch blocks for different exceptions.

c) throw

 The throw keyword is used to explicitly throw an exception.

SYNTAX:

throw new ArithmeticException("Custom divide by zero error");

Example:

int divide(int a, int b) {


if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}

d) throws

 The throws keyword is used in the method signature to declare the exceptions that a
method might throw.

SYNTAX:

void readFile() throws IOException {


// code that may throw IOException
}

Example:

void divide(int a, int b) throws ArithmeticException {


[Link](a / b);
}

Note: throw is for actual exception objects, throws is for declaring exceptions.

SVCAS
70
JAVA PROGRAMMING
UNIT-II

e) finally

 The finally block contains code that always executes, whether an exception occurs or not.
 Typically used for cleanup, like closing files, streams, or database connections.

try {
int data = 25 / 0;
} catch (ArithmeticException e) {
[Link](e);
} finally {
[Link]("This always executes");
}

3. Built-in Exceptions

Java provides many pre-defined exceptions:

Exception Description
ArithmeticException Divide by zero
NullPointerException Using null object reference
ArrayIndexOutOfBoundsException Invalid array index
NumberFormatException Invalid number conversion
IOException Input/output failure
FileNotFoundException File not found

Example:

String str = null;


[Link]([Link]()); // Throws NullPointerException

4. Creating Custom Exception Classes

You can create your own exception by extending Exception or RuntimeException.

Example:
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}

public class TestCustomException {


static void validate(int age) throws My
******************

SVCAS
71
JAVA PROGRAMMING
UNIT-III

UNIT-III
What is Thread :

A thread in Java is essentially a lightweight unit of execution within a program. Think of


a Java program as a process, and a thread as a path of execution within that process. Multiple
threads can run concurrently inside the same program, allowing tasks to be performed
simultaneously.

Key Points About Threads

1. Definition:
o A thread is an independent path of execution within a program.
o Each thread has its own program counter, stack, and local variables but shares
memory with other threads of the same process.
2. Why Threads?
o To perform multiple tasks at the same time (concurrent execution).
o For example:
 Downloading a file while updating a progress bar.
 Running a server that handles multiple client requests simultaneously.
3. Java Support for Threads:
o Java provides built-in support for multithreading through the Thread class and the
Runnable interface.

Creating Threads in Java

There are two ways to create a thread:

1. Extending the Thread class

class MyThread extends Thread {


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

public class Test {


public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link](); // starts the thread
}
}

2. Implementing the Runnable interface

class MyRunnable implements Runnable {

SVCAS 72
JAVA PROGRAMMING
UNIT-III

public void run() {


[Link]("Thread is running");
}
}

public class Test {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
[Link]();
}
}

Important: Calling start() executes the thread in a new path of execution. Calling run() directly
just runs it like a normal method in the current thread.

Thread Life Cycle

A thread in Java can be in one of these states:

1. New – Thread object is created but not started.


2. Runnable – Thread is ready to run and waiting for CPU time.
3. Running – Thread is actively executing code.
4. Waiting/Blocked – Thread is waiting for some resource or event.
5. Terminated – Thread has finished execution.

Key Methods of Thread Class

Method Description
start() Starts a new thread and calls run()
run() Contains the code executed by the thread
sleep(ms) Pauses thread for given milliseconds
join() Waits for thread to finish execution
getName() Returns thread name
setName() Sets thread name
currentThread() Returns currently executing thread
setPriority() Sets thread priority (1–10)

************************

Multithreaded Programming: Thread Class

1. What is Multithreading?

Multithreading is a Java feature that allows concurrent execution of two or more threads
(lightweight processes) simultaneously.

SVCAS 73
JAVA PROGRAMMING
UNIT-III

 A thread is a single path of execution in a program.


 Multithreading helps in performing multiple tasks in parallel, improving performance,
especially in tasks like GUI applications, servers, or real-time systems.

2. Advantages of Multithreading

 Better CPU utilization.


 Improves performance.
 Provides concurrent execution of tasks.
 Useful in tasks like animation, file downloading, and network operations.

3. Thread Class in Java

In Java, a thread can be created in two ways:

1. By extending the Thread class.


2. By implementing the Runnable interface.

Here we focus on the Thread class.

a) Creating a Thread by Extending Thread Class

1. Step 1: Extend the Thread class.


2. Step 2: Override the run() method — this contains the code that executes in the new
thread.
3. Step 3: Create an instance of your class and call start() method to begin execution.

class MyThread extends Thread {


public void run() {
for(int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + " is running: " + i);
try {
[Link](500); // pauses for 500 ms
} catch (InterruptedException e) {
[Link](e);
}
}
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

[Link](); // starts new thread

SVCAS 74
JAVA PROGRAMMING
UNIT-III

[Link]();
}
}

Explanation:

 start() → Creates a new thread and calls run() internally.


 [Link](500) → pauses the thread for 500 milliseconds.
 [Link]().getName() → gets the name of the currently executing thread.

b) Important Thread Methods

Method Description
start() Starts the thread; invokes run() method
run() Contains the code executed by the thread
sleep(milliseconds) Pauses thread for specified time
getName() Returns thread name
setName(String name) Sets thread name
join() Waits for a thread to die before executing next code
yield() Suggests scheduler to give other threads a chance
isAlive() Checks if thread is still running
currentThread() Returns reference to the current thread

c) Thread Life Cycle

A thread goes through 5 states:

1. New → Thread object created.


2. Runnable → Thread eligible to run, waiting for CPU.
3. Running → Thread executes run() method.
4. Waiting/Blocked → Thread waiting for resource or sleep time.
5. Terminated → Thread has finished execution.

d) Thread Priority

 Threads can have priorities from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY). Default


is 5.
 Higher priority threads are more likely to run first.

[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);

e) Example with Thread Methods

class DemoThread extends Thread {

SVCAS 75
JAVA PROGRAMMING
UNIT-III

public void run() {


for(int i = 1; i <= 3; i++) {
[Link](getName() + " is running, priority: " + getPriority());
}
}
}

public class ThreadMethodsDemo {


public static void main(String[] args) {
DemoThread t1 = new DemoThread();
DemoThread t2 = new DemoThread();

[Link]("Thread-A");
[Link]("Thread-B");

[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);

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

Runnable interface

1. What is the Runnable Interface?

The Runnable interface is a functional interface in Java that represents a task to be executed
by a thread.

 It contains a single abstract method:

public void run();

 Unlike extending the Thread class, implementing Runnable allows your class to extend
another class, because Java supports single inheritance.
 Threads created with Runnable share the same memory, making it easier to manage
multiple threads.

2. Why Use Runnable?

 Flexibility: Your class can extend another class and still be runnable.
 Separation of Concerns: You separate the task (Runnable) from the thread (Thread) that
executes it.

SVCAS 76
JAVA PROGRAMMING
UNIT-III

 Resource Sharing: Multiple threads can share the same Runnable object, allowing
shared data and reducing memory usage.

3. Steps to Use Runnable

1. Create a class that implements Runnable.


2. Override the run() method with the task code.
3. Create a Thread object, passing the Runnable object to its constructor.
4. Call start() on the Thread object.

4. Example of Runnable

class MyRunnable implements Runnable {


public void run() {
for(int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + " is running: " + i);
try {
[Link](500); // Pause for 500ms
} catch (InterruptedException e) {
[Link](e);
}
}
}
}

public class RunnableDemo {


public static void main(String[] args) {
MyRunnable task = new MyRunnable();

Thread t1 = new Thread(task, "Thread-1");


Thread t2 = new Thread(task, "Thread-2");

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

Explanation:

 Thread t1 = new Thread(task, "Thread-1") → Wraps the Runnable object in a thread.


 start() → Starts the thread, calling the run() method internally.
 Both threads share the same Runnable object task.

SVCAS 77
JAVA PROGRAMMING
UNIT-III

Synchronization

1. What is Synchronization?

Synchronization in Java is a mechanism that controls access to shared resources by multiple


threads.

 When multiple threads try to access the same resource (like variables, objects, or
methods) concurrently, it can lead to inconsistent data.
 Synchronization ensures that only one thread can access a resource at a time, preventing
data corruption.

2. Why Synchronization is Needed

 Problem: Multiple threads modifying shared data at the same time → race condition.
 Solution: Synchronization → threads access shared resources one at a time.

Example of race condition:

class Counter {
int count = 0;

void increment() {
count++;
}
}

public class RaceConditionDemo {


public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();

Runnable r = () -> {
for (int i = 0; i < 1000; i++) {
[Link]();
}
};

Thread t1 = new Thread(r);


Thread t2 = new Thread(r);
[Link]();
[Link]();

[Link]();
[Link]();
[Link]("Count: " + [Link]); // Expected: 2000, might not be 2000 due to race
condition

SVCAS 78
JAVA PROGRAMMING
UNIT-III

}
}

Without synchronization, count may not be 2000 because both threads can read and write
simultaneously.

3. How to Achieve Synchronization in Java

a) Synchronized Methods

 Add the synchronized keyword to a method.


 Only one thread can execute a synchronized method of an object at a time.

class Counter {
int count = 0;

synchronized void increment() {


count++;
}
}

b) Synchronized Block

 Synchronizes only a specific block of code, not the entire method.


 Improves performance by reducing the scope of synchronization.

class Counter {
int count = 0;

void increment() {
synchronized(this) {
count++;
}
}
}

this refers to the current object. You can also synchronize on other objects.

c) Static Synchronization

 Synchronize static methods to lock the class object instead of the instance.

class Counter {
static int count = 0;
static synchronized void increment() {
count++;

SVCAS 79
JAVA PROGRAMMING
UNIT-III

}
}

4. Key Points

1. Thread safety: Synchronization ensures thread-safe access to shared resources.


2. Performance: Synchronization can slow down the program if overused. Only
synchronize critical sections.
3. Locks:
o Synchronized methods/blocks use intrinsic locks (monitor) on objects.
o Only one thread can hold the lock at a time.
4. Deadlock: Be careful! Multiple threads waiting for locks can cause deadlock.

5. Example of Synchronized Counter

class Counter {
int count = 0;

synchronized void increment() {


count++;
}
}

public class SyncDemo {


public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();

Runnable r = () -> {
for (int i = 0; i < 1000; i++) {
[Link]();
}
};

Thread t1 = new Thread(r);


Thread t2 = new Thread(r);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Count: " + [Link]); // Always 2000
}
}
Here, synchronized ensures that no two threads increment count simultaneously, so the output is
consistent.

*****************
SVCAS 80
JAVA PROGRAMMING
UNIT-III

Using Synchronized Methods

1. What is a Synchronized Method?

A synchronized method in Java is a method that allows only one thread at a time to execute it
on the same object.

 It ensures thread safety when multiple threads access shared resources.


 Java provides the synchronized keyword for this purpose.

SYNTAX:

synchronized returnType methodName(parameters) {


// critical section code
}

Critical Section: The part of code where shared resources are accessed and must be executed by
one thread at a time.

2. Why Use Synchronized Methods?

 Prevent race conditions (when two or more threads modify shared data at the same time).
 Ensure data consistency when multiple threads access shared variables.

3. Example of Synchronized Method

class Counter {
private int count = 0;

// Synchronized method
public synchronized void increment() {
count++;
[Link]([Link]().getName() + " incremented count to " + count);
}

public int getCount() {


return count;
}
}

public class SynchronizedMethodDemo {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();

// Runnable task
Runnable task = () -> {

SVCAS 81
JAVA PROGRAMMING
UNIT-III

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


[Link](); // only one thread can execute this at a time
}
};

Thread t1 = new Thread(task, "Thread-1");


Thread t2 = new Thread(task, "Thread-2");

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

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

[Link]("Final Count: " + [Link]());


}
}

Explanation:

 synchronized ensures that only one thread can execute increment() on the same Counter
object at a time.
 Without synchronized, two threads could interleave, causing an incorrect final count.

Sample Output:

Thread-1 incremented count to 1


Thread-1 incremented count to 2
Thread-2 incremented count to 3
Thread-2 incremented count to 4
Thread-1 incremented count to 5
Thread-2 incremented count to 6
Thread-1 incremented count to 7
Thread-2 incremented count to 8
Thread-1 incremented count to 9
Thread-2 incremented count to 10
Final Count: 10

4. Notes on Synchronized Methods

1. Instance Methods
o Lock is applied on the object instance (this).
o Only one thread per object can execute synchronized instance methods.
2. Static Methods
o Lock is applied on the class object.
o Only one thread per class can execute synchronized static methods.

SVCAS 82
JAVA PROGRAMMING
UNIT-III

class Counter {
private static int count = 0;

public static synchronized void incrementStatic() {


count++;
[Link]([Link]().getName() + " incremented count to " + count);
}
}

[Link] Consideration

o Synchronization can reduce performance due to thread contention.


o Only synchronize critical sections, not the entire method if unnecessary.

*********************

Using synchronized statement:

1. What is a Synchronized Statement?

A synchronized statement (or synchronized block) in Java is a way to synchronize only a part
of a method instead of the entire method.

 It helps improve performance, because only the critical section (code that accesses shared
resources) is synchronized.
 Syntax:

synchronized(objectReference) {
// critical section code
}

Key Points:

 objectReference is the lock. Only one thread can hold the lock at a time.
 Other threads must wait until the lock is released.
 Can be used inside instance methods, static methods, or regular methods.

2. Why Use Synchronized Blocks?

 Performance: Instead of synchronizing the whole method, synchronize only the part that
needs protection.
 Flexibility: Can synchronize on different objects, not just this.
 Helps prevent race conditions when multiple threads access shared data.

3. Example of Synchronized Statement

SVCAS 83
JAVA PROGRAMMING
UNIT-III

class Counter {
private int count = 0;

public void increment() {


// Only the critical section is synchronized
synchronized(this) {
count++;
[Link]([Link]().getName() + " incremented count to " +
count);
}
}

public int getCount() {


return count;
}
}

public class SynchronizedBlockDemo {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();

Runnable task = () -> {


for (int i = 0; i < 5; i++) {
[Link]();
}
};

Thread t1 = new Thread(task, "Thread-1");


Thread t2 = new Thread(task, "Thread-2");
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Final Count: " + [Link]());
}
}

Explanation:

 Only the count++ and println lines are synchronized, so threads cannot execute this block
simultaneously.
 Other non-critical code outside the synchronized block can run in parallel.

Sample Output:

Thread-1 incremented count to 1

SVCAS 84
JAVA PROGRAMMING
UNIT-III

Thread-2 incremented count to 2


Thread-1 incremented count to 3
Thread-2 incremented count to 4
...
Final Count: 10

4. Synchronizing on Different Objects

class Printer {
public void print(String message) {
synchronized(this) { // lock on this Printer object
[Link]("[");
try { [Link](100); } catch (InterruptedException e) {}
[Link](message + "]");
}
}
}

public class SyncDifferentObjects {


public static void main(String[] args) {
Printer p1 = new Printer();
Printer p2 = new Printer();

Thread t1 = new Thread(() -> [Link]("Hello"), "T1");


Thread t2 = new Thread(() -> [Link]("World"), "T2");
[Link]();
[Link]();
}
}

Explanation:

 t1 locks on p1, t2 locks on p2.


 They can run simultaneously because locks are on different objects.

5. Key Points

1. Use synchronized blocks when only part of the method needs thread safety.
2. Can synchronize on:
o this → lock the current object.
o Any other object → fine-grained locking.
3. Static methods or blocks → lock on the class object.
4. Reduces thread contention and improves performance compared to synchronized
methods.

******************

SVCAS 85
JAVA PROGRAMMING
UNIT-III

Interthread Communication

1. What is Inter-thread Communication?

Inter-thread communication in Java is a mechanism that allows threads to communicate with


each other while sharing resources.

 It is mainly used when one thread is producing data and another thread is consuming it.
 Helps coordinate thread execution to avoid conflicts like race conditions or busy waiting.

Common Scenario: Producer-Consumer problem.

2. Why Inter-thread Communication?

 Multiple threads may need to wait for some condition before continuing.
 Threads should be able to notify each other when the condition changes.
 Example:
o Thread 1 (Producer) adds data to a buffer.
o Thread 2 (Consumer) waits until data is available.

3. Methods Used for Inter-thread Communication

Java provides three key methods in the Object class (every object in Java inherits these):

Method Description
wait() Makes the current thread release the lock and wait until another thread calls notify()
or notifyAll().
notify() Wakes up one waiting thread.
notifyAll() Wakes up all waiting threads.

Important:

 These methods must be called inside synchronized context.


 wait() releases the lock, allowing other threads to enter the synchronized block.

4. Example: Producer-Consumer Using wait() and notify()

class SharedResource {
private int data;
private boolean available = false;

// Producer method
public synchronized void produce(int value) {
while (available) { // if data is already available, wait
try {
wait();

SVCAS 86
JAVA PROGRAMMING
UNIT-III

} catch (InterruptedException e) {}
}
data = value;
[Link]("Produced: " + data);
available = true;
notify(); // notify consumer
}

// Consumer method
public synchronized void consume() {
while (!available) { // if no data, wait
try {
wait();
} catch (InterruptedException e) {}
}
[Link]("Consumed: " + data);
available = false;
notify(); // notify producer
}
}

public class InterThreadDemo {


public static void main(String[] args) {
SharedResource sr = new SharedResource();

Thread producer = new Thread(() -> {


for (int i = 1; i <= 5; i++) {
[Link](i);
}
});

Thread consumer = new Thread(() -> {


for (int i = 1; i <= 5; i++) {
[Link]();
}
});

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

Explanation:

 produce() waits if the resource is already available.


 consume() waits if no data is available.

SVCAS 87
JAVA PROGRAMMING
UNIT-III

 notify() wakes up the other thread after producing or consuming.

Sample Output:

Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
...

5. Key Points

1. Synchronization required: wait(), notify(), notifyAll() must be called inside


synchronized blocks/methods.
2. Releases lock on wait(): When a thread calls wait(), it releases the object lock so other
threads can enter the synchronized block.
3. notify() vs notifyAll():
o notify() → wakes one waiting thread (arbitrary choice).
o notifyAll() → wakes all waiting threads.
4. Avoid busy waiting: Inter-thread communication avoids threads constantly checking a
condition.

********************

Deadlock

1. What is Deadlock?

A deadlock in Java is a situation where two or more threads are blocked forever, waiting for
resources held by each other.

 In other words, each thread is waiting for a resource that another thread has, so none of
them can proceed.
 It is a common problem in multithreaded programs involving synchronization.

2. Conditions for Deadlock

For a deadlock to occur, all four Coffman conditions must be present:

1. Mutual Exclusion: At least one resource must be held in a non-shareable mode.


2. Hold and Wait: A thread holding a resource is waiting to acquire additional resources
held by other threads.
3. No Preemption: Resources cannot be forcibly taken from threads; they must be released
voluntarily.
4. Circular Wait: A circular chain of threads exists, where each thread waits for a resource
held by the next thread.

SVCAS 88
JAVA PROGRAMMING
UNIT-III

3. Example of Deadlock in Java

class Resource {
String name;
Resource(String name) {
[Link] = name;
}
}

public class DeadlockDemo {


public static void main(String[] args) {
final Resource r1 = new Resource("Resource-1");
final Resource r2 = new Resource("Resource-2");

// Thread 1 tries to lock r1 then r2


Thread t1 = new Thread(() -> {
synchronized (r1) {
[Link]("Thread-1 locked " + [Link]);
try { [Link](100); } catch (InterruptedException e) {}
synchronized (r2) {
[Link]("Thread-1 locked " + [Link]);
}
}
});

// Thread 2 tries to lock r2 then r1


Thread t2 = new Thread(() -> {
synchronized (r2) {
[Link]("Thread-2 locked " + [Link]);
try { [Link](100); } catch (InterruptedException e) {}
synchronized (r1) {
[Link]("Thread-2 locked " + [Link]);
}
}
});

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

Explanation:

1. Thread-1 locks r1 and waits for r2.


2. Thread-2 locks r2 and waits for r1.
3. Both threads are blocked forever, causing a deadlock.

SVCAS 89
JAVA PROGRAMMING
UNIT-III

Sample Output (may vary):

Thread-1 locked Resource-1


Thread-2 locked Resource-2

 Program hangs after this point.

4. How to Avoid Deadlock

1. Lock Ordering: Acquire locks in a consistent order in all threads.


2. Try-Lock with Timeout: Use tryLock() (in [Link]) to acquire a
lock with a timeout.
3. Avoid Nested Locks: Minimize locking multiple resources at the same time.
4. Deadlock Detection: Monitor thread states and detect circular waiting patterns.

I/O Streams: Concepts Of Streams

1. What are I/O Streams in Java?

I/O Streams in Java are sequences of data used to read from or write to a source or
destination, such as files, memory, or network connections.

 Input Stream → used to read data from a source.


 Output Stream → used to write data to a destination.
 Java uses the concept of streams to provide a continuous flow of data.

2. Key Concepts

1. Stream:
o A flow of data from a source (input) or to a destination (output).
2. Byte Stream vs Character Stream:

Type Base Class Data Handled Example Classes


Byte Stream InputStream / 8-bit binary FileInputStream,
OutputStream data FileOutputStream
Character Reader / Writer 16-bit FileReader, FileWriter
Stream characters

3. Unidirectional:
o Streams are one-way: either input or output.
4. Buffered Streams (Optional):
o Improve performance by reading/writing large chunks instead of one byte/char at
a time.

SVCAS 90
JAVA PROGRAMMING
UNIT-III

3. Hierarchy of I/O Streams

a) Byte Streams

 InputStream → abstract class for reading bytes.


 OutputStream → abstract class for writing bytes.

Common Classes:

 FileInputStream → read bytes from file.


 FileOutputStream → write bytes to file.
 BufferedInputStream / BufferedOutputStream → buffered byte streams.

b) Character Streams

 Reader → abstract class for reading characters.


 Writer → abstract class for writing characters.

Common Classes:

 FileReader → read characters from file.


 FileWriter → write characters to file.
 BufferedReader / BufferedWriter → buffered character streams.

4. Example: Byte Stream

import [Link];
import [Link];
import [Link];
public class ByteStreamExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("[Link]");
FileOutputStream fos = new FileOutputStream("[Link]")) {

int b;
while ((b = [Link]()) != -1) {
[Link](b); // write byte to output
}

[Link]("File copied successfully!");

} catch (IOException e) {
[Link]();
}
}
}

SVCAS 91
JAVA PROGRAMMING
UNIT-III

5. Example: Character Stream

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

public class CharStreamExample {


public static void main(String[] args) {
try (FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]")) {

int c;
while ((c = [Link]()) != -1) {
[Link](c); // write character to output
}

[Link]("File copied successfully!");

} catch (IOException e) {
[Link]();
}
}
}

6. Key Points

1. Streams are unidirectional: Input or Output, not both.


2. Byte streams are used for binary data, character streams for text data.
3. Buffered streams improve efficiency by reducing I/O operations.
4. Always close streams to release system resources (try-with-resources is preferred).

**********************

Stream classes
1. What are Stream Classes in Java?

In Java, a stream class is a class that provides methods for reading and writing data in a
continuous flow.

 Java I/O is built around streams, which can be byte-oriented or character-oriented.


 Streams provide a uniform way to handle I/O, regardless of the source (file, memory,
network, etc.).

SVCAS 92
JAVA PROGRAMMING
UNIT-III

2. Types of Streams

Java divides streams into two main categories:

A) Byte Streams

 Handle binary data (8-bit bytes).


 Useful for reading/writing images, audio, video, and other binary files.
 Base classes:
o InputStream → abstract class for reading bytes.
o OutputStream → abstract class for writing bytes.

Common Byte Stream Classes:

Class Description
FileInputStream Reads bytes from a file
FileOutputStream Writes bytes to a file
BufferedInputStream Buffers input bytes for efficiency
BufferedOutputStream Buffers output bytes for efficiency
DataInputStream Reads primitive data types
DataOutputStream Writes primitive data types

B) Character Streams

 Handle text data (16-bit characters).


 Useful for reading/writing text files.
 Base classes:
o Reader → abstract class for reading characters.
o Writer → abstract class for writing characters.

Common Character Stream Classes:

Class Description
FileReader Reads characters from a file
FileWriter Writes characters to a file
BufferedReader Buffers input characters
BufferedWriter Buffers output characters
PrintWriter Writes formatted text easily

SVCAS 93
JAVA PROGRAMMING
UNIT-III

3. Stream Class Hierarchy (Simplified)

Byte Streams:

InputStream
|__ FileInputStream
|__ BufferedInputStream
|__ DataInputStream

OutputStream
|__ FileOutputStream
|__ BufferedOutputStream
|__ DataOutputStream

Character Streams:

Reader
|__ FileReader
|__ BufferedReader
|__ InputStreamReader

Writer
|__ FileWriter
|__ BufferedWriter
|__ OutputStreamWriter
|__ PrintWriter

4. Example: Using Stream Classes

Byte Stream Example:

import [Link].*;
public class ByteStreamExample {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("[Link]");
FileOutputStream fos = new FileOutputStream("[Link]");
int b;
while ((b = [Link]()) != -1) {
[Link](b);
}

[Link]();
[Link]();
[Link]("File copied successfully using byte streams!");
}
}

SVCAS 94
JAVA PROGRAMMING
UNIT-III

Character Stream Example:

import [Link].*;

public class CharStreamExample {


public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}

[Link]();
[Link]();
[Link]("File copied successfully using character streams!");
}
}

5. Key Points

1. Byte Streams → binary data (images, audio, video).


2. Character Streams → text data (files with characters).
3. Buffered Streams → improve performance by reducing I/O operations.
4. Streams are unidirectional: Input or Output.
5. Always close streams to free resources (or use try-with-resources).

****************

Byte and Character stream


1. Byte Streams in Java

Definition:
Byte streams are used to read and write data in 8-bit bytes. They are suitable for binary
data such as images, audio, video, or any file where character encoding matters.

 Base Classes:
o InputStream → abstract class for reading bytes.
o OutputStream → abstract class for writing bytes.

SVCAS 95
JAVA PROGRAMMING
UNIT-III

Common Byte Stream Classes:

Class Purpose
FileInputStream Reads bytes from a file
FileOutputStream Writes bytes to a file
BufferedInputStream Buffers input bytes for efficiency
BufferedOutputStream Buffers output bytes for efficiency
DataInputStream Reads primitive data types (int, float, etc.)
DataOutputStream Writes primitive data types

Example of Byte Stream:

import [Link].*;

public class ByteStreamExample {


public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("[Link]"); // binary file
FileOutputStream fos = new FileOutputStream("[Link]");

int b;
while ((b = [Link]()) != -1) {
[Link](b); // write byte to output
}

[Link]();
[Link]();
[Link]("Binary file copied successfully!");
}
}

Key Points:

 Reads and writes raw bytes.


 Suitable for binary files.
 Can handle any file type.

2. Character Streams in Java

Definition:
Character streams are used to read and write data in 16-bit Unicode characters. They
are suitable for text files where proper encoding matters.

 Base Classes:
o Reader → abstract class for reading characters.
o Writer → abstract class for writing characters.

SVCAS 96
JAVA PROGRAMMING
UNIT-III

Common Character Stream Classes:

Class Purpose
FileReader Reads characters from a text file
FileWriter Writes characters to a text file
BufferedReader Buffers input characters
BufferedWriter Buffers output characters
PrintWriter Writes formatted text easily

Example of Character Stream:

import [Link].*;

public class CharStreamExample {


public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("[Link]"); // text file
FileWriter fw = new FileWriter("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c); // write character to output
}

[Link]();
[Link]();
[Link]("Text file copied successfully!");
}
}

Key Points:

 Reads and writes characters, not raw bytes.


 Automatically handles Unicode encoding.
 Ideal for text files.

3. Key Differences Between Byte and Character Streams

Feature Byte Stream Character Stream


Base Classes InputStream, OutputStream Reader, Writer
Data Unit 8-bit bytes 16-bit characters
Suitable For Binary files (images, audio, video) Text files (txt, csv, etc.)
Encoding Handling No automatic encoding handling Handles Unicode automatically
Example Classes FileInputStream, FileOutputStream FileReader, FileWriter

*******************

SVCAS 97
JAVA PROGRAMMING
UNIT-III

Reading console Input and Writing Console output

1. Writing Console Output

In Java, the standard way to write output to the console is using the [Link] object.

Common Methods:

 [Link]() → prints text without newline.


 [Link]() → prints text with newline.
 [Link]() → prints formatted text, similar to C’s printf.

Example:

public class ConsoleOutputExample {


public static void main(String[] args) {
[Link]("Hello "); // no newline
[Link]("World!"); // newline after printing
[Link]("Number: %d%n", 100); // formatted output
}
}

Output:

Hello World!
Number: 100

2. Reading Console Input

Java provides multiple ways to read input from the console:

A) Using Scanner Class

 Part of [Link] package.


 Can read different data types: int, double, String, etc.

Example:

import [Link];

public class ScannerInputExample {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

SVCAS 98
JAVA PROGRAMMING
UNIT-III

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Hello " + name + ", you are " + age + " years old.");

[Link]();
}
}

Sample Input/Output:

Enter your name: Alice


Enter your age: 25
Hello Alice, you are 25 years old.

Notes:

 nextLine() → reads a line of text.


 next() → reads a single word.
 nextInt(), nextDouble() → read numeric input.

B) Using BufferedReader

 Part of [Link] package.


 Reads text efficiently using buffered input.
 Returns input as a String, so numeric input requires conversion.

Example:

import [Link].*;

public class BufferedReaderExample {


public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]([Link]()); // convert string to int

[Link]("Hello " + name + ", you are " + age + " years old.");
}
}

SVCAS 99
JAVA PROGRAMMING
UNIT-III

Notes:

 InputStreamReader([Link]) converts bytes to characters.


 readLine() reads one line of input.
 Numeric conversion needed for non-string inputs.

C) Using Console Class

 Part of [Link] package.


 Provides methods like readLine() and readPassword().
 Not available in all IDEs (works in real console).

Example:

import [Link];

public class ConsoleClassExample {


public static void main(String[] args) {
Console console = [Link]();

if (console != null) {
String name = [Link]("Enter your name: ");
String ageStr = [Link]("Enter your age: ");
int age = [Link](ageStr);

[Link]("Hello %s, you are %d years old.%n", name, age);


} else {
[Link]("Console not available");
}
}
}

***********************

File Handling

1. What is File Handling in Java?

File Handling in Java allows programs to create, read, write, and manipulate files on the file
system.

 Java provides the [Link] and [Link] packages for file handling.
 A file is a collection of data stored on disk.

SVCAS 100
JAVA PROGRAMMING
UNIT-III

Common Operations:

1. Create a file
2. Write data to a file
3. Read data from a file
4. Append data to a file
5. Delete a file
6. Check if a file exists

2. Classes Used in File Handling

A) [Link]

 Represents a file or directory in the file system.


 Does not handle file content directly.

Common Methods:

Method Description
createNewFile() Creates a new file
exists() Checks if file exists
delete() Deletes the file
getName() Returns file name
length() Returns file size in bytes
isDirectory() Checks if it is a directory

Example:

import [Link];
import [Link];

public class FileExample {


public static void main(String[] args) throws IOException {
File file = new File("[Link]");

if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}

[Link]("File exists? " + [Link]());


[Link]("File size: " + [Link]() + " bytes");
}
}

SVCAS 101
JAVA PROGRAMMING
UNIT-III

B) Writing to a File

 Use FileWriter or BufferedWriter for text files.


 Can write characters or strings.

Example:

import [Link];
import [Link];

public class FileWriteExample {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("[Link]");
[Link]("Hello, Java File Handling!\n");
[Link]("This is a new line.");
[Link](); // Always close the writer
[Link]("Data written to file successfully.");
} catch (IOException e) {
[Link]();
}
}
}

C) Reading from a File

 Use FileReader, BufferedReader, or Scanner.

Example with BufferedReader:

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

public class FileReadExample {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}

SVCAS 102
JAVA PROGRAMMING
UNIT-III

D) Appending Data to a File

 Use FileWriter with append flag set to true.

import [Link];
import [Link];

public class FileAppendExample {


public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("[Link]", true); // append mode
[Link]("\nThis line is appended.");
[Link]();
[Link]("Data appended successfully.");
} catch (IOException e) {
[Link]();
}
}
}

E) Deleting a File

import [Link];

public class FileDeleteExample {


public static void main(String[] args) {
File file = new File("[Link]");
if ([Link]()) {
[Link]("File deleted successfully.");
} else {
[Link]("Failed to delete the file.");
}
}
}

SVCAS 103
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
Container IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV
Java programming

UNIT -
IV

Working with Font

1. Creating a Font

You can create a Font object using the constructor:

Font font = new Font(String name, int style, int size);

 name: The font name (e.g., "Serif", "Arial", "Times New Roman", etc.)
 style: The style of the font. It can be one of the following constants:
o [Link] (normal)
o [Link]
o [Link]
o [Link] + [Link]
 size: The size of the font in points (e.g., 12, 16, 20).

Example of Creating a Font:

Font font = new Font("Serif", [Link], 20);

2. Setting the Font in a Component

Once you have a Font object, you can set it on a component such as a Label, Button, TextField, etc.

For example, to set a font on a Label:

Label label = new Label("Hello, World!");


[Link](font);
Java Programming Unit -
IV
Layout manager

The Layout managers enable us to control the way in which visual components are
arranged in the GUI forms by determining the size and position of components within the
containers.

Types of Layout Manager

There are 6 layout managers in Java

 FlowLayout:
 It arranges the components in a container like the words on a page. It fills the
top line from left to right and top to bottom.
 The components are arranged in the order as they are added i.e. first
components appears at top left, if the container is not wide enough to display
all the components, it is wrapped around the line.
 Vertical and horizontal gap between components can be controlled. The
components can be left, center or right aligned.
 BorderLayout:
 It arranges all the components along the edges or the middle of the container
i.e. top, bottom, right and left edges of the area.
 The components added to the top or bottom gets its preferred height, but its
width will be the width of the container and also the components added to the
left or right gets its preferred width, but its height will be the remaining height
of the container.
 The components added to the center gets neither its preferred height or width.
It covers the remaining area of the container.
 GridLayout:
 It arranges all the components in a grid of equally sized cells, adding them
from the left to right and top to bottom.
 Only one component can be placed in a cell and each region of the grid will
have the same size.
 When the container is resized, all cells are automatically resized. The order of
placing the components in a cell is determined as they were added.
 GridBagLayout:
 It is a powerful layout which arranges all the components in a grid of cells and
maintains the aspect ration of the object whenever the container is resized.
 In this layout, cells may be different in size. It assigns a consistent horizontal
and vertical gap among components.
 It allows us to specify a default alignment for components within the columns
or rows.
 BoxLayout:
 It arranges multiple components in either vertically or horizontally, but not
both. The components are arranged from left to right or top to bottom.
 If the components are aligned horizontally, the height of all components will
be the same and equal to the largest sized components.
 If the components are aligned vertically, the width of all components will be
the same and equal to the largest width components.
 CardLayout:
 It arranges two or more components having the same size. The components

19
are arranged in a deck, where all the cards of the same size and the only top
card are visible at any time.
SVCAS
Java Programming Unit -
IV
 The first component added in the container will be kept at the top of the deck.
The default gap at the left, right, top and bottom edges are zero and the card
components are displayed either horizontally or vertically.

Example
import [Link].*;
import [Link].*;
public class LayoutManagerTest extends JFrame {
JPanel flowLayoutPanel1, flowLayoutPanel2, gridLayoutPanel1, gridLayoutPanel2,
gridLayoutPanel3;
JButton one, two, three, four, five, six;
JLabel bottom, lbl1, lbl2, lbl3;
public LayoutManagerTest() {
setTitle("LayoutManager Test");
setLayout(new BorderLayout()); // Set BorderLayout for JFrame
flowLayoutPanel1 = new JPanel();
one = new JButton("One");
two = new JButton("Two");
three = new JButton("Three");
[Link](new FlowLayout([Link])); // Set
FlowLayout Manager
[Link](one);
[Link](two);
[Link](three);
flowLayoutPanel2 = new JPanel();
bottom = new JLabel("This is South");
[Link] (new FlowLayout([Link])); // Set
FlowLayout Manager
[Link](bottom);
gridLayoutPanel1 = new JPanel();
gridLayoutPanel2 = new JPanel();
gridLayoutPanel3 = new JPanel();
lbl1 = new JLabel("One");
lbl2 = new JLabel("Two");
lbl3 = new JLabel("Three");
four = new JButton("Four");
five = new JButton("Five");
six = new JButton("Six");
[Link](new GridLayout(1, 3, 5, 5)); // Set GridLayout Manager
[Link](lbl1);
[Link](lbl2);
[Link](lbl3);
[Link](new GridLayout(3, 1, 5, 5)); // Set GridLayout Manager
[Link](four);
[Link](five);
[Link](six);
[Link](new GridLayout(2, 1)); // Set GridLayout Manager
[Link](gridLayoutPanel2);
[Link](gridLayoutPanel3);

20
add(flowLayoutPanel1, [Link]);
add(flowLayoutPanel2, [Link]);
SVCAS
Java Programming Unit -
IV
add(gridLayoutPanel1, [Link]);
setSize(400, 325);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new LayoutManagerTest();
}
}

Output

Event Handling

Event handling in Java AWT (Abstract Window Toolkit) is an important concept to


understand for creating interactive applications. Java uses the Event-Listener model to
handle user interactions like button clicks, key presses, mouse movements, etc.

1. What is an Event?

An event is an action or occurrence that is recognized by the program. Common examples of


events are:

 A button is clicked.
 The mouse is moved.
 A key is pressed.
 A window is resized.

2. Event Handling Process

Event handling in Java typically follows these steps:


SVCAS
21
Java Programming Unit -
IV
1. Event Source: The component (such as a button, text field, or mouse) that generates an
event.
2. Event Listener: An interface implemented by a class to handle the event.
3. Event Object: An object that contains information about the event (e.g., ActionEvent,
MouseEvent).
4. Event Handling: When the event occurs, the listener reacts to it by invoking the
corresponding method.

Here are some of the event handling components in Java:


 Java ActionListener
 Java MouseListener
 Java MouseMotionListener
 Java ItemListener
 Java KeyListener
 Java WindowListener
 Close AWT Window
1. Java ActionListener
Java ActionListner is a interface which responds to the actions performed by the
components like buttons, menu items ,etc.
Syntax of Java ActionListener:
public class ActionListenerExample Implements ActionListener
There is only methods associated with ActionListner class that is actionPerformed().
Syntax of actionPerformed() method:
public abstract void actionPerformed(ActionEvent e);
2. Java MouseListener
Java MouseListner is a interface that responds to the actions performed by mouse
events generated by the user. Example: mouse clicks , mouse movements, etc.
There are 5 Methods associated with MouseListner:
1. mouseClicked(MouseEvent e):
Responds to mouse buttons when clicked on a component in the Application.
2. mousePressed(MouseEvent e):
Responds to mouse button is Pressed on a component in the Application.
3. mouseReleased(MouseEvent e):
Responds to Mouse button released after being pressed over a component in the
Application.
4. mouseEntered(MouseEvent e):
Responds to the situation when a Mouse cursor enters the bounds of a component in an
Application.
5. mouseExited(MouseEvent e):
Responds to the situation when a Mouse cursor exits a component’s bounds.

3. Java MouseMotionListener
Java MouseMotionListner is a interface which is notified when mouse is moved or
dragged.
It contains two Methods mentioned below:
1. mouseDragged(MouseEvent e):
Responds when the mouse is dragged with mouse button clicked over a component in
Application.
2. mouseMoved(MouseEvent e):
Responds when the mouse is moved over a component in Application.

22
4. Java ItemListener

SVCAS
Java Programming Unit -
IV
Java ItemListner is an interface which handles events related to item selection and
deselection those that occur with checkboxes, radio buttons, etc. There is only one Method
associated with ItemListner that is itemStateChanged(). This method provides information
about the event, i.e. source of the event and the changed state.
Syntax of itemStateChanged() method:
itemStateChanged(ItemEvent e)
5. Java KeyListener
Java KeyListner is an interface in Java notified whenever you change the state of
key or can be said for key related events.
Syntax of KeyListener:
public interface KeyListener extends EventListener
There are three methods associated with KeyListner as mentioned below:
1. keyPressed (KeyEvent e):
Responds to the event when key is pressed.
2. keyReleased (KeyEvent e):
Responds to the event when the key is released.
3. keyTyped (KeyEvent e):
Responds to the key has been typed.
6. Java WindowListener
Java WindowListener is a interface used for handling events related to window
actions. Events like opening , closing, minimizing, etc are handled using WindowListener.
Syntax of WindowListener
public interface WindowListener extends EventListener
There are seven methods associated with WindowListener as mentioned below:
1. windowActivated (WindowEvent e):
Responds when window is first opened
2. windowClosed (WindowEvent e):
Responds when the user attempts to close the window
3. windowClosing (WindowEvent e):
Responds after a window has been closed
4. windowDeactivated (WindowEvent e):
Responds when a window is minimized
5. windowDeiconified (WindowEvent e):
Responds when a window is restored from a minimized state
6. windowIconified (WindowEvent e):
Responds when a window is activated
7. windowOpened (WindowEvent e):
Responds when a window loses focus
7. Java Adapter classes
Java adapter classes provide the default implementation of listener interfaces.
8. Close AWT Window
At the end we will need to Close AWT Window, So to perform this task we will use
dispose() method. This method releases the resources associated with the window and also
removes it from the screen.

Event delegation model (EDM)


It is a mechanism to control the events and to decide what should happen after an

23
event occur. To handle the events, Java follows the Delegation Event model.

SVCAS
Java Programming Unit -
IV
Delegation Event model
 It has Sources and Listeners.

 Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate
events.
 Listeners: Listeners are used for handling the events generated from the source. Each of
these listeners represents interfaces that are responsible for handling events.

Handling Mouse and Keyboard Events

Handling Mouse Events:

•To handle mouse events, we must implement one of the appropriate interfaces as follows:
1) MouseListener
2) MouseMotionListener
3) MouseWheelListener
•If any one of the above interfaces is implemented, we must provide implementations for all
the methods available in that interface.
•Methods available in “MouseListener” interface are:
1) mouseClicked()
2) mousePressed()
3) mouseReleased()
4) mouseEntered()
5) mouseExited()
•Methods available in “MouseMotionListener” interface are:
1) mouseMoved()
2) mouseDragged()
•Methods available in “MouseWheelListener” are:
1) mouseWheelMoved()
•We can get the x-coordinate and y-coordinate where the mouse is clicked by using two
methods available in “MouseEvent” class. Those methods are:

24
1) int getX() – To get the x-coordinate

SVCAS
Java Programming Unit -
IV
2) int getY() – To get the y-coordinate

Handling Keyboard Events:

•To handle keyboard events, we must implement the “KeyListener” interface.


•When the “KeyListener” interface is implemented, we must provide implementations for
three methods available in that interface. They are:
1) keyPressed()
2) keyReleased()
3) keyTyped()
•To get the character, when the keyTyped() event occurs, we use the method:
char getKeyChar()

Java Adapter Classes


Java adapter classes provide the default implementation of listener interfaces.

If you inherit the adapter class, you will not be forced to provide the implementation
of all the methods of listener interfaces. So it saves code.

Pros of using Adapter classes:

o It assists the unrelated classes to work combinedly.


o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.
The adapter classes are found in [Link],
[Link] and [Link] packages. The Adapter classes with their corresponding
listener interfaces are given below.

[Link] Adapter classes

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

SVCAS
25
Java Programming Unit -
IV
HierarchyBoundsAdapter HierarchyBoundsListener

Java WindowAdapter

In the following example, we are implementing the WindowAdapter class of AWT


and one its methods windowClosing() to close the frame window.

Java MouseAdapter

In the following example, we are implementing the MouseAdapter class. The


MouseListener interface is added into the frame to listen the mouse event in the frame.

Java MouseMotionAdapter

In the following example, we are implementing the MouseMotionAdapter class and


its different methods to listen to the mouse motion events in the Frame window.

Java KeyAdapter

In the following example, we are implementing the KeyAdapter class and its method.

Inner classes:-

A Java inner class is a class that is defined inside another class.

The concept of inner class works with nested Java classes where outer and inner classes are
used.

The main class in which inner classes are defined is known as the outer class and all other
classes which are inside the outer class are known as Java inner classes.

Nested Classes
In Java, just like methods, variables of a class too can have another class as its member.
Writing a class within another is allowed in Java.

The class written within is called the nested class, and the class that holds the inner class is
called the outer class.

Syntax

class Outer_Demo {
class Inner_Demo {
}
}

Nested classes are divided into two types −

 Non-static nested classes − These are the non-static members of a class.


 Static nested classes − These are the static members of a class.

SVCAS
26
Java Programming Unit -
IV

Types of Java Inner Classes

Inner classes are of three types depending on how and where you define them. They are −

 Inner Class
 Method-local Inner Class
 Anonymous Inner Class

Inner Class

 Creating an inner class is quite simple. You just need to write a class within a
class. Unlike a class, an inner class can be private and once you declare an
inner class private, it cannot be accessed from an object outside the class.
 Following is the program to create an inner class and access it. In the given
example, we make the inner class private and access the class through a
method.

Method-local Inner Class

 In Java, we can write a class within a method and this will be a local type.
Like local variables, the scope of the inner class is restricted within the
method.
 A method-local inner class can be instantiated only within the method where
the inner class is defined. The following program shows how to use a method-
local inner class.

Anonymous Inner Class

 An inner class declared without a class name is known as an anonymous


inner class.

SVCAS
27
Java Programming Unit -
IV
 In case of anonymous inner classes, we declare and instantiate them at the
same time.
 Generally, they are used whenever you need to override the method of a class
or an interface.

Syntax:

AnonymousInner an_inner = new AnonymousInner() {


public void my_method() {
........
........
}
};

Static Nested Class

 A static inner class is a nested class which is a static member of the outer class.
 It can be accessed without instantiating the outer class, using other static members.
Just like static members, a static nested class does not have access to the instance
variables and methods of the outer class.

Syntax

class MyOuter {
static class Nested_Demo {
}
}

SVCAS
28
Java Programming
Unit -
V
Unit- V [Swing]

What is Swing:-
 Swing is a framework or API that is used to create GUI (or) window-based
applications.
 It is anadvanced version of AWT(Abstract Window Toolkit) API and entirely
written in java.
 Unlike AWT, Java Swing provides platform Independent and light weight
components.
 The [Link] package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.,

Difference Between AWT and Swing:-

There are many differences between java awt and swing that are given below.

[Link] AWT Swing


AWT Components are Platform Swing Components are Platform
1
dependent Independent
2 AWT components are heavy weight. Swing components are light weight.
Swing Provides more powerful
AWT provides less components than
3 Components Such as tables, lists,
Swing.
Scrollpanes.,etc.,
AWT doesn’t follows MVC(Model View
Controller ) Where model represents
4 data, view represents presentation and Swing Follows MVC.
controller acts as a interface between
model and view
Commonly Used Methods of Component Class:-

[Link] Method Description

1 add(Componentc) Inserts a component on this component.

Sets the size(width and height)of the


2 setSize(int width, int height)
component.

Defines the layout manager for the


3 setLayout(LayoutManager m)
component.
Changes the visibility of the
4 setVisibIe(Boolean status)
component, by default false.

5 setTitle(String text) Sets the title for component

svcas
1
Java Programming
Unit -
V
Hierarchy of Swing Components:-

To create simple swing example, you need a frame.

 In swing, we use JFrame class to create a frame.


There are two ways to create a frame in swing.
 By extending JFrame Class(inheritance)
Ex:
Class Example extends JFrame
{
…………………
…………………
}
 By creating the object of JFrameclass(association)
Ex:
Class Example
{
JFrame obj=new JFrame();
…………………
}

Containers;-
A container holds a group of components. It provides a space where a component
can be managed and displayed. Containers are of two types:

 Top Level Containers


svcas
2
Java Programming
Unit -
V
 Light Weight Containers

JFrames:-
Thе Java JFrame is an еssеntial component of Java Swing, which is a part of
thе Java SWT(Standard Widget Toolkit).
JFrame in Java is a class that allows you to create and manage a top-level
window in a Java application.
It sеrvеs as thе main window for GUI-basеd Java applications and providеs a
platform-indеpеndеnt way to crеatе graphical usеr interfaces.

For Example:-
import [Link];
import [Link];

// Driver Class
public class MyJFrame {
// main function
public static void main(String[] args)
{
// Create a new JFrame
JFrame frame = new JFrame("My First JFrame");

// Create a label
JLabel label = new JLabel("Hello Java Programming");

// Add the label to the frame


svcas
3
Java Programming
Unit -
V
[Link](label);

// Set frame properties


[Link](300,200); // Set the size of the frame

// Close operation
[Link](JFrame.EXIT_ON_CLOSE);

// Make the frame visible


[Link](true);
}
}

JWindows:-

The class JWindow is a container that can be displayed but does not have the title
bar or window-management buttons.

Class Declaration:-

Following is the declaration for [Link] class

public class JWindow extends Window implements Accessible, RootPaneContainer

JDialog:
The JDialog control represents a top level window with a border and a title used to
take some form of input from the user.

Unlike JFrame, it doesn't have maximize and minimize buttons.

Syntax:
JFrame f=new JFrame();
JDialog d=new JDiaIog(f, "Dialog", true);
JButton b = new JButton ("OK");
[Link](b);

JPanel:

The JPanel is a simplest container class. It provides space in which an application


can attach any other component.

svcas
4
Java Programming
Unit -
V
Syntax:
JPanel paneI=new JPanel();

[Link](40,80,200,200);

[Link]([Link]);

JButtonb1=newJButton("Button1");

[Link](50,100,80,30);

[Link](b1);

Example :
Import [Link].*;

Import [Link].*;

Public class JPanelExample

Public static void main(String args[])

JFrame f=new JFrame("PanelExample");

JPanel paneI=new JPanel();

[Link](40,80,200,200);

[Link]([Link]);

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

[Link](50,100,80,30);

[Link]([Link]);

JButton b2=new JButton("Button 2");

[Link](100,100,80,30);

[Link]([Link]);

[Link](b1);

[Link](b2);

[Link](panel);
svcas
5
Java Programming
Unit -
V
[Link](400,400);

[Link](null);

[Link](true);

Output:
-,PanelExample

Bu«on1

JButton:
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.

Syntax:
JButtonb=newJButton(“Text"); (Or)

JButtonb1,b2;

b1=new JButton(“Text”);

[Link](50,100,80,30);

JToggleButton:

A JToggleButton is a two-state button. The two states are selected and


unselected. The JRadioButton and JCheckBox classes are subclasses of this class.
When the user presses the toggle button, it toggles between being pressed or
unpressed. JToggleButton is used to select a choice from a list of possible choices.

svcas
6
Java Programming
Unit -
V
Constructors in JToggleButton:
1. JToggleButton(): Creates an initially unselected toggle button without setting the
text or image.
2. JToggleButton(Action a): Creates a toggle button where properties are taken from
the Action supplied.
3. JToggleButton(Icon icon): Creates an initially unselected toggle button with the
specified image but no text.
4. JToggleButton(Icon icon, boolean selected): Creates a toggle button with the
specified image and selection state, but no text.
5. JToggleButton(String text): Creates an unselected toggle button with the specified
text.

JCheckBox:
The JCheckBox class is used to create acheckbox. It is used to turn an option on
(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or from
"off" to "on".

Syntax:
JCheckBox c1=new JCheckBox(“Text”);

(or)
JCheckBoxc1,c2;
c1=new JCheckBox(“Text”);
JRadioButton
The JRadio Button class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.

It should be added in Button Group to select one radio button only.

Syntax:
ButtonGroup bg=new ButtonGroup();

JRadioButton r1=new JRadioButton("Male");

JRadioButtonr2=newJRadioButton("Female");

[Link](r1);

[Link](r2);

JLabel:
The JLabel class is a component for placing text in a container. It is used to
display
svcas
7
Java Programming
Unit -
V
A single line of read only text. The text can be changed by an application but a
user cannot edit it directly.

Syntax:
JLabel I1=new JLabeI(“Text”);

(or)

JLabel 11,12;

I1=new JLabeI(“Text”);

JTextField:
The JTextField class is a text component that allows the editing of a single line
text.

Syntax:

JTextField t1=new JTextFieId(“Text”);

(or)

JTextField t1,t2;

t1=new JTextFieId(“Text”);

JTextArea:
The JTextArea class is a multiline region that displays text. It allows the
editing of multiple line text.

Syntax:
JTextArea t1=new JTextArea(“Text”);

(or)

JTextArea t1,t2;

t1=new JTextArea(“Text”);

JList:
The object of JList class represents a list of text items. The list of text items can be
set up so that the user can choose one or more items from list of items.
Syntax:

svcas
8
Java Programming
Unit -
V
DefauItListModeI<String>11 =new DefauItListModeI<>();

[Link]("Item1");

[Link]("Item2");

[Link]("Item3");

[Link]("Item4");

JListlist=new JList<>(I1);

JComboBox:
The JComboBox class is used to show pop up menu of items. Item selected by user is
shown on the top of a menu.(like Choice class in AWT)
Syntax:
String country[]=("India","Aus","U.S.A","England","Newzealand"};

JComboBox cb=new JComboBox(country);

[Link](50,50,90,20);

JScrollPane:
Java JScrollPane is a component in the Java Swing library that provides a
scrollable view of another component, usually a JPanel or a JTextArea.
It provides a scrolling functionality to the display for which the size changes
dynamically.
It is useful to display the content which exceeds the visible area of the window. In
this article, we are going to see some constructors, methods, and examples of JScrollPane.

Constructor of JScrollPane

Constructors Descriptions

It is a default constructor that creates an empty


JScrollPane()
JScrollPane.

This constructor creates a JScrollPane with the


JScrollPane(Component comp)
specified view component as the scrollable content.

JScrollPane(int vertical, int This constructor creates an empty JScrollPane with


horizontal) the specified vertical and horizontal scrollbar.

JScrollPane(LayoutManager This constructor creates a JScrollPane with the

svcas
9
Java Programming
Unit -
V
Constructors Descriptions

layout) specified layout manager.

Methods of JScrollPane

Methods Description

void setVerticalScrollBarPolicy(int
Sets the vertical scrollbar policy
vertical)

void setHorizontalScrollBarPolicy(int
Sets the horizontal scrollbar policy
horizontal)

void
setColumnHeaderView(Component sets the column header for the JScrollPane
comp)

void setRowHeaderView(Component
sets the rowheader for the JScrollPane
comp)

setCorner(String key, Component It is used to set a component to be displayed


corner) in one of the corners of the scroll pane

It is used to retrieve the component that has


Component getCorner(String key) been previously set in one of the corners of the
scroll pane using the setCorner method

void setViewportView(Component It is used to set the component that will be


comp) displayed in the viewport of the scroll pane

svcas
10

You might also like