0% found this document useful (0 votes)
13 views74 pages

Java Kirat 36exp

The document provides a comprehensive introduction to Java, detailing its core definition, historical context, and key features such as platform independence, object-oriented design, and security. It also explains the Java ecosystem components including JDK, JRE, and JVM, and outlines the lifecycle of a Java program from source code writing to execution. Additionally, it includes comparisons with C and C++, applications of Java, and several example programs demonstrating basic Java functionalities.

Uploaded by

Mankirat Singh
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)
13 views74 pages

Java Kirat 36exp

The document provides a comprehensive introduction to Java, detailing its core definition, historical context, and key features such as platform independence, object-oriented design, and security. It also explains the Java ecosystem components including JDK, JRE, and JVM, and outlines the lifecycle of a Java program from source code writing to execution. Additionally, it includes comparisons with C and C++, applications of Java, and several example programs demonstrating basic Java functionalities.

Uploaded by

Mankirat Singh
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

Date: - 02/04/2026 1

INTRODUCTION TO JAVA
Introduction: Foundation and Philosophy

 Core Definition: Java is a high-level, class-based, object-oriented programming


language. It was specifically designed to have as few implementation
dependencies as possible, making it highly portable across different computing
environments.
 Historical Context: Originally developed by Sun Microsystems and released in
1995, Java has evolved into a staple language for enterprise software, backend
services, and Android application development.
 The "WORA" Philosophy: The cornerstone of Java is the "Write Once, Run
Anywhere" (WORA) capability. This means developers can write code on a
Windows machine, compile it, and run that same executable file on Linux or
macOS without modification, provided the Java Virtual Machine (JVM) is
installed.
 Platform Independence: This portability is achieved because Java is compiled
into bytecode rather than machine code. The JVM translates this bytecode into
the specific machine instructions of the host operating system at runtime.
 Object-Oriented Design: Java forces a structured approach to programming,
where data and behavior are packaged together into "objects." This improves
code reusability, maintainability, and scalability for large projects.
 Robust and Secure: Java is designed to be highly reliable, featuring strong
memory management via automatic garbage collection and strict type checking
to prevent common programming errors.

Key Features of Java: Why It Remains Popular

 Platform Independence: Java’s hallmark feature is its ability to run on any


device regardless of the operating system. This is achieved through the Java
Virtual Machine (JVM), which acts as an abstraction layer between the compiled
bytecode and the underlying hardware.
 Object-Oriented Programming (OOP): Java is built around the OOP paradigm,
focusing on creating modular, reusable code through classes and objects. It
supports core concepts like inheritance, encapsulation, polymorphism, and
abstraction, making it ideal for managing complex software systems.
 Robustness and Memory Management: Java promotes reliability by
performing strong compile-time and runtime checks. Notably, it utilizes automatic
garbage collection, which manages memory allocation and deallocation, reducing

Mankirat Singh
Date: - 02/04/2026 2

the risk of memory leaks and segmentation faults common in languages like
C++.
 Security: Designed for networked environments, Java provides a secure
execution environment. It runs applications within a "sandbox" (the JVM),
restricting access to the host system unless explicitly permitted, thus preventing
malicious code execution.
 Multithreading: Java has built-in support for concurrent programming, allowing
developers to execute multiple threads (parts of a program) simultaneously. This
enhances performance in highly responsive applications and server-side
processing.

The Java Ecosystem: Understanding the Core Components

 JDK (Java Development Kit): The JDK is the complete software development
package required to create Java applications. It includes the Java Runtime
Environment (JRE) along with essential tools for developers, such as the javac
compiler, the Javadoc tool for documentation, and the jdb debugger.
 JRE (Java Runtime Environment): The JRE is a subset of the JDK designed
for end-users who only need to run Java applications, not develop them. It
provides the necessary libraries and the JVM to execute compiled bytecode.
 JVM (Java Virtual Machine): The JVM is the heart of the Java ecosystem. It is
an abstract computing machine that provides the runtime environment in which
Java bytecode is executed. It is platform-dependent, meaning there are different
JVMs for Windows, Linux, and macOS.
 Platform Independence Workflow: When Java code is compiled, it is converted
into bytecode, which is not machine code but an intermediate language. The
JVM on the target machine interprets or compiles this bytecode into machine-
specific instructions on the fly, enabling the "Write Once, Run Anywhere"
functionality.
 Just-In-Time (JIT) Compiler: Inside the JVM, a JIT compiler enhances
performance by translating frequently executed bytecode segments directly into
native machine code, significantly speeding execution times compared to pure
interpretation.

Mankirat Singh
Date: - 02/04/2026 3

The Lifecycle of a Java Program: Compilation to Execution

 Source Code Writing: The process begins with the developer writing human-
readable code in a .java file. This code adheres to Java syntax, defining
classes, methods, and logic.
 Compilation Phase (javac): The Java compiler, included in the JDK, translates
