Que No1.
Creating a simple program in java to print “Hello World”;
public class HelloWorld
public static void main(String[] args)
// Print "Hello World" to the console
System.out.println("Hello World");
Output-
Hello World
Que No 2. Implementing basic control structure such as if else, switch and loops.
A) Implementing if else control structure.
import java.util.Scanner;
public class AgeCheck
{
public static void main(String[] args)
{
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Ask the user for their age
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Using if-else control structure to check age
if (age >= 18)
{
System.out.println("Your age is above 18.");
}
else
{
System.out.println("You are a minor.");
}
// Close the scanner
scanner.close();
}
}
Output –
Enter your age: 20
Your age is above 18.
B) Implementing basic control structure such as switch Case
import java.util.Scanner;
public class WeekDay
{
public static void main(String[] args)
{
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Ask the user to enter a number between 1 and 7
System.out.print("Enter a number between 1 and 7: ");
int dayNumber = scanner.nextInt();
// Using switch-case to print the corresponding day of the week
switch (dayNumber)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid number! Please enter a number
between 1 and 7.");
}
scanner.close();
}
}
Output—
Enter a number between 1 and 7: 3
Wednesday
Enter a number between 1 and 7: 8
Invalid number! Please enter a number between 1 and 7.
C) Implementing basic control structure such as loops.
public class ForLoop
public static void main(String[] args)
// Using a for loop to print numbers from 1 to 5
for (int i = 1; i <= 5; i++)
System.out.println(i);
Output—
5
Que No 3. Creating and using arrays in Java.
import java.util.Scanner;
public class ArrayExample
public static void main(String[] args)
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Ask the user for the size of the array
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt(); // Read the size of the array
int[] numbers = new int[n]; // Declare an array of size n
// Taking input from the user
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++)
System.out.print("Element " + (i + 1) + ": ");
numbers[i] = scanner.nextInt(); // Assign input to the array
// Printing the elements of the array
System.out.println("\nThe elements in the array are:");
for (int i = 0; i < n; i++)
System.out.println("Element at index " + i + ": " + numbers[i]);
// Close the scanner
scanner.close();
}
}
Enter the number of elements in the array: 5
Enter 5 integers:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
The elements in the array are:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Que No 4 Implementation of Inheritance in Java
public class InheritanceExample
{
// Superclass: Person
public static class Person
{
// Fields of the class
String name;
int age;
// Constructor to initialize name and age
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
// Method to display details of a person
public void displayInfo()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
// Subclass: Student extends Person
public static class Student extends Person
{
// Additional field specific to the Student class
String schoolName;
public Student(String name, int age, String schoolName) // Constructor
{
// Calling the superclass constructor to set name and age
super(name, age);
this.schoolName = schoolName;
}
// Overriding the displayInfo method to include school details
@Override
public void displayInfo()
{
super.displayInfo(); // Call the superclass method
System.out.println("School: " + schoolName);
}
public void study() // Additional method specific to the Student class
{
System.out.println(name + " is studying.");
}
}
public static void main(String[] args)
Person person = new Person("John", 30);
System.out.println("Person Information:");
person.displayInfo(); // Outputs: Name, Age
System.out.println("\n------------------------\n");
Student student = new Student("Alice", 18, "Greenwood High School");
System.out.println("Student Information:");
student.displayInfo(); // Outputs: Name, Age, School
// Call the study method specific to Student
student.study(); // Outputs: Alice is studying.
System.out.println("\n------------------------\n");
Person anotherPerson = new Student("Bob", 20, "Riverdale College");
System.out.println("Another Person Information (treated as Student):");
anotherPerson.displayInfo(); // Outputs: Name, Age, School
}
Output-
Person Information:
Name: John
Age: 30
------------------------
Student Information:
Name: Alice
Age: 18
School: Greenwood High School
Alice is studying.
------------------------
Another Person Information (treated as Student):
Name: Bob
Age: 20
School: Riverdale College
Que No 5 Overriding methods in java.
public class MethodOverridingExample
{
// Superclass: Animal
public static class Animal
{
// Method in the superclass
public void sound()
{
System.out.println("Animal makes a sound");
}
}
// Subclass: Dog extends Animal
public static class Dog extends Animal
{
// Overriding the sound method in the Dog class
@Override
public void sound()
{
System.out.println("Dog barks");
}
}
// Subclass: Cat extends Animal
public static class Cat extends Animal
{
// Overriding the sound method in the Cat class
@Override
public void sound()
{
System.out.println("Cat meows");
}
}
public static void main(String[] args)
// Creating objects of Animal, Dog, and Cat
Animal animal = new Animal();
Dog dog = new Dog();
Cat cat = new Cat();
// Calling the sound method
System.out.println("Animal:");
animal.sound(); // Output: Animal makes a sound
System.out.println("\nDog:");
dog.sound(); // Output: Dog barks
System.out.println("\nCat:");
cat.sound(); // Output: Cat meows
// Demonstrating polymorphism: Upcasting
Animal myAnimal = new Dog();
System.out.println("\nPolymorphism - Animal as Dog:");
myAnimal.sound(); // Output: Dog barks (The Dog's sound method is called)
myAnimal = new Cat();
System.out.println("\nPolymorphism - Animal as Cat:");
myAnimal.sound(); // Output: Cat meows (The Cat's sound method is called)
Output-
Animal:
Animal makes a sound
Dog:
Dog barks
Cat:
Cat meows
Polymorphism - Animal as Dog:
Dog barks
Polymorphism - Animal as Cat:
Cat meows
Que No 7 Implementing Exception handling in Java with try catch throw and finally.
public class ExceptionHandlingExample
{
public static void main(String[] args)
{
try {
// Example 1: ArithmeticException (Division by zero)
int result = 10 / 0; // This will throw ArithmeticException
System.out.println("Result: " + result);
}
catch (ArithmeticException e) // Handling ArithmeticException
{
System.out.println("Error: Division by zero is not allowed!");
}
try {
// Example 2: ArrayIndexOutOfBoundsException
int[] numbers = {1, 2, 3};
System.out.println("Element at index 5: " + numbers[5]); // This will
throw ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e)
{
// Handling ArrayIndexOutOfBoundsException
System.out.println("Error: Array index is out of bounds!");
}
// Finally block (this always gets executed)
finally
{
System.out.println("Finally block is executed.");
}
// Example 3: Using throw keyword to throw a custom exception
try {
validateAge(15); // This will throw an exception
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
// Custom method to throw an exception if age is less than 18
public static void validateAge(int age) throws Exception
{
if (age < 18)
{
throw new Exception("Age must be at least 18!");
} else
{
System.out.println("Age is valid.");
}
}
}
Output
Error: Division by zero is not allowed!
Error: Array index is out of bounds!
Finally block is executed.
Age must be at least 18!
Que No 8 Creating and using interface in Java
// Defining an interface
interface Animal
{
// Abstract method (no body)
void sound();
// Default method (introduced in Java 8)
default void sleep()
{
System.out.println("This animal is sleeping.");
}
}
// Implementing the interface in a class
class Dog implements Animal
{
@Override
public void sound()
{
System.out.println("Dog barks");
}
}
class Cat implements Animal
{
@Override
public void sound()
{
System.out.println("Cat meows");
}
}
Output—
Dog's sound:
Dog barks
Cat's sound:
Cat meows
Dog sleep:
This animal is sleeping.
Cat sleep:
This animal is sleeping.
Que No 9 String operations in java concat , substring , length.
public class StringOperations
{
public static void main(String[] args)
{
// Concatenation Example
String str1 = "Hello";
String str2 = " World";
String concatenated = str1.concat(str2); // Using concat() method
// Output: Hello World
System.out.println("Concatenated String: " + concatenated);
// Substring Example
String original = "Java Programming";
// Extract substring from index 5 to the end
String substring1 = original.substring(5);
// Output: Programming
System.out.println("Substring from index 5: " + substring1);
// Extract substring from index 0 to 4 (5th character)
String substring2 = original.substring(0, 4);
System.out.println("Substring from index 0 to 4: " + substring2);
// Length Example
String str = "Hello World!";
int length = str.length();
System.out.println("Length of the string: " + length);
}
}
Output—
Concatenated String: Hello World
Substring from index 5: Programming
Substring from index 0 to 4: Java
Length of the string: 13
Que No 10 Creating and using interface in Java.
interface Animal
{
void sound();
default void sleep()
{
System.out.println("Animal is sleeping");
}
}
interface Pet
{
void play();
}
class Dog implements Animal, Pet
{
public void sound()
{
System.out.println("Woof");
}
public void play()
{
System.out.println("Dog is playing");
}
// override the default method
public void sleep()
{
System.out.println("Dog is sleeping");
}
}
public class Main
{
public static void main(String[] args)
{
Dog myDog = new Dog();
myDog.sound(); // Outputs: Woof
myDog.play(); // Outputs: Dog is playing
myDog.sleep(); // Outputs: Dog is sleeping
}
}
Output-
Woof
Dog is playing
Dog is sleeping
Que No 11 Implement multi-threading Program in Java.
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread
{
public void run()
{
try {
// Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId()+ " is running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Output-
Thread 13 is running
Thread 12 is running
Thread 14 is running
Thread 15 is running
Thread 16 is running
Thread 17 is running
Thread 18 is running
Thread 19 is running
Que no 12 Implementing Thread-Synchronization in Java.
class Counter
{
private int count = 0;
public void increment()
{
count++;
}
public int getCount()
{
return count;
}
}
class ThreadDemo extends Thread
{
Counter counter;
ThreadDemo(Counter counter)
{
this.counter = counter;
}
public void run()
{
for (int i = 0; i < 1000; i++)
{
counter.increment();
}
}
}
public class Main
{
public static void main(String[] args)
{
Counter counter = new Counter();
ThreadDemo t1 = new ThreadDemo(counter);
ThreadDemo t2 = new ThreadDemo(counter);
t1.start();
t2.start();
try
{
t1.join();
t2.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Final count: " + counter.getCount());
}
}
Output—
Final count: 2000
Que no 13 Creating and using constructor method in java
class Person
{
String name;
int age;
// Default constructor
public Person()
{
// Initializing default values
name = "Unknown";
age = 0;
}
public void display()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main
{
public static void main(String[] args)
{
// Creating an object using the default constructor
Person person = new Person();
person.display();
}
}
Output-
Name: Unknown
Age: 0
Que No 14 Program to implement string and string buffer class in java.
A) Using String Class-
public class StringExample
{
public static void main(String[] args)
{
// Creating a String object
String str1 = "Hello, ";
String str2 = "World!";
// Concatenating strings (creating a new String object)
String result = str1 + str2;
System.out.println("Concatenated String: " + result);
// Comparing two strings
String str3 = "Hello, World!";
if (result.equals(str3))
{
System.out.println("The strings are equal.");
}
else
{
System.out.println("The strings are not equal.");
}
// Finding the length of the string
System.out.println("Length of result string: " + result.length());
// Converting string to uppercase
System.out.println("Uppercase: " + result.toUpperCase());
// Extracting a substring
System.out.println("Substring (7 to 12): " + result.substring(7, 12));
// Finding the index of a character
System.out.println("Index of 'W': " + result.indexOf('W'));
}
}
Output—
Concatenated String: Hello, World!
The strings are equal.
Length of result string: 13
Uppercase: HELLO, WORLD!
Substring (7 to 12): World
Index of 'W': 7
B) Using String Buffer class.
public class StringBufferExample
{
public static void main(String[] args)
{
// Creating a StringBuffer object
StringBuffer sb = new StringBuffer("Hello, ");
// Appending another string (modifies the same object)
sb.append("World!");
System.out.println("Appended String: " + sb);
// Inserting a string at a specific index
sb.insert(7, "Beautiful ");
System.out.println("String after insert: " + sb);
// Reversing the string
sb.reverse();
System.out.println("Reversed String: " + sb);
// Reversing the string back to original
sb.reverse();
// Deleting a part of the string
sb.delete(7, 18); // Deletes characters from index 7 to 18
System.out.println("String after deletion: " + sb);
// Replacing a part of the string
sb.replace(7, 13, "Java");
System.out.println("String after replacement: " + sb);
// Finding the length of the string
System.out.println("Length of StringBuffer: " + sb.length());
}
}
Output—
Appended String: Hello, World!
String after insert: Hello, Beautiful World!
Reversed String: !dlroW lacifituaeB ,olleH
String after deletion: Hello, Java!
String after replacement: Hello, Java!
Length of StringBuffer: 13