PROGRAM 1
Aim: To write a java program to print biggest of 3 numbers using logical operators
Program :
import [Link];
public class BiggestOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input 3 numbers
[Link]("Enter first number (a): ");
int a = [Link]();
[Link]("Enter second number (b): ");
int b = [Link]();
[Link]("Enter third number (c): ");
int c = [Link]();
int biggest;
// Using logical operators to find the biggest
if ((a >= b) && (a >= c)) {
biggest = a;
} else if ((b >= a) && (b >= c)) {
biggest = b;
} else {
biggest = c;
}
// Output the result
[Link]("The biggest number is: " + biggest);
[Link]();
}
}
Output:
Enter first number (a): 25
Enter second number (b): 78
Enter third number (c): 62
The biggest number is: 78
PROGRAM 2
Aim: To write write a java program to test for prime number
Program:
import [Link];
public class PrimeNumberTest {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input from user
[Link]("Enter a number to check if it's prime: ");
int number = [Link]();
// Check if number is prime
boolean isPrime = true;
if (number <= 1) {
isPrime = false; // 0 and 1 are not prime numbers
} else {
// Only check up to square root of the number
for (int i = 2; i <= [Link](number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}
// Output result
if (isPrime) {
[Link](number + " is a prime number.");
} else {
[Link](number + " is not a prime number.");
}
[Link]();
}
}
Output
Enter a number to check if it's prime: 13
13 is a prime number.
PROGRAM 3
Aim: To write a java program to create a simple class to find out the area and perimeter
of rectangle an box using super and this keyword.
Program :
// Superclass: Rectangle
class Rectangle {
int length;
int width;
// Constructor using this keyword
Rectangle(int length, int width) {
[Link] = length;
[Link] = width;
}
// Method to calculate area of rectangle
int getArea() {
return length * width;
}
// Method to calculate perimeter of rectangle
int getPerimeter() {
return 2 * (length + width);
}
}
// Subclass: Box extends Rectangle
class Box extends Rectangle {
int height;
// Constructor using super and this keyword
Box(int length, int width, int height) {
super(length, width); // calling Rectangle constructor
[Link] = height; // current class variable
}
// Method to calculate volume of box
int getVolume() {
return length * width * height;
}
// Method to calculate surface area of box
int getSurfaceArea() {
return 2 * (length * width + width * height + height * length);
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Create Rectangle object
Rectangle rect = new Rectangle(10, 5);
[Link]("Rectangle:");
[Link]("Area = " + [Link]());
[Link]("Perimeter = " + [Link]());
// Create Box object
Box box = new Box(10, 5, 3);
[Link]("\nBox:");
[Link]("Volume = " + [Link]());
[Link]("Surface Area = " + [Link]());
}
}
Output
Rectangle:
Area = 50
Perimeter = 30
Box:
Volume = 150
Surface Area = 190
PROGRAM 4
Aim: To Write a java program to design a class account using the inheritance and static that
shows all function of bank (withdrawl, deposit)
Program :
// Base class: Account
class Account {
String accountHolderName;
int accountNumber;
double balance;
static int totalAccounts = 0; // static variable to track total accounts
// Constructor
Account(String name, int accNo, double initialBalance) {
[Link] = name;
[Link] = accNo;
[Link] = initialBalance;
totalAccounts++;
}
// Method to deposit money
void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: ₹" + amount);
} else {
[Link]("Invalid deposit amount.");
}
}
// Method to withdraw money
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Withdrawn: ₹" + amount);
} else {
[Link]("Insufficient balance or invalid amount.");
}
}
// Method to display account info
void display() {
[Link]("Account Holder: " + accountHolderName);
[Link]("Account Number: " + accountNumber);
[Link]("Balance: ₹" + balance);
}
// Static method to show total accounts
static void showTotalAccounts() {
[Link]("Total accounts created: " + totalAccounts);
}
}
// Derived class: SavingsAccount (example of inheritance)
class SavingsAccount extends Account {
double interestRate;
// Constructor
SavingsAccount(String name, int accNo, double initialBalance, double interestRate) {
super(name, accNo, initialBalance);
[Link] = interestRate;
}
// Method to add interest
void addInterest() {
double interest = (balance * interestRate) / 100;
balance += interest;
[Link]("Interest added: ₹" + interest);
}
}
// Main class
public class BankDemo {
public static void main(String[] args) {
// Creating account 1
SavingsAccount acc1 = new SavingsAccount("Alice", 1001, 5000.0, 4.5);
[Link]();
[Link](1500);
[Link](2000);
[Link]();
[Link]();
[Link]();
// Creating account 2
SavingsAccount acc2 = new SavingsAccount("Bob", 1002, 8000.0, 5.0);
[Link]();
[Link](9000); // Should fail
[Link](2000);
[Link]();
[Link]();
[Link]();
// Show total number of accounts
[Link]();
}
}
Output
Account Holder: Alice
Account Number: 1001
Balance: ₹5000.0
Deposited: ₹1500.0
Withdrawn: ₹2000.0
Interest added: ₹202.5
Account Holder: Alice
Account Number: 1001
Balance: ₹6702.5
Account Holder: Bob
Account Number: 1002
Balance: ₹8000.0
Insufficient balance or invalid amount.
Deposited: ₹2000.0
Interest added: ₹500.0
Account Holder: Bob
Account Number: 1002
Balance: ₹10500.0
Total accounts created: 2
PROGRAM 5
Aim: To write a java program to design a class using abstract methods and classes
Program :
// Abstract class
abstract class Shape {
// Abstract methods (no body)
abstract double area();
abstract double perimeter();
// Concrete method
void display() {
[Link]("This is a shape.");
}
}
// Rectangle class extends Shape
class Rectangle extends Shape {
double length, width;
// Constructor
Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
// Implement abstract methods
double area() {
return length * width;
}
double perimeter() {
return 2 * (length + width);
}
}
// Circle class extends Shape
class Circle extends Shape {
double radius;
// Constructor
Circle(double radius) {
[Link] = radius;
}
// Implement abstract methods
double area() {
return [Link] * radius * radius;
}
double perimeter() {
return 2 * [Link] * radius;
}
}
// Main class
public class AbstractShapeDemo {
public static void main(String[] args) {
// Create Rectangle object
Shape rect = new Rectangle(10, 5);
[Link]("Rectangle:");
[Link]();
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
[Link]();
// Create Circle object
Shape circle = new Circle(7);
[Link]("Circle:");
[Link]();
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
}
}
Output
Rectangle:
This is a shape.
Area: 50.0
Perimeter: 30.0
Circle:
This is a shape.
Area: 153.93804002589985
Perimeter: 43.982297150257104
PROGRAM 6
Aim: To Write a java program to design a string class that performs string method (equal,
reverse the string, change case)
Program :
import [Link];
// Custom string class
class MyString {
String str;
// Constructor
MyString(String str) {
[Link] = str;
}
// Method to check equality with another string (case-sensitive)
boolean isEqual(String other) {
if ([Link]() != [Link]()) return false;
for (int i = 0; i < [Link](); i++) {
if ([Link](i) != [Link](i)) {
return false;
}
}
return true;
}
// Method to reverse the string
String reverse() {
String rev = "";
for (int i = [Link]() - 1; i >= 0; i--) {
rev += [Link](i);
}
return rev;
}
// Method to change case of each character
String changeCase() {
String changed = "";
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if ([Link](ch)) {
changed += [Link](ch);
} else if ([Link](ch)) {
changed += [Link](ch);
} else {
changed += ch; // Non-alphabetic characters remain unchanged
}
}
return changed;
}
// Method to display the original string
void display() {
[Link]("Original String: " + str);
}
}
// Main class
public class StringOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input string
[Link]("Enter a string: ");
String input = [Link]();
MyString myStr = new MyString(input);
[Link]();
// Reverse the string
[Link]("Reversed String: " + [Link]());
// Change case
[Link]("Changed Case: " + [Link]());
// Check equality
[Link]("Enter another string to compare: ");
String compareTo = [Link]();
if ([Link](compareTo)) {
[Link]("Strings are equal.");
} else {
[Link]("Strings are NOT equal.");
}
[Link]();
}
}
Output
Enter a string: Hello World
Original String: Hello World
Reversed String: dlroW olleH
Changed Case: hELLO wORLD
Enter another string to compare: Hello World
Strings are equal.
PROGRAM 7
Aim :To write a java program to handle the exception using try and multiple catch block
Program :
import [Link];
public class ExceptionHandlingDemo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
try
{
// Input numbers for division
[Link]("Enter numerator: ");
int num = [Link]();
[Link]("Enter denominator: ");
int den = [Link]();
// Division operation (may cause ArithmeticException)
int result = num / den;
[Link]("Result of division: " + result);
// Array operation (may cause ArrayIndexOutOfBoundsException)
int[] arr = {10, 20, 30};
[Link]("Enter index to access (0-2): ");
int index = [Link]();
[Link]("Element at index " + index + ": " + arr[index]);
}
// Specific exception handling
catch (ArithmeticException e)
{
[Link]("Error: Cannot divide by zero.");
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Error: Invalid array index.");
}
// Generic exception handler
catch (Exception e)
{
[Link]("An unexpected error occurred: " + [Link]());
}
[Link]("Program continues after exception handling.");
[Link]();
}
}
Output
Enter numerator: 20
Enter denominator: 4
Result of division: 5
Enter index to access (0-2): 2
Element at index 2: 30
Program continues after exception handling.
PROGRAM 8
Aim: write a java program that import the user define package and access the member
variable of classes that contained by package
Program :
Step 1: Create the package and class
// File path: mypackage/[Link]
package mypackage;
public class Person {
// Member variables
public String name;
public int age;
// Constructor
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
// Method to display details
public void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
Step 2: Create main program that imports and uses this package
// File path: [Link]
import [Link]; // Importing the user-defined package and class
public class MainProgram {
public static void main(String[] args) {
// Create an object of Person from mypackage
Person p = new Person("Alice", 30);
// Access member variables directly
[Link]("Accessing member variables directly:");
[Link]("Name: " + [Link]);
[Link]("Age: " + [Link]);
// Use method to display details
[Link]("\nUsing display() method:");
[Link]();
}
}
How to Compile and Run
project_folder/
├── mypackage/
│ └── [Link]
└── [Link]
javac mypackage/[Link]
javac [Link]
java MainProgram
Output
Accessing member variables directly:
Name: Alice
Age: 30
Using display() method:
Name: Alice
Age: 30
PROGRAM 9
Aim : To write a java program that show the implementation of interface
Program :
// Interface definition
interface Animal {
void sound(); // abstract method
void sleep(); // abstract method
}
// Class implementing the interface
class Dog implements Animal {
// Implementing sound() method
public void sound() {
[Link]("Dog barks: Woof Woof!");
}
// Implementing sleep() method
public void sleep() {
[Link]("Dog is sleeping...");
}
}
// Main class
public class InterfaceDemo {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
[Link]();
}
}
Output
Dog barks: Woof Woof!
Dog is sleeping...
PROGRAM 10
Aim : To write a java program to create a thread that implement the runnable interface
Program :
// Class implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread running: Count " + i);
try {
[Link](500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
[Link]("Thread interrupted");
}
}
}
}
// Main class
public class RunnableDemo {
public static void main(String[] args) {
MyRunnable runnableObj = new MyRunnable();
// Create thread with runnable object
Thread thread = new Thread(runnableObj);
// Start the thread
[Link]();
[Link]("Main thread finished.");
}
}
Output
Main thread finished.
Thread running: Count 1
Thread running: Count 2
Thread running: Count 3
Thread running: Count 4
Thread running: Count 5
PROGRAM 11
Aim: To write a java program to draw the line, rectangle, oval, text using the graphics
method
Program
import [Link];
import [Link];
import [Link];
public class GraphicsDemo extends JPanel {
@Override
public void paint(Graphics g) {
[Link](g);
// Draw a line from (20, 30) to (200, 30)
[Link](20, 30, 200, 30);
// Draw a rectangle at (20, 50) with width 150 and height 100
[Link](20, 50, 150, 100);
// Draw an oval inside rectangle at (200, 50) with width 150 and height 100
[Link](200, 50, 150, 100);
// Draw some text at (20, 180)
[Link]("Graphics Drawing Example", 20, 180);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Graphics Demo");
GraphicsDemo panel = new GraphicsDemo();
[Link](panel);
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
How to Run:
Save this as [Link].
Compile: javac [Link]
Run: java GraphicsDemo
PROGRAM 12
Aim : To write a java program to create menu using frame
Program :
import [Link].*;
import [Link].*;
public class MenuDemo extends Frame implements ActionListener {
MenuItem openItem, saveItem, exitItem, aboutItem;
public MenuDemo() {
// Create a Frame
setTitle("Menu Demo");
setSize(400, 300);
setLayout(new FlowLayout());
// Create MenuBar
MenuBar menuBar = new MenuBar();
// Create Menus
Menu fileMenu = new Menu("File");
Menu helpMenu = new Menu("Help");
// Create MenuItems for File Menu
openItem = new MenuItem("Open");
saveItem = new MenuItem("Save");
exitItem = new MenuItem("Exit");
// Add MenuItems to File Menu
[Link](openItem);
[Link](saveItem);
[Link]();
[Link](exitItem);
// Create MenuItem for Help Menu
aboutItem = new MenuItem("About");
[Link](aboutItem);
// Add Menus to MenuBar
[Link](fileMenu);
[Link](helpMenu);
// Set MenuBar to Frame
setMenuBar(menuBar);
// Add action listeners
[Link](this);
[Link](this);
[Link](this);
[Link](this);
// Window closing event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}
// Handle MenuItem clicks
public void actionPerformed(ActionEvent e) {
String command = [Link]();
switch (command) {
case "Open":
[Link]("Open menu clicked");
break;
case "Save":
[Link]("Save menu clicked");
break;
case "Exit":
[Link]("Exiting...");
[Link](0);
break;
case "About":
[Link]("Menu Demo Application v1.0");
break;
}
}
public static void main(String[] args) {
MenuDemo frame = new MenuDemo();
[Link](true);
}
}
How to run:
1. Save as [Link]
2. Compile with javac [Link]
3. Run with java MenuDem
PROGRAM 13
Aim: write a java program to create a dialog box
Program :
import [Link].*;
public class DialogBoxDemo {
public static void main(String[] args) {
// Show a message dialog
[Link](null, "Welcome to the Dialog Box Demo!", "Message",
JOptionPane.INFORMATION_MESSAGE);
// Show an input dialog
String name = [Link](null, "Enter your name:", "Input Dialog",
JOptionPane.QUESTION_MESSAGE);
// Show a confirmation dialog
int choice = [Link](null, "Do you want to continue?", "Confirm",
JOptionPane.YES_NO_OPTION);
// Show results based on user input
if (choice == JOptionPane.YES_OPTION) {
[Link](null, "Hello, " + name + "! You chose to continue.");
} else {
[Link](null, "Goodbye, " + name + "!");
}
[Link](0); // Close application
}
}
How to Run:
1. Save the file as [Link]
2. Compile: javac [Link]
3. Run: java DialogBoxDemo
PROGRAM 14
Aim: To write a java program to implement flow layout and border layout
Program:
import [Link].*;
import [Link].*;
public class LayoutDemo extends JFrame {
public LayoutDemo() {
setTitle("FlowLayout and BorderLayout Demo");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 1)); // Two rows, one column
// Panel with FlowLayout
JPanel flowPanel = new JPanel();
[Link](new FlowLayout());
[Link]([Link]("FlowLayout Panel"));
// Add buttons to flowPanel
for (int i = 1; i <= 5; i++) {
[Link](new JButton("Button " + i));
}
// Panel with BorderLayout
JPanel borderPanel = new JPanel();
[Link](new BorderLayout(5, 5));
[Link]([Link]("BorderLayout Panel"));
// Add buttons to borderPanel regions
[Link](new JButton("North"), [Link]);
[Link](new JButton("South"), [Link]);
[Link](new JButton("East"), [Link]);
[Link](new JButton("West"), [Link]);
[Link](new JButton("Center"), [Link]);
// Add both panels to frame
add(flowPanel);
add(borderPanel);
setVisible(true);
}
public static void main(String[] args) {
new LayoutDemo();
}
}
How to run:
1. Save as [Link]
2. Compile: javac [Link]
3. Run: java LayoutDemo
PROGRAM 15
Aim: To write a java program to create frame that display the student information
Program ;
import [Link].*;
import [Link].*;
public class StudentInfoFrame extends JFrame {
public StudentInfoFrame() {
// Set title and size
setTitle("Student Information");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 1, 10, 10)); // 5 rows, 1 column, with spacing
// Create labels for student info
JLabel headingLabel = new JLabel("Student Details", [Link]);
[Link](new Font("Arial", [Link], 20));
JLabel nameLabel = new JLabel("Name: Alice Johnson");
JLabel rollLabel = new JLabel("Roll No: 20250123");
JLabel deptLabel = new JLabel("Department: Computer Science");
JLabel yearLabel = new JLabel("Year: 3rd Year");
// Add labels to the frame
add(headingLabel);
add(nameLabel);
add(rollLabel);
add(deptLabel);
add(yearLabel);
}
public static void main(String[] args) {
// Create and show the frame
StudentInfoFrame frame = new StudentInfoFrame();
[Link](true);
}
}
How to Run:
1. Save as: [Link]
2. Compile: javac [Link]
3. Run: java StudentInfoFrame
-------THE END-------