JAVA Lab Programs

1. Calculator using switch case:
import java.util.Scanner;
public class Calculator{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Calculator");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice){
case 1:
System.out.println("Enter two numbers: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int sum = num1 + num2;
System.out.println("The sum is: "+ sum);
break;
case 2:
System.out.println("Enter two numbers: ");
int n3 = scanner.nextInt();
int n4 = scanner.nextInt();
int difference = n3 - n4;
System.out.println("The difference is: "+ difference);
break;
case 3:
System.out.println("Enter two numbers: ");
int n5 = scanner.nextInt();
int n6 = scanner.nextInt();
int product = n5 * n6;
System.out.println("The product is: "+ product);
break;
case 4:
System.out.println("Enter two numbers: ");
int n7 = scanner.nextInt();
int n8 = scanner.nextInt();
if (n8 != 0) {
int division = n7 / n8;
System.out.println("The division is: "+ division);
} else {
System.out.println("Division by zero is not allowed.");
}
break;
case 5:
System.out.println("Exiting");
System.exit(0);
default:
System.out.println("Invalid choice");
break;
}
scanner.close();
}
}



3. Implement parameter passing techniques
public class ParameterPassing {
public static void main(String[] args) {
// Pass by value
int x = 10;
System.out.println("Before passing by value: x = " + x);
passByValue(x);
System.out.println("After passing by value: x = " + x);

// Pass by reference
Person person = new Person("Apple");
System.out.println("Before passing by reference: name = " + person.getName());
passByRef(person);
System.out.println("After passing by reference: name = " + person.getName());
}

public static void passByValue(int y) {
y++;
}

public static void passByRef(Person person) {
person.setName("Ball");
}
}

class Person {
private String name;

public Person(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}



4. Program that read 2d array, create 1d array that contains row & col avg.
import java.util.Scanner;
public class TwoArray Avg {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the no. of rows: ");
int rows = scanner.nextInt();
System.out.println("Enter the no. of columns: ");
int cols = scanner.nextInt();
int[][] array = new int[rows][cols];
System.out.println("Enter the values for the array");
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
array[i][j] = scanner.nextInt();
}
}
double[] rowAverages = new double[rows];
double[] colAverages = new double[cols];
for(int i=0; i<rows; i++){
int rowsum = 0;
for(int j=0; j<cols; j++){
rowsum += array[i][j];
}
rowAverages[i] = (double) rowsum/cols;
}
for(int j=0; j<cols; j++){
int colsum = 0;
for(int i=0; i<rows; i++){
colsum += array[i][j];
}
colAverages[j] = (double) colsum/rows;
}
System.out.println("Row Averages: ");
for(int i=0; i<rows; i++){
System.out.println("Rows"+(i+1)+":"+rowAverages[i]);
}
System.out.println("Column Averages: ");
for(int j=0; j<cols; j++){
System.out.println("Rows"+(j+1)+":"+colAverages[j]);
}
scanner.close();
}
}




6. to create class called person with private instance variable name, age and country.
public class Person {
private String name;
private int age;
private String country;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public String getCountry(){
return country;
}
public void setCountry(String country){
this.country = country;
}
public static void main(String[] args){
Person person = new Person();
person.setName("xyz");
person.setAge(19);
person.setCountry("India");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("Country: " + person.getCountry());
}
}




7. Program for method overloading
public class Sum {
public int sum(int x, int y) {
return (x + y);
}

public int sum(int x, int y, int z) {
return (x + y + z);
}

public double sum(double x, double y) {
return (x + y);
}

public static void main(String[] args) {
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(30, 40, 300));
System.out.println(s.sum(10.5, 12.5));
}
}



8. Create class called shape with methods called getperimeter() & getArea(). create subclass called circle that overrides the getperimeter() & getArea() 
calculate the area & perimeter of a cirlce.
class shape{
public double getPerimeter(){
return 0.0;
}
public double getArea(){
return 0.0;
}
}
class circle extends shape{
private double radius;
public circle(double radius) {
this.radius = radius;
}

@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}

