OneCompiler

hijava

83

import java.util.Scanner;

class Student {
String name;
int rollNo;
int marks[] = new int[3]; // marks for 3 subjects
int total;
double percentage;
double gpa;
String grade;
String status;

// Calculate total, percentage, GPA, grade, status
void calculate() {
total = 0;
for (int mark : marks) {
total += mark;
}

// Widening type casting: int -> double
percentage = (double) total / 3;  

// GPA (out of 10)
gpa = percentage / 10;

// Narrowing type casting: double -> int (round GPA)
gpa = (int) gpa;  

// Grade logic
if (percentage >= 90) grade = "A+";
else if (percentage >= 80) grade = "A";
else if (percentage >= 70) grade = "B";
else if (percentage >= 60) grade = "C";
else if (percentage >= 50) grade = "D";
else grade = "F";

// Pass/Fail status
status = (percentage >= 50) ? "Pass" : "Fail";

}

void display() {
System.out.println("\n--- Student Report ---");
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
System.out.println("Total Marks: " + total);
System.out.println("Percentage: " + percentage);
System.out.println("GPA: " + gpa);
System.out.println("Grade: " + grade);
System.out.println("Status: " + status);
}
}

public class StudentAnalyzer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter number of students: ");
int n = sc.nextInt();

Student[] students = new Student[n];

for (int i = 0; i < n; i++) {
    students[i] = new Student();

    System.out.println("\nEnter details for Student " + (i + 1));
    System.out.print("Name: ");
    students[i].name = sc.next();
    System.out.print("Roll No: ");
    students[i].rollNo = sc.nextInt();

    System.out.println("Enter marks for 3 subjects:");
    for (int j = 0; j < 3; j++) {
        students[i].marks[j] = sc.nextInt();
    }

    students[i].calculate();
}

// Display results and compute class stats
double totalPercentage = 0;
double highest = 0, lowest = 100;
String topper = "";

for (Student s : students) {
    s.display();
    totalPercentage += s.percentage;

    if (s.percentage > highest) {
        highest = s.percentage;
        topper = s.name;
    }
    if (s.percentage < lowest) {
        lowest = s.percentage;
    }
}

System.out.println("\n===== CLASS STATISTICS =====");
System.out.println("Class Average: " + (totalPercentage / n));
System.out.println("Highest Percentage: " + highest);
System.out.println("Lowest Percentage: " + lowest);
System.out.println("Topper: " + topper);

}
}

..................................2nd

import java.util.Scanner;

public class SmartTrafficSystem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

int totalVehicles, redLightViolations = 0;
int speedViolations = 0;
int congestionLevel = 0;

System.out.print("Enter number of vehicles passing the signal: ");
totalVehicles = sc.nextInt();

// Loop through each vehicle
for (int i = 1; i <= totalVehicles; i++) {
    System.out.println("\n--- Vehicle " + i + " ---");
    System.out.print("Enter vehicle speed (km/h): ");
    int speed = sc.nextInt();

    System.out.print("Did the vehicle break red light? (yes=1 / no=0): ");
    int redLight = sc.nextInt();

    // Detect violations
    if (speed > 80) {
        speedViolations++;
        System.out.println("⚠️ Over-speeding detected!");
    }

    if (redLight == 1) {
        redLightViolations++;
        System.out.println("🚨 Red light violation detected!");
    }

    // Detect congestion
    congestionLevel++;
    if (congestionLevel > 10) {
        System.out.println("⚠️ Heavy congestion detected! Clearing traffic...");
        congestionLevel = 0;  // Reset congestion
        continue; // Skip to next vehicle, continue monitoring
    }

    // Handle critical condition
    if (speed > 150) {
        System.out.println("🚓 Critical condition! Extremely high speed detected!");
        System.out.println("Emergency alert sent to nearest traffic police!");
        break; // Stop monitoring for safety
    }
}

// Generate report
System.out.println("\n===== TRAFFIC REPORT =====");
System.out.println("Total vehicles monitored: " + totalVehicles);
System.out.println("Red light violations: " + redLightViolations);
System.out.println("Over-speeding violations: " + speedViolations);
System.out.println("System Status: " + (redLightViolations + speedViolations > 0 ? "⚠️ Violations detected" : "✅ All clear"));

sc.close();

}
}

..........................3rd

// LibraryManagementSystem.java
import java.util.*;

class Book {
String title;
String author;
static int totalBooks = 0; // Static member

// Constructor
Book(String title, String author) {
this.title = title;
this.author = author;
totalBooks++;
}

// Display book details
void display() {
System.out.println("Book: " + title + " | Author: " + author);
}

// Method to demonstrate garbage collection
protected void finalize() {
System.out.println("Book '" + title + "' is removed from memory.");
}
}

