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

Java Programming Exercises and Solutions

Uploaded by

rohitkoslia509
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)
8 views21 pages

Java Programming Exercises and Solutions

Uploaded by

rohitkoslia509
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

Session: 2021-22

JAVA PROGRAMMING

Submitted To : - Submitted By:-


Miss Prachi Rohit Kumar

Assistant Professor (202046)

CSE Department
[Link]. PROGRAMS/TOPICS DATE SIGNATURE

1. Write a program to print whether the


given number is Armstrong or Not

2. Write a program to demonstrate method


overloading with different number of
parameters in argument list

3. Write a program to print prime number


between the given range

4. Write a program to facilitates the


multilevel inheritance

5. Try to implement the concept of


multiple inheritance with use of
Interfaces

6. Write a program that demonstrate use of


package and import statement

7. Write a program to demonstrate user


define exception

8. Write a program to implement the


concept of inter thread communication
producer consumer problem.
PROGRAM -1
Write a program to print whether the given number is Armstrong or
Not.

import [Link];

public class JavaExample {

public static void main(String[] args) {

int num, number, temp, total = 0;

[Link]("Ënter 3 Digit Number");

Scanner scanner = new Scanner([Link]);

num = [Link]();

[Link]();

number = num;

for( ;number!=0;number /= 10)

temp = number % 10;

total = total + temp*temp*temp;

if(total == num)

[Link](num + " is an Armstrong number");

else

[Link](num + " is not an Armstrong number");

}
PROGRAM-2
Write a program to demonstrate method overloading with different number of
parameters in argument list.
class MethodOverloading {
private static void display(int a){
[Link]("Arguments: " + a);
}

private static void display(int a, int b){


[Link]("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}
PROGRAM -3
Write a program to print prime number between the given range .
import [Link];
public class Prime
{
public static void main(String args[])
{
int s1, s2, s3, flag = 0, i, j;
Scanner s = new Scanner([Link]);
[Link] ("Enter the lower limit :");
s1 = [Link]();
[Link] ("Enter the upper limit :");
s2 = [Link]();
[Link] ("The prime numbers in between the entered limits are :");
for(i = s1; i <= s2; i++)
{
for( j = 2; j < i; j++)
{
if(i % j == 0)
{
flag = 0;
break;
}
else
flag = 1;
}
if(flag == 1)
{
[Link](i);
}
}
}}
PROGRAM-4
Write a program to facilitates the multilevel inheritance.
class Car{

public Car()

[Link]("Class Car");

public void vehicleType()

[Link]("Vehicle Type: Car");

class Maruti extends Car{

public Maruti()

[Link]("Class Maruti");

public void brand()

[Link]("Brand: Maruti");

public void speed()

[Link]("Max: 90Kmph");

public class Maruti800 extends Maruti{

public Maruti800()

[Link]("Maruti Model: 800");


}

public void speed()

[Link]("Max: 80Kmph");

public static void main(String args[])

Maruti800 obj=new Maruti800();

[Link]();

[Link]();

[Link]();

}
PROGRAM-5
Try to implement the concept of multiple inheritance with use of
Interfaces .
interface AnimalEat {

void eat();

interface AnimalTravel {

void travel();

class Animal implements AnimalEat, AnimalTravel {

public void eat() {

[Link]("Animal is eating");

public void travel() {

[Link]("Animal is travelling");

public class Demo {

public static void main(String args[]) {

Animal a = new Animal();

[Link]();

[Link]();

}
PROGRAM-6
Write a program that demonstrate use of package and import statement.
1).
package pack;
public class A{
public void add(int a,int b)
{
[Link](a+b);}
}
2).
package mypack;
Import pack.*;
Class B{
Public static void main(String args[])
{
[Link]=new a();
[Link](5,10);
}
}
PROGRAM-7
Write a program to demonstrate user define exception .
class MyException extends Exception {
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

// A Class that uses above MyException


public class Main {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException("rohit");
}
catch (MyException ex) {
[Link]("Caught");

// Print the message from MyException object


[Link]([Link]());
}
}
}
PROGRAM-8
Write a program to implement the concept of inter thread communication
producer consumer problem.
public class ProducerConsumer

public static void main(String[] args)

Shop c = new Shop();

Producer p1 = new Producer(c, 1);

Consumer c1 = new Consumer(c, 1);

[Link]();

[Link]();

class Shop

private int materials;

private boolean available = false;

public synchronized int get()

while (available == false)

try

wait();

catch (InterruptedException ie)

available = false;
notifyAll();

return materials;

public synchronized void put(int value)

while (available == true)

try

wait();

catch (InterruptedException ie)

[Link]();

materials = value;

available = true;

notifyAll();

class Consumer extends Thread

private Shop Shop;

private int number;

public Consumer(Shop c, int number)

Shop = c;

[Link] = number;

public void run() {


int value = 0;

for (int i = 0; i < 10; i++)

value = [Link]();

[Link]("Consumed value " + [Link]+ " got: " + value);

class Producer extends Thread

private Shop Shop;

private int number;

public Producer(Shop c, int number)

Shop = c;

[Link] = number;

public void run()

for (int i = 0; i < 10; i++)

[Link](i);

[Link]("Produced value " + [Link]+ " put: " + i);

try

sleep((int)([Link]() * 100));

catch (InterruptedException ie)

[Link]();

} }}}

Common questions

Powered by AI

A Java program determines whether a number is an Armstrong number by summing the cubes of its digits and comparing the result to the original number. The modulus operator is used to extract the last digit of the number in each step, ensuring that each digit is processed separately. This is demonstrated in Source 1, where the modulus operator aids in isolating the digits for cube calculations, pivotal for the algorithm to compare this summed result with the original number .

Method overloading in Java allows a class to have multiple methods with the same name but different parameter lists. This enhances Java's capability by enabling methods to handle different types and quantities of inputs without requiring separate method names, providing a cleaner and more intuitive API. For example, in Source 1, the 'display' method is overloaded with one version accepting a single integer and another accepting two integers, demonstrating how overloading manages varying argument lists without confusion or redundancy .

User-defined exceptions in Java allow developers to create custom exceptions tailored to specific conditions. This is significant because it enhances error handling by allowing the generation of meaningful error messages that better describe the cause of the problem compared to standard exceptions. In Source 2, a custom exception class 'MyException' extends the Exception class and is utilized in a try-catch block, demonstrating how custom messages like 'rohit' are handled when exceptions are thrown and caught .

Inheritance allows subclasses to inherit methods and fields from a parent, facilitating the reuse and extension of functionalities. Method overriding is when a subclass modifies a method declared in a parent class to provide specific behavior. In the Maruti800 class hierarchy from Source 1, Maruti800 inherits a 'speed' method from 'Maruti', but overrides it to change the output, demonstrating polymorphism. This allows objects of Maruti800 to respond differently to 'speed' calls than generic 'Maruti' objects, enhancing customizability .

Inter-thread communication in Java, as described, involves coordinating actions between threads using shared objects and synchronizing access to these objects. The wait() method is used by a thread to release the lock it holds on the monitor, allowing other threads a chance to acquire it. notifyAll() prompts all threads waiting on the monitor to wake up and compete for the lock. This is essential for resolving synchronization issues and preventing deadlocks, as seen in Source 2 where 'Shop' manages resource availability, preventing erroneous operations during production and consumption .

Java does not support multiple inheritance through classes to avoid complexity and ambiguity. Instead, it uses interfaces to achieve similar functionality. An interface can be implemented by multiple classes, allowing a class to inherit abstract functionalities from multiple sources. In Source 2, the 'Animal' class implements two interfaces, 'AnimalEat' and 'AnimalTravel', thereby adopting methods from both, thus simulating multiple inheritance and allowing 'Animal' to inherit and define 'eat' and 'travel' methods .

Multilevel inheritance in Java is represented by a class hierarchy where a class is derived from another derived class. For example, in Source 1, 'Maruti800' inherits from 'Maruti', which in turn inherits from 'Car'. This forms a chain of inheritance where 'Maruti800' indirectly inherits 'Car's features, demonstrating practical implications such as inheriting vehicle types and brand attributes across different levels, promoting code reusability and logical hierarchy in applications .

Packages and import statements in Java are used for organizing classes into namespaces, preventing naming conflicts, and enhancing reusability and maintainability of code. Packages create a structured directory layout that separates class functionalities and allows access control. Source 2 illustrates this with 'pack' and 'mypack' packages; importing 'pack.*' into 'mypack' allows class 'B' to utilize class 'A's methods, promoting modularity and clarity in code .

The producer-consumer problem is addressed in Java by using synchronized methods and inter-thread communication mechanisms like wait() and notifyAll(). Synchronization ensures that the 'Shop' object's state (e.g., whether items are available or being consumed) is managed consistently across threads, preventing data corruption and race conditions. In Source 2, 'Producer' and 'Consumer' threads synchronize on a 'Shop' object to coordinate production and consumption, using wait() to pause threads when conditions are not met and notifyAll() to resume them, thus maintaining thread-safe operation .

Handling both checked and unchecked exceptions is crucial in Java to create reliable applications that can gracefully handle runtime anomalies and obligatory conditions known at compile time. Checked exceptions force the programmer to either handle errors, whereas unchecked exceptions indicate programming errors. This distinction ensures comprehensive error management where conditions like I/O failures are explicitly managed while programming bugs like null pointers are corrected. Source 2 exemplifies this by demonstrating user-defined exceptions which emphasize handling conditions anticipated by the application logic .

You might also like