@Override
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
}
public class Main {
public static void main(String[] args) {
circle circle = new circle(5.0);
System.out.println("Perimeter: " + circle.getPerimeter());
System.out.println("Area: " + circle.getArea());
}
}



9. Program for different methods of string class
public class StringMethods {
public static void main(String[] args) {
String str = "Hello world!";
System.out.println("Character at index 0: " + str.charAt(0));
System.out.println("String1 equals String2: " + str.equals("Hello world!"));
System.out.println("String1 equals String2 (ignoring case): " + str.equalsIgnoreCase("hello world!"));
System.out.println("Index of 'o': " + str.indexOf('o'));
System.out.println("Length of the string: " + str.length());
System.out.println("String after replacing 'world' with 'Java': " + str.replace("world", "Java"));
System.out.println("Substring from index 6 to 10: " + str.substring(6, 11));
System.out.println("String in lowercase: " + str.toLowerCase());
System.out.println("String in uppercase: " + str.toUpperCase());
String strwithwhitespace = " Hello world! ";
System.out.println("String with whitespace: '" + strwithwhitespace + "'");
System.out.println("String after trimming whitespace: '" + strwithwhitespace.trim() + "'");
}
}



10. Program to create an abstract class Animal with an abstract method called sound(). create subclasses lion & tiger that extend the Animal class & implement the sound() method to make a specific sound for each animal.
abstract class Animal{
abstract void Sound();
}
class Lion extends Animal{
@Override
void Sound() {
System.out.println("Roar!");
}
}
class Tiger extends Animal{
@Override
void Sound() {
System.out.println("Grow!");
}
}

public class Main {
public static void main(String[] args) {
Animal lion = new Lion();
lion.Sound();
Animal tiger = new Tiger();
tiger.Sound();
}
}



12. Program to implement multiple inhertance with the help of interface.
interface Interface1{
void method1();
}
interface Interface2{
void method2();
}
class Myclass implements Interface1, Interface2{
public void method1() {
System.out.println("This is method1");
}

public void method2() {
System.out.println("This is method2");
}
}

public class Main {
public static void main(String[] args) {
Myclass myclass = new Myclass();
myclass.method1();
myclass.method2();
}
}



14. Program to input name & age of a person & throws a user defined exception if entered age is negative
import java.util.Scanner;

public class UserDefinedException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Enter your age: ");
int age = scanner.nextInt();
try {
if (age < 0) {
throw new InvalidAgeException("Age can't be negative");
}
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
return;
}
System.out.println("Hello " + name + ", you are " + age + " years old");
}
}

class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}



15. Program to create  & access a user defined package.
Myclass.java:
package com.example.mypackage;

public class Myclass {
public void MyMethod() {
System.out.println("This is my method!");
}
}

Main.java:
import com.example.mypackage.Myclass;
public class Main {
public static void main(String[] args) {
Myclass myclass = new Myclass();
myclass.MyMethod();
}
}



16. Program that creates 2 threads. First thread prints the numbers from 1 to 10 & other thread prints the numbers from 10 to 1.
public class NumberPrinting{
public static void main(String[] args) {
Thread ascendingThread = new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("Ascending Thread");
for(int i=1; i<=10; i++){
System.out.println("Ascending: " + i);
}
}
});
Thread descendingThread = new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("Descending Thread");
for(int i=10; i>=1; i--){
System.out.println("Descending: " + i);
}
}
});
ascendingThread.start();
descendingThread.start();
try{
ascendingThread.join();
descendingThread.join();
}catch (InterruptedException e){
System.out.println("Thread execution interrupted: " + e.getMessage());
Thread.currentThread().interrupt();
}
System.out.println("Both threads have completed thier execution.");
}
}



18. Program that works as a simple calculator. Use a grid layout to arrange buttons for the digits & for the +, -, *, % operations. Add a text field to display the result. Handle any possible exceptions like divide by zero.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleCalculator extends JFrame implements ActionListener {
private JTextField display;
private StringBuilder currentInput;
private double result;
private String lastOperator;

public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setFont(new Font("Arial", Font.BOLD, 20));
currentInput = new StringBuilder();
result = 0;
lastOperator = " ";

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4));

