0% found this document useful (0 votes)
8 views42 pages

OOPs 2.0 Java Programming Exercises

The document contains a series of Java programming exercises covering basic concepts such as printing text, calculating areas, checking prime numbers, generating Fibonacci series, and working with classes and objects. It also includes advanced topics like method and constructor overloading, inheritance, exception handling, and array manipulations. Each exercise is accompanied by code examples and expected outputs.

Uploaded by

55 Sana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views42 pages

OOPs 2.0 Java Programming Exercises

The document contains a series of Java programming exercises covering basic concepts such as printing text, calculating areas, checking prime numbers, generating Fibonacci series, and working with classes and objects. It also includes advanced topics like method and constructor overloading, inheritance, exception handling, and array manipulations. Each exercise is accompanied by code examples and expected outputs.

Uploaded by

55 Sana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lab Turn

1 JAVA
BASIC

1. Write a Program to print the text “Hello to World of Java”. Save


it with name
[Link] in your folder.

class Hello {
public static void main (String[] args) {
[Link]("Hello to world of Java");
}
}

Output

2. Write a Program to print the area of triangle. Save it with


name [Link] in your folder.

class Area {
public static void main(String[]
args) { int height = 10, base
= 6;
float area = 0.5F * base * height;
[Link]("Area of triangle = " +
area);
}
}
Output

3. Write a java Program to check the number is Prime or not.