class Member {
String name;
int memberId;
static int memberCount = 0;

// Constructor
Member(String name) {
this.name = name;
this.memberId = ++memberCount;
}

// Display member details
void display() {
System.out.println("Member ID: " + memberId + " | Name: " + name);
}
}

class Transaction {
Book book;
Member member;
String date;

// Constructor 1 (Issue book)
Transaction(Book book, Member member, String date) {
this.book = book;
this.member = member;
this.date = date;
}

// Constructor 2 (Overloaded: Return book)
Transaction(Book book, Member member) {
this.book = book;
this.member = member;
this.date = "Returned";
}

// Display transaction details
void display() {
System.out.println("Transaction: " + member.name + " - " + book.title + " (" + date + ")");
}
}

public class LibraryManagementSystem {
public static void main(String[] args) {
// Create some books
Book b1 = new Book("Java Programming", "James Gosling");
Book b2 = new Book("Python Basics", "Guido van Rossum");

// Create a member
Member m1 = new Member("Alice");

// Display details
b1.display();
b2.display();
m1.display();

// Create transactions
Transaction t1 = new Transaction(b1, m1, "05-Nov-2025");
Transaction t2 = new Transaction(b2, m1); // Overloaded constructor

t1.display();
t2.display();

// Static members demo
System.out.println("\nTotal Books: " + Book.totalBooks);
System.out.println("Total Members: " + Member.memberCount);

// Demonstrate Garbage Collection
b1 = null;
System.gc(); // Request garbage collection

System.out.println("\nEnd of Program!");

}
}

.................4th
// Base class
class Employee {
String name;
double salary;

Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}

// Method to calculate bonus (to be overridden)
double calculateBonus() {
return 0;
}

void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Base Salary: " + salary);
System.out.println("Bonus: " + calculateBonus());
System.out.println("Total Pay: " + (salary + calculateBonus()));
System.out.println("--------------------------");
}
}

// Derived class - Manager
class Manager extends Employee {
Manager(String name, double salary) {
super(name, salary);
}

// Overriding method
double calculateBonus() {
return salary * 0.20; // 20% bonus
}
}

// Derived class - Engineer
class Engineer extends Employee {
Engineer(String name, double salary) {
super(name, salary);
}

// Overriding method
double calculateBonus() {
return salary * 0.10; // 10% bonus
}
}

// Derived class - Intern
class Intern extends Employee {
Intern(String name, double salary) {
super(name, salary);
}

// Overriding method
double calculateBonus() {
return salary * 0.05; // 5% bonus
}
}

// Main class
public class PayrollSystem {
public static void main(String[] args) {
// Polymorphism: base class reference -> derived class objects
Employee e1 = new Manager("Alice", 80000);
Employee e2 = new Engineer("Bob", 60000);
Employee e3 = new Intern("Charlie", 20000);

// Display payroll details
e1.displayDetails();
e2.displayDetails();
e3.displayDetails();

}
}

..................5th
// Sensor interface
interface Sensor {
void detect(); // method to detect condition
}

// Abstract class Appliance
abstract class Appliance {
String name;

Appliance(String name) {
this.name = name;
}

abstract void turnOn();
abstract void turnOff();
}

// SmartLight class implementing Sensor and extending Appliance
class SmartLight extends Appliance implements Sensor {

SmartLight(String name) {
super(name);
}

@Override
public void turnOn() {
System.out.println(name + " Light is turned ON.");
}

@Override
public void turnOff() {
System.out.println(name + " Light is turned OFF.");
}

@Override
public void detect() {
System.out.println(name + " Light sensor detects darkness!");
}
}

// SmartThermostat class implementing Sensor and extending Appliance
class SmartThermostat extends Appliance implements Sensor {

SmartThermostat(String name) {
super(name);
}

@Override
public void turnOn() {
System.out.println(name + " Thermostat is now ON.");
}

@Override
public void turnOff() {
System.out.println(name + " Thermostat is now OFF.");
}

@Override
public void detect() {
System.out.println(name + " Thermostat detects room temperature!");
}
}

// Main class to test the simulation
public class SmartHomeSimulation {
public static void main(String[] args) {
SmartLight light = new SmartLight("Living Room");
SmartThermostat thermostat = new SmartThermostat("Bedroom");

light.detect();
light.turnOn();
light.turnOff();

System.out.println();

thermostat.detect();
thermostat.turnOn();
thermostat.turnOff();

}
}