String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"c"
};

for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.BOLD, 20));
button.addActionListener(this);
panel.add(button);
}

add(display, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}

@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("0123456789.".contains(command)) {
currentInput.append(command);
display.setText(currentInput.toString());
} else if ("+-*/".contains(command)) {
calculate();
lastOperator = command;
currentInput.setLength(0);
} else if ("=".equals(command)) {
calculate();
display.setText(String.valueOf(result));
lastOperator = " ";
currentInput.setLength(0);
} else if ("c".equals(command)) {
result = 0;
currentInput.setLength(0);
display.setText(" ");
lastOperator = " ";
}
}

private void calculate() {
double currentNumber = Double.parseDouble(currentInput.toString());
switch (lastOperator) {
case " ":
result = currentNumber;
break;
case "+":
result += currentNumber;
break;
case "-":
result -= currentNumber;
break;
case "*":
result *= currentNumber;
break;
case "/":
if (currentNumber == 0) {
JOptionPane.showMessageDialog(this, "Error: Division by Zero", "ERROR", JOptionPane.ERROR_MESSAGE);
} else {
result /= currentNumber;
}
break;
}
display.setText(String.valueOf(result));
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}



19. Program that handles all mouse events & shows the event name at the center of the window when a mouse event is fired.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MouseEventDemo extends JFrame implements MouseListener, MouseMotionListener {
private String eventText = " ";

public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(this);
addMouseMotionListener(this);
}

@Override
public void paint(Graphics g) {
super.paint(g);
g.setFont(new Font("Arial", Font.BOLD, 20));
FontMetrics fm = g.getFontMetrics();
int x = (getWidth() - fm.stringWidth(eventText)) / 2;
int y = (getHeight() - fm.getHeight()) / 2 + fm.getAscent();
g.drawString(eventText, x, y);
}

@Override
public void mouseClicked(MouseEvent e) {
eventText = "Mouse Clicked";
repaint();
}

@Override
public void mousePressed(MouseEvent e) {
eventText = "Mouse Pressed";
repaint();
}

@Override
public void mouseReleased(MouseEvent e) {
eventText = "Mouse Released";
repaint();
}

@Override
public void mouseEntered(MouseEvent e) {
eventText = "Mouse Entered";
repaint();
}

@Override
public void mouseExited(MouseEvent e) {
eventText = "Mouse Exited";
repaint();
}

@Override
public void mouseDragged(MouseEvent e) {
eventText = "Mouse Dragged";
repaint();
}

@Override
public void mouseMoved(MouseEvent e) {
eventText = "Mouse Moved";
repaint();
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MouseEventDemo frame = new MouseEventDemo();
frame.setVisible(true);
});
}
}



20. Program to create a frame window that responds to key strokes.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class keyEventDemo extends JFrame implements KeyListener {
private String keyText = " ";

public keyEventDemo() {
setTitle("Key Event Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}

@Override
public void paint(Graphics g) {
super.paint(g);
g.setFont(new Font("Arial", Font.BOLD, 20));
FontMetrics fm = g.getFontMetrics();
int x = (getWidth() - fm.stringWidth(keyText)) / 2;
int y = (getHeight() - fm.getHeight()) / 2 + fm.getAscent();
g.drawString(keyText, x, y);
}

@Override
public void keyTyped(KeyEvent e) {
keyText = "Key Typed: " + e.getKeyChar();
repaint();
}

@Override
public void keyPressed(KeyEvent e) {
keyText = "Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode());
repaint();
}

@Override
public void keyReleased(KeyEvent e) {
keyText = "Key Released: " + KeyEvent.getKeyText(e.getKeyCode());
repaint();
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
keyEventDemo frame = new keyEventDemo();
frame.setVisible(true);
});
}
}

Comments

Popular posts from this blog

HANGMAN GAME

WD 22. StylingLinks&Buttons