Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

1 A java program to read an integer value through

Scanner class and find prime number within


given range.
Aim:
The aim of this program is to read an integer value from the user and find all prime
numbers within a given range.

Procedure:
1. Read an integer value from the user using the Scanner class.
2. Define a method to check if a number is prime.
3. Use a loop to generate numbers within the given range.
4. Check each number if it is prime using the method defined in step 2.
5. Print the prime numbers found.

Source Code:
import java.util.Scanner;

public class PrimeNumbers {


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

// Read the range from the user


System.out.println("Enter the range (start and end):");
int start = scanner.nextInt();
int end = scanner.nextInt();

// Check for prime numbers within the range


for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.println(i + " is a prime number");
}
}
}

// Method to check if a number is prime


public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

Input:
Enter the range (start and end):

10 20

OUTPUT

10 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number

19 is a prime number

2.A java program to find largest among n


numbers.
Aim:
The aim of this program is to read n numbers from the user and find the
largest number among them.

Procedure:
1. Read the number of elements (n) from the user.
2. Create an array to store the n numbers.
3. Read the n numbers from the user and store them in the array.
4. Iterate through the array to find the largest number.
5. Print the largest number.

Source Code:
import java.util.Scanner;

public class LargestNumber {


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

// Read the number of elements


System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();

// Create an array to store the numbers


int[] numbers = new int[n];

// Read the numbers from the user


System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}

// Find the largest number


int largest = numbers[0];
for (int i = 1; i < n; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}

// Print the largest number


System.out.println("The largest number is: " + largest);
}
}
INPUT :
Enter the number of elements: 5
Enter the numbers:
10
5
20
15
8
OUTPUT;
The largest number is: 20

3.A java program to implement getter and setter


method.
Aim:
The aim of this program is to create a simple class with private instance variables and
implement getter and setter methods to access and modify these variables.

Procedure:
1. Create a class with private instance variables.
2. Implement getter methods to access these variables.
3. Implement setter methods to modify these variables.
4. Create an object of the class and demonstrate the use of getter and setter
methods.

