JAVAPROGRAMS Practicalkhushi
JAVAPROGRAMS Practicalkhushi
Program no-1
WAP in java to print Hello word.
1
JAVA PROGRAMING
Program no-2
WAP in java to find the sum of two numbers using
Command Line Arguments.
try {
// Parse the command line arguments to integers
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
2
JAVA PROGRAMING
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please provide two valid
numbers.");
}
}
}
Result :
Program no-3
3
JAVA PROGRAMING
// Default constructor
public Rectangle() {
this.length = 0;
this.width = 0;
}
4
JAVA PROGRAMING
Program no-4
WAP in java to implement Method Overloading.
5
JAVA PROGRAMING
6
JAVA PROGRAMING
}
Result:
7
JAVA PROGRAMING
Program no-5
WAP in java to implement Method Overriding.
// Superclass
class Animal {
// Method to be overridden
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
// Overriding the makeSound method
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
// Another Subclass
class Cat extends Animal {
// Overriding the makeSound method
@Override
8
JAVA PROGRAMING
9
JAVA PROGRAMING
Program no-6
WAP in java to implement Static method, static class
and static Variables.
// Static variable
static int count = 0;
// Static method
static void displayCount() {
System.out.println("Count: " + count);
}
10
JAVA PROGRAMING
Program no-7
11
JAVA PROGRAMING
// Static variable
static int staticCount;
// Instance variable
int instanceCount;
// Static block
static {
staticCount = 10;
System.out.println("Static block executed. Static count: " +
staticCount);
}
// Instance block
{
instanceCount = 5;
System.out.println("Instance block executed. Instance count: " +
instanceCount);
}
// Constructor
12
JAVA PROGRAMING
public BlockDemo() {
System.out.println("Constructor executed.");
}
13
JAVA PROGRAMING
Program no-8
WAP in Java to implement Single Inheritance.
// Superclass
class Animal {
// Method of the superclass
void eat() {
System.out.println("This animal eats food.");
14
JAVA PROGRAMING
}
}
// Subclass
class Dog extends Animal {
// Method of the subclass
void bark() {
System.out.println("The dog barks.");
}
}
15
JAVA PROGRAMING
Program no-9
WAP in Java to implement Multilevel Inheritance.
// Base class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
16
JAVA PROGRAMING
// Derived class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Calling methods from the base class, derived class, and further
derived class
myPuppy.eat(); // Method inherited from Animal
myPuppy.bark(); // Method inherited from Dog
myPuppy.weep(); // Method of Puppy
}
}
Result:
17
JAVA PROGRAMING
Program no-10
WAP in Java to implement Hierarchical Inheritance.
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
18
JAVA PROGRAMING
}
}
// Subclass 1
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Subclass 2
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
19
JAVA PROGRAMING
20
JAVA PROGRAMING
Program no-11
WAP in java to show the use of Abstract Class.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void makeSound();
// Concrete method
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass 1
class Dog extends Animal {
// Implementation of the abstract method
void makeSound() {
System.out.println("The dog barks.");
}
}
// Subclass 2
class Cat extends Animal {
21
JAVA PROGRAMING
22
JAVA PROGRAMING
23
JAVA PROGRAMING
Program no-12
WAP in java to show the use of interface.
// Interface
interface Animal {
// Abstract method (does not have a body)
void makeSound();
// Default method
default void eat() {
System.out.println("This animal eats food.");
}
}
24
JAVA PROGRAMING
25
JAVA PROGRAMING
26
JAVA PROGRAMING
Program no-13
WAP in java to show the use of try catch and finally.
// Another example
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
} finally {
System.out.println("The 'try catch' block has finished
executing.");
}
}
} public class TryCatchFinallyDemo {
public static void main(String[] args) {
// Example of try, catch, and finally
27
JAVA PROGRAMING
try {
// Code that may throw an exception
int[] numbers = {1, 2, 3};
System.out.println("Element at index 3: " + numbers[3]);
} catch (ArrayIndexOutOfBoundsException e) {
// Code to handle the exception
System.out.println("Exception caught: Array index is out of
bounds.");
} finally {
// Code that will always execute
System.out.println("The 'try catch' block has finished
executing.");
}
// Another example
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
} finally {
System.out.println("The 'try catch' block has finished
executing.");
}
}
}
Result:
Program no-14
28
JAVA PROGRAMING
29
JAVA PROGRAMING
Or
30
JAVA PROGRAMING
Program no-15
WAP in java to show the use of nested try and catch.
public class NestedTryCatchDemo {
public static void main(String[] args) {
// Outer try block
try {
// Code that may throw exceptions
int[] numbers = {1, 2, 3};
System.out.println("Element at index 1: " + numbers[1]);
31
JAVA PROGRAMING
System.out.println("Outer catch:
ArrayIndexOutOfBoundsException caught - Array index is out of
bounds.");
} catch (Exception e) {
System.out.println("Outer catch: Exception caught - " + e);
} finally {
System.out.println("The outer 'try catch' block has finished
executing.");
}
}
}
Result:
Or
Program no-16
32
JAVA PROGRAMING
try {
checkAge(20); // This will not throw AgeException
} catch (AgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Result:
33
JAVA PROGRAMING
Program no-17
WAP in java Create multithreading using Thread Class
and show the use of important Methods of Thread class.
34
JAVA PROGRAMING
(getName(),setName(), getPriority(),
setPriority(),getID(), join()).
class MyThread extends Thread {
public MyThread(String name) {
super(name); // Set the thread name
}
@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + " - Count: " + i);
Thread.sleep(500); // Sleep for 500 milliseconds
}
} catch (InterruptedException e) {
System.out.println(getName() + " interrupted.");
}
}
}
public class MultithreadingDemo {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");
35
JAVA PROGRAMING
thread1.start();
thread2.start();
try {
// Main thread waits for thread1 and thread2 to finish
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
thread1.setName("Renamed-Thread-1");
36
JAVA PROGRAMING
37
JAVA PROGRAMING
Program no-18
WAP in java to create thread using Runnable interface
and show the use of printStacktrace(), toString(), and
getMessage() methods.
// Define a class that implements Runnable interface
class MyRunnable implements Runnable {
public void run() {
try {
// Simulate some work that might throw an exception
int result = 10 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
// Print stack trace using printStackTrace() method
e.printStackTrace();
38
JAVA PROGRAMING
39
JAVA PROGRAMING
Program no-19
Write a program in java to create a String ans show the
use of equals() and ==.
public class StringComparisonExample {
public static void main(String[] args) {
// Creating two String objects
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
40
JAVA PROGRAMING
s1 = s1 + " World";
// Check again
System.out.println("\nAfter modification:");
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);
System.out.println("s3: " + s3);
System.out.println("s1 == s2: " + (s1 == s2)); // false (references
are different after modification)
System.out.println("s1.equals(s2): " + s1.equals(s2)); // false
(contents are different after modification)
}
}
Result:
Program no-20
41
JAVA PROGRAMING
42
JAVA PROGRAMING
Program no-21
Write a program in java to show the use of default and static methods.
// Define an interface with default and static methods
interface MyInterface {
// Abstract method (public and abstract by default)
void abstractMethod();
43
JAVA PROGRAMING
44
JAVA PROGRAMING
Program no-22
Write a program in java to show the use of Lambda of
single argument, no argument and two arguments.
// Functional interface with single abstract method (SAM)
interface SingleArgument {
void printMessage(String message);
}
45
JAVA PROGRAMING
46
JAVA PROGRAMING
Program no-23
Write a program in java to show the use of method
reference.
import java.util.ArrayList;
import java.util.List;
47
JAVA PROGRAMING
Program no-24
48
JAVA PROGRAMING
Program no-25
49
JAVA PROGRAMING
// Create an ArrayList
List<String> arrayList = new ArrayList<>(linkedList); //
Copying LinkedList to ArrayList
50
JAVA PROGRAMING
51
JAVA PROGRAMING
Program no-26
Write a program in java to input a paragraph and find
the occurrence of each unique words.
import java.util.*;
52
JAVA PROGRAMING
} else {
wordCountMap.put(word, 1);
}
}
}
53
JAVA PROGRAMING
Program no-27
Write a program in java to create a Employee class and
sort the object of this class using Comparable.
// Employee class implementing Comparable interface
class Employee implements Comparable<Employee> {
private int id;
private String name;
private int age;
private double salary;
// Constructor
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
// Getter methods
public int getId() {
return id;
}
54
JAVA PROGRAMING
55
JAVA PROGRAMING
56
JAVA PROGRAMING
57
JAVA PROGRAMING
Program no-28
Write a program in java to create a Employee class and
sort the object of this class using Comparator of many
field.
public class Employee {
private String name;
private int id;
private double salary;
// Constructor
public Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
// Getters
public String getName() {
return name;
}
58
JAVA PROGRAMING
59
JAVA PROGRAMING
60
JAVA PROGRAMING
}
// Sort the list using the comparator
Collections.sort(employees,
EmployeeComparators.BY_SALARY_NAME_ID);
// Print sorted list
System.out.println("\nSorted list (by salary, then name, then
ID):");
for (Employee emp : employees) {
System.out.println(emp);
}
}
}
Result:
Program no-29
Write a program in java to implement Set interface.
61
JAVA PROGRAMING
Using hashset
import java.util.HashSet;
import java.util.Set;
// Remove an element
hashSet.remove("Banana");
62
JAVA PROGRAMING
63
JAVA PROGRAMING
// Remove an element
linkedHashSet.remove("Banana");
System.out.println("LinkedHashSet after removing 'Banana': " +
linkedHashSet);
64
JAVA PROGRAMING
}
}
Result:
Using treeset:
import java.util.Set;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// Create a TreeSet
Set<String> treeSet = new TreeSet<>();
// Add elements to the TreeSet
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Orange");
treeSet.add("Apple"); // Duplicate element, will not be added
// Print the TreeSet
System.out.println("TreeSet: " + treeSet);
// Check if an element exists
65
JAVA PROGRAMING
Program no-30
Write a program in java to implement HashMap and
TreeMap.
import java.util.HashMap;
import java.util.Map;
66
JAVA PROGRAMING
import java.util.TreeMap;
// Accessing an element
System.out.println("\nValue for 'Banana': " +
hashMap.get("Banana"));
// Removing an element
67
JAVA PROGRAMING
hashMap.remove("Orange");
System.out.println("\nHashMap after removing 'Orange':");
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Using TreeMap
Map<String, Integer> treeMap = new TreeMap<>();
// Accessing an element
System.out.println("\nValue for 'Banana': " +
treeMap.get("Banana"));
68
JAVA PROGRAMING
// Removing an element
treeMap.remove("Orange");
System.out.println("\nTreeMap after removing 'Orange':");
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Result for hashmap:
69
JAVA PROGRAMING
70
JAVA PROGRAMING
71
JAVA PROGRAMING
72
JAVA PROGRAMING
73