20EC5S12` JAVA PROGRAMMING
(Skill Oriented Course)
List of Experiments:
Exercise - 1 (Basics)
a) Write a JAVA program to display default value of all primitive data type of JAVA
b) Write a java program that display the roots of a quadratic equation ax2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.
Exercise - 2 (Operations, Expressions, Control-flow, Strings)
a) Write a JAVA program to search for an element in a given list of elements using binary
search mechanism.
b) Write a JAVA program to sort for an element in a given list of elements using bubble sort
c) Write a JAVA program to sort for an element in a given list of elements using merge sort.
d) Write a JAVA program using String Buffer to delete, remove character.
Exercise - 3 (Class, Objects)
Implement java programs using the concept of
a) Class mechanism. Create a class, methods and invoke them inside main method.
b) Constructor.
c) Constructor overloading.
d) Method overloading.
Exercise -4 (Inheritance)
Implement java programs using the concept of
a) Single Inheritance
b) Multilevel Inheritance
c) Abstract class
Exercise - 5 (Inheritance - Continued)
Implement java programs using the concept of
a)“super” keyword. b) Interfaces
Exercise – 6 (Runtime Polymorphism)
a) Write a JAVA program that implements Runtime polymorphism
Exercise – 7 (Exception)
Implement the programs by using the concepts of
a. Exception handling mechanism
b. Multiple catch clauses
c. Finally
d. Creating user defined exceptions
Exercise – 8 (Threads)
a) Write a JAVA program that creates threads by extending Thread class. First thread displays
“Good Morning” every 1 sec, the second thread displays “Hello” every 2 seconds and the
third display “Welcome” every 3 seconds,(Repeat the same by implementing Runnable)
b) Write a program illustrating isAlive and join ()
c) Write a Program illustrating Daemon Threads.
Exercise – 9 (Packages)
a) Create a user defined package and demonstrate different ways of importing packages
Exercise - 10 (Applet)
a) Write a JAVA program to paint like paint brush in applet.
b) Write a JAVA program to create different shapes and fill colors using Applet.
Exercise 1 (Basics)
a) Display default values of all primitive data types in Java:
public class DefaultValues {
public static void main(String[] args) {
byte byteDefault = 0;
short shortDefault = 0;
int intDefault = 0;
long longDefault = 0L;
float floatDefault = 0.0f;
double doubleDefault = 0.0;
char charDefault = '\u0000';
boolean booleanDefault = false;
System.out.println("Default values:");
System.out.println("byte: " + byteDefault);
System.out.println("short: " + shortDefault);
System.out.println("int: " + intDefault);
System.out.println("long: " + longDefault);
System.out.println("float: " + floatDefault);
System.out.println("double: " + doubleDefault);
System.out.println("char: " + charDefault);
System.out.println("boolean: " + booleanDefault);
}
}
b) Display roots of a quadratic equation and describe their nature:
import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the values of a, b, and c: ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Two distinct real roots: " + root1 + " and " + root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("One real root: " + root);
} else {
System.out.println("No real roots (complex roots).");
}
}
}
--------------------------------------------------------------------------------------------------------------
Exercise 2 (Operations, Expressions, Control-flow, Strings)
a) Search for an element in a list using binary search:
import java.util.Arrays;
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 6;
int result = Arrays.binarySearch(arr, target);
if (result >= 0) {
System.out.println("Element " + target + " found at index " + result);
} else {
System.out.println("Element " + target + " not found in the array.");
}
}
}
b) Sort a list of elements using bubble sort:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 9, 3, 6, 1};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("Sorted array using Bubble Sort:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
c) Sort a list of elements using merge sort (recursive):
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] arr = {5, 2, 9, 3, 6, 1};
mergeSort(arr, 0, arr.length - 1);
System.out.println("Sorted array using Merge Sort:");
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int middle = (left + right) / 2;
mergeSort(arr, left, middle);
mergeSort(arr, middle + 1, right);
merge(arr, left, middle, right);
}
}
public static void merge(int[] arr, int left, int middle, int right) {
int n1 = middle - left + 1;
int n2 = right - middle;
int[] L = Arrays.copyOfRange(arr, left, left + n1);
int[] R = Arrays.copyOfRange(arr, middle + 1, middle + 1 + n2);
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
}
d) Use StringBuffer to delete or remove characters:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("Hello, World!");
// Delete a character at a specific index
str.deleteCharAt(5); // Deletes ','
// Remove a range of characters
str.delete(0, 5); // Removes "Hello"
System.out.println(str); // Output: " World!"
}
}
----------------------------------------------------------------------------------------------------------------
Exercise 3 (Class, Objects)
a) Implement a Java program using the class mechanism:
public class MyClass {
public static void main(String[] args) {
MyObject myObj = new MyObject();
myObj.displayMessage();
}
}
class MyObject {
public void displayMessage() {
System.out.println("Hello from MyObject class!");
}
}
b) Implement a Java program using constructors:
public class ConstructorExample {
public static void main(String[] args) {
MyObject obj = new MyObject("Hello, Constructor!");
obj.displayMessage();
}
}
class MyObject {
private String message;
public MyObject(String msg) {
message = msg;
}
public void displayMessage() {
System.out.println(message);
}
}
c) Implement a Java program using constructor overloading:
public class ConstructorOverloadingExample {
public static void main(String[] args) {
MyObject obj1 = new MyObject();
MyObject obj2 = new MyObject("Hello, Constructor!");
obj1.displayMessage();
obj2.displayMessage();
}
}
class MyObject {
private String message;
// Default constructor
public MyObject() {
message = "Default Message";
}
// Parameterized constructor
public MyObject(String msg) {
message = msg;
}
public void displayMessage() {
System.out.println(message);
}
}
d) Implement a Java program using method overloading:
public class MethodOverloadingExample {
public static void main(String[] args) {
MyObject obj = new MyObject();
obj.displayMessage("Hello, Method Overloading!");
obj.displayMessage(42);
}
}
class MyObject {
public void displayMessage(String message) {
System.out.println("String message: " + message);
}
public void displayMessage(int number) {
System.out.println("Integer number: " + number);
}
}
---------------------------------------------------------------------------------------------------------------
Exercise 4 (Inheritance)
a) Implement a Java program using single inheritance:
class Parent {
void displayParent() {
System.out.println("This is the parent class.");
}
}
class Child extends Parent {
void displayChild() {
System.out.println("This is the child class.");
}
public static void main(String[] args) {
Child childObj = new Child();
childObj.displayParent();
childObj.displayChild();
}
}
b) Implement a Java program using multilevel inheritance:
class Grandparent {
void displayGrandparent() {
System.out.println("This is the grandparent class.");
}
}
class Parent extends Grandparent {
void displayParent() {
System.out.println("This is the parent class.");
}
}
class Child extends Parent {
void displayChild() {
System.out.println("This is the child class.");
}
public static void main(String[] args) {
Child childObj = new Child();
childObj.displayGrandparent();
childObj.displayParent();
childObj.displayChild();
}
}
c) Implement a Java program using an abstract class:
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a Circle");
}
}
class Square extends Shape {
void draw() {
System.out.println("Drawing a Square");
}
}
public class AbstractExample {
public static void main(String[] args) {
Shape circle = new Circle();
Shape square = new Square();
circle.draw();
square.draw();
}
}
----------------------------------------------------------------------------------------------------------------
Exercise 5 (Inheritance - Continued)
a) Implement a Java program using the "super" keyword:
class Parent {
String message = "Hello from Parent";
void display() {
System.out.println(message);
}
}
class Child extends Parent {
String message = "Hello from Child";
void display() {
super.display(); // Using "super" to call the parent class method
System.out.println(message);
}
public static void main(String[] args) {
Child childObj = new Child();
childObj.display();
}
}
b) Implement a Java program using interfaces:
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() {
System.out.println("Drawing a Circle");
}
}
class Rectangle implements Shape {
public void draw() {
System.out.println("Drawing a Rectangle");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();
circle.draw();
rectangle.draw();
}
}
----------------------------------------------------------------------------------------------------------------
Exercise 6 (Runtime Polymorphism)
a) Write a Java program that implements runtime polymorphism (method overriding):
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof! Woof!");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Meow!");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
dog.makeSound(); // Calls Dog's makeSound method
cat.makeSound(); // Calls Cat's makeSound method
}
}
----------------------------------------------------------------------------------------------------------------
Exercise 7 (Exception)
a) Implement a Java program using exception handling:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Attempt to divide by zero
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
b) Implement a Java program using multiple catch clauses:
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] arr = new int[5];
int result = arr[7]; // Accessing an out-of-bounds index
System.out.println("Result: " + result);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception: " + e.getMessage());
}
}
}
c) Implement a Java program using the "finally" block:
public class FinallyBlockExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Attempt to divide by zero
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
d) Create a user-defined exception:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class UserDefinedExceptionExample {
public static void main(String[] args) {
try {
int age = 17;
if (age < 18) {
throw new CustomException("Age is below 18.");
}
System.out.println("Age is valid.");
} catch (CustomException e) {
System.out.println("Custom Exception: " + e.getMessage());
}
}
}
-------------------------------------------------------------------------------------------------------------
Exercise 8 (Threads)
a) Create threads by extending the Thread class to display messages at different
intervals:
class DisplayThread extends Thread {
private String message;
private int interval;
public DisplayThread(String message, int interval) {
this.message = message;
this.interval = interval;
}
public void run() {
while (true) {
System.out.println(message);
try {
Thread.sleep(interval * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadExample {
public static void main(String[] args) {
DisplayThread thread1 = new DisplayThread("Good Morning", 1);
DisplayThread thread2 = new DisplayThread("Hello", 2);
DisplayThread thread3 = new DisplayThread("Welcome", 3);
thread1.start();
thread2.start();
thread3.start();
}
}
b) Write a program illustrating isAlive() and join():
public class ThreadJoinExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 is running.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread 2 is running.");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Both threads have completed their execution.");
}
}
c) Write a program illustrating Daemon Threads:
public class DaemonThreadExample {
public static void main(String[] args) {
Thread daemonThread = new Thread(() -> {
while (true) {
System.out.println("Daemon thread is running.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
daemonThread.setDaemon(true);
daemonThread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread exiting.");
}
}
------------------------------------------------------------------------------------------------------------
Exercise 9 (Packages)
a) Create a user-defined package and demonstrate different ways of importing
packages:
Create a package named myPackage with a class MyClass inside it:
package myPackage;
public class MyClass {
public void display() {
System.out.println("Hello from MyClass in myPackage.");
}
}
Import the package and use the class in another Java file:
import myPackage.MyClass;
public class PackageExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Another way to import the class using a wildcard import:
import myPackage.*;
public class PackageExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
----------------------------------------------------------------------------------------------------------------
Exercise 10 (Applet)
a) Write a Java program to paint like a paintbrush in an applet:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class PaintBrushApplet extends Applet {
int x, y;
public void init() {
x = -1;
y = -1;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
});
}
public void paint(Graphics g) {
if (x != -1 && y != -1) {
g.fillOval(x, y, 5, 5);
}
}
}
b) Write a Java program to create different shapes and fill colors using an applet:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class ShapesAndColorsApplet extends Applet {
public void paint(Graphics g) {
// Draw a red rectangle
g.setColor(Color.RED);
g.fillRect(20, 20, 80, 40);
// Draw a blue oval
g.setColor(Color.BLUE);
g.fillOval(120, 20, 80, 40);
// Draw a green rounded rectangle
g.setColor(Color.GREEN);
g.fillRoundRect(220, 20, 80, 40, 10, 10);
// Draw a yellow arc
g.setColor(Color.YELLOW);
g.fillArc(320, 20, 80, 40, 45, 180);
}
}
----------------------------------------------------------------------------------------------------------------