Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java Lab Material

The document contains a series of Java programming exercises, including displaying default values of primitive data types, solving quadratic equations, implementing binary and bubble sort algorithms, and demonstrating various object-oriented programming concepts such as inheritance, polymorphism, and exception handling. Each exercise is accompanied by code examples and expected outputs. The exercises cover fundamental Java programming topics suitable for beginners to intermediate learners.

Uploaded by

Hemanth Atla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Lab Material

The document contains a series of Java programming exercises, including displaying default values of primitive data types, solving quadratic equations, implementing binary and bubble sort algorithms, and demonstrating various object-oriented programming concepts such as inheritance, polymorphism, and exception handling. Each exercise is accompanied by code examples and expected outputs. The exercises cover fundamental Java programming topics suitable for beginners to intermediate learners.

Uploaded by

Hemanth Atla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Exercise – 1:

a. Write a JAVA program to display default value of all primitive data type of JAVA

Code :
class MainClass {
static byte a;
static short b;
static int c;
static long d;
static float e;
static double f;
static char g;
static boolean h;

public static void main(String[] args) {


System.out.println("Byte default value : " + a);
System.out.println("Short default value :" + b);
System.out.println("int default value :" + c);
System.out.println("long default value :" + d);
System.out.println("float default value :" + e);
System.out.println("double default value :" + f);
System.out.println("char default value :" + g);
System.out.println("boolean default value :" + h);
}
}

Output :

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.

Code :
import java.util.Scanner;
class QuadraticEquation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter co-efficient 'a' :");
double a = sc.nextDouble();
System.out.println("Enter co-efficient 'b' :");
double b = sc.nextDouble();
System.out.println("Enter co-efficient 'c' :");
double c = sc.nextDouble();
double D = b * b - 4 * a * c;
if (D > 0) {
double root1 = (-b + Math.sqrt(D)) / (2 * a);
double root2 = (-b - Math.sqrt(D)) / (2 * a);
System.out.println("Root 1 :" + root1);
System.out.println("Root 2 :" + root2);
} else if (D == 0) {
double root = -b / (2 * a);
System.out.println("Root :" + root);
} else {
double realroot = -b / (2 * a);
double ip = Math.sqrt(-D) / (2 * a);

System.out.println("Root 1 :" + realroot + " + i" + ip);


System.out.println("Root 2 :" + realroot + " - i" + ip);
}
}
}

Output :

Exercise - 2
a. Write a JAVA program to search for an element in a given list of elements using binary search mechanism.

Code :
import java.util.Arrays;
import java.util.Scanner;

class BinarySearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size :");
int size = sc.nextInt();
int[] arr = new int[size];
// storing array dynamically
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter Any value at the index :" + i);
arr[i] = sc.nextInt();
}

// Sort array and convert to String


Arrays.sort(arr);
System.out.println("Sorted Array :" + Arrays.toString(arr));

System.out.println("Enter the Element to search :");


int target = sc.nextInt();

int result = binarySearch(arr, target);

if (result == -1) {
System.out.println("Element not found");
} else {
System.out.println("Element found at index :" + result);
}
}

// Binary search logic


public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;

if (arr[mid] == target) {
return mid;
}

if (arr[mid] > target) {


right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
}

Output :

b. Write a JAVA program to sort for an element in a given list of elements using bubble sort

Code :
import java.util.Arrays;
import java.util.Scanner;

class BubbleSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size :");
int size = sc.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
System.out.println("Enter Value at the index :" + i);
arr[i] = sc.nextInt();
}
bubbleSort(arr);
}
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - i - 1; 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: " + Arrays.toString(arr));
}
}

Output :

c. Write a JAVA program using String Buffer to delete, remove character.

Code :
class StringBufferClass {
public static void main(String[] args) {
StringBuffer s1=new StringBuffer("Hello world");
System.out.println("Actual String : "+s1);
//delete String at the index 0 to 5
s1.delete(0, 5);
System.out.println("deleted String at the index 0 to 5 :"+s1);
//delete character based on the index value
s1.deleteCharAt(2);
System.out.println("Deleting character at the index 2 :"+s1);
}
}

Output :
Exercise - 3
a. Write a JAVA program to implement class mechanism. Create a class, methods and invoke them inside
main method.
Code :
public class MainClass {
public static void main(String[] args) {
Demo.add();
Demo.sub(10,20);
System.out.println(Demo.mul());
}
}

class Demo {
//static method
public static void add() {
System.out.println("This is add method in Demo class...");
}

//method with parameters


public static void sub(int a,int b) {
System.out.println("b-a ="+(b-a));
}

//method with return type


public static int mul() {
int a=10;
int b=30;
int c=a*b;
return c;
}
}

