Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Java Programs Final

Uploaded by

rajora.rohan02
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Java Programs Final

Uploaded by

rajora.rohan02
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Java Programs

1. Program in Java to design simple calculator for (+, -, *, and /) using switch
case.
Ans.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = input.nextDouble();
System.out.print("Enter second number: ");
double num2 = input.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = input.next().charAt(0);
double result;

switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num2 != 0 ? num1 / num2 : Double.NaN;
break;
default:
System.out.println("Invalid operator");
return;
}
System.out.println("Result: " + result);
}
}

2. Program in Java to design accounts class and two functions withdraw() and
deposit ().
Ans.
public class Account {
private double balance;
public Account(double initialBalance) {
balance = initialBalance > 0 ? initialBalance : 0;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Deposit amount must be positive");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrew: " + amount);
} else {
System.out.println("Insufficient balance or invalid amount");
}
}
public void displayBalance() {
System.out.println("Current Balance: " + balance);
}
public static void main(String[] args) {
Account account = new Account(500);
account.displayBalance();
account.deposit(200);
account.displayBalance();
account.withdraw(100);
account.displayBalance();
}
}
3. Program in Java to search a particular element in a one dimensional array.
Ans.
import java.util.Scanner;

public class ArraySearch {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] array = {10, 20, 30, 40, 50, 60};
System.out.print("Enter element to search: ");
int searchElement = input.nextInt();
boolean found = false;

for (int i = 0; i < array.length; i++) {


if (array[i] == searchElement) {
System.out.println("Element found at index: " + i);
found = true;
break;
}
}
if (!found) {
System.out.println("Element not found in the array");
}
}
}
4. Program in Java to the concept of polymorphism by designing functions to
sum different type of numbers.
Ans.
public class SumNumbers {
public int sum(int a, int b) {
return a + b;
}

public double sum(double a, double b) {


return a + b;
}
public int sum(int[] numbers) {
int total = 0;
for (int number : numbers) {
total += number;
}
return total;
}
public static void main(String[] args) {
SumNumbers calculator = new SumNumbers();

System.out.println("Sum of two integers: " + calculator.sum(5, 10));


System.out.println("Sum of two doubles: " + calculator.sum(5.5, 10.2));
System.out.println("Sum of an array: " + calculator.sum(new int[]{1, 2, 3, 4,
5}));
}
}
5. Program to show the concept of method overriding in Java.
Ans.
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}

}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}

}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Cat meows");
}

}
public class MethodOverridingExample {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();

myAnimal.sound();
myDog.sound();
myCat.sound();
}
}

6. Program in Java that import the user define package and access the
Member variable of classes that Contained by Package.
Ans.
Step 1: Create the Package and Class
1. Create a folder named mypackage.
2. Inside this folder, create a file called Person.java.
Code:
package mypackage;

public class Person {


public String name;
public int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

Step 2: Write the Main Program


Code:
import mypackage.Person;

public class Main {


public static void main(String[] args) {
Person person = new Person("Alice", 25);
System.out.println("Accessing member variables:");
System.out.println("Name: " + person.name);
System.out.println("Age: " + person.age);
System.out.println("Calling method to display info:");
person.displayInfo();
}
}
7. Program in Java to handle the Exception using try and multiple catch block.
Ans.
import java.util.Scanner;

public class ExceptionHandlingExample {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = input.nextInt();

System.out.print("Enter a divisor: ");


int divisor = input.nextInt();

int result = number / divisor;


System.out.println("Result: " + result);

int[] array = {1, 2, 3};


System.out.println("Accessing element at index 5: " + array[5]);
}
catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds.");
}
catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}
8. Program in Java demonstrating text I/O and binary I/O.
Ans.
import java.io.*;

public class TextAndBinaryIOExample {


public static void main(String[] args) {
textIOExample();
binaryIOExample();
}

public static void textIOExample() {


try {
FileWriter textWriter = new FileWriter("example.txt");
textWriter.write("Hello, this is a text file.\n");
textWriter.write("This is the second line.");
textWriter.close();

FileReader textReader = new FileReader("example.txt");


BufferedReader bufferedReader = new BufferedReader(textReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
System.out.println("Text I/O Error: " + e.getMessage());
}
}

public static void binaryIOExample() {


try {
FileOutputStream binaryWriter = new FileOutputStream("example.dat");
DataOutputStream dataOutput = new DataOutputStream(binaryWriter);
dataOutput.writeInt(123);
dataOutput.writeDouble(456.78);
dataOutput.writeUTF("Hello in binary format");
dataOutput.close();

FileInputStream binaryReader = new FileInputStream("example.dat");


DataInputStream dataInput = new DataInputStream(binaryReader);
System.out.println(dataInput.readInt());
System.out.println(dataInput.readDouble());
System.out.println(dataInput.readUTF());
dataInput.close();
} catch (IOException e) {
System.out.println("Binary I/O Error: " + e.getMessage());
}
}
}

9. Program in Java using Multi threading.


Ans.
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
}
}

public class MultiThreadingExample {


public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();

thread1.start();
thread2.start();
}
}

10. Program in Java demonstrating Applet.


Ans.
import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorldApplet extends Applet {


public void paint(Graphics g) {
g.drawString("Hello, World!", 20, 20);
}
}

HTML to run the applet:


<html>
<body>
<applet code="HelloWorldApplet.class" width="300"
height="200"></applet>
</body>
</html>

You might also like