0% found this document useful (0 votes)
7 views12 pages

Java OOP Problem Solving Examples

The document contains a series of Java programming assignments focused on problem-solving using Object-Oriented Programming (OOP) concepts. Each assignment includes a description of the problem, followed by the corresponding Java code that implements the solution. Topics covered include calculating distances, counting set bits, finding occurrences in arrays, sorting with minimum swaps, demonstrating inheritance and polymorphism, validating parentheses, file writing, and threading.

Uploaded by

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

Java OOP Problem Solving Examples

The document contains a series of Java programming assignments focused on problem-solving using Object-Oriented Programming (OOP) concepts. Each assignment includes a description of the problem, followed by the corresponding Java code that implements the solution. Topics covered include calculating distances, counting set bits, finding occurrences in arrays, sorting with minimum swaps, demonstrating inheritance and polymorphism, validating parentheses, file writing, and threading.

Uploaded by

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

NAME: Phad Nitin Dattatraya

SUBJECT: PROBLEM SOLVING USING OOP JAVA


PRN: 202502080009
ROLL NO: 80 BATCH: A4

ASSIGNMENT NO: 6

1. Chef wants to become fit for which he decided to walk to the office and return home
by walking. It is known that Chef's office is X km away from his home. If his office is
open on 5 days in a week, find the number of kilometres Chef travels through office
trips in a week.
Code:
import [Link];
public class ChefFitness {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter distance from home to office (in km): ");
int X = [Link]();
int totalDistance = 2 * X * 5;
[Link]("Total distance Chef travels in a week: " + totalDistance + " km");
}
}
Output:
2. Given a positive Integer n, print count of set bits in it

Code:
import [Link];

public class SetBitsCounter {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a positive integer: ");
int N = [Link]();
int count = 0;
while (N > 0) {
if ((N & 1) == 1) {
count++;
}
N = N >> 1;
}
[Link]("Number of set bits: " + count);
}
}
Output:
3. Given a sorted array arr containing n elements with possibly duplicate elements, the task is
to find indexes of first and last occurrences of an element x in the given array.

Code:

import [Link].*;

public class FirstLastOccurrence {

static int findOccurrence(int[] arr, int x, boolean first) {

int low = 0, high = [Link] - 1, res = -1;

while (low <= high) {

int mid = (low + high) / 2;

if (arr[mid] == x) {

res = mid;

if (first) high = mid - 1;

else low = mid + 1;

} else if (arr[mid] < x) low = mid + 1;

else high = mid - 1;

return res;

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link](), arr[] = new int[n];

for (int i = 0; i < n; arr[i++] = [Link]());

int x = [Link]();

int first = findOccurrence(arr, x, true), last = findOccurrence(arr, x, false);


[Link](first == -1 ? "Element not found." : "First: " + first + ", Last: " + last);

Output:
4. Given an array of n distinct elements. Find the minimum number of swaps required to sort
the array in strictly increasing order.

Code:

import [Link].*;

public class MinSwapsToSort {

public static int minSwaps(int[] arr) {

int n = [Link];

int swaps = 0;

Pair[] pairs = new Pair[n];

for (int i = 0; i < n; i++) {

pairs[i] = new Pair(arr[i], i);

[Link](pairs, [Link](p -> [Link]));

boolean[] visited = new boolean[n];

for (int i = 0; i < n; i++) {

if (visited[i] || pairs[i].index == i) continue;

int cycleSize = 0;

int j = i;

while (!visited[j]) {

visited[j] = true;

j = pairs[j].index;

cycleSize++;

if (cycleSize > 0) swaps += (cycleSize - 1);

return swaps;

static class Pair {

int value, index;

Pair(int value, int index) {


[Link] = value;

[Link] = index;

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

int[] arr = new int[n];


for (int i = 0; i < n; i++) arr[i] = [Link]();

[Link](minSwaps(arr));

[Link]();

Output:
5. Program to demonstrate an example of Single Inheritance
Code:

class Animal {

void eat() {

[Link]("This animal eats food.");

class Dog extends Animal {

void bark() {

[Link]("The dog barks.");

public class SingleInheritanceExample {

public static void main(String[] args) {

Dog myDog = new Dog();

[Link]();

[Link]();

Output:
6. Program to demonstrate Run time polymorphism
Code:

class Animal {

void sound() {

[Link]("Animal makes a sound");

class Dog extends Animal {

@Override

void sound() {

[Link]("Dog barks");

class Cat extends Animal {

@Override

void sound() {

[Link]("Cat meows");

public class RuntimePolymorphismExample {

public static void main(String[] args) {

Animal a;

a = new Dog();

[Link]();

a = new Cat();

[Link]();

}
}

Output:
7. Write a Java program to iterate through all elements in an array list.
Code:

import [Link];

public class IterateArrayList {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<>();

[Link]("Apple");

[Link]("Banana");

[Link]("Cherry");

for (int i = 0; i < [Link](); i++) {

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

Output:
8. Implement a program to check valid parenthesis
Code:

import [Link];

public class ValidParentheses {

public static boolean isValid(String s) {

Stack<Character> stack = new Stack<>();

for (char c : [Link]()) {

if (c == '(' || c == '{' || c == '[') {

[Link](c);

} else {

if ([Link]()) {

return false;

char top = [Link]();

if (!matches(top, c)) {

return false;

return [Link]();

private static boolean matches(char open, char close) {

return (open == '(' && close == ')') ||

(open == '{' && close == '}') ||

(open == '[' && close == ']');

public static void main(String[] args) {

String test1 = "()[]{}";

String test2 = "([)]";

String test3 = "{[()]}";

[Link](test1 + " -> " + isValid(test1));


[Link](test2 + " -> " + isValid(test2));

[Link](test3 + " -> " + isValid(test3));

Output:
9. Write a program to append “Hello World” to a file
Code:

import [Link];

import [Link];

public class WriteToFile {

public static void main(String[] args) {

try {

FileWriter writer = new FileWriter("[Link]");

[Link]("Hello world");

[Link]();

[Link]("Successfully wrote to the file.");

} catch (IOException e) {

[Link]("An error occurred.");

[Link]();

Output:
10. Write a program to implement a thread.
Code:

public class SimpleThread implements Runnable {

@Override

public void run() {

[Link]("Thread is running!");

public static void main(String[] args) {

SimpleThread myThread = new SimpleThread();

Thread thread = new Thread(myThread);

[Link]();

Output:

You might also like