Output :

b. Write a JAVA program implement method overloading.


Code :
public class WhatsApp {
public void send(int number) {
System.out.println("Sending number : " + number);
}
public void send(String text) {
System.out.println("Sending text : " + text);
}
public void send(String location, String image) {
System.out.println("Sending location and image : " + location + " , " + image);
}
public void send(String video, long number) {
System.out.println("Sending video and number : " + video + " , " + number);
}
public static void main(String[] args) {
WhatsApp w1=new WhatsApp();
w1.send(100);
w1.send("hi hello");
w1.send("vijayawada ","image1.png");
w1.send("vedio.mp4",987456214);
}
}

Output :

c. Write a JAVA program to implement constructor.


Code :
public class EmpDetails {
int empid;
String empname;
double empsal;
EmpDetails(int id, String name, double sal) {
empid = id;
empname = name;
empsal = sal;
}
public static void main(String[] a) {
EmpDetails emp1 = new EmpDetails(100, "ravi", 50008.38);
EmpDetails emp2 = new EmpDetails(200, "raju", 38505.);
EmpDetails emp3 = new EmpDetails(300, "Ravi", 60088.4);
System.out.println("************Employee 1 details*************");
System.out.println("EMPID : " + emp1.empid + " EMPNAME : " + emp1.empname +
" EMPSAL : " + emp1.empsal);
System.out.println("************Employee 2 details************");
System.out.println("EMPID : " + emp2.empid + " EMPNAME : " + emp2.empname +
" EMPSAL : " + emp2.empsal);
System.out.println("************Employee 3 details************");
System.out.println("EMPID : " + emp3.empid + " EMPNAME : " + emp3.empname +
" EMPSAL : " + emp3.empsal);
}
}

Output :
d. Write a JAVA program to implement constructor overloading.
Code :
public class DemoClass {
int a, b, c;
String str;
boolean k;
DemoClass(int a) {
this.a = a;
}
DemoClass(int b, int c) {
this.b = b;
this.c = c;
}
DemoClass(String str) {
this.str = str;
}
protected DemoClass(String str, boolean k) {
this.str = str;
this.k = k;
}
public static void main(String[] args) {
DemoClass d1=new DemoClass(100);
DemoClass d2=new DemoClass(200,300);
DemoClass d3=new DemoClass("hello java");
DemoClass d4=new DemoClass("hey raju",true);
System.out.println(d1.a);
System.out.println(d2.b+" , "+ d2.c);
System.out.println(d3.str);
System.out.println(d4.str+" , "+d4.k);
}
}

Output :

Exercise - 4
a. Write a JAVA program to implement Single Inheritance

Code :
class Animal{
public void eat() {
System.out.println("Animal eating food....");
}
}

class Dog extends Animal{


public void noise() {
System.out.println("Dog making some noise...");
}
}

public class MainClass1 {


public static void main(String[] args) {
Dog d1=new Dog();
d1.noise();
d1.eat();
}
}

Output :

b. Write a JAVA program to implement multi level Inheritance

Code :

class GrandParentClass{
public void land1() {
System.out.println("grand parent earn 4 acers land");
}
}
class ParentClass extends GrandParentClass{
public void land2() {
System.out.println("parent earn 2 acers land");
}
}
class ChildClass extends ParentClass{
public void land3() {
System.out.println("Child earn 1 acers land....");
}
}

public class MainClass2 {


public static void main(String[] args) {
ChildClass c1=new ChildClass();
c1.land1();
c1.land2();
c1.land3();
}
}

Output :

c. Write a JAVA program for abstract class to find areas of different shapes
Code :
abstract class Shape {
abstract double calculateArea();

void displayArea() {
System.out.println("Area :" + calculateArea());
}
}
//Area of circle
class Circle extends Shape {
double radius;

Circle(double radius) {
this.radius = radius;
}

double calculateArea() {
double area = 3.14 * radius * radius;
return area;
}
}