import [Link];
class Prime {
public static void main(String
arr[]) { int c;
Scanner in = new Scanner([Link]);
[Link]("Enter the number to be tested for
prime: "); int n = [Link]();

boolean isPrime = true;

if (n <= 1) {
isPrime =
false;
} else {
for (c = 2; c <= n - 1;
c++) { if (n % c ==
0) {
isPrime = false;
break;
}
}
}
if (isPrime)
[Link](n + " is a PRIME
number."); else
[Link](n + " is NOT a prime
number."); [Link]();
}
}

Output

4. Write a java Program to generate a Fibonacci Series.

class FibonacciExample1 {
public static void main(String
args[]) { int n1 = 0, n2 = 1,
n3, i, count = 10;

[Link](n1 + " " + n2);

for (i = 2; i < count; +


+i) { n3 = n1 + n2;
[Link](" " +
n3); n1 = n2;
n2 = n3;
}
}
}
Output

5. Write a java Program to generate a Ladder of number. import


[Link];

class Ladder {
public static void main(String arr[]) {
Scanner in = new
Scanner([Link]);
[Link]("Enter the number of
rows"); int a = [Link]();
for (int i = 1; i <= a;
i++) { for (int j = 1; j
<= i; j++)
[Link](j
);
for (int k = i - 1; k >= 1; k--)
[Link](k);
[Link]("\n");
}
}
}

Output
6. Write a java Program to Convert any decimal number into its
binary equivalent.

import [Link];

class DecimalToBinary {
public static void main(String[] args)
{ Scanner in = new
Scanner([Link]);
[Link]("Enter a decimal
number:"); int decimal = [Link]();
String binary =
""; if (decimal
== 0) { binary
= "0";
} else
{
while (decimal > 0) {
binary = (decimal % 2) +
binary; decimal = decimal
/ 2;
}
}
[Link]("Binary equivalent: " +
binary); [Link]();
}
}

Output
Lab Turn 2
Program based on the concepts of classes and objects, constructor,
parameterized constructor

7. Write a program to create a class Student with data ‘name,


city and age’ along with method printData to display the data.
Create the two objects s1 ,s2 to declare and access the values.

class Student {
String name,
city; int age;
static int m;

void printData() {
[Link]("Student name = " +
name); [Link]("Student city =
" + city); [Link]("Student age
= " + age);
}
}

class Stest {
public static void main(String
args[]) { Student s1 = new
Student(); Student s2 = new
Student();

[Link] = "Amit";
[Link] =
"Dehradun"; [Link]
= 22;
[Link] = "Kapil";
[Link] =
"Delhi"; [Link]
= 23;

[Link]();
[Link]();

s1.m = 20;
s2.m = 22;
Student.m = 27;

[Link]("s1.m = " + s1.m);


[Link]("s2.m = " + s2.m);
[Link]("Student.m = " +
Student.m);
}
}

Output
8. Write a program to create a class Student2 along with two
method getData(),printData() to get the value through argument
and display the data in printData. Create the two objects s1 ,s2 to
declare and access the values from class STtest.

class Student2 {
private String name,
city; private int age;
public void getData(String x, String y, int
t) { name = x;
city =
y; age
= t;
}

public void printData() {


[Link]("Student name = " +
name); [Link]("Student city =
" + city); [Link]("Student age
= " + age);
}
}

class STtest {
public static void main(String
args[]) { Student2 s1 = new
Student2(); Student2 s2 =
new Student2();

[Link]("Kapil", "Delhi",
23); [Link]();
[Link]("Amit", "Dehradun", 22);
[Link]();
}
}

Output

G. WAP using parameterized constructor with two parameters id


and name. While creating the objects obj1 and obj2 passed two
arguments so that this constructor gets invoked after creation of
obj1 and obj2.

class
Student
{ int id;
String name;
Student(int id, String
name) { [Link] = id;
[Link] = name;
}

void display() {
[Link]("ID: " + id + ", Name: " + name);
}
}

class Test {
public static void main(String[] args) {
Student obj1 = new Student(101,
"Alice"); Student obj2 = new
Student(102, "Bob");

[Link]();
[Link]();
}
}

Output
Lab Turn 3
Method overloading, constructor overloading

10. Write a program in JAVA to demonstrate the method and


constructor overloading.

class
OverloadingExample {
int x, y;

// Constructor with no parameters


OverloadingExample() {
x = 0;
y = 0;
[Link]("Default constructor called");
}

// Constructor with two parameters (constructor


overloading) OverloadingExample(int a, int b) {
x=
a; y
= b;
[Link]("Parameterized constructor called");
}

// Method with no parameters (method


overloading) void display() {
[Link]("x = " + x + ", y = " + y);
}

// Method with two parameters (method overloading)


void display(int a, int b) {
[Link]("Sum = " + (a +
b));
}
}

public class Test {


public static void main(String[] args) {
OverloadingExample obj1 = new
OverloadingExample(); [Link]();

OverloadingExample obj2 = new


OverloadingExample(10, 20); [Link]();
[Link](5, 15);
}
}

Output
11. Write a program in JAVA to create a class Bird also
declares the different parameterized constructor to display
the name of Birds.

class Bird {
String
name;

// Constructor with one


parameter Bird(String name)
{
[Link] = name;
[Link]("Bird name: " +
name);
}

// Constructor with two


parameters Bird(String name,
String type) {
[Link] = name;
[Link]("Bird name: " + name + ", Type: " + type);
}

// Constructor with three parameters


Bird(String name, String type, String
color) {
[Link] = name;
[Link]("Bird name: " + name + ", Type: " + type + ", Color: " +
color);
}
}
public class TestBird {
public static void main(String[]
args) { Bird b1 = new
Bird("Parrot");
Bird b2 = new Bird("Eagle", "Bird of Prey");
Bird b3 = new Bird("Peacock", "Game Bird", "Blue and Green");
}
}

Output

12. Write a program in java to generate an abstract class A also


class B inherits the
class A. generate the object for class B and display the text “call me
from B”.

abstract class A {
abstract void
callMe();
}

class B extends
A { void
callMe() {
[Link]("call me from B");
}
}

public class Test {


public static void main(String[]
args) { B obj = new B();
[Link]();
}
}
Output

13. Write a java program in which you will declare two interface
sum and Add inherits these interface through class A1 and display
their content.

interface Sum {
void sum(int a, int b);
}

interface Add {
void add(int x, int y);
}

class A1 implements Sum, Add


{ public void sum(int a, int b)
{
[Link]("Sum is: " + (a + b));
}

public void add(int x, int y) {


[Link]("Add is: " + (x + y));
}
}

public class Test {


public static void main(String[]
args) { A1 obj = new A1();
[Link](10, 20);
[Link](30, 40);
}
}

Output
Lab Turn 4
Single level s Multi level inheritance , Method Overriding

14. Java program to illustrate the concept of 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 class Test {


public static void main(String[] args)
{ Child obj = new Child();
[Link](); // inherited
method [Link](); // own
method
}
}

Output
15. A Simple Java program to demonstrate method overriding in
java.

class Parent
{ void
show() {
[Link]("Parent's show() method");
}
}

class Child extends


Parent { @Override
void show() {
[Link]("Child's overridden show() method");
}
}

public class Test {


public static void main(String[]
args) { Parent p = new
Parent();
[Link](); // Calls Parent's show()

Child c = new Child();


[Link](); // Calls Child's overridden show()

Parent pc = new Child();


[Link](); // Calls Child's show() due to runtime polymorphism
}
}
Output

16. Super Keyword in Java Use of super with variables.

class Parent {
int num =
100;
}

class Child extends


Parent { int num =
200;
void display() {
[Link]("Value of num in Child class: " + num);
[Link]("Value of num in Parent class: " + [Link]);
}
}
public class Test {
public static void main(String[]
args) { Child obj = new
Child(); [Link]();
}
}

Output
Lab Turn 5
Array and
String

17. Write a Java Program to to find maximum in arr[].

class MaxInArray {
public static void main(String[]
args) { int arr[] = {10, 25, 5,
30, 15};
int max = arr[0];

for (int i = 1; i < [Link];


i++) { if (arr[i] > max) {
max = arr[i];
}
}
[Link]("Maximum value in the array is: " + max);
}
}

Output
18. implementation of the sort() function across different
scenarios of the Arrays class.

import [Link];
import
[Link];

public class ArraysSortDemo {


public static void main(String[]
args) { int[] intArr = {5, 2, 8,
12, 1}; [Link](intArr);
[Link]("Sorted int array: " + [Link](intArr));

double[] doubleArr = {3.5, 1.2, 4.8, 2.9};


[Link](doubleArr);
[Link]("Sorted double array: " + [Link](doubleArr));

String[] stringArr = {"Banana", "Apple", "Mango",


"Cherry"}; [Link](stringArr);
[Link]("Sorted String array: " + [Link](stringArr));

int[] partialArr = {10, 3, 7, 5, 9};


[Link](partialArr, 1, 4);
[Link]("Partially sorted int array: " + [Link](partialArr));
Integer[] integerObjArr = {5, 2, 8, 12, 1};
[Link](integerObjArr, [Link]());
[Link]("Sorted Integer array (descending): " +
[Link](integerObjArr));
}
}
Output

1G. Java program for addition of two matrices.

public class MatrixAddition {


public static void main(String[]
args) { int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6}
};

int[][] matrix2 = {
{7, 8, 9},
{10, 11, 12}
};

int rows =
[Link]; int cols
= matrix1[0].length;

int[][] sum = new int[rows][cols];

for (int i = 0; i < rows;


i++) { for (int j = 0; j
< cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

[Link]("Sum of the two


matrices:"); for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](sum[i][j] + " ");
}
[Link]();
}
}
}

Output

20. java program to reverse a word.

import [Link];

public class ReverseWord {


public static void main(String[] args)
{ Scanner sc = new
Scanner([Link]);
[Link]("Enter a word: ");
String word = [Link]();

String reversed = "";


for (int i = [Link]() - 1; i >= 0;
i--) { reversed += [Link](i);
}

[Link]("Reversed word: " + reversed);


}
}

Output
Lab Turn 6
Exception handling s Packages

21. Write a program in java if number is less than 10 and greater


than 50 it generate the exception out of range. Else it displays the
square of number. // Custom Exception class

class OutOfRangeException extends


Exception { public
OutOfRangeException(String message) {
super(message);
}
}

public class NumberCheck {


public static void main(String[]
args) { int number = 25;

try {
checkNumber(number);
} catch (OutOfRangeException e) {
[Link]("Exception: " +
[Link]());
}
}

public static void checkNumber(int num) throws


OutOfRangeException { if (num < 10 || num > 50) {
throw new OutOfRangeException("Number is out of range!");
} else {
[Link]("Square of " + num + " is " + (num * num));
}
}
}

Output

22. Write a program in java to enter the number through


command line argument if first and second number is not entered it
will generate the exception. Also divide the first number with
second number and generate the arithmetic exception.

class Divide2 {
public static void main(String
arr[]) { try {
if ([Link] < 2)
throw new Exception("Two arguments must be provided");

int a =
[Link](arr[0]); int b
= [Link](arr[1]);

if (b == 0)
throw new Exception("Second argument should be non-zero");

int c = a / b;
[Link]("Result: "
+ c);
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}

Output

23. Example of package that import the packagename.*

File: mypack/[Link]

package mypack;

public class MyClass {


public void displayMessage() {
[Link]("Hello from MyClass in
mypack!");
}
}

File:

[Link]

import mypack.*;

public class MainApp {


public static void main(String[]
args) { MyClass obj = new
MyClass(); [Link]();
}
}
Output

24. Example of package by import fully qualified name.

File: mypack/[Link]
package mypack;
public class
MyClass {
public void show() {
[Link]("Hello from MyClass in mypack!");
}
}

File: [Link]

public class MainApp {


public static void main(String[] args)
{ [Link] obj = new
[Link](); [Link]();
}
}

Output
Lab Turn7
Multithread
ing

25. Write a java program in which thread sleep for 5 sec and
change the name of thread.

import [Link].*;

class ThreadTest extends Thread {

static {
Thread t = [Link]();
[Link]("ThreadTest is loaded by " + [Link]() + " thread");

[Link]("vishal");
[Link]("Changed the name of thread to: " + [Link]());

[Link]("Suspending thread for 5


seconds..."); try {
[Link](5000);
} catch (Exception ex) {
[Link]("Exception: " + ex);
}
}

public static void main(String


arr[]) { Thread t =
[Link]();
[Link]("Inside main, current thread name: " + [Link]());
[Link]("Thread priority: " + [Link]());
[Link]("Thread ID: " + [Link]());
}
}

Output

26. Write a java program for multithread in which user thread and
thread started from main method invoked at a timeeach thread
sleep for 1 sec.

class UserThread extends Thread


{ public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("User thread: "
+ i); try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("User thread
interrupted");
}
}
}
}

public class MultiThreadDemo {


public static void main(String[]
args) { UserThread ut = new
UserThread();
[Link]();
for (int i = 1; i <= 5; i++) {
[Link]("Main thread: "
+ i); try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("Main thread
interrupted");
}
}
}
}

Output

27. Write a java program for to solve producer consumer problem


in which a producer produce a value and consumerconsume the
value before producer generate the next value.

class SharedData
{ private int
value;
private boolean available = false;

public synchronized void produce(int


val) { while (available) {
try {
wait();
} catch (InterruptedException e) {
[Link]("Producer
interrupted");
}
}
value = val;
[Link]("Produced: " +
value); available = true;
notify();
}

public synchronized void


consume() { while (!available)
{
try {
wait();
} catch (InterruptedException e) {
[Link]("Consumer
interrupted");
}
}
[Link]("Consumed: " + value);
available = false;
notify();
}
}

// Producer thread
class Producer extends Thread {
SharedData data;

Producer(SharedData
d) { data = d;
}

public void run() {


for (int i = 1; i <= 5; i++) {
[Link](i);
try {
[Link](500);
} catch (InterruptedException e) {}
}
}
}

// Consumer thread
class Consumer extends Thread {
SharedData data;

Consumer(SharedData d)
{ data = d;
}

public void run() {


for (int i = 1; i <= 5; i++) {
[Link]();
try {
[Link](500);
} catch (InterruptedException e) {}
}
}
}
public class ProducerConsumerDemo
{ public static void main(String[]
args) {
SharedData data = new
SharedData(); Producer p = new
Producer(data); Consumer c = new
Consumer(data);

[Link]();
[Link]();
}
}

Output
Lab Turn 8
I/O and File Handling

28 .Write a java program to create a file and write the text in it and
save the file.

import [Link].*;

class CreateFile {
public static void main(String
arr[]) { if ([Link] < 1) {
[Link]("Usage: java CreateFile
<filename>"); [Link](0);
}

try {
BufferedReader br = new BufferedReader(new
InputStreamReader([Link])); PrintStream fos = new PrintStream(new
FileOutputStream(arr[0])); [Link]("Enter text (type 'end' to
finish and save):");

PrintStream originalOut = [Link];


[Link](fos);

while (true) {
String str = [Link]();
if ([Link]("end"))
{ break;
}
[Link](str);
}

[Link](originalOut);
[Link]("File saved as: " +
arr[0]);

} catch (IOException e) {
[Link]("Error: " +
[Link]());
}
}
}

Output

[Link] a java program to read a file and display the content on


screen.

import [Link].*;

public class ReadFile {


public static void main(String[]
args) { if ([Link] < 1) {
[Link]("Usage: java ReadFile
<filename>"); return;
}
String filename = args[0];

try (BufferedReader reader = new BufferedReader(new


FileReader(filename))) { String line;
[Link]("File
content:"); while ((line =
[Link]()) != null) {
[Link](line);
}
} catch (FileNotFoundException e) {
[Link]("File not found: " +
filename);
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
}
}

Output
Lab Turn G
Collections in
Java

import [Link].*;

public class AList {


public static void main(String args[]) {
ArrayList<String> str = new
ArrayList<String>();

[Link]("Size at the beginning: " + [Link]());

[Link]("Hello");
[Link]("Hi");
[Link]("Namaste");
[Link]("Bonjour");

[Link](str);

[Link]("Size after addition: " + [Link]());

[Link](0);

[Link](str);

[Link]("Size after removal: " + [Link]());


}
}
Output

You might also like