Java Programming Notes
Java Programming Notes
UNIT-I
UNIT – I
Introduction in java:
What is Java?
This means Java programs can run on any device that has a Java Virtual Machine (JVM).
✔Simple
Easy to learn if you know C/C++, but with fewer complex features.
✔Object-Oriented
✔Platform Independent
Java code is compiled into bytecode, which runs on the JVM — making it portable.
✔Secure
✔Robust
✔Multithreaded
SVCAS
1
JAVA PROGRAMMING
UNIT-I
[Link]("Hello, World!");
}
}
Explanation:
*****************
1. Class
class Car {
String color;
void drive() {
[Link]("Car is driving");
}
}
SVCAS
2
JAVA PROGRAMMING
UNIT-I
2. Object
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;
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...");
}
}
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.
class MathUtil {
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
class Animal {
void sound() { [Link]("Animal makes a sound"); }
}
6. Abstraction
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
✔Super Keyword
✔This Keyword
******************
History of Java
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.
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.
Java programs could run on any device using the Java Virtual Machine (JVM).
Internet applications
Cross-platform software
Java 5 (2004):
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)
Lambda expressions
Streams API
Functional programming features
In 2010, Oracle acquired Sun Microsystems and became the owner of Java.
Oracle continued the development and distribution of Java.
Better performance
Better memory use
Modern programming features
Platform independence
Strong security
Reliability and stability
Large community
SVCAS
7
JAVA PROGRAMMING
UNIT-I
Widely used in enterprise and Android development
*****************
Java Buzzwords
1. Simple:
[Link]-Oriented:
[Link]:
4. Robust:
[Link]:
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.
[Link]
[Link] Performance
[Link]
[Link]
[Link] Neutral
[Link]
***************
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.
Responsibilities:
a) Method Area
b) Heap Area
SVCAS
10
JAVA PROGRAMMING
UNIT-I
c) Stack Area
Method frames
Local variables
Operand stack
Return values
3. Execution Engine
Components:
a) Interpreter
d) HotSpot Compiler
SVCAS
11
JAVA PROGRAMMING
UNIT-I
4. Native Method Interface (JNI)
***************
Datatypes in Java
1. Primitive Datatypes
2. Non-Primitive (Reference) Datatypes
SVCAS
12
JAVA PROGRAMMING
UNIT-I
1. Primitive Datatypes:
Numeric Type
INTEGER:
1. Byte:
SVCAS
13
JAVA PROGRAMMING
UNIT-I
2. Short:
Size: 2 bytes
Range: -32,768 to 32,767
3. Int:
Size: 4 bytes
Range: -2,147,483,648 to 2,147,483,647
4. Long:
Size: 8 bytes
Used for large integer values
Must end with L
FLOATING POINT :
The floating point type can hold whole number followed by fractional part.
5. Float:
Size: 4 bytes
Used for decimal numbers
Must end with f
6. Double:
Size: 8 bytes
Default datatype for decimal values
More precise than float
SVCAS
14
JAVA PROGRAMMING
UNIT-I
Non-Numeric Type:
7. char
8. boolean
These do not store actual data — they store addresses (references) to memory.
Examples:
String
Array
Class
Interface
Object
Example:
Key features:
******************
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:
1. Local Variables
void display() {
int x = 10; // local variable
[Link](x);
}
class Student {
int marks; // instance variable
}
class Student {
static String schoolName = "ABC School"; // static variable
}
SYNTAX:
SVCAS
16
JAVA PROGRAMMING
UNIT-I
datatype variableName = value;
Examples:
Valid:
Invalid:
1age
class
student-name
SVCAS
17
JAVA PROGRAMMING
UNIT-I
void show() {
int c = 20; // local variable
[Link](a + b + c);
}
}
**************
1. Local Variables
2. Instance Variables
3. Static (Class) Variables
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:
✔Notes:
SVCAS
18
JAVA PROGRAMMING
UNIT-I
2. Instance Variables (Non-static variables)
✔Scope:
class Demo {
int age = 20; // instance variable
}
✔Lifetime:
✔Notes:
class Demo {
static int count = 0; // static variable
}
✔Lifetime:
✔Notes:
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:
Characteristics of Arrays
1. One-Dimensional Array
2. Multi-Dimensional Array
(mostly 2-D arrays)
1. One-Dimensional Array
✔Declaration
int[] arr;
✔Creation
✔Initialization
arr[0] = 10;
SVCAS
20
JAVA PROGRAMMING
UNIT-I
arr[1] = 20;
✔Combined form
✔Accessing elements
[Link](arr[2]); // Output: 30
✔Declaration
int[][] matrix;
✔Creation
✔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
Arrays of Objects
String[] names = new String[3];
names[0] = "John";
Advantages of Arrays
Limitations of Arrays
Fixed size.
Cannot store different data types.
Inserting/deleting is difficult.
SVCAS
22
JAVA PROGRAMMING
UNIT-I
*****************
Operators in Java
[Link] Operators
Example:
int a = 10, b = 3;
[Link](a % b); // Output: 1
[Link] Operators
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
Operator Meaning
= Assign
+= Add & assign
-= Subtract & assign
*= Multiply & assign
/= Divide & assign
%= Modulus & assign
Example:
int a = 10;
a += 5; // a = 15
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater or equal
<= Less or equal
Example:
5. Logical Operators
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
Operator Meaning
& Bitwise AND
` `
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Right shift
>>> Zero-fill right shift
Example:
[Link] Operator
SYNTAX:
Example:
8. Instance of Operator
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 are used to change the normal flow of program execution.
They decide which instructions execute and how many times.
1. Decision-Making Statements
2. Looping Statements
3. Jump Statements
1. Decision-Making Statements
a) if Statement
b) if-else Statement
SVCAS
26
JAVA PROGRAMMING
UNIT-I
} else {
[Link]("Minor");
}
c) else-if Ladder
d) switch Statement
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
a) for Loop
b) while Loop
int i = 1;
while(i <= 5){
[Link](i);
i++;
}
SVCAS
27
JAVA PROGRAMMING
UNIT-I
c) do-while Loop
int i = 1;
do{
[Link](i);
i++;
} while(i <= 5);
3. Jump Statements
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
Output:
1
2
4
SVCAS
28
JAVA PROGRAMMING
UNIT-I
}
Output:
*
**
***
*************
In Java, type conversion is the process of converting one data type into another.
It is also called typecasting.
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)
SYNTAX:
Example:
double d = 9.78;
int i = (int) d; // double explicitly converted to int
[Link](i); // Output: 9
Notes:
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'
Example:
class Animal {}
class Dog extends Animal {}
SVCAS
30
JAVA PROGRAMMING
UNIT-I
5. Type Conversion Rules
Example:
int a = 10;
float b = 5.5f;
float result = a + b; // int promoted to float
Type Size
byte 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
float 4 bytes
double 8 bytes
char 2 bytes
***************
🔶 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.
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!
****************
Constructors in Java
🔶 Features of Constructors
SVCAS
32
JAVA PROGRAMMING
UNIT-I
🔶 Types of Constructors
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);
}
}
2. Parameterized Constructor
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
}
[Link] Overloading
class Student {
int id;
String name;
Student() { // Default
id = 0; name = "Unknown";
}
void display() {
[Link](id + " " + name);
}
}
[Link](); // 0 Unknown
[Link](); // 102 Unknown
[Link](); // 103 Bob
}
}
SVCAS
34
JAVA PROGRAMMING
UNIT-I
*****************
Methods in Java
🔶 Structure of a Method
modifier returnType methodName(parameters) {
// body of method
// statements
return value; // if returnType is not void
}
Parts:
Part Description
returnType Type of value the method returns (int, double, String, void)
SVCAS
35
JAVA PROGRAMMING
UNIT-I
}
}
Output:
Hello, Jav
🔶 Types of Methods
🔶 Method Overloading
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);
}
Output:
No parameters
Integer: 10
String: Hello
🔶 Calling a Method
🔶 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
// Static block
static {
data = 50;
[Link]("Static block executed");
}
Output:
SVCAS
38
JAVA PROGRAMMING
UNIT-I
Explanation:
static {
[Link]("Static block 2");
}
Output:
Static block 1
Static block 2
Main method
Note: Static blocks execute in the order they appear in the class.
static {
count = 100; // initialize static variable
}
**************
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;
}
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);
}
}
SVCAS
40
JAVA PROGRAMMING
UNIT-I
[Link]([Link]);
}
}
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);
}
}
Output:
Total students: 3
Explanation:
[Link];
SVCAS
41
JAVA PROGRAMMING
UNIT-I
2. Using Object Reference (Works, but not recommended)
[Link];
🔹 Key Points
****************
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!");
}
SVCAS
42
JAVA PROGRAMMING
UNIT-I
Output:
Hello, Java!
Notes:
Creating Strings
String s1 = "Hello";
Example
SVCAS
43
JAVA PROGRAMMING
UNIT-I
String str = "Hello";
[Link]([Link]()); // 5
[Link]([Link]()); // HELLO
Creating StringBuffer
Example
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 in Java
Inheritance is a mechanism in Java by which one class acquires the properties and behaviors
(fields and methods) of another class.
🔶 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
Note: Java does not support multiple inheritance with classes to avoid ambiguity (diamond
problem).
🔶 Syntax of Inheritance
class Superclass {
// members of superclass
}
SVCAS
45
JAVA PROGRAMMING
UNIT-II
class Animal {
String color = "White";
}
void printColor() {
[Link](color); // Dog color
[Link]([Link]); // Animal color
}
}
Output:
Black
White
🔶 Advantages 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
Example:
class Animal {
void eat() { [Link]("Animal eats"); }
}
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
Diagram:
Animal
↑
|
Dog
↑
|
Puppy
3. Hierarchical Inheritance
Example:
class Animal {
void eat() { [Link]("Animal eats"); }
}
SVCAS
48
JAVA PROGRAMMING
UNIT-II
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Diagram:
Animal
/ \
Dog Cat
Example:
interface Animal {
void eat();
}
interface Pet {
void play();
}
SVCAS
49
JAVA PROGRAMMING
UNIT-II
Diagram:
Animal Pet
\ /
\ /
Dog
Single One child inherits one parent class Dog extends Animal
Hierarchical Multiple children from same parent Dog & Cat extend Animal
Multiple One class implements multiple interfaces class Dog implements Animal, Pet
******************
Explanation:
SVCAS
50
JAVA PROGRAMMING
UNIT-II
Access Modifier Same Class Same Package Subclass (different package) World
Private ✅ ❌ ❌ ❌
Default ✅ ✅ ❌ ❌
Protected ✅ ✅ ✅ ❌
Public ✅ ✅ ✅ ✅
// File: Package1/[Link]
package Package1;
void display() {
[Link](privateVar);
[Link](defaultVar);
[Link](protectedVar);
[Link](publicVar);
}
}
// File: Package1/[Link]
package Package1;
SVCAS
51
JAVA PROGRAMMING
UNIT-II
🔶 Key Points
🔶 Quick Tips
*******************
Uses of this
SVCAS
52
JAVA PROGRAMMING
UNIT-II
SVCAS
53
JAVA PROGRAMMING
UNIT-II
Uses of super
Output:
20
10
🔶 Key Points
*******************
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
🔶 Key Points
🔶 SYNTAX
returnType methodName(parameterList) {
// method body
}
Example: Two methods with the same name but different parameters.
class Demo {
Output:
SVCAS
55
JAVA PROGRAMMING
UNIT-II
class Demo {
void display(int a) {
[Link]("Integer: " + a);
}
void display(String s) {
[Link]("String: " + s);
}
Output:
Integer: 100
String: Hello
🔶 Advantages
*****************
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
}
}
@Override annotation is optional but recommended. It tells the compiler that you intend to
override a method.
class Parent {
void show() {
[Link]("Parent method");
}
}
SVCAS
57
JAVA PROGRAMMING
UNIT-II
Output:
Parent method
Child method
Child method
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
🔶 Advantages
***************
SVCAS
58
JAVA PROGRAMMING
UNIT-II
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
🔶 SYNTAX
// concrete method
void show() {
[Link]("This is a concrete method in abstract class");
}
}
// Concrete method
void eat() {
[Link]("Animal eats");
}
}
SVCAS
59
JAVA PROGRAMMING
UNIT-II
[Link]("Dog barks");
}
}
Output:
Dog barks
Animal eats
Shape(int x, int y) {
this.x = x;
this.y = y;
}
@Override
void area() {
[Link]("Rectangle area: " + (width * height));
}
}
SVCAS
60
JAVA PROGRAMMING
UNIT-II
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
**************
Key Points
SVCAS
61
JAVA PROGRAMMING
UNIT-II
Output:
Dog barks
Cat meows
Explanation:
Although the reference type is Animal, the subclass method is called because Java
resolves overridden methods at runtime.
SVCAS
62
JAVA PROGRAMMING
UNIT-II
Examples
void show() {
// x = 20; // ❌Error: cannot assign a value to final variable
[Link](x);
}
// class Child extends Parent { } // ❌Error: cannot inherit from final class
************************
Packages in Java
SVCAS
63
JAVA PROGRAMMING
UNIT-II
It is used to:
1. Definition
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.
Java provides access modifiers to control visibility of classes, methods, and variables
across packages:
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
File: mypackage/[Link]
package mypackage;
public class Demo {
public void display() {
[Link]("Hello from Demo class");
}
}
File: [Link]
import mypackage.*;
5. Key Points
*****************
SVCAS
65
JAVA PROGRAMMING
UNIT-II
Key Points:
SYNTAX:
interface InterfaceName {
// abstract methods
void method1();
void method2();
// constant variable
int MAX = 100; // public static final by default
}
2. Implementation of Interfaces
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
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");
}
}
SVCAS
67
JAVA PROGRAMMING
UNIT-II
Output:
Dog eats
Dog plays
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
************
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.
a) try
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
SYNTAX:
Example:
d) throws
The throws keyword is used in the method signature to declare the exceptions that a
method might throw.
SYNTAX:
Example:
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
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:
Example:
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
SVCAS
71
JAVA PROGRAMMING
UNIT-III
UNIT-III
What is Thread :
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.
SVCAS 72
JAVA PROGRAMMING
UNIT-III
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.
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)
************************
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
2. Advantages of Multithreading
SVCAS 74
JAVA PROGRAMMING
UNIT-III
[Link]();
}
}
Explanation:
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
d) Thread Priority
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
SVCAS 75
JAVA PROGRAMMING
UNIT-III
[Link]("Thread-A");
[Link]("Thread-B");
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]();
[Link]();
}
}
*********************
Runnable interface
The Runnable interface is a functional interface in Java that represents a task to be executed
by a thread.
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.
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.
4. Example of Runnable
[Link]();
[Link]();
}
}
Explanation:
SVCAS 77
JAVA PROGRAMMING
UNIT-III
Synchronization
1. What is Synchronization?
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.
Problem: Multiple threads modifying shared data at the same time → race condition.
Solution: Synchronization → threads access shared resources one at a time.
class Counter {
int count = 0;
void increment() {
count++;
}
}
Runnable r = () -> {
for (int i = 0; i < 1000; i++) {
[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.
a) Synchronized Methods
class Counter {
int count = 0;
b) Synchronized Block
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
class Counter {
int count = 0;
Runnable r = () -> {
for (int i = 0; i < 1000; i++) {
[Link]();
}
};
*****************
SVCAS 80
JAVA PROGRAMMING
UNIT-III
A synchronized method in Java is a method that allows only one thread at a time to execute it
on the same object.
SYNTAX:
Critical Section: The part of code where shared resources are accessed and must be executed by
one thread at a time.
Prevent race conditions (when two or more threads modify shared data at the same time).
Ensure data consistency when multiple threads access shared variables.
class Counter {
private int count = 0;
// Synchronized method
public synchronized void increment() {
count++;
[Link]([Link]().getName() + " incremented count to " + count);
}
// Runnable task
Runnable task = () -> {
SVCAS 81
JAVA PROGRAMMING
UNIT-III
[Link]();
[Link]();
[Link]();
[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:
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;
[Link] Consideration
*********************
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.
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.
SVCAS 83
JAVA PROGRAMMING
UNIT-III
class Counter {
private int count = 0;
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:
SVCAS 84
JAVA PROGRAMMING
UNIT-III
class Printer {
public void print(String message) {
synchronized(this) { // lock on this Printer object
[Link]("[");
try { [Link](100); } catch (InterruptedException e) {}
[Link](message + "]");
}
}
}
Explanation:
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
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.
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.
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:
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
}
}
[Link]();
[Link]();
}
}
Explanation:
SVCAS 87
JAVA PROGRAMMING
UNIT-III
Sample Output:
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
...
5. Key Points
********************
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.
SVCAS 88
JAVA PROGRAMMING
UNIT-III
class Resource {
String name;
Resource(String name) {
[Link] = name;
}
}
[Link]();
[Link]();
}
}
Explanation:
SVCAS 89
JAVA PROGRAMMING
UNIT-III
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.
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:
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
a) Byte Streams
Common Classes:
b) Character Streams
Common Classes:
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
}
} catch (IOException e) {
[Link]();
}
}
}
SVCAS 91
JAVA PROGRAMMING
UNIT-III
import [Link];
import [Link];
import [Link];
int c;
while ((c = [Link]()) != -1) {
[Link](c); // write character to output
}
} catch (IOException e) {
[Link]();
}
}
}
6. Key Points
**********************
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.
SVCAS 92
JAVA PROGRAMMING
UNIT-III
2. Types of Streams
A) Byte Streams
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
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
Byte Streams:
InputStream
|__ FileInputStream
|__ BufferedInputStream
|__ DataInputStream
OutputStream
|__ FileOutputStream
|__ BufferedOutputStream
|__ DataOutputStream
Character Streams:
Reader
|__ FileReader
|__ BufferedReader
|__ InputStreamReader
Writer
|__ FileWriter
|__ BufferedWriter
|__ OutputStreamWriter
|__ PrintWriter
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
import [Link].*;
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]();
[Link]();
[Link]("File copied successfully using character streams!");
}
}
5. Key Points
****************
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
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
import [Link].*;
int b;
while ((b = [Link]()) != -1) {
[Link](b); // write byte to output
}
[Link]();
[Link]();
[Link]("Binary file copied successfully!");
}
}
Key Points:
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
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
import [Link].*;
int c;
while ((c = [Link]()) != -1) {
[Link](c); // write character to output
}
[Link]();
[Link]();
[Link]("Text file copied successfully!");
}
}
Key Points:
*******************
SVCAS 97
JAVA PROGRAMMING
UNIT-III
In Java, the standard way to write output to the console is using the [Link] object.
Common Methods:
Example:
Output:
Hello World!
Number: 100
Example:
import [Link];
SVCAS 98
JAVA PROGRAMMING
UNIT-III
[Link]("Hello " + name + ", you are " + age + " years old.");
[Link]();
}
}
Sample Input/Output:
Notes:
B) Using BufferedReader
Example:
import [Link].*;
[Link]("Hello " + name + ", you are " + age + " years old.");
}
}
SVCAS 99
JAVA PROGRAMMING
UNIT-III
Notes:
Example:
import [Link];
if (console != null) {
String name = [Link]("Enter your name: ");
String ageStr = [Link]("Enter your age: ");
int age = [Link](ageStr);
***********************
File Handling
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
A) [Link]
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];
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
SVCAS 101
JAVA PROGRAMMING
UNIT-III
B) Writing to a File
Example:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
SVCAS 102
JAVA PROGRAMMING
UNIT-III
import [Link];
import [Link];
E) Deleting a File
import [Link];
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
1. Creating a Font
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).
Once you have a Font object, you can set it on a component such as a Label, Button, TextField, etc.
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.
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
1. What is an Event?
A button is clicked.
The mouse is moved.
A key is pressed.
A window is resized.
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.
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.
•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
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.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
SVCAS
25
Java Programming Unit -
IV
HierarchyBoundsAdapter HierarchyBoundsListener
Java WindowAdapter
Java MouseAdapter
Java MouseMotionAdapter
Java KeyAdapter
In the following example, we are implementing the KeyAdapter class and its method.
Inner classes:-
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 {
}
}
SVCAS
26
Java Programming Unit -
IV
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.
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.
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:
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.,
There are many differences between java awt and swing that are given below.
svcas
1
Java Programming
Unit -
V
Hierarchy of Swing Components:-
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:
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");
// Close operation
[Link](JFrame.EXIT_ON_CLOSE);
JWindows:-
The class JWindow is a container that can be displayed but does not have the title
bar or window-management buttons.
Class Declaration:-
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.
Syntax:
JFrame f=new JFrame();
JDialog d=new JDiaIog(f, "Dialog", true);
JButton b = new JButton ("OK");
[Link](b);
JPanel:
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].*;
[Link](40,80,200,200);
[Link]([Link]);
[Link](50,100,80,30);
[Link]([Link]);
[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:
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.
Syntax:
ButtonGroup bg=new ButtonGroup();
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:
(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"};
[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
svcas
9
Java Programming
Unit -
V
Constructors Descriptions
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)
svcas
10