................6th

import java.util.Scanner;

class Account {
private double balance;

public Account(double balance) {
this.balance = balance;
}

public void deposit(double amount) {
balance += amount;
System.out.println("Deposited ₹" + amount);
}

public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn ₹" + amount);
} else {
System.out.println("Insufficient balance!");
}
}

public double getBalance() {
return balance;
}
}

class Customer {
private String name;
private Account account;

public Customer(String name, double initialBalance) {
this.name = name;
this.account = new Account(initialBalance);
}

public void showDetails() {
System.out.println("\n--- Customer Details ---");
System.out.println("Name: " + name);
System.out.println("Account Balance: ₹" + account.getBalance());
}

public Account getAccount() {
return account;
}
}

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter customer name: ");
String name = sc.nextLine();
System.out.print("Enter initial deposit: ₹");
double amount = sc.nextDouble();

Customer customer = new Customer(name, amount);
int choice;

do {
    System.out.println("\n===== BANK MENU =====");
    System.out.println("1. Deposit");
    System.out.println("2. Withdraw");
    System.out.println("3. Show Account Details");
    System.out.println("4. Exit");
    System.out.print("Enter choice: ");
    choice = sc.nextInt();

    switch (choice) {
        case 1:
            System.out.print("Enter amount to deposit: ₹");
            customer.getAccount().deposit(sc.nextDouble());
            break;

        case 2:
            System.out.print("Enter amount to withdraw: ₹");
            customer.getAccount().withdraw(sc.nextDouble());
            break;

        case 3:
            customer.showDetails();
            break;

        case 4:
            System.out.println("Thank you for banking with us!");
            break;

        default:
            System.out.println("Invalid choice! Try again.");
    }
} while (choice != 4);

sc.close();

}
}

............7th

class TicketBooking implements Runnable {
int availableSeats = 5; // total seats
synchronized void bookTicket(String name, int seats) {
if (availableSeats >= seats) {
System.out.println(name + " booked " + seats + " seat(s).");
availableSeats -= seats;
} else {
System.out.println(name + " failed to book. Only " + availableSeats + " left.");
}
}

public void run() {
bookTicket(Thread.currentThread().getName(), 2);
}

public static void main(String[] args) {
TicketBooking booking = new TicketBooking();
Thread t1 = new Thread(booking, "User1");
Thread t2 = new Thread(booking, "User2");
Thread t3 = new Thread(booking, "User3");
Thread t4 = new Thread(booking, "User4");

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

}
}

//..................8th

import java.io.;
import java.util.;

// Custom Exception
class StudentNotFoundException extends Exception {
public StudentNotFoundException(String msg) {
super(msg);
}
}

