1.
Write a program in Java to perform arithmetic operations using
switch case.
import java.util.Scanner;
public class ArithmeticOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operator!");
return;
}
System.out.println("Result: " + result);
scanner.close();
}
}
2. Write a program in Java to create class Employee with methods
getdata() and putdata() and instantiate its object.
import java.util.Scanner;
class Employee {
private String name;
private int id;
public void getdata() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter employee name: ");
name = scanner.nextLine();
System.out.print("Enter employee ID: ");
id = scanner.nextInt();
}
public void putdata() {
System.out.println("Employee Name: " + name);
System.out.println("Employee ID: " + id);
}
}
public class Main {
public static void main(String[] args) {
Employee employee = new Employee();
employee.getdata();
employee.putdata();
}
}
3. Write a program for Factorial using Function.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("Factorial of " + number + " is: " +
factorial(number));
scanner.close();
}
static int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
}
Autoboxing and unboxing are features introduced in Java to automatically
convert between primitive types and their corresponding wrapper classes
(objects).
- **Autoboxing**: Autoboxing is the automatic conversion of a primitive type
to its corresponding wrapper class object. For example, when you assign a
primitive `int` value to an `Integer` reference, Java automatically converts
the `int` value to an `Integer` object. This conversion is done implicitly by
the compiler.
```java
int primitiveInt = 10;
Integer wrappedInt = primitiveInt; // Autoboxing
```
- **Unboxing**: Unboxing is the automatic conversion of a wrapper class
object to its corresponding primitive type. For example, when you assign an
`Integer` object to an `int` variable, Java automatically extracts the value
from the `Integer` object and assigns it to the `int` variable. This conversion
is done implicitly by the compiler.
```java
Integer wrappedInt = 20;
int primitiveInt = wrappedInt; // Unboxing
```
Autoboxing and unboxing were introduced in Java 5 to simplify code and
make it more readable by reducing the need for explicit conversions between
primitive types and wrapper classes. These features are particularly useful
when working with collections such as `ArrayList` and `Vector`, which
require objects rather than primitive types.
4. Write a program for Wrapper Class.(Autoboxing)
public class AutoboxingExample {
public static void main(String[] args) {
int primitiveInt = 10;
Integer wrappedInt = primitiveInt; // Autoboxing
System.out.println("Primitive int: " + primitiveInt);
System.out.println("Wrapped Integer: " + wrappedInt);
}
}
5. Write a program for Wrapper Class.(Unboxing)
public class UnboxingExample {
public static void main(String[] args) {
Integer wrappedInt = 20;
int primitiveInt = wrappedInt; // Unboxing
System.out.println("Wrapped Integer: " + wrappedInt);
System.out.println("Primitive int: " + primitiveInt);
}
}
6 Write a program for Parameterised Constructor
class Box {
double width;
double height;
double depth;
// Parameterized constructor
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// Method to calculate and return volume
double volume() {
return width * height * depth;
}
}
public class ParameterizedConstructor {
public static void main(String[] args) {
// Create box object using parameterized constructor
Box myBox = new Box(10, 20, 15);
// Display volume of the box
System.out.println("Volume of myBox is " + myBox.volume());
}
}
7 Write a program in Java to apply string methods : equals(),
compareTo(), charAt(), toUpperCase() over entered strings
from user
import java.util.Scanner;
public class StringMethodsExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = scanner.next();
System.out.print("Enter second string: ");
String str2 = scanner.next();
// equals()
System.out.println("Equality check using equals(): " +
str1.equals(str2));
// compareTo()
System.out.println("Comparison using compareTo(): " +
str1.compareTo(str2));
// charAt()
System.out.print("Character at index 0 of first string: " +
str1.charAt(0));
// toUpperCase()
System.out.println("Uppercase conversion of first string: " +
str1.toUpperCase());
scanner.close();
}
}
8 Write a program in Java to apply String methods :
equalsIgnoreCase(), compareTo(), indexOf(),
toLowerCase() over entered strings from user
import java.util.Scanner;
public class StringMethodsExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = scanner.next();
System.out.print("Enter second string: ");
String str2 = scanner.next();
// equalsIgnoreCase()
System.out.println("Equality check (case-insensitive) using
equalsIgnoreCase(): " + str1.equalsIgnoreCase(str2));
// compareTo()
System.out.println("Comparison using compareTo(): " +
str1.compareTo(str2));
// indexOf()
System.out.println("Index of 'a' in first string: " +
str1.indexOf('a'));
// toLowerCase()
System.out.println("Lowercase conversion of first string: "
+ str1.toLowerCase());
scanner.close();
}
}
9. Write a program in Java to implement a vector and add five elements
of type Integer, Character, Boolean, Long, Float into that vector. Also
display vector elements.
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
// Create a Vector
Vector vector = new Vector();
// Add elements of different types
Integer intValue = Integer.valueOf(10);
Character charValue = Character.valueOf('A');
Boolean boolValue = Boolean.valueOf(true);
Long longValue = Long.valueOf(10000000000L);
Float floatValue = Float.valueOf(3.14f);
vector.add(intValue); // Integer
vector.add(charValue); // Character
vector.add(boolValue); // Boolean
vector.add(longValue); // Long
vector.add(floatValue); // Float
// Display vector elements
System.out.println("Vector elements:");
for (int i = 0; i < vector.size(); i++) {
System.out.println(vector.get(i));
}
}
}
10. Write a program in Java to apply Vector methods : addElement(),
elementAt(), firstElement(), removeElementAt() over vector v.
import java.util.Vector;
public class VectorMethodsExample {
public static void main(String[] args) {
// Create a Vector
Vector v = new Vector();
// Add elements to the Vector using addElement() method
v.addElement(10);
v.addElement(20);
v.addElement(30);
v.addElement(40);
// Display the elements of the Vector
System.out.println("Vector elements:");
for (int i = 0; i < v.size(); i++) {
System.out.println(v.elementAt(i));
}
// Display the first element of the Vector using firstElement()
method
System.out.println("First element: " + v.firstElement());
// Remove an element at index 2 using removeElementAt()
method
v.removeElementAt(2);
// Display the elements of the Vector after removal
System.out.println("Vector elements after removal:");
for (int i = 0; i < v.size(); i++) {
System.out.println(v.elementAt(i));
}
}
}
11 Write a program in Java to implement single inheritance with
super class Student and sub class Marks.
class Student {
protected String name;
protected int rollNumber;
public Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
}
}
class Marks extends Student {
private int marks;
public Marks(String name, int rollNumber, int marks) {
super(name, rollNumber);
this.marks = marks;
}
public void displayMarks() {
display(); // Call display() method of superclass
System.out.println("Marks: " + marks);
}
}
public class Main {
public static void main(String[] args) {
Marks student1 = new Marks("John", 101, 85);
student1.displayMarks();
}
}
12 Write a program in Java to create package with class student.
Write another program to import created package(class and
methods).
Package file ;
package school;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
Java File where package is to be imported :
import school.Student;
public class Main {
public static void main(String[] args) {
// Create an object of Student class from the imported package
Student student = new Student("John", 20);
// Call the display() method of the Student class
student.display();
}
}
13 Write a program in Java to handle Arithmetic Exception.
import java.util.Scanner;
public class ArithmeticExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter denominator: ");
int denominator = scanner.nextInt();
// Division operation
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("Cannot divide by zero.");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close(); // Close scanner
}
}
}
14 Write a program in Java to throw user defined exception if
entered number is Negative.
import java.util.Scanner;
// Define a custom exception class for negative numbers
class NegativeNumberException extends Exception {
public NegativeNumberException() {
super("Negative numbers are not allowed.");
}
}
public class NegativeNumberDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Check if the entered number is negative
if (number < 0) {
throw new NegativeNumberException(); // Throw custom
exception
}
System.out.println("Entered number is: " + number);
} catch (NegativeNumberException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close(); // Close scanner
}
}
}
15 Write a program in Java to create two threads: one will print even
numbers and other odd number from 1 to 20.
public class EvenOddNumbers {
public static void main(String[] args) {
// Create two threads
Thread evenThread = new Thread(new EvenNumbers());
Thread oddThread = new Thread(new OddNumbers());
// Start both threads
evenThread.start();
oddThread.start();
}
}
class EvenNumbers implements Runnable {
public void run() {
for (int i = 2; i <= 20; i += 2) {
System.out.println("Even number: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class OddNumbers implements Runnable {
public void run() {
for (int i = 1; i <= 19; i += 2) {
System.out.println("Odd number: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
18 Write a program to copy contents of one File into another file.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) throws IOException {
String sourceFile ="sourceFile.txt";
String destFile="destFile.txt";
FileReader reader =null;
FileWriter writer =null;
reader = new FileReader(sourceFile);
writer= new FileWriter(destFile);
int ch;
while((ch= reader.read()) != -1){
writer.write((char)ch);
}
System.out.println("File Copied Successfully !!...");
if(reader != null)
reader.close();
if(writer != null)
writer.close();
}
}
19 Write a program in Java to create class Student with methods
getdata() and putdata() and instantiate its object.
import java.util.Scanner;
class Student {
private String name;
private int age;
// Method to get data from the user
public void getdata() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name: ");
name = scanner.nextLine();
System.out.print("Enter age: ");
age = scanner.nextInt();
}
// Method to display data
public void putdata() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Create an object of Student class
Student student = new Student();
// Call getdata() method to input data
System.out.println("Enter student details:");
student.getdata();
// Call putdata() method to display data
System.out.println("\nStudent details:");
student.putdata();
}
20 Write a program in Java to create two threads: one will print
numbers 1 to 20 and other reverse number from 20 to 1.
class StraighPrinter extends Thread{
public void run()
{
for(int i=1;i<=20;i++)
{
System.out.println("Straight : "+i);
}
}
}
class ReversePrinter extends Thread{
public void run()
{
for(int i=20;i>=1;i--)
{
System.out.println("Reversed : "+i);
}
}
}
public class TwoThreads {
public static void main(String[] args) {
StraighPrinter SP = new StraighPrinter();
ReversePrinter RP= new ReversePrinter();
SP.start();
RP.start();
}
}
22 Write a program in Java to implement a vector and add five elements
of type Integer, Character, Boolean, Long, Float into that vector. Also
display vector elements
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
// Create a Vector
Vector vector = new Vector();
// Add elements of different types
Integer intValue = Integer.valueOf(10);
Character charValue = Character.valueOf('A');
Boolean boolValue = Boolean.valueOf(true);
Long longValue = Long.valueOf(10000000000L);
Float floatValue = Float.valueOf(3.14f);
vector.add(intValue); // Integer
vector.add(charValue); // Character
vector.add(boolValue); // Boolean
vector.add(longValue); // Long
vector.add(floatValue); // Float
// Display vector elements
System.out.println("Vector elements:");
for (int i = 0; i < vector.size(); i++) {
System.out.println(vector.get(i));
}
}
}
23 Write a program to implement following interface with multiple
inheritance.
import java.util.Scanner;
class Student
{
int roll_no;
String name;
float total;
}
interface Marks
{
int sp_wt=5;
}
class Result extends Student implements Marks {
int m1,m2,m3;
void accept()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter Roll No of the Student : ");
roll_no = sc.nextInt();
sc.nextLine();
System.out.println("Enter Name of the Student : ");
name= sc.nextLine();
System.out.println("Enter marks in three subjects : ");
m1=sc.nextInt();
m2= sc.nextInt();
m3= sc.nextInt();
}
void display()
{
total=m1+m2+m3;
System.out.println("Name of the Student is : "+name);
System.out.println("Roll no of "+name+ " is "+roll_no);
System.out.println("Total Marks are : "+total);
System.out.println("Sp Wt = "+sp_wt);
}
}
public class TestInterface {
public static void main(String[] args) {
Result R = new Result();
R.accept();
R.display();
}
}
24 Write a Java program for implementation of implicit and explicit
type conversion.
public class TypeConversionExample {
public static void main(String[] args) {
// Implicit type conversion (Widening)
int intValue = 100;
long longValue = intValue; // Implicit conversion from int to long
float floatValue = longValue; // Implicit conversion from long to float
double doubleValue = floatValue; // Implicit conversion from float to double
System.out.println("Implicit Type Conversion (Widening):");
System.out.println("int value: " + intValue);
System.out.println("long value: " + longValue);
System.out.println("float value: " + floatValue);
System.out.println("double value: " + doubleValue);
// Explicit type conversion (Narrowing)
double doubleNumber = 123.456;
float floatNumber = (float) doubleNumber; // Explicit conversion from
double to float
long longNumber = (long) floatNumber; // Explicit conversion from float to
long
int intNumber = (int) longNumber; // Explicit conversion from long to int
System.out.println("\nExplicit Type Conversion (Narrowing):");
System.out.println("double value: " + doubleNumber);
System.out.println("float value: " + floatNumber);
System.out.println("long value: " + longNumber);
System.out.println("int value: " + intNumber);
}
}
25 Write a Java program to sort the array elements using arrays.
import java.util.Arrays;
import java.util.Scanner;
public class ImplementArrays {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Size of the Array : ");
int size= sc.nextInt();
int arr[] = new int[size];
System.out.println("Enter Array Elements : ");
for(int i=0;i<size;i++)
{
arr[i]= sc.nextInt();
}
System.out.print("Array Elements are : ");
for(int num : arr)
{
System.out.print(num+" ");
}
Arrays.sort(arr);
System.out.println();
System.out.print("Sorted Array is : ");
for(int num : arr)
{
System.out.print(num+" ");
}
}
}