Source Code:
public class Person {
private String name;
private int age;

// Getter for name


public String getName() {
return name;
}

// Setter for name


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

// Getter for age


public int getAge() {
return age;
}

// Setter for age


public void setAge(int age) {
this.age = age;
}

public static void main(String[] args) {


Person person = new Person();

// Using setter methods to set values


person.setName("Alice");
person.setAge(30);

// Using getter methods to retrieve values


System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
INPUT:
No specific input is required as the program demonstrates the use of getter and setter
methods with predefined values.

OUTPUT:

Name: Alice
Age: 30

4.A java program to create constructor of a class


and initialize values in it and later print them.
Aim:
The aim of this program is to create a class with a constructor that initializes values
and then print these values.

Procedure:
1. Create a class with a constructor.
2. Initialize values in the constructor.
3. Create an object of the class.
4. Print the values.

Source Code:
public class Person {
private String name;
private int age;

// Constructor to initialize values


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

// Method to print values


public void printDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

public static void main(String[] args) {


// Create an object with constructor
Person person = new Person("John", 25);

// Print the values


person.printDetails();
}

INPUT:

No specific input is required as the program demonstrates the use of a constructor to


initialize values.

Output:
Name: John
Age: 25

5.A java program to implement the concept of


method overloading and constructor overloading.
Aim:
The aim of this program is to create a class with multiple constructors and methods
that are overloaded, and then demonstrate their usage.

Procedure:
1. Create a class with multiple constructors that take different parameters.
2. Create multiple methods within the class that are overloaded with different
parameter lists.
3. Create objects of the class using the different constructors.
4. Call the overloaded methods with different arguments.
5. Print the results.

Source Code:
public class Calculator {
private int num1;
private int num2;
// Constructor overloading
public Calculator() {
num1 = 0;
num2 = 0;
}

public Calculator(int num1) {


this.num1 = num1;
num2 = 0;
}

public Calculator(int num1, int num2) {


this.num1 = num1;
this.num2 = num2;
}

// Method overloading
public int add() {
return num1 + num2;
}

public int add(int num) {


return num1 + num;
}

public int add(int num1, int num2) {


return num1 + num2;
}

public static void main(String[] args) {


// Using different constructors
Calculator calc1 = new Calculator();
Calculator calc2 = new Calculator(10);
Calculator calc3 = new Calculator(5, 10);

// Using overloaded methods


System.out.println("calc1.add(): " + calc1.add());
System.out.println("calc2.add(20): " + calc2.add(20));
System.out.println("calc3.add(2, 3): " + calc3.add(2, 3));
}
}
INPUT:
No specific input is required as the program demonstrates the use of constructor and
method overloading.

OUTPUT:
calc1.add(): 0
calc2.add(20): 30
calc3.add(2, 3): 7

6.Create a class Shape and override area () method to


calculate area of rectangle, square and circle.
Aim:
The aim of this program is to create a Shape class with an abstract area() method
and override it in subclasses to calculate the area of different shapes.

Procedure:
1. Create a Shape class with an abstract area() method.
2. Create subclasses for rectangle, square, and circle.
3. Override the area() method in each subclass to calculate the area of the
respective shape.
4. Create objects of the subclasses and call the area() method to calculate their
areas.

Source Code:
// Abstract Shape class
abstract class Shape {
abstract double area();
}

// Rectangle class
class Rectangle extends Shape {
private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double area() {
return length * width;
}
}

// Square class
class Square extends Shape {
private double side;

public Square(double side) {


this.side = side;
}

@Override
public double area() {
return side * side;
}
}

// Circle class
class Circle extends Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

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

public class Main {


public static void main(String[] args) {
// Create objects of the subclasses
Rectangle rectangle = new Rectangle(5, 3);
Square square = new Square(4);
Circle circle = new Circle(2);

// Calculate and print the areas


System.out.println("Rectangle area: " + rectangle.area());
System.out.println("Square area: " + square.area());
System.out.println("Circle area: " + circle.area());
}
}
OUTPUT:
Rectangle area: 15.0
Square area: 16.0
Circle area: 12.566370614359172

7.A java program to implement the concept of


abstract classes and interface.
Aim:
The aim of this program is to create an abstract class and an interface, and
demonstrate their usage in a program.

Procedure:
1. Create an abstract class with abstract and non-abstract methods.
2. Create an interface with abstract methods.
3. Create a concrete class that extends the abstract class and implements the
interface.
4. Create an object of the concrete class and call the methods.

Source Code:
// Abstract class
abstract class Animal {
public abstract void makeSound();

public void eat() {


System.out.println("The animal is eating.");
}
}

// Interface
interface Flyable {
void fly();
}

// Concrete class
class Bird extends Animal implements Flyable {
@Override
public void makeSound() {
System.out.println("The bird chirps.");
}

@Override
public void fly() {
System.out.println("The bird is flying.");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the concrete class
Bird bird = new Bird();
// Call the methods
bird.makeSound();
bird.eat();
bird.fly();
}
}
OUTPUT:
The bird chirps.
The animal is eating.
The bird is flying.

8.A java code to implement the concept of simple


inheritance, multilevel inheritance, and hierarchical
inheritance.
Aim:
The aim of this program is to create a hierarchy of classes and demonstrate the
different types of inheritance.

Procedure:
1. Create a base class called Animal.
2. Create a derived class called Dog that inherits from Animal (simple inheritance).
3. Create another derived class called Poodle that inherits from Dog (multilevel
inheritance).
4. Create another derived class called Cat that also inherits
from Animal (hierarchical inheritance).
5. Create objects of the derived classes and call their methods.

Source Code:
// Base class
class Animal {
public void eat() {
System.out.println("The animal is eating.");
}
}

// Derived class (simple inheritance)


class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}

// Derived class (multilevel inheritance)


class Poodle extends Dog {
public void swim() {
System.out.println("The poodle is swimming.");
}
}

// Derived class (hierarchical inheritance)


class Cat extends Animal {
public void meow() {
System.out.println("The cat meows.");
}
}

public class Main {


public static void main(String[] args) {
// Simple inheritance
Dog dog = new Dog();
dog.eat();
dog.bark();

// Multilevel inheritance
Poodle poodle = new Poodle();
poodle.eat();
poodle.bark();
poodle.swim();

// Hierarchical inheritance
Cat cat = new Cat();
cat.eat();
cat.meow();
}
}

Output:
The animal is eating.
The dog barks.
The animal is eating.
The dog barks.
The poodle is swimming.
The animal is eating.
The cat meows.
9.A java program to implement multiple inheritances
using interface.
Aim:
The aim of this program is to show how multiple inheritance can be achieved in Java
using interfaces.

Procedure:
1. Create multiple interfaces with different methods.
2. Create a class that implements these interfaces.
3. Implement the methods defined in the interfaces in the class.
4. Create an object of the class and call the methods.

Source Code:
// Interface 1
interface Swim {
void swim();
}

// Interface 2
interface Fly {
void fly();
}

// Class implementing multiple interfaces


class Bird implements Swim, Fly {
@Override
public void swim() {
System.out.println("The bird is swimming.");
}

@Override
public void fly() {
System.out.println("The bird is flying.");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the class
Bird bird = new Bird();
// Call the methods
bird.swim();
bird.fly();
}
}

Output:
The bird is swimming.
The bird is flying.

10.A java programs for Exception handling using try,


catch, throw, throws and finally.
Aim:
The aim of this program is to show how to handle exceptions using various
exception handling constructs in Java.

Procedure:
1. Create a method that throws an exception.
2. Use try-catch blocks to handle the exception.
3. Use throw to explicitly throw an exception.
4. Use throws to declare that a method can throw an exception.
5. Use finally to execute code regardless of whether an exception occurs or
not.

Source Code:
import java.util.Scanner;

public class ExceptionHandling {


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

try {
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int result = divide(num);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("General exception occurred.");
} finally {
System.out.println("Finally block executed.");
}
}

public static int divide(int num) throws ArithmeticException {


if (num == 0) {
throw new ArithmeticException("Cannot divide by zero.");
}
return 100 / num;
}
}

Input:
Enter a number: 0

Output:
Error: Cannot divide by zero.
Finally block executed.

11.A java program to implement the usage of


customized exceptions.
Aim:
The aim of this program is to create a custom exception and use it in a program.

Procedure:
1. Create a custom exception class that extends the Exception class.
2. Create a method that can throw the custom exception.
3. Use a try-catch block to handle the custom exception.
4. Demonstrate the usage of the custom exception.

Source Code:
// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomException {
public static void main(String[] args) {
try {
checkAge(15);
checkAge(-5);
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static void checkAge(int age) throws InvalidAgeException {


if (age < 0) {
throw new InvalidAgeException("Age cannot be negative.");
} else if (age > 120) {
throw new InvalidAgeException("Age cannot be greater than 120.");
} else {
System.out.println("Age is valid: " + age);
}
}
}

Output:
Age is valid: 15
Error: Age cannot be negative.

12.Implement concept of multithreading in Java by


a)Extending Thread class
b)Implementing Runnable interface
Aim:
The aim of this program is to create and execute multiple threads using the two
different approaches and observe the output.

Procedure:
a) Extending the Thread class:
1. Create a class that extends the Thread class.
2. Override the run() method to define the task to be performed by the thread.
3. Create objects of the class and start the threads.
b) Implementing the Runnable interface:
1. Create a class that implements the Runnable interface.
2. Implement the run() method to define the task to be performed by the
thread.
3. Create a Thread object and pass the instance of the class that
implements Runnable.
4. Start the thread.

Source Code:
a) Extending the Thread class:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread " + Thread.currentThread().getId() + " is running.");
}
}

public class MultiThreadingExample {


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

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

b) Implementing the Runnable interface:


class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread " + Thread.currentThread().getId() + " is running.");
}
}

public class MultiThreadingExample {


public static void main(String[] args) {
Runnable runnable1 = new MyRunnable();
Runnable runnable2 = new MyRunnable();

Thread thread1 = new Thread(runnable1);


Thread thread2 = new Thread(runnable2);
thread1.start();
thread2.start();
}
}

Output:
The output may vary as the threads are executed concurrently, but it will generally
look similar to the following:
Thread 12 is running.
Thread 13 is running.
Thread 14 is running.
Thread 15 is running.

You might also like