0% found this document useful (0 votes)
11 views15 pages

Java Programming Practical Exercises

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)
11 views15 pages

Java Programming Practical Exercises

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

K.V.

R Shinde Shikshan Sanstha's

Shivraj College of Arts, Commerce and [Link] Science College,


Gadhinglaj. ([Link])
BCOM-IT (3rd Year)
Practical No :- 1 Date:-
Title :- Write a java program that test a number as input and print its multiplication table.

Program:
package practicall; import [Link].*;
public class Main
public static void main(String] args)
int a,i;
Scanner s-new Scanner([Link]);
[Link]("Enter Number="); a=[Link]();
for(i=1;i<=10;i++)
[Link]("" +(a*i);

Output:
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 2 Date:-
Title :- Write a java program that takes a year from the user and prints whether it is a leap
year or not.

Program:
package practical2;
import [Link].*;

public class Main {


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

if((year % 400 == 0) || (year % 4 == 0 && year % 100 !=


0)) {
[Link]("This is leap year");
} else {
[Link]("This is not a leap year");
}
}
}

Output:
Enter year: 2024
This is leap year
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 3 Date:-
Title :- Write a java program to take number from user and display whether it is an
Armstrong number.

Program:
package practical3;
import [Link].*;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
int original = num, sum = 0;

while(num > 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}

if(original == sum) {
[Link]("Armstrong number");
} else {
[Link]("Not an Armstrong number");
}
}
}

Output:
Enter a number: 153
Armstrong number
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 4 Date:-
Title :- Write a java program to display a right angle triangle pattern with numbers up to 10.

Program:
package practical4;

public class Main {


public static void main(String[] args) {
for(int i = 1; i <= 4; i++) {
for(int j = 1; j <= i; j++) {
[Link](j + " ");
}
[Link]();
}
}
}

Output:
1
1 2
1 2 3
1 2 3 4
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 5 Date:-
Title :- Write a java program to create a class called Book with instance variables title,
author and price. Implement different constructors.

Program:
package practical5;

class Book {
String title;
String author;
double price;

Book() {
title = "Unknown";
author = "Unknown";
price = 0.0;
}

Book(String t, String a) {
title = t;
author = a;
}

Book(String t, String a, double p) {


title = t;
author = a;
price = p;
}

void display() {
[Link]("Title: " + title + ", Author: " +
author + ", Price: " + price);
}
}

public class Main {


public static void main(String[] args) {
Book b1 = new Book();
Book b2 = new Book("Java Programming", "James Gosling");
Book b3 = new Book("OOP Concepts", "Bjarne Stroustrup",
450.50);

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

Output:
Title: Unknown, Author: Unknown, Price: 0.0
Title: Java Programming, Author: James Gosling, Price: 0.0
Title: OOP Concepts, Author: Bjarne Stroustrup, Price: 450.5
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 6 Date:-
Title :- Write a java program to create a class called Shape with a method getArea(). Create a
subclass Rectangle that overrides getArea().

Program:
package practical6;

class Shape {
double getArea() {
return 0.0;
}
}

class Rectangle extends Shape {


double length, width;

Rectangle(double l, double w) {
length = l;
width = w;
}

double getArea() {
return length * width;
}
}

public class Main {


public static void main(String[] args) {
Rectangle r = new Rectangle(5, 10);
[Link]("Area of Rectangle: " + [Link]());
}
}

Output:
Area of Rectangle: 50.0
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 7 Date:-
Title :- Write a java program to create a class BankAccount with deposit and withdraw
methods. Create a subclass SavingsAccount that prevents withdrawal beyond balance.

Program:
package practical7;

class BankAccount {
double balance;

void deposit(double amount) {


balance += amount;
[Link]("Deposited: " + amount);
}

void withdraw(double amount) {


balance -= amount;
[Link]("Withdrawn: " + amount);
}
}

class SavingsAccount extends BankAccount {


@Override
void withdraw(double amount) {
if(amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount);
} else {
[Link]("Insufficient balance!");
}
}
}

public class Main {


public static void main(String[] args) {
SavingsAccount sa = new SavingsAccount();
[Link](1000);
[Link](500);
[Link](600);
}
}

Output:
Deposited: 1000.0
Withdrawn: 500.0
Insufficient balance!
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 8 Date:-
Title :- Write a java program to create an interface Flyable with method fly(). Create 3
classes SpaceShuttle, Aeroplane, Helicopter that implement Flyable.

Program:
package practical8;

interface Flyable {
void fly();
}

class SpaceShuttle implements Flyable {


public void fly() {
[Link]("SpaceShuttle is flying to space.");
}
}

class Aeroplane implements Flyable {


public void fly() {
[Link]("Aeroplane is flying in the sky.");
}
}

class Helicopter implements Flyable {


public void fly() {
[Link]("Helicopter is hovering above
ground.");
}
}

public class Main {


public static void main(String[] args) {
Flyable f1 = new SpaceShuttle();
Flyable f2 = new Aeroplane();
Flyable f3 = new Helicopter();

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

Output:
SpaceShuttle is flying to space.
Aeroplane is flying in the sky.
Helicopter is hovering above ground.
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 9 Date:-
Title :- Write a java program to demonstrate method overloading.

Program:
package practical9;

class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](5, 10));
[Link]([Link](3.5, 2.5));
[Link]([Link](1, 2, 3));
}
}