the high-level .java source code into intermediate bytecode, storing it in
a .class file.
 Bytecode Platform Independence: Unlike machine code, bytecode is not
specific to any processor or operating system. This intermediate format allows
Java to be portable across different computing platforms.
 Loading and Verification: When the program is run, the JVM's Class Loader
brings the bytecode into memory. The Bytecode Verifier then ensures the code is
valid and does not violate security restrictions, preventing unauthorized access to
the underlying system.
 Execution Phase (Interpreter & JIT Compiler): The JVM executes the
bytecode. Initially, an interpreter may translate bytecode instructions to machine
code one by one. For improved performance, the Just-In-Time (JIT) compiler
identifies "hot spots" (frequently used code) and compiles them directly into
native machine code for faster execution.

Mankirat Singh
Date: - 02/04/2026 4

Difference between Java and c


Key feature Java C
Java is a pure object- C is a procedural language
Paradigm oriented language focusing focusing on functions and
on classes and objects steps.

Java uses automatic C requires manual memory


Memory Management: garbage collection, which management using
reduces the risk of memory functions like malloc()
leaks and segmentation and free(), which can
faults. lead to bugs if not handled
correctly.

Platform Dependency Java compiles bytecode, C code is compiled directly


allowing it to run on any into machine code for a
machine with a Java specific architecture,
Virtual Machine (JVM) making it highly dependent
(WORA - Write Once, Run on the operating system.
Anywhere).

Pointers Java does not support C heavily utilizes pointers


explicit pointers, enhancing to directly manipulate
security and safety. memory addresses,
offering high performance
but lower security.

Libraries Java boasts a vast C has a limited standard


standard library suitable for library focused on
networking, GUI design, operating system
and database connectivity. interactions.

Difference between Java and C++


Key Features C++ Java

Memory Management: C++ requires manual Java relies entirely on


memory management, garbage collection for
though it offers more automated memory
advanced concepts like handling.
destructors and smart
pointers.

Mankirat Singh
Date: - 02/04/2026 5

Inheritance: C++ supports multiple Java supports single


inheritance (a class inheritance classes but
inheriting from more than achieves functionality like
one parent class), which multiple inheritance
can lead to complexity. through interfaces.

Compilation: C++ compiles directly into Java compiles to bytecode,


machine-dependent code. which is interpreted or
compiled just-in-time by
the JVM.

Pointer Support: C++ supports pointers, Java eliminates pointers to


giving developers low-level ensure type safety and
control over memory. prevent unauthorized
memory access.

Performance: C++ generally offers higher Java may have slight


performance and faster overhead due to the JVM,
execution speeds because though the Just-In-Time
it compiles directly to (JIT) compiler minimizes
native machine code. this gap.

Applications and Popularity: Where Java is Used

 Enterprise Applications: Java is the dominant language for building large-


scale, secure, and reliable backend systems for banking, retail, and government
sectors. Frameworks like Spring and Jakarta EE facilitate the development of
complex enterprise software.
 Android Development: Java is one of the primary languages for native Android
application development. It provides the foundation for building mobile apps that
run on billions of devices, utilizing the Android SDK.
 Big Data Technologies: Java is heavily used in the data analytics ecosystem.
Major tools like Apache Hadoop, Apache Spark, and Apache Kafka are built
using Java, making it essential for processing massive datasets.
 Server-Side Web Applications: It is widely used to develop high-performance
server-side applications and web services. Its stability and scalability make it
ideal for handling high traffic volumes on the internet.

Mankirat Singh
Date: - 02/04/2026 6

 Scientific Computing and Embedded Systems: Java is used in scientific


modeling, numerical computing, and embedded systems, such as smart cards
and IoT devices, due to its robustness and portability.

PROGRAM 1

Write a program to print Hello World.


CODE:-

import [Link].*;