public class StudentManager {
static final String FILE = "students.txt";

// Add a student
static void addStudent(int id, String name, int age) {
try (FileWriter fw = new FileWriter(FILE, true)) {
fw.write(id + "," + name + "," + age + "\n");
System.out.println("✅ Student added!");
} catch (IOException e) {
System.out.println("❌ Error writing file: " + e.getMessage());
}
}

// View all students
static void viewStudents() {
try (BufferedReader br = new BufferedReader(new FileReader(FILE))) {
String line;
boolean empty = true;
while ((line = br.readLine()) != null) {
System.out.println(line);
empty = false;
}
if (empty) System.out.println("No records found.");
} catch (FileNotFoundException e) {
System.out.println("❌ File not found.");
} catch (IOException e) {
System.out.println("❌ Error reading file.");
}
}

// Update student by ID
static void updateStudent(int id, String newName, int newAge) throws StudentNotFoundException {
List<String> lines = new ArrayList<>();
boolean found = false;

try (BufferedReader br = new BufferedReader(new FileReader(FILE))) {
    String line;
    while ((line = br.readLine()) != null) {
        String[] data = line.split(",");
        if (Integer.parseInt(data[0]) == id) {
            lines.add(id + "," + newName + "," + newAge);
            found = true;
        } else {
            lines.add(line);
        }
    }
} catch (IOException e) {
    System.out.println("❌ Error reading file.");
}

if (!found) throw new StudentNotFoundException("Student ID not found!");

try (FileWriter fw = new FileWriter(FILE)) {
    for (String l : lines) fw.write(l + "\n");
} catch (IOException e) {
    System.out.println("❌ Error writing file.");
}
System.out.println("✅ Student updated!");

}

// Delete student by ID
static void deleteStudent(int id) throws StudentNotFoundException {
List<String> lines = new ArrayList<>();
boolean found = false;

try (BufferedReader br = new BufferedReader(new FileReader(FILE))) {
    String line;
    while ((line = br.readLine()) != null) {
        String[] data = line.split(",");
        if (Integer.parseInt(data[0]) != id)
            lines.add(line);
        else
            found = true;
    }
} catch (IOException e) {
    System.out.println("❌ Error reading file.");
}

if (!found) throw new StudentNotFoundException("Student ID not found!");

try (FileWriter fw = new FileWriter(FILE)) {
    for (String l : lines) fw.write(l + "\n");
} catch (IOException e) {
    System.out.println("❌ Error writing file.");
}
System.out.println("✅ Student deleted!");

}

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

while (true) {
    System.out.println("\n--- Student Record Manager ---");
    System.out.println("1. Add Student");
    System.out.println("2. View Students");
    System.out.println("3. Update Student");
    System.out.println("4. Delete Student");
    System.out.println("5. Exit");
    System.out.print("Enter choice: ");
    int ch = sc.nextInt();

    try {
        switch (ch) {
            case 1 -> {
                System.out.print("ID: "); int id = sc.nextInt();
                System.out.print("Name: "); String name = sc.next();
                System.out.print("Age: "); int age = sc.nextInt();
                addStudent(id, name, age);
            }
            case 2 -> viewStudents();
            case 3 -> {
                System.out.print("ID: "); int id = sc.nextInt();
                System.out.print("New Name: "); String n = sc.next();
                System.out.print("New Age: "); int a = sc.nextInt();
                updateStudent(id, n, a);
            }
            case 4 -> {
                System.out.print("ID: "); int id = sc.nextInt();
                deleteStudent(id);
            }
            case 5 -> { System.out.println("Goodbye!"); return; }
            default -> System.out.println("Invalid choice!");
        }
    } catch (StudentNotFoundException e) {
        System.out.println("❌ " + e.getMessage());
    }

}
}
}

///////..............9th

import java.awt.;
import java.awt.event.;

public class SimpleRegistration extends Frame implements ActionListener {
TextField nameField, ageField;
Checkbox java, python;
Button submit;
Label output;

public SimpleRegistration() {
setTitle("Student Registration");
setSize(300, 250);
setLayout(new FlowLayout());

add(new Label("Name:"));
nameField = new TextField(15);
add(nameField);

add(new Label("Age:"));
ageField = new TextField(5);
add(ageField);

add(new Label("Languages:"));
java = new Checkbox("Java");
python = new Checkbox("Python");
add(java); add(python);

submit = new Button("Submit");
add(submit);
submit.addActionListener(this);

output = new Label("");
add(output);

addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) { dispose(); }
});

setVisible(true);

}

public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String age = ageField.getText();
String langs = "";
if (java.getState()) langs += "Java ";
if (python.getState()) langs += "Python";
output.setText("Hi " + name + " (" + age + ") - " + langs);
}

public static void main(String[] args) {
new SimpleRegistration();
}
}

////............10th
import java.awt.;
import java.awt.event.;

public class SimpleBankApp extends Frame {
double balance = 0;
Label lbl;
TextField tf;

SimpleBankApp() {
setTitle("Simple Bank");
setLayout(new BorderLayout());

lbl = new Label("Balance: ₹0", Label.CENTER);
add(lbl, BorderLayout.NORTH);

Panel mid = new Panel(new FlowLayout());
mid.add(new Label("Amount:"));
tf = new TextField(10);
mid.add(tf);
add(mid, BorderLayout.CENTER);

Panel btns = new Panel(new FlowLayout());
Button dep = new Button("Deposit");
Button wit = new Button("Withdraw");
Button exit = new Button("Exit");
btns.add(dep); btns.add(wit); btns.add(exit);
add(btns, BorderLayout.SOUTH);

dep.addActionListener(e -> {
    try {
        double a = Double.parseDouble(tf.getText());
        if (a > 0) balance += a;
        lbl.setText("Balance: ₹" + balance);
    } catch (Exception ex) { lbl.setText("Invalid amount!"); }
});

wit.addActionListener(e -> {
    try {
        double a = Double.parseDouble(tf.getText());
        if (a > 0 && a <= balance) balance -= a;
        lbl.setText("Balance: ₹" + balance);
    } catch (Exception ex) { lbl.setText("Invalid amount!"); }
});

exit.addActionListener(e -> System.exit(0));

addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) { dispose(); }
});

setSize(300, 200);
setVisible(true);

}

public static void main(String[] args) {
new SimpleBankApp();
}
}