Output:
15
6.0
6
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 10 Date:-
Title :- Write a java program to create a producer-consumer problem using wait() and
notify().

Program:
package practical10;

class Shared {
private int data;
private boolean available = false;

synchronized void produce(int value) {


while(available) {
try { wait(); } catch(Exception e) {}
}
data = value;
available = true;
[Link]("Produced: " + value);
notify();
}

synchronized int consume() {


while(!available) {
try { wait(); } catch(Exception e) {}
}
available = false;
[Link]("Consumed: " + data);
notify();
return data;
}
}

class Producer extends Thread {


Shared s;
Producer(Shared s) { this.s = s; }
public void run() {
for(int i=1; i<=5; i++) {
[Link](i);
}
}
}

class Consumer extends Thread {


Shared s;
Consumer(Shared s) { this.s = s; }
public void run() {
for(int i=1; i<=5; i++) {
[Link]();
}
}
}

public class Main {


public static void main(String[] args) {
Shared s = new Shared();
new Producer(s).start();
new Consumer(s).start();
}
}

Output:
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
K.V.R Shinde Shikshan Sanstha's
Shivraj College of Arts, Commerce and [Link] Science College,
Gadhinglaj. ([Link])

BCOM-IT (3rd Year)


Practical No :- 11 Date:-
Title :- Write a java program that reads a list of numbers from a file and throws an exception
if any number is negative.

Program:
package practical11;
import [Link].*;

public class Main {


public static void main(String[] args) {
int[] numbers = {10, 20, -5, 30};

try {
for(int num : numbers) {
if(num < 0) {
throw new Exception("Negative number found: "
+ num);
}
[Link](num);
}
} catch(Exception e) {
[Link]("Exception: " + [Link]());
}
}
}

Output:
10
20
Exception: Negative number found: -5

Common questions

Powered by AI

The Flyable interface demonstrates the principles of abstraction and contract-based design by defining a set method fly() that must be implemented by any class (e.g., SpaceShuttle, Aeroplane, Helicopter) that represents a flying entity. This promotes loose coupling and increases flexibility, allowing for different types of flying vehicles to be added without modifying the interface, thereby adhering to the Open/Closed Principle of software design .

Polymorphism via interfaces, such as the Flyable interface, allows different classes (SpaceShuttle, Aeroplane, Helicopter) to implement a common method fly() in their unique way, promoting loose coupling. In contrast, inheritance, as seen in BankAccount and its subclass SavingsAccount, allows method overriding while maintaining a direct parent-child relationship, implying a stronger coupling. Interfaces provide more flexibility by supporting multiple implementations that are not bound by inheritance hierarchies .

The producer-consumer problem is effectively addressed by using synchronized methods with wait() and notify() to manage access to shared resources. In the implementation, the Shared class alternates between producing and consuming actions, ensuring that a new item is not produced until the previous one is consumed, thus avoiding race conditions and ensuring data consistency. However, using wait() and notify() could lead to thread starvation if not managed carefully with additional control structures or handling mechanisms .

An Armstrong number is a number that equals the sum of its own digits each raised to the power of the number of digits. The program reads an integer, computes the sum of the cubes of its digits, and checks if the sum equals the original number. If true, it confirms the number as an Armstrong number; otherwise, it is not .

To create a Java program that tests if a year is a leap year, first use the Scanner class to obtain user input. Then, apply the leap year condition using if-else statements: check if the year is divisible by 400, or if it is divisible by 4 and not by 100. Print the corresponding result indicating whether the year is a leap year or not .

The Rectangle class overrides the getArea() method of the Shape class by providing a concrete implementation that calculates and returns the area based on its length and width. This allows for specialized behavior in subclasses, where specific calculations are required, thus leading to code reusability and refinement of general methods in base classes to cater to specific needs of derived classes .

Using nested for loops to print patterns, like a right angle triangle, offers simplicity and clarity in implementation by systematically varying parameters to achieve the desired output structure. However, nested loops can become increasingly complex and inefficient for larger patterns or more intricate outputs, potentially leading to readability issues and higher execution time due to increased iterations, thereby necessitating more optimized algorithms for extensive scaling .

Handling exceptions for negative numbers in a Java program enhances robustness and ensures data integrity by preventing invalid data from potentially corrupting computational logic. By throwing an exception upon detecting a negative number, the program can signal an error state and prompt corrective action, thereby maintaining the flow of execution while alerting users or developers to potential data issues .

Implementing constructors in a class like Book allows for initializing objects with default or specific values, enhancing code readability and maintainability. Constructors offer flexibility by allowing the instantiation of objects with varying initial states, thus facilitating higher modularity and adaptability in object-oriented programming by enabling different configurations through constructor overloading .

Method overloading enhances the flexibility of a Java class by allowing the same method name to perform different operations based on parameter types and numbers. For numerical operations in a class like Calculator, method overloading allows for handling both integers and doubles, as well as different numbers of arguments, enabling a more versatile and user-friendly code design .

You might also like