0% found this document useful (0 votes)
16 views28 pages

Ap Lab

Uploaded by

Rishab Goyal
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)
16 views28 pages

Ap Lab

Uploaded by

Rishab Goyal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Experiment 1 :- Basic Arithmetic Operations – Create a calculator that

performs addition , subtraction , multiplication and division

Code :-
import java.util.Scanner;

public class experiment1{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter number 1");
int num1 = sc.nextInt();
System.out.println("enter number 2");
int num2 = sc.nextInt();
System.out.println("enter the operation to be performed");
int op = sc.next().charAt(0);
if(op == '+'){
System.out.println(num1 + " + "+ num2 + " = "+ (num1 + num2));
}else if(op == '-'){
System.out.println(num1 + " - " + num2 + " = "+ (num1 - num2));
}else if(op == '*'){
System.out.println(num1 + " * " + num2 + " = "+ (num1 * num2));
}else if(op == '/'){
System.out.println(num1 + " / " + num2 + " = "+ (num1 / num2));
}else {
System.out.println("Invalid Operation");
}
sc.close();
}
}

Output :-
Experiment 2 :- Control Structure – Write program to demonstrate the use of if
, else , switch , for , while and do-while loops .
Code :-
import java.util.Scanner;

public class experiment2 {


public static void main(String[] args) {

//if - else
int marks;
Scanner sc = new Scanner(System.in);
System.out.println("enter marks");
marks = sc.nextInt();

if(marks < 100 && marks >= 90 ){


System.out.println("A+");
}else if(marks >= 80 && marks < 90 ){
System.out.println("A");
}else if(marks >= 70 && marks < 80 ){
System.out.println("B+");
}else if(marks >= 60 && marks < 70 ){
System.out.println("B");
}else if(marks >= 50 && marks < 60 ){
System.out.println("C");
}else if(marks >= 40 && marks < 50 ){
System.out.println("D");
}else if(marks < 40 && marks >= 0){
System.out.println("F");
}else {
System.out.println("Invalid marks");
}

Output :-

Code : -
//Switch case
int day ;
System.out.println("enter the day number");
day = sc.nextInt();
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
break;
}

Output :-

Code :-
//for loop
for(int i = 0 ; i < 6; i++){
for(int j = 5-i ; j < 6 ; j++){
System.out.print("* ");
}
System.out.println();
}
Output :-

Code :-
//while loop
int i = 1;
while(i < 10){
System.out.println(i);
i++;
}
Output : -

Code :-
//do while loop
int k = 1;
do{
System.out.println(k);
k++;
}while(k < 8);
Output : -
Experiment 3 :- Classes and Objects – Create a class Car with attributes like
model , year and price. Instantiate objects of this class.

Code :-

class car{

String model;
int year;
int price;
}

public class experiment3 {


public static void main(String[] args) {
car c = new car();
c.model = "R8";
c.year = 2015;
c.price = 2000000;
System.out.println("model of the car is "+ c.model);
System.out.println("year of manufacturing of car is "+ c.year);
System.out.println("price of car is "+ c.price);
}
}

Output :-
Experiment 4 :- Inheritance – Implement a class hierarchy with base class
animal and derived classes Dog and Cat.

Code :-
class animal{
String color;
int height;
int age ;
}

class dog extends animal{


int weight ;
void bark(){
System.out.println("bow.. bow..");
}

class cat extends animal{


int weight;
void meow(){
System.out.println("meow.. meow...");
}
}
public class experiment4 {
public static void main(String[] args) {
dog d = new dog();
cat c = new cat();
d.age = 5;
d.color = "white";
d.height = 3;

c.age = 7;
c.color = "black";
c.height = 2;

System.out.println("dog's age is " + d.age + " years ");


System.out.println("cat's age is " + c.age + " years ");
}
}

Output : -
Experiment 5 :- Polymorphism – Demonstrate the method overriding and
overloading with class shape and derived classes Circle , Square and Triangle.

Code :-

class shape {
public void sides() {
System.out.println("shape is not defined");
}

public void area() {


System.out.println("this method print area");
}

public void area(double radius) {


System.out.println("area of circle is " + 3.14 * radius * radius);
}

public void area(int side) {


System.out.println("area of square is " + side * side);
}

public void area(int base, int height) {


System.out.println("area of triangle is " + 0.5 * base * height);
}
}

class circle extends shape {


public void sides() {
System.out.println("circle has no sides");
}
}

class square extends shape {


public void sides() {
System.out.println("a square has 4 sides");
}
}

class triangle extends shape {


public void sides() {
System.out.println("a triangle has 3 sides");
}
}

public class experiment5 {


public static void main(String[] args) {
shape s = new shape();
circle c = new circle();
square sq = new square();
triangle t = new triangle();

// method overridding
System.out.println("Method Over Ridding");
s.sides();;
c.sides();
sq.sides();
t.sides();

System.out.println();

//method over loading


System.out.println("method Over Loading");
s.area();
s.area(4);
s.area(2.5);
s.area(3, 4);
}
}

Output : -
Experiment 6:- Encapsulation – Create a class student with private attributes
and public getter and setter methods.
Code :-
class student{
private int age;
private String name;
private int rollno ;
//getters
public String getName(){
return name;
}

public int getAge(){


return age;
}
public int getRollno(){
return rollno;
}
//setters
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public void setRollno(int rollno){
this.rollno = rollno;
}
}
public class experiment6 {
public static void main(String[] args) {
student s1 = new student();
s1.setAge(5);
s1.setName("lucky");
s1.setRollno(21);
System.out.println(s1.getAge());
System.out.println(s1.getName());
System.out.println(s1.getRollno());
}
}
Output :-
Experiment 7 : -Abstraction – Implement abstract classes and Interfaces to
define a contract for a set of operations.

Code :-

interface Operation {
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
}

abstract class Calculator implements Operation {


public int add(int a, int b) {
return a + b; }
public abstract int subtract(int a, int b);
public abstract int multiply(int a, int b);
}

class BasicCalculator extends Calculator {


public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
}

public class experiment7 {


public static void main(String[] args) {
BasicCalculator calculator = new BasicCalculator();
int result1 = calculator.add(2, 3); // returns 5
int result2 = calculator.subtract(5, 2); // returns 3
int result3 = calculator.multiply(4, 5); // returns 20
System.out.println("Result 1: " + result1);
System.out.println("Result 2: " + result2);
System.out.println("Result 3: " + result3);
}
}

Output : -
Experiment 8 :- Linked List – Create a simple linked list implementation and
perform basic operations like insertion , deletion and traversal.

Code : -

class Node {
int data;
Node next;

public Node(int data) {


this.data = data;
this.next = null;
}
}

class LinkedList {
Node head;

public LinkedList() {
head = null;
}

// Insertion at the end


public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}

// Delete the last node


public void deleteNode() {
if (head == null) return;

Node temp = head;


Node prePtr = temp;
while (temp.next != null) {
prePtr = temp;
temp = temp.next;
}
prePtr.next = null ;
}

// Traversal of the list


public void traverse() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}

public class experiment8 {


public static void main(String[] args) {
LinkedList list = new LinkedList();

list.insert(10);
list.insert(20);
list.insert(30);
list.insert(40);
System.out.println("list after inserting 4 nodes");
list.traverse();

list.deleteNode();

System.out.println("list after deleting the last node");


list.traverse();
}
}

Output :-
Experiment 9 :- Stack – Implement a stack using an array or a linked list and
demonstrate push , pop and peek operations.

Code :-
//implementation of stack using array
class StackArray {
private int maxSize;
private int top;
private int[] stackArray;

public StackArray(int size) {


maxSize = size;
stackArray = new int[maxSize];
top = -1;
}

public void push(int value) {


if (top >= maxSize - 1) {
System.out.println("Stack Overflow");
} else {
stackArray[++top] = value;
}
}

public int pop() {


if (top < 0) {
System.out.println("Stack Underflow");
return -1;
} else {
return stackArray[top--];
}
}

public int peek() {


if (top < 0) {
System.out.println("Stack Underflow");
return -1;
} else {
return stackArray[top];
}
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
}

//implementaion of stack using linkedlist


class Node {
int data;
Node next;

public Node(int value) {


data = value;
next = null;
}
}

class StackLinkedList {
private Node top;

public StackLinkedList() {
top = null;
}

public void push(int value) {


Node newNode = new Node(value);
if (top == null) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
}

public int pop() {


if (top == null) {
System.out.println("Stack Underflow");
return -1;
} else {
int value = top.data;
top = top.next;
return value;
}
}

public int peek() {


if (top == null) {
System.out.println("Stack Underflow");
return -1;
} else {
return top.data;
}
}

public boolean isEmpty() {


return (top == null);
}
}
public class experiment9 {
public static void main(String[] args) {
StackArray stackArray = new StackArray(5);
stackArray.push(10);
stackArray.push(20);
stackArray.push(30);
System.out.println("implementation of stack using array ");
System.out.println("Peek: " + stackArray.peek());
System.out.println("Pop: " + stackArray.pop());
System.out.println("Peek: " + stackArray.peek());

System.out.println();

StackLinkedList stackLinkedList = new StackLinkedList();


stackLinkedList.push(10);
stackLinkedList.push(20);
stackLinkedList.push(30);
System.out.println("implementation of stack using linkedList");
System.out.println("Peek: " + stackLinkedList.peek());
System.out.println("Pop: " + stackLinkedList.pop());
System.out.println("Peek: " + stackLinkedList.peek());
}
}

Output :-
Experiment 10 :- Try-Catch-Finally - Write a program to demonstrate the use of
try-catch-finally blocks for exception handling.

Code:-

class ExceptionHandlingDemo{

public void divideNumbers(int a, int b) {


try {
System.out.println("Dividing " + a + " by " + b);
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero. " + e.getMessage());
} finally {
System.out.println("Execution of divideNumbers method completed.\n");
}
}
}

public class experiment10 {


public static void main(String[] args) {
ExceptionHandlingDemo demo = new ExceptionHandlingDemo();
demo.divideNumbers(10, 0);
demo.divideNumbers(10, 2);

}
}

Output :-
Experiment 11 :- Thread Creation - Create and start multiple threads using
Thread class and Runnable interface.
Code :-
// thread creation using Thread class
class MyThread extends Thread {
private String threadName;

MyThread(String name) {
this.threadName = name;
}

public void run() {


System.out.println(threadName + " is running.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
System.out.println(threadName + " has finished.");
}
}

//thread creation using runnable interface


class MyRunnable implements Runnable {
private String threadName;

MyRunnable(String name) {
this.threadName = name;
}

public void run() {


try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
System.out.println(threadName + " is running.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
System.out.println(threadName + " has finished.");
}
}

public class experiment11 {


public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread 1 using thread class");
MyThread thread2 = new MyThread("Thread 2 using thread class");
MyThread thread3 = new MyThread("Thread 3 using thread class");

thread1.start();
thread2.start();
thread3.start();

Thread t1 = new Thread(new MyRunnable("Thread 1 using Runnable


interface"));
Thread t2 = new Thread(new MyRunnable("Thread 2 using Runnable
interface"));
Thread t3 = new Thread(new MyRunnable("Thread 3 using Runnable
interface"));

t1.start();
t2.start();
t3.start();
}
}

Output :-
Experiment 12:- Thread Synchronization - Demonstrate thread synchronization
using the synchronized keyword and wait/notify methods.
Code:-
class NumberPrinter {
private int count = 1;
private final int max;

public NumberPrinter(int max) {


this.max = max;
}

public synchronized void printEven() throws InterruptedException {


while (count <= max) {
while (count % 2 != 0) {
wait();
}
System.out.println("Even: " + count);
count++;
notify();
}
}

public synchronized void printOdd() throws InterruptedException {


while (count <= max) {
while (count % 2 == 0) {
wait();
}
System.out.println("Odd: " + count);
count++;
notify();
}
}
}

class EvenPrinter implements Runnable {


private final NumberPrinter numberPrinter;

public EvenPrinter(NumberPrinter numberPrinter) {


this.numberPrinter = numberPrinter;
}

public void run() {


try {
numberPrinter.printEven();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

class OddPrinter implements Runnable {


private final NumberPrinter numberPrinter;

public OddPrinter(NumberPrinter numberPrinter) {


this.numberPrinter = numberPrinter;
}

public void run() {


try {
numberPrinter.printOdd();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

public class experiment12 {


public static void main(String[] args) {
NumberPrinter numberPrinter = new NumberPrinter(10);

Thread evenThread = new Thread(new EvenPrinter(numberPrinter));


Thread oddThread = new Thread(new OddPrinter(numberPrinter));

evenThread.start();
oddThread.start();
}
}
Output : -
Experiment 13:- JDBC - Connect to a database using JDBC, execute SQL queries,
and retrieve results.
Code:-
import java.sql.*;

public class experiment13 {


public static void main(String[] args) {

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


String username = "root";
String password = "root";

String query = "SELECT id, name, email FROM users";

try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.err.println("Driver not found: " + e.getMessage());
}

try (Connection conn = DriverManager.getConnection(url, username, password);


Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {

while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");

System.out.printf("ID: %d, Name: %s, Email: %s%n", id, name, email);


}

} catch (SQLException e) {
System.err.println("SQL Exception: " + e.getMessage());
}
}
}
Output :-
Experiment 14 :- Design Patterns: Implement common design patterns like
Singleton, Factory, and Observer.
Code:-
import java.util.*;

// Singleton Pattern
class Singleton {
private static Singleton instance;
public int value;
private Singleton() {
value = 0;
}

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}

public void increment() {


value++;
}
}

// Factory Pattern
interface Vehicle {
void drive();
}

class Car implements Vehicle {


public void drive() {
System.out.println("Driving a car...");
}
}
class Bike implements Vehicle {
public void drive() {
System.out.println("Riding a bike...");
}
}
// Factory Class
class VehicleFactory {
public static Vehicle getVehicle(String type) {
if (type.equalsIgnoreCase("Car")) {
return new Car();
} else if (type.equalsIgnoreCase("Bike")) {
return new Bike();
}
return null;
}
}
// Observer Pattern
interface Subject {
void registerObserver(Observer o);
void unregisterObserver(Observer o);
void notifyObservers();
}

interface Observer {
void update(int state);
}

class ConcreteSubject implements Subject {


private List<Observer> observers = new ArrayList<>();
private int state;

public void setState(int state) {


this.state = state;
notifyObservers();
}

public void registerObserver(Observer o) {


observers.add(o);
}

public void unregisterObserver(Observer o) {


observers.remove(o);
}

public void notifyObservers() {


for (Observer observer : observers) {
observer.update(state);
}
}
}

class ConcreteObserver implements Observer {


private String name;
public ConcreteObserver(String name) {
this.name = name;
}
public void update(int state) {
System.out.println(name + " received update. New state: " + state);
}
}

public class experiment14 {


public static void main(String[] args) {
System.out.println("Singleton Pattern Output:");
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
singleton1.increment();
singleton1.increment();
System.out.println("singleton1 value: " + singleton1.value);
System.out.println("singleton2 value: " + singleton2.value);
System.out.println("Are both instances the same? " + (singleton1 ==
singleton2) + "\n");

System.out.println("Factory Pattern Output:");


Vehicle car = VehicleFactory.getVehicle("Car");
car.drive();
Vehicle bike = VehicleFactory.getVehicle("Bike");
bike.drive();

System.out.println("\nObserver Pattern Output:");


ConcreteSubject subject = new ConcreteSubject();
ConcreteObserver observer1 = new ConcreteObserver("Observer1");
ConcreteObserver observer2 = new ConcreteObserver("Observer2");

subject.registerObserver(observer1);
subject.registerObserver(observer2);

subject.setState(10);
subject.unregisterObserver(observer1);
subject.setState(20);
}
}
Output:-
Experiment 15 :- Producer-Consumer Problem - Implement solution of
Producer-Consumer Problem.
Code:-
import java.util.LinkedList;
import java.util.Queue;

class Buffer {
private Queue<Integer> queue = new LinkedList<>();
private int capacity;

public Buffer(int capacity) {


this.capacity = capacity;
}

public synchronized void produce(int value) throws InterruptedException {


while (queue.size() == capacity) {
System.out.println("Buffer is full. Producer is waiting...");
wait();
}

queue.add(value);
System.out.println("Produced: " + value);
notifyAll();
}

public synchronized int consume() throws InterruptedException {


while (queue.isEmpty()) {
System.out.println("Buffer is empty. Consumer is waiting...");
wait();
}

int value = queue.poll();


System.out.println("Consumed: " + value);
notifyAll();
return value;
}
}

// Producer Thread
class Producer extends Thread {
private Buffer buffer;

public Producer(Buffer buffer) {


this.buffer = buffer;
}
public void run() {
int value = 0;
try {
while (value < 6) {
buffer.produce(value++);
Thread.sleep(500);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

// Consumer Thread
class Consumer extends Thread {
private Buffer buffer;

public Consumer(Buffer buffer) {


this.buffer = buffer;
}

public void run() {


try {
while (true) {
buffer.consume();
Thread.sleep(1500); // Sleep to simulate time taken to consume
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

public class experiment15 {


public static void main(String[] args) {
Buffer buffer = new Buffer(3);

Producer producer = new Producer(buffer);


Consumer consumer = new Consumer(buffer);

producer.start();
consumer.start();
}
}
Output :-
Experiment 16 : - File Reading and Writing - Write a program to read data from
a file and write data to a file.
Code: -

import java.io.*;

public class experiment16 {


public static void main(String[] args) {
String inputFilePath = "E:\\code\\Assignments\\Ap lab\\input.txt";
String outputFilePath = "E:\\code\\Assignments\\Ap lab\\output.txt";

try (BufferedReader reader = new BufferedReader(new


FileReader(inputFilePath))) {
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(outputFilePath))) {
String line;

System.out.println("Reading from input file:");


while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line);
writer.newLine();
}

System.out.println("\nData has been successfully written to "


+ outputFilePath);
} catch (IOException e) {
System.err.println("Error writing to file: " +
e.getMessage());
}
} catch (IOException e) {
System.err.println("Error reading from file: " + e.getMessage());
}
}
}

Output: -

You might also like