class hello {

public static void main(String[] args) {

[Link]("Hello World");

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 7

PROGRAM 2
Write a program to find square root of a number

CODE:-

import [Link];

import [Link];

public class sqrt {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter a number to find its square root: ");

double number = [Link]();

if (number < 0) {

[Link]("Error: Cannot calculate the square root of a negative


number.");

} else {

double result = [Link](number);

[Link]("The square root of " + number + " is: " + result);

}}}

OUTPUT: -

Mankirat Singh
Date: - 02/04/2026 8

PROGRAM 3
Write a program to find the largest of three numbers using if else loop.

CODE: -

import [Link];

public class largest {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter three numbers:");

[Link]("Number 1: ");

double num1 = [Link]();

[Link]("Number 2: ");

double num2 = [Link]();

[Link]("Number 3: ");

double num3 = [Link]();

double largest;

if (num1 >= num2 && num1 >= num3) {

largest = num1;

} else if (num2 >= num1 && num2 >= num3) {

largest = num2;

} else {

largest = num3;

[Link]("The largest number is: " + largest);

Mankirat Singh
Date: - 02/04/2026 9

[Link]();

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 10

PROGRAM 4
Write a program to find factorial of a number using non recurssion.

CODE: -

import [Link];

public class factorial {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter a number to calculate its factorial: ");

int number = [Link]();

if (number < 0) {

[Link]("Error: Factorial is not defined for negative numbers.");

} else {

long factorial = 1;

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

factorial *= i; }

[Link]("The factorial of " + number + " is: " + factorial); }

[Link](); }}

OUTPUT: -

Mankirat Singh
Date: - 02/04/2026 11

PROGRAM 5
Write a program to find fibonacci series upto a number using non
recurssion.

CODE: -

import [Link];

public class fibonacci {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the number of terms for the Fibonacci series: ");

int n = [Link]();

long a = 0, b = 1;

[Link]("Fibonacci Series up to " + n + " terms:");

int count = 0;

while (count < n) {

[Link](a + " ");

long c = a + b;

a = b;

b = c;

count++;

[Link]();

Mankirat Singh
Date: - 02/04/2026 12

OUTPUT: -

Mankirat Singh
Date: - 02/04/2026 13

PROGRAM 6
Write a program to find factorial of a number using recurssion.

CODE: -

import [Link];

public class FactorialRecursion {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the number to calculate its factorial ");

int number = [Link]();

[Link]("Factorial of "+ number +" is ");

long result = findFactorial(number);

[Link](result); }

public static long findFactorial(int n) {

if (n <= 1) {

return 1; }

return n * findFactorial(n - 1); } }

OUTPUT: -

Mankirat Singh
Date: - 02/04/2026 14

PROGRAM 7
Write a program to find fibonacci series upto a number using recurssion.

CODE: -

import [Link];

public class FibonacciRecursion {

public static void main(String[] args) {

[Link]("Enter the number of terms for the Fibonacci series: ");

Scanner scanner = new Scanner([Link]);

int count = [Link]();

[Link]("Fibonacci Series up to " + count + " terms:");

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

[Link](findFibonacci(i) + " "); } }

public static int findFibonacci(int n) {

if (n <= 1) {

return n; }

return findFibonacci(n - 1) + findFibonacci(n - 2); } }

OUTPUT: -

PROGRAM 8
Mankirat Singh
Date: - 02/04/2026 15

Write a program to print prime numbers from 1 to 100.

CODE: -

import [Link];

public class PrimeNumbers {

public static void main(String[] args) {

[Link]("The prime numbers between 1 to 100 are ");

for (int i = 2; i <= 100; i++) {

if (isPrime(i)) {

[Link](i + " "); } } }

public static boolean isPrime(int n) {

if (n <= 1) return false;

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

if (n % i == 0) {

return false; } }

return true; } }

OUTPUT: -

Mankirat Singh
Date: - 02/04/2026 16

PROGRAM 9
Write a program to find whether the given number is Armstrong or not.

CODE: -

import [Link];

public class Armstrong {

public static void main(String[] args) {

[Link]("Enter the number to be checked ");

Scanner sc = new Scanner([Link]);

int n = [Link]();

int temp = n;

int count = 0;

while (temp > 0) {

count++;

temp = temp / 10;

temp = n;

int sum = 0;

while (temp > 0) {

int digit = temp % 10;

sum = sum + (int) [Link](digit, count);

temp = temp / 10;

if (sum == n)

Mankirat Singh
Date: - 02/04/2026 17

[Link]("Armstrong Number");

else

[Link]("Not Armstrong Number");

[Link]();

OUTPUT: -

Mankirat Singh
Date: - 02/04/2026 18

PROGRAM 10
Write a program to print sum of matrices.

CODE: -

import [Link];

public class MatrixSum {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter the number of rows and columns of matrics ");

int rows = [Link]();

int cols = [Link]();

int[][] matrix1 = new int[rows][cols];

int[][] matrix2 = new int[rows][cols];

int[][] sum = new int[rows][cols];

[Link]("Enter the first matrics ");

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

for (int j = 0; j < cols; j++) {

matrix1[i][j] = [Link]();

[Link]("Enter the second matrics ");

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

for (int j = 0; j < cols; j++) {

matrix2[i][j] = [Link]();

Mankirat Singh
Date: - 02/04/2026 19

[Link]("The sum of matrics is ");

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

for (int j = 0; j < cols; j++) {

sum[i][j] = matrix1[i][j] + matrix2[i][j];

[Link](sum[i][j] + " ");

[Link]();

OUTPUT: -

Mankirat Singh
Date: - 02/04/2026 20

PROGRAM 11
Write a program to find the area and perimeter of rectangle using methods.

CODE: -

import [Link];

public class Rectangle {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter the length and breadth of rectangle ");

double length = [Link]();

double breadth = [Link]();

[Link]("Area of rectangle is " + calculateArea(length, breadth));

[Link]("Perimeter of rectangle is " + calculatePerimeter(length,


breadth));}

public static double calculateArea(double l, double b) {

return l * b; }

public static double calculatePerimeter(double l, double b) {

return 2 * (l + b); } }

OUTPUT: -

Mankirat Singh
Date: - 02/04/2026 21

PROGRAM 12
Write a program to perform linear search on array.

CODE: -

import [Link];

class LinearSearch {

public static void main(String str[]) {

int arr[];

Scanner sc = new Scanner([Link]);

[Link]("Enter the number of elements in array: ");

int n = [Link]();

arr = new int[n];

[Link]("Enter the elements of array: ");

for (int j = 0; j < n; j++) {

arr[j] = [Link]();

[Link]("Enter the number to search: ");

int target = [Link]();

boolean found = false;

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

if (arr[i] == target) {

[Link]("Element found at position: " + (i + 1));

found = true;

break;

Mankirat Singh
Date: - 02/04/2026 22

if (!found) {

[Link]("Element not found!!");

[Link]();

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 23

PROGRAM 13
Write a program to demonstrate Default and Parameterized Constructor.

CODE: -

import [Link];

class Student {

String name;

int age;

Student() {

[Link]("Default constructor called");

name = "Unknown";

age = 0;

Student(String n, int a) {

[Link]("Parametric constructor called");

name = n;

age = a;

void display() {

[Link]("Name: " + name);

[Link]("Age: " + age);

public class Main {

Mankirat Singh
Date: - 02/04/2026 24

public static void main(String[] args) {

Student s1 = new Student();

[Link]();

Student s2 = new Student("John", 20);

[Link]();

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 25

PROGRAM 14
Write a program to find Area of Rectangle and Circle using Polymorphism.

CODE: -

import [Link];

class Shape {

void area() {} }

class Rectangle extends Shape {

double length, breadth;

Rectangle(double l, double b) {

length = l;

breadth = b; }

@Override

void area() {

[Link]("Rectangle Area: " + (length * breadth)); } }

class Circle extends Shape {

double radius;

Circle(double r) {

radius = r; }

@Override

void area() {

[Link]("Circle Area: " + (3.14 * radius * radius)); } }

public class Polymorphism {

public static void main(String[] args) {

Shape s1 = new Rectangle(10, 20);

Mankirat Singh
Date: - 02/04/2026 26

Shape s2 = new Circle(5);

[Link]();

[Link](); } }

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 27

PROGRAM 15

(a)
Write a program to perform various string operations (Lowercase,
Uppercase, Concatenation, Length of String, Replace of String).

CODE: -

import [Link];

public class StringOps {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");

String str = [Link]();

[Link]("Lowercase: " + [Link]());

[Link]("Uppercase: " + [Link]());

[Link]("Enter another string to concatenate: ");

String str2 = [Link]();

[Link]("Concatenated: " + [Link](str2));

[Link]("Length of string: " + [Link]());

[Link]("Enter character to replace: ");

char oldChar = [Link]().charAt(0);

[Link]("Enter new character: ");

char newChar = [Link]().charAt(0);

[Link]("Replaced string: " + [Link](oldChar, newChar));

Mankirat Singh
Date: - 02/04/2026 28

OUTPUT:-

(b)
Write a program to perform various StringBuffer operations.

CODE: -

import [Link];

public class StringBufferOperations {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

[Link](" World");

[Link]("Append: " + sb);

[Link](6, "Beautiful ");

[Link]("Insert: " + sb);

[Link](6, 16);

[Link]("Delete: " + sb);

[Link](6, 11, "Java");

[Link]("Replace: " + sb);

Mankirat Singh
Date: - 02/04/2026 29

[Link]();

[Link]("Reverse: " + sb);

[Link]("Capacity: " + [Link]());

[Link]("Length: " + [Link]());

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 30

PROGRAM 16
Write a program to demonstrate Super Keyword.

CODE: -

class Vehicle {

void drive() {

[Link]("Driving a vehicle"); } }

class Car extends Vehicle {

@Override

void drive() {

[Link]();

[Link]("Driving a car"); } }

public class superkey {

public static void main(String[] args) {

Car c = new Car();

[Link](); } }

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 31

PROGRAM 17
Write a program to demonstrate this Keyword.

CODE: -

class Student {

int rollno;

String name;

Student(int rollno, String name) {

[Link] = rollno;

[Link] = name; }

void display() {

[Link]("Roll No: " + [Link]);

[Link]("Name: " + [Link]); } }

public class thiskey {

public static void main(String[] args) {

Student s = new Student(1, "Karan");

[Link](); } }

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 32

PROGRAM 18
Write a program to demonstrate Final Keyword.

CODE: -

final class Constants {

final int MAX_SIZE = 100;

final void display() {

[Link]("Max size: " + MAX_SIZE); } }

public class finalkey {

public static void main(String[] args) {

final int x = 10;

Constants c = new Constants();

[Link]();

print(50); }

static void print(final int num) {

[Link]("Number: " + num); } }

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 33

PROGRAM 19
Write a program to demonstrate abstract class and abstract method.

CODE: -

abstract class Shape {

abstract void draw();

void color() {

[Link]("Shape color is red"); }}

class Circle extends Shape {

@Override

void draw() {

[Link]("Drawing a circle"); } }

public class abstractclass {

public static void main(String[] args) {

Shape s = new Circle();

[Link]();

[Link](); } }

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 34

PROGRAM 20
Write a program to calculate area of rectangle and circle using interface.

CODE: -

interface Shape {

void calculateArea();

class Rectangle implements Shape {

int length, breadth;

Rectangle(int length, int breadth) {

[Link] = length;

[Link] = breadth;

@Override

public void calculateArea() {

[Link]("Rectangle area: " + (length * breadth));

class Circle implements Shape {

int radius;

Circle(int radius) {

[Link] = radius;

@Override

Mankirat Singh
Date: - 02/04/2026 35

public void calculateArea() {

[Link]("Circle area: " + (3.14 * radius * radius));

public class interfaceuse {

public static void main(String[] args) {

Shape rect = new Rectangle(10, 20);

[Link]();

Shape circle = new Circle(5);

[Link]();

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 36

PROGRAM 21
Write a program to demonstrate exception handling.

CODE: -

import [Link].*;

public class exceptionhandling {

public static void main (String[] args) {

Scanner sc = new Scanner([Link]);

try { [Link]("Enter first number: ");

int a = [Link]();

[Link]("Enter second number: ");

int b = [Link]();

int result = a / b;

[Link]("Result = " + result); }

catch (ArithmeticException e) {

[Link]("Error: Cannot divide by zero"); }

finally {

[Link]("Execution completed");

[Link](); } } }

OUTPUT:-

Mankirat Singh
Date: - 02/04/2026 37

PROGRAM 22
Write a program to create and display a simple applet.

CODE: -

HTML -

<html>

<body>

<applet cod e="[Link]" width="20" height="20"></applet>

</body>

</html>

Java -

import [Link];

import [Link];

public class Demo extends Applet {

public void paint(Graphics g) {

[Link]("Welcome to applet program", 100, 100);

Mankirat Singh
Date: - 02/04/2026 38

PROGRAM 23
To implement producer-consumer problem using concept of threads

CODE: -

import [Link];

public class Threadexample {

public static void main(String[] args) throws InterruptedException {

final PC pc = new PC();

Thread t1 = new Thread(new Runnable() {

public void run() {

try {

[Link]();

} catch (InterruptedException e) {

[Link]();

});

Thread t2 = new Thread(new Runnable() {

public void run() {

try {

[Link]();

} catch (InterruptedException e) {

[Link]();

Mankirat Singh
Date: - 02/04/2026 39

});

[Link]();

[Link]();

[Link]();

[Link]();

public static class PC {

LinkedList<Integer> list = new LinkedList<>();

int capacity = 2;

public void produce() throws InterruptedException {

int value = 0;

while (true) {

synchronized (this) {

while ([Link]() == capacity)

wait();

[Link]("Producer produced-" + value);

[Link](value++);

notify();

[Link](1000);

Mankirat Singh
Date: - 02/04/2026 40

public void consume() throws InterruptedException {

while (true) {

synchronized (this) {

while ([Link]() == 0)

wait();

int val = [Link]();

[Link]("Consumer consumed-" + val);

notify();

[Link](1000);

Mankirat Singh
Date: - 02/04/2026 41

PROGRAM 24
To create 3 threads by extending the Thread class. First thread displays
“Good Morning” every 1 sec, Second displays “Hello” every 2 sec, Third
displays “Welcome” every 3 sec

CODE: -

import [Link].*;

public class Hal extends Thread {

public void run() {

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

try {

[Link](1000);

[Link]("Good Morning");

[Link](2000);

[Link]("Hello Mankira");

[Link](3000);

[Link]("Welcome");

} catch (Exception e) {

[Link](e);

public static void main(String[] args) {

Hal h = new Hal();

Mankirat Singh
Date: - 02/04/2026 42

[Link]();

Mankirat Singh
Date: - 02/04/2026 43

PROGRAM 25
To create three threads by implementing Runnable. First thread displays
“Good Morning” every 1 sec, Second displays “Hello” every 2 sec, Third
displays “Welcome” every 3 sec.

CODE: -

class Frst implements Runnable {

Thread t;

Frst() {

t = new Thread(this);

[Link]("Good Morning");

[Link]();

public void run() {

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

[Link]("Good Morning " + i);

try {

[Link](1000);

} catch (Exception e) {

[Link](e);

Mankirat Singh
Date: - 02/04/2026 44

class sec implements Runnable {

Thread t;

sec() {

t = new Thread(this);

[Link]("Hello");

[Link]();

public void run() {

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

[Link]("Hello " + i);

try {

[Link](2000);

} catch (Exception e) {

[Link](e);

} } } }

class third implements Runnable {

Thread t;

third() {

t = new Thread(this);

[Link]("Welcome");

[Link]();

public void run() {

Mankirat Singh
Date: - 02/04/2026 45

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

[Link]("Welcome " + i);

try {

[Link](3000);

} catch (Exception e) {

[Link](e);

} } } }

public class Thrun {

public static void main(String args[]) {

new Frst();

new sec();

new third();

} }

Mankirat Singh
Date: - 02/04/2026 46

PROGRAM 26
WAP to develop a program using AWT components: text field, text area,
button, and label.

CODE: -

import [Link].*;

import [Link].*;

public class btnApplet extends Applet {

public void init() {

Frame f = new Frame("Details");

[Link](null);

[Link](true);

[Link](600, 600);

Label l1 = new Label("Name:");

[Link](50, 80, 40, 20);

TextField t1 = new TextField();

[Link](100, 80, 90, 25);

Label l2 = new Label("E-Mail:");

[Link](50, 130, 40, 20);

TextField t2 = new TextField();

[Link](100, 130, 120, 25);

Label l3 = new Label("Address:");

[Link](40, 170, 50, 20);

TextArea ta = new TextArea();

Mankirat Singh
Date: - 02/04/2026 47

[Link](100, 170, 200, 200);

Label l4 = new Label("Password:");

[Link](30, 410, 60, 20);

TextField t3 = new TextField();

[Link](100, 410, 120, 25);

Button btn = new Button("Submit");

[Link](180, 470, 150, 40);

[Link](l1); [Link](t1);

[Link](l2); [Link](t2);

[Link](l3); [Link](ta);

[Link](l4); [Link](t3);

[Link](btn);

Mankirat Singh
Date: - 02/04/2026 48

PROGRAM 27
WAP to make simple calculator and make use of grid layout and text field
to display the result.

CODE: -

import [Link].*;

import [Link].*;

import [Link].*;

public class Calculator extends Applet implements ActionListener {

TextField t;

Button b[] = new Button[15];

Button b1[] = new Button[6];

String op2[] = {"+", "-", "*", "/", "%", "C"};

String str = "";

int p = 0, q = 0;

String oper;

public void init() {

setLayout(new GridLayout(5, 4));

t = new TextField(20);

[Link]([Link]);

[Link]("0");

int k = 0;

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

Mankirat Singh
Date: - 02/04/2026 49

b[k] = new Button("" + k);

add(b[k]);

b[k].addActionListener(this);

k++;

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

b1[i] = new Button(op2[i]);

add(b1[i]);

b1[i].addActionListener(this);

add(t);

public void actionPerformed(ActionEvent ae) {

String str = [Link]();

if ([Link]("+") || [Link]("-") || [Link]("*") || [Link]("%")) {

p = [Link]([Link]());

oper = str;

[Link]("");

else if ([Link]("=")) {

q = [Link]([Link]());

if ([Link]("+"))

[Link]([Link](p + q));

Mankirat Singh
Date: - 02/04/2026 50

else if ([Link]("-"))

[Link]([Link](p - q));

else if ([Link]("*"))

[Link]([Link](p * q));

else if ([Link]("%"))

[Link]([Link](p % q));

else if ([Link]("C")) {

p = q = 0;

[Link]("");

else {

[Link]([Link]() + str);

Mankirat Singh
Date: - 02/04/2026 51

PROGRAM 28
Write a program to demonstrate mouse listener using grid layout.

CODE: -

import [Link].*;

import [Link].*;

import [Link].*;

public class MouseListenerDemo extends JFrame implements MouseListener {

JPanel panel = new JPanel();

public MouseListenerDemo() {

setTitle("Mouse Listener Demo");

setSize(300, 200);

add(panel);

[Link](new GridLayout(3, 3, 10, 10));

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

JButton button = new JButton("Button " + (i + 1));

[Link](button);

[Link](this);

public void mouseClicked(MouseEvent e) {

JButton button = (JButton) [Link]();

[Link]("Mouse clicked on " + [Link]());

Mankirat Singh
Date: - 02/04/2026 52

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {

JButton button = (JButton) [Link]();

[Link]("Mouse entered " + [Link]());

public void mouseExited(MouseEvent e) {

JButton button = (JButton) [Link]();

[Link]("Mouse exited " + [Link]());

public static void main(String[] args) {

MouseListenerDemo frame = new MouseListenerDemo();

[Link](JFrame.EXIT_ON_CLOSE);

[Link](true);

Mankirat Singh
Date: - 02/04/2026 53

PROGRAM 29
WAP to write an application to simulate calculator using grid bag layout.

CODE: -

import [Link].*;

import [Link].*;

public class Calculator1 {

public static void main(String[] args) {

JFrame frame = new JFrame("Calculator");

[Link](JFrame.EXIT_ON_CLOSE);

GridBagLayout layout = new GridBagLayout();

GridBagConstraints c = new GridBagConstraints();

[Link](layout);

JTextField textField = new JTextField(20);

[Link](false);

[Link] = 0;

[Link] = 0;

[Link] = 4;

[Link] = [Link];

[Link](textField, c);

String[][] buttons = {

{"7", "8", "9", "/"},

{"4", "5", "6", "*"},

{"1", "2", "3", "-"},

Mankirat Singh
Date: - 02/04/2026 54

{"0", ".", "=", "+"}

};

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

for (int j = 0; j < buttons[i].length; j++) {

[Link] = j;

[Link] = i + 1;

[Link] = 1;

JButton btn = new JButton(buttons[i][j]);

[Link](btn, c);

[Link]();

[Link](true);

Mankirat Singh
Date: - 02/04/2026 55

PROGRAM 30
WAP to develop a program to create a menu with various menu and sub-
menu items.

CODE: -

import [Link].*;

import [Link].*;

public class MenuExample extends Applet {

MenuBar menuBar = new MenuBar();

Menu menu = new Menu("Menu");

MenuItem item1 = new MenuItem("Menu Item 1");

MenuItem item2 = new MenuItem("Menu Item 2");

MenuItem item3 = new MenuItem("Menu Item 3");

Menu submenu = new Menu("Submenu");

MenuItem sub1 = new MenuItem("Submenu Item 1");

MenuItem sub2 = new MenuItem("Submenu Item 2");

public void init() {

[Link](menu);

[Link](item1);

[Link](item2);

[Link](item3);

[Link](submenu);

[Link](sub1);

[Link](sub2);

Mankirat Singh
Date: - 02/04/2026 56

Frame frame = new Frame("Menu Example");

[Link](menuBar);

[Link](300, 300);

[Link](this);

[Link](true);

Mankirat Singh
Date: - 02/04/2026 57

PROGRAM 31
WAP to develop a program to handle keyboard events.

CODE: -

import [Link].*;

import [Link].*;

public class KeyboardEventExample extends JFrame implements KeyListener {

public KeyboardEventExample() {

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

addKeyListener(this);

public static void main(String[] args) {

new KeyboardEventExample();

public void keyTyped(KeyEvent e) {

[Link]("Key typed: " + [Link]());

public void keyPressed(KeyEvent e) {

[Link]("Key pressed: " + [Link]());

public void keyReleased(KeyEvent e) {

Mankirat Singh
Date: - 02/04/2026 58

[Link]("Key released: " + [Link]());

Mankirat Singh
Date: - 02/04/2026 59

PROGRAM 32
To develop a program demonstrating the use of URL connection.

CODE: -

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class connection {

public static void main(String[] args) throws IOException {

URL url = new URL("[Link]

HttpURLConnection connection = (HttpURLConnection) [Link]();

[Link]("GET");

BufferedReader in = new BufferedReader(

new InputStreamReader([Link]()));

String line;

while ((line = [Link]()) != null) {

[Link](line);

[Link]();

Mankirat Singh
Date: - 02/04/2026 60

Mankirat Singh
Date: - 02/04/2026 61

PROGRAM 33
WAP to develop a program using JDBC demonstrating the use of prepared
statement.

CODE: -

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class Student {

private int studentroll;

private String studentname;

private int studentclass;

public Student(int studentroll, String studentname, int studentclass) {

super();

[Link] = studentroll;

[Link] = studentname;

[Link] = studentclass;

Mankirat Singh
Date: - 02/04/2026 62

public Student() {

super();

public Student(String studentname, int studentclass) {

super();

[Link] = studentname;

[Link] = studentclass;

public int getStudentroll() {

return studentroll;

public void setStudentroll(int studentroll) {

[Link] = studentroll;

public String getStudentname() {

return studentname;

public void setStudentname(String studentname) {

[Link] = studentname;

public int getStudentclass() {

return studentclass;

Mankirat Singh
Date: - 02/04/2026 63

public void setStudentclass(int studentclass) {

[Link] = studentclass;

@Override

public String toString() {

return "Student [Studentroll=" + studentroll +

", Studentname=" + studentname +

", Studentclass=" + studentclass + "]";

public class Cpr {

static Connection con;

public static Connection createC() {

try {

[Link]("[Link]");

String user = "root";

String password = "19032003";

String url = "jdbc:mysql://localhost:3306/javalab";

con = [Link](url, user, password);

} catch (Exception e) {

[Link]();

Mankirat Singh
Date: - 02/04/2026 64

return con;

public class StudentDao {

public static boolean insertStudentToDb(Student st) {

boolean f = false;

try {

Connection con = [Link]();

String q = "insert into student(sname,sclass) values(?,?)";

PreparedStatement pstmt = [Link](q);

[Link](1, [Link]());

[Link](2, [Link]());

[Link]();

f = true;

} catch (Exception e) {

[Link]();

return f;

public static boolean deleteStudent(int userId) {

boolean f = false;

try {

Connection con = [Link]();

Mankirat Singh
Date: - 02/04/2026 65

String q = "delete from students where sroll=?";

PreparedStatement pstmt = [Link](q);

[Link](1, userId);

[Link]();

f = true;

} catch (Exception e) {

[Link]();

return f;

public static void displayData() {

try {

Connection con = [Link]();

String q = "select * from students";

Statement stmt = [Link]();

ResultSet set = [Link](q);

while ([Link]()) {

int roll = [Link](1);

String name = [Link](2);

int cl = [Link]("sclass");

[Link]("roll: " + roll +

" name: " + name +

" class: " + cl);

Mankirat Singh
Date: - 02/04/2026 66

[Link]("++++++++++++++++++++++++++++++++++++++++++++");

} catch (Exception e) {

[Link]();

public class start {

public static void main(String[] args) throws Exception {

[Link]("Welcome to my program");

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

while (true) {

[Link]("press 1 to add students data");

[Link]("press 2 to delete students data");

[Link]("press 3 to display students data");

[Link]("press 4 to exit from students data");

int c = [Link]([Link]());

if (c == 1) {

[Link]("Enter the student name:");

String name = [Link]();

[Link]("Enter the class of the student:");

int studentClass = [Link]([Link]());

Mankirat Singh
Date: - 02/04/2026 67

Student st = new Student(name, studentClass);

boolean ans = [Link](st);

if (ans) {

[Link]("data added successfully");

} else {

[Link]("error plz try again");

[Link](st);

} else if (c == 2) {

[Link]("Enter the roll number of the student:");

int userId = [Link]([Link]());

boolean f = [Link](userId);

if (f) {

[Link]("data deleted successfully");

} else {

[Link]("error plz try again");

} else if (c == 3) {

[Link]();

} else if (c == 4) {

break;

} else {

[Link]("Invalid choice");

Mankirat Singh
Date: - 02/04/2026 68

} }

[Link]("Thank you by Mankirat");

} }

Mankirat Singh
Date: - 02/04/2026 69

PROGRAM 34
WAP to demonstrate Stack(using array)

CODE: -

public class Kirat {

private int[] stack;

private int top;

private int capacity;

public Kirat(int size) {

stack = new int[size];

capacity = size;

top = -1; } // Stack is empty initially

public void push(int value) {

if (top == capacity - 1) {

[Link]("Stack Overflow! Cannot push " + value);

return; }

stack[++top] = value;

[Link](value + " pushed into stack"); }

public int pop() {

if (top == -1) {

[Link]("Stack Underflow! Cannot pop");

return -1;

return stack[top--]; }

Mankirat Singh
Date: - 02/04/2026 70

public void display() {

if (top == -1) {

[Link]("Stack is empty");

return; }

[Link]("Stack elements: ");

for (int i = 0; i <= top; i++) { [Link](stack[i] + " "); }

[Link]();

public static void main(String[] args) {

Kirat stack = new Kirat(5); // Stack of size 5

[Link](10);

[Link](20);

[Link](30);

[Link]();

[Link]("Popped element: " + [Link]());

[Link]("Popped element: " + [Link]());

[Link]();

Mankirat Singh
Date: - 02/04/2026 71

PROGRAM 35
WAP to demonstrate Queue(using array)

CODE: -
class Queue {

int arr[] = new int[5];

int front = -1, rear = -1;

void enqueue(int x) {

if (rear == [Link] - 1) {

[Link]("Queue Overflow");

} else {

if (front == -1) front = 0;

arr[++rear] = x;

[Link](x + " inserted");

void dequeue() {

if (front == -1 || front > rear) {

[Link]("Queue Underflow");
} else {

[Link](arr[front++] + " deleted");

void display() {

if (front == -1 || front > rear) {

[Link]("Queue is empty");
} else {

Mankirat Singh
Date: - 02/04/2026 72

for (int i = front; i <= rear; i++) {

[Link](arr[i] + " ");

[Link]();

public static void main(String[] args) {

Queue q = new Queue();

[Link](40);
[Link](50);

[Link](60);

[Link]();

[Link]();

[Link]();

Mankirat Singh
Date: - 02/04/2026 73

PROGRAM 36
WAP to demonstrate Dynamic Polymorphism

CODE: -

class Animal {

void sound() {

[Link]("Animal makes sound"); }}

class Dog extends Animal {

void sound() {

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

class Cat extends Animal {

void sound() {

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

public class DynamicPoly {

public static void main(String[] args) {

Animal a;

a = new Dog(); // reference of parent, object of child

[Link]();
a = new Cat();

[Link](); }

Mankirat Singh
Date: - 02/04/2026 74

Mankirat Singh

You might also like