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
1|Page
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.
2|Page
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;
[Link]("Default values:");
[Link]("byte: " + byteDefault);
[Link]("short: " + shortDefault);
[Link]("int: " + intDefault);
[Link]("long: " + longDefault);
[Link]("float: " + floatDefault);
[Link]("double: " + doubleDefault);
[Link]("char: " + charDefault);
[Link]("boolean: " + booleanDefault);
}
}
Output:
Default values:
byte: 0
short: 0
int: 0
long: 0
float: 0.0
double: 0.0
char:
boolean: false
3|Page
b) Display roots of a quadratic equation and describe their nature:
import [Link];
public class QuadraticEquation {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter the values of a, b, and c: ");
double a = [Link]();
double b = [Link]();
double c = [Link]();
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + [Link](discriminant)) / (2 * a);
double root2 = (-b - [Link](discriminant)) / (2 * a);
[Link]("Two distinct real roots: " + root1 + " and " + root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
[Link]("One real root: " + root);
} else {
[Link]("No real roots (complex roots).");
}
}
}
Output:
Enter the values of a, b, and c: 1 2 3
No real roots (complex roots).
--------------------------------------------------------------------------------------------------------------
4|Page
Exercise 2 (Operations, Expressions, Control-flow, Strings)
a) Search for an element in a list using binary search:
import [Link];
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 = [Link](arr, target);
if (result >= 0) {
[Link]("Element " + target + " found at index " + result);
} else {
[Link]("Element " + target + " not found in the array.");
}
}
}
Output:
Element 6 found at index 5
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 < [Link] - 1; i++) {
for (int j = 0; j < [Link] - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
[Link]("Sorted array using Bubble Sort:");
for (int num : arr) {
[Link](num + " ");
}
}
}
5|Page
Output:
Sorted array using Bubble Sort:
123569
c) Sort a list of elements using merge sort (recursive):
import [Link];
public class MergeSort {
public static void main(String[] args) {
int[] arr = {5, 2, 9, 3, 6, 1};
mergeSort(arr, 0, [Link] - 1);
[Link]("Sorted array using Merge Sort:");
for (int num : arr) {
[Link](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 = [Link](arr, left, left + n1);
int[] R = [Link](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];
6|Page
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
}
Output:
Sorted array using Merge Sort:
123569
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
[Link](5); // Deletes ','
// Remove a range of characters
[Link](0, 5); // Removes "Hello"
[Link](str); // Output: " World!"
}
}
Output:
World!
----------------------------------------------------------------------------------------------------------------
7|Page
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();
[Link]();
}
}
class MyObject {
public void displayMessage() {
[Link]("Hello from MyObject class!");
}
}
Output:
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!");
[Link]();
}
}
class MyObject {
private String message;
public MyObject(String msg) {
message = msg;
}
public void displayMessage() {
[Link](message);
}
}
Output:
Hello, Constructor
8|Page
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!");
[Link]();
[Link]();
}
}
class MyObject {
private String message;
// Default constructor
public MyObject() {
message = "Default Message";
}
// Parameterized constructor
public MyObject(String msg) {
message = msg;
}
public void displayMessage() {
[Link](message);
}
}
Output:
Default Message
Hello, Constructor!
d) Implement a Java program using method overloading:
public class MethodOverloadingExample {
public static void main(String[] args) {
MyObject obj = new MyObject();
[Link]("Hello, Method Overloading!");
[Link](42);
}
}
class MyObject {
public void displayMessage(String message) {
9|Page
[Link]("String message: " + message);
}
public void displayMessage(int number) {
[Link]("Integer number: " + number);
}
}
Output:
String message: Hello, Method Overloading! Integer number: 42
----------------------------------------------------------------------------------------------------------
Exercise 4 (Inheritance)
a) Implement a Java program using single inheritance:
class Parent {
void displayParent() {
[Link]("This is the parent class.");
}
}
class Child extends Parent {
void displayChild() {
[Link]("This is the child class.");
}
public static void main(String[] args) {
Child childObj = new Child();
[Link]();
[Link]();
}
}
Output:
This is the parent class.
This is the child class.
b) Implement a Java program using multilevel inheritance:
class Grandparent {
void displayGrandparent() {
[Link]("This is the grandparent class.");
}
}
class Parent extends Grandparent {
10 | P a g e
void displayParent() {
[Link]("This is the parent class.");
}
}
class Child extends Parent {
void displayChild() {
[Link]("This is the child class.");
}
public static void main(String[] args) {
Child childObj = new Child();
[Link]();
[Link]();
[Link]();
}
}
Output:
This is the parent class.
This is the child class.
c) Implement a Java program using an abstract class:
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
[Link]("Drawing a Circle");
}
}
class Square extends Shape {
void draw() {
[Link]("Drawing a Square");
}
}
public class AbstractExample {
public static void main(String[] args) {
Shape circle = new Circle();
Shape square = new Square();
[Link]();
11 | P a g e
[Link]();
}
}
Output:
Drawing a Circle
Drawing a Square
----------------------------------------------------------------------------------------------------------------
Exercise 5 (Inheritance - Continued)
a) Implement a Java program using the "super" keyword:
class Parent {
String message = "Hello from Parent";
void display() {
[Link](message);
}
}
class Child extends Parent {
String message = "Hello from Child";
void display() {
[Link](); // Using "super" to call the parent class method
[Link](message);
}
public static void main(String[] args) {
Child childObj = new Child();
[Link]();
}
}
Output:
Hello from Parent
Hello from Child
12 | P a g e
b) Implement a Java program using interfaces:
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() {
[Link]("Drawing a Circle");
}
}
class Rectangle implements Shape {
public void draw() {
[Link]("Drawing a Rectangle");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();
[Link]();
[Link]();
}
}
Output:
Drawing a Circle
Drawing a Rectangle
----------------------------------------------------------------------------------------------------------------
13 | P a g e
Exercise 6 (Runtime Polymorphism)
a) Write a Java program that implements runtime polymorphism (method overriding):
class Animal {
void makeSound() {
[Link]("Some sound");
}
}
class Dog extends Animal {
void makeSound() {
[Link]("Woof! Woof!");
}
}
class Cat extends Animal {
void makeSound() {
[Link]("Meow!");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
[Link](); // Calls Dog's makeSound method
[Link](); // Calls Cat's makeSound method
}
}
Output:
Woof! Woof!
Meow!
----------------------------------------------------------------------------------------------------------------
14 | P a g e
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
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
}
}
}
Output:
Exception caught: / by zero
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
[Link]("Result: " + result);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of bounds: " + [Link]());
} catch (ArithmeticException e) {
[Link]("Arithmetic exception: " + [Link]());
}
}
}
Output:
Array index out of bounds: Index 7 out of bounds for length 5
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
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Arithmetic exception: " + [Link]());
15 | P a g e
} finally {
[Link]("Finally block executed.");
}
}
}
Output:
Arithmetic exception: / by zero
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.");
}
[Link]("Age is valid.");
} catch (CustomException e) {
[Link]("Custom Exception: " + [Link]());
}
}
}
Output:
Custom Exception: Age is below 18.
-------------------------------------------------------------------------------------------------------------
16 | P a g e
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) {
[Link] = message;
[Link] = interval;
}
public void run() {
while (true) {
[Link](message);
try {
[Link](interval * 1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
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);
[Link]();
[Link]();
[Link]();
}
}
Output:
Welcome
Good Morning
Hello
Good Morning
Hello
17 | P a g e
Good Morning
Welcome
Good Morning
Hello
Good Morning
Good Morning
^C
b) Write a program illustrating isAlive() and join():
public class ThreadJoinExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
[Link]("Thread 1 is running.");
try {
[Link](2000);
} catch (InterruptedException e) {
[Link]();
}
});
Thread thread2 = new Thread(() -> {
[Link]("Thread 2 is running.");
try {
[Link](3000);
} catch (InterruptedException e) {
[Link]();
}
});
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
}
[Link]("Both threads have completed their execution.");
}
}
18 | P a g e
Output:
Thread 1 is running.
Thread 2 is running.
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) {
[Link]("Daemon thread is running.");
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
});
[Link](true);
[Link]();
try {
[Link](5000);
} catch (InterruptedException e) {
[Link]();
}
[Link]("Main thread exiting.");
}
}
Output:
Daemon thread is running.
Daemon thread is running.
Daemon thread is running.
Daemon thread is running.
Daemon thread is running.
Main thread exiting.
------------------------------------------------------------------------------------------------------------
19 | P a g e
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() {
[Link]("Hello from MyClass in myPackage.");
}
}
Import the package and use the class in another Java file:
import [Link];
public class PackageExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}
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();
[Link]();
}
}
Output:
Hello from MyClass in myPackage.
----------------------------------------------------------------------------------------------------------------
20 | P a g e
Exercise 10 (Applet)
a) Write a Java program to paint like a paintbrush in an applet:
import [Link];
import [Link];
import [Link];
import [Link];
public class PaintBrushApplet extends Applet {
int x, y;
public void init() {
x = -1;
y = -1;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
x = [Link]();
y = [Link]();
}
});
}
public void paint(Graphics g) {
if (x != -1 && y != -1) {
[Link](x, y, 5, 5);
}
}
}
Output:
Applet
21 | P a g e
b) Write a Java program to create different shapes and fill colors using an applet:
import [Link];
import [Link];
import [Link];
public class ShapesAndColorsApplet extends Applet {
public void paint(Graphics g) {
// Draw a red rectangle
[Link]([Link]);
[Link](20, 20, 80, 40);
// Draw a blue oval
[Link]([Link]);
[Link](120, 20, 80, 40);
// Draw a green rounded rectangle
[Link]([Link]);
[Link](220, 20, 80, 40, 10, 10);
// Draw a yellow arc
[Link]([Link]);
[Link](320, 20, 80, 40, 45, 180);
}
}
Output:
----------------------------------------------------------------------------------------------------------------
22 | P a g e