//Area of rectangle
class Rectangle extends Shape {
double length;
double width;

Rectangle(double length, double width) {


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

double calculateArea() {
double area = length * width;

return area;
}
}

//Area of Triangle
class Triangle extends Shape {
double base;
double height;

Triangle(double base, double height) {


this.base = base;
this.height = height;
}

double calculateArea() {
double area = 0.5 * base * height;

return area;
}
}

class AbstractClass {
public static void main(String[] args) {
Circle c1 = new Circle(10);
System.out.println("*****Circle******");
c1.displayArea();
Rectangle r1 = new Rectangle(10, 20);
System.out.println("******Rectangle******");
r1.displayArea();
Triangle t1 = new Triangle(5, 10);
System.out.println("******Triangle******");
t1.displayArea();
}
}

Output :

Exercise - 5
a. Write a JAVA program give example for “super” keyword.

Code :

//super class(Parent class)


class WhatsAppVersionOld {
String version = "1.1.1";
WhatsAppVersionOld() {
System.out.println("This is WhatsApp Version Old Constractor.");
}
public void features() {
System.out.println("sent text, send images , send location , send videos , statues , audio calling ..etc");
}
}

//sub class(Child class)


class WhatsAppVersionNew extends WhatsAppVersionOld {
String version = "1.1.2";
WhatsAppVersionNew() {
super(); // to call super class constructor
System.out.println("This is WhatsApp Version New Constractor..");
}
public void features() {
super.features(); //to call super class method
System.out.println("Meta AI , payment options, channels , statues UI changed...etc");
System.out.println("Version : "+super.version); //to call super class variable
}
}

//main class
public class MainClass {
public static void main(String[] args) {
WhatsAppVersionNew v1 = new WhatsAppVersionNew();
v1.features();
System.out.println("Version : "+v1.version);
}
}

Output :

b. Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?

Code :
//define the first interface
interface Animal{
void sound() ;
void eat();
}

//define the second interface


interface Pet{
void play();
}

class Dog implements Animal,Pet{


//providing implementations to Animal interface
public void sound() {
System.out.println("Dog barks..");
}
public void eat() {
System.out.println("Dog eats food");
}
//providing implementations to Pet interface
public void play() {
System.out.println("Dog plays fetch");
}
}

public class MainClass1 {


public static void main(String[] args) {
Dog d1=new Dog();
d1.sound();
d1.eat();
d1.play();
}
}
Output :

c. Write a JAVA program that implements Runtime polymorphism

Code :
package method_overriding;

class YouTube{
public void watch() {
System.out.println("User watching something in youtube");
}
}
class Studies extends YouTube{
public void watch() {
System.out.println("User accessing Studies....");
}
}
class Movies extends YouTube{
public void watch() {
System.out.println("User accessing Movies....");
}
}
class Technology extends YouTube{
public void watch() {
System.out.println("User can access technology...");
}
}
class User{
public static void access(YouTube a) {
a.watch();
}
}

public class MainClass2 {


public static void main(String[] args) {
User.access(new Studies());
User.access(new Movies());
User.access(new Technology());
}

}
Output :

Exercise - 6
a. Write a JAVA program that describes exception handling mechanism

Code :
public class MainClass {
public static void main(String[] args) {
try {
int a=10/0;
System.out.println(a);
}catch(ArithmeticException e) {
System.out.println("Arithmetic Exception Handled....");
}finally {
System.out.println("Exception completed....");
}
}
}

Output :

b. Write a JAVA program Illustrating Multiple catch clauses

Code :
package exception;
import java.util.Scanner;
public class MainClass1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter numerator :");
int a=sc.nextInt();
System.out.println("Enter denominator :");
int b=sc.nextInt();

try {
int result =a/b;
System.out.println("The division of a and b is :"+result);

int[] arr= {10,20,30,40,50};


System.out.println("Enter index value to print array element :");
int i=sc.nextInt();
System.out.println("value at the index: "+arr[i]);
String str="hello java";
System.out.println("Enter index value to print charactor in given string :");
int ch=sc.nextInt();

System.out.println(str.charAt(ch));
}
catch(ArithmeticException e) {
System.out.println("caught Arithmetic Exception");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("caught Array Index Out Of Bounds Exception ");
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("caught String Index Out Of Bounds Exception");
}finally {
System.out.println("Exception completed ...");
}
}

Output :
Case 1 :

Case 2:

Case 3:
c. Write a JAVA program for creation of Java Built-in Exceptions

Code :
import java.util.Scanner;

class Display {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


try {
int a = 10 / 0;

} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception handled");

int arr[] = { 10, 20, 30 };


System.out.println("Enter array index value :");
try {
int i = sc.nextInt();
System.out.println("value in the index "+i+" is : "+arr[i]);

String str = "hello java";


System.out.println("Enter index value to print charactor in given
String :");
int j = sc.nextInt();
System.out.println("Charactor :" + str.charAt(j));

//compile time exception


for(int k=0;k<5;k++) {
System.out.println(k);
try {
Thread.sleep(2000);
}
catch(Exception a) {
e.printStackTrace();
}
}
} catch (ArrayIndexOutOfBoundsException a) {
System.out.println("Array Index Out Of Bounds Exception handled");
} catch (StringIndexOutOfBoundsException a) {
System.out.println("String Index Out Of Bounds Exception handled");
}
}
}
}

Output :

Case 1:
Case 2:

Case 3 :

d. Write a JAVA program for creation of User Defined Exception

Code :
import java.util.Scanner;
class AgeNotFoundException extends Exception {
String msg;

AgeNotFoundException(String msg) {
this.msg = msg;
}
}

class AgeVerification {
public static void verification() throws AgeNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your Age :");
int age = sc.nextInt();
if (age > 18) {
System.out.println("Your eligible to apply voter ID ....please apply ");
} else {
throw new AgeNotFoundException("Your not eligible to apply voter ID is
please wait still "+(18-age)+" years") ;
}
}
}

public class MainClass {


public static void main(String[] args) {
try {
AgeVerification.verification();
} catch (AgeNotFoundException e) {
System.out.println(e.msg);
}
}
}

Output :
Case 1:

Case 2:

Exercise - 7
a. Write a JAVA program that creates threads by extending Thread class.First thread display “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)

Code :

class Thread1 extends Thread{


public void run() {
while(true) {
System.out.println("Good Morning");
try {
Thread.sleep(1000);
}
catch(InterruptedException e) {
System.out.println("Thread1 is Interrupted..");
}
}
}
}

class Thread2 extends Thread {


public void run() {
while(true) {
System.out.println("Hello");
try {
Thread.sleep(2000);
}catch(InterruptedException e) {
System.out.println("Thread2 is Interrupted..");
}
}
}
}
class Thread3 extends Thread{
public void run() {
while(true) {
System.out.println("Welcome");
try {
Thread.sleep(3000);
}catch(InterruptedException e) {
System.out.println("Thread3 is Interrupted..");
}
}
}
}
public class ThreadExample {
public static void main(String[] args) {
new Thread1().start();
new Thread2().start();
new Thread3().start();
}
}

Output :

Same question with (Repeat the same by implementing Runnable)

Code :

class Demo1 implements Runnable {


public void run() {
while (true) {
System.out.println("Good Morning");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread1 is Interrupted");
}
}
}
}

class Demo2 implements Runnable {


public void run() {
while (true) {
System.out.println("Hello");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread 2 is Interrupted");
}
}
}
}

class Demo3 implements Runnable {


public void run() {
while(true) {
System.out.println("Welcome");
try {
Thread.sleep(3000);
}catch(InterruptedException e) {
System.out.println("Thread 3 is Interrupted");
}
}

}
}

public class RunnableInterfaceExample {


public static void main(String[] args) {
Thread t1 = new Thread(new Demo1());
t1.start();// to start thread-1

Thread t2=new Thread(new Demo2());


t2.start(); //to start thread-2

Thread t3=new Thread(new Demo3());


t3.start();//to start thread-3
}
}
Output :

b. Write a Java program illustrating is Alive and join ()

Code :

class Mythread extends Thread {


String name;
Mythread(String name) {
this.name = name;
}
public void run() {
System.out.println(name + " is starting");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println(name + " was Interrupted");
}
System.out.println(name + " Has finished");
}
}

public class ThreadExample {


public static void main(String[] args) {
Mythread t1 = new Mythread("Thread1");
Mythread t2 = new Mythread("Thread2");

System.out.println("Starting treads....");
t1.start();
t2.start();

// check if threads are alive


System.out.println("Is thread 1 alive ? " + t1.isAlive());
System.out.println("Is thread 2 alive ? " + t2.isAlive());

try {
// wait for thread 1 to finish
t1.join();
System.out.println("Thread 1 has finished execution");

// wait for thread 2 to finish


t2.join();
System.out.println("Thread 2 has finished execution");
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}

// check again if threads are alive


System.out.println("Is thread 1 alive ? " + t1.isAlive());
System.out.println("Is thread 2 alive ? " + t2.isAlive());

}
}

Output :

c. Write a Java Program illustrating Daemon Threads.

Code :

class MyThread1 extends Thread {


public void run() {
if (isDaemon()) {
System.out.println(getName() + " Is a daemon thread");
} else {
System.out.println(getName() + " Is a user thread");
}
for (int i = 1; i < 3; i++) {
System.out.println(i+" ->" +getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
}
}

public class MainClass1 {


public static void main(String[] args) {
MyThread1 m1 = new MyThread1();
MyThread1 m2 = new MyThread1();
m2.setDaemon(true);// Set as Daemon Thread
m1.setName("UserThread");
m2.setName("DaemonThread");

m1.start();
m2.start();

}
}

Output :

You might also like