[Go to site: main page, start]

0% found this document useful (0 votes)
9 views29 pages

Simple Java Programs For Practice

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)
9 views29 pages

Simple Java Programs For Practice

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

1.

Write a very simple Java program with a Car class and a method that prints the brand
and year

class Car {

String brand;

int year;

// Method to print details

void printDetails() {

[Link]("Brand: " + brand);

[Link]("Year: " + year);

public class Main {

public static void main(String[] args) {

Car myCar = new Car();

[Link] = "Honda";

[Link] = 2022;

[Link](); // Calling the method

}
2. Write a simple Java program that models a BankAccount with private data members
(beneficiaryName, accountNumber, balance) and deposit/withdraw methods.

class BankAccount {

// Private data (encapsulation)

private String beneficiaryName;

private String accountNumber;

private double balance;

// Constructor

public BankAccount(String beneficiaryName, String accountNumber, double


openingBalance) {

[Link] = beneficiaryName;

[Link] = accountNumber;

[Link] = openingBalance;

// Deposit money

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

// Withdraw money (simple check)

public void withdraw(double amount) {

if (amount > 0 && amount <= balance) {

balance -= amount;

// Print account details


public void printDetails() {

[Link]("Beneficiary: " + beneficiaryName);

[Link]("Account No.: " + accountNumber);

[Link]("Balance: " + balance);

public class Main {

public static void main(String[] args) {

BankAccount a = new BankAccount("Rahul Sharma", "SB-00123", 1000.0);

[Link]();

[Link]("---");

[Link](500); // balance: 1500

[Link](300); // balance: 1200

[Link](2000); // ignored (not enough balance)

[Link]();

}
3. Write a program to input the radius and height of a cylinder and find its volume and
total surface area.

import [Link];

public class Cylinder {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter radius: ");

double r = [Link]();

[Link]("Enter height: ");

double h = [Link]();

double volume = [Link] * r * r * h;

double tsa = 2 * [Link] * r * (r + h);

[Link]("Volume of Cylinder: " + volume);

[Link]("Total Surface Area: " + tsa);

}
4. Write a program to input a floating point number and round it off to the nearest integer.
Do not use math function

import [Link];

public class RoundOff {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter a floating number: ");


double num = [Link]();

int rounded = (int)(num + 0.5);

[Link]("Rounded value: " + rounded);


}
}
5. Write a program to input a floating point number and round it off to two places of
decimal.

import [Link];

public class RoundTwo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter a floating number: ");


double num = [Link]();

double result = (int)(num * 100 + 0.5) / 100.0;

[Link]("Rounded to 2 decimals: " + result);


}
}
6. Write a program to input three integers and print the largest and the smallest number
using [Link]( ) and [Link]( ) function.

import [Link];

public class LargestSmallest {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter three integers: ");


int a = [Link]();
int b = [Link]();
int c = [Link]();

int largest = [Link](a, [Link](b, c));


int smallest = [Link](a, [Link](b, c));

[Link]("Largest: " + largest);


[Link]("Smallest: " + smallest);
}
}
7. A cloth showroom has announced the following festival discounts on the purchase of
items, based on the total cost of the items purchased:
Total Cost Discount (in Percentage)
Less than ₹ 2000 5%
₹ 2001 to ₹ 5000 25%
₹ 5001 to ₹ 10000 35%
Above ₹ 10000 50%
Write a program to input the total cost and compute and display the amount to be paid
by the customer after availing the discount.

import [Link];

public class FestivalDiscountSlab {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter total cost: ");

double cost = [Link]();

double discount=0;

double amounttopay;

if (cost<=2000)

discount = 0.05*cost;

}else if(cost<=5000){

discount = 0.05*2000+0.25*(cost-2000);

}else if(cost<=10000){

discount = 0.05*2000+0.25*3000+0.35*(cost-5000);

}else{

discount = 0.05*2000+0.25*3000+0.35*5000+0.5*(cost-10000);

amounttopay=cost-discount;

[Link]("Amount to pay is "+ amounttopay);

}
}
8. Write a program to input an integer and check whether it is a 5-digit number or not. If it
is extract the central digit and print it.
Example
INPUT: Enter an integer: 76549
OUTPUT: Central digit: 5

import [Link];

public class FiveDigitCentral {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter an integer: ");


int n = [Link]();
int m = [Link](n);

if (m >= 10000 && m <= 99999) {


int central = (m / 100) % 10; // ABCDE → (ABCDE/100)=ABC → ABC%10=C
[Link]("Central digit: " + central);
} else {
[Link]("Not a 5-digit number");
}
}
}
9. A special two-digit number is such that when the sum of its digits is added to the
product of its digits, the result is equal to the original two-digit number.
Example:
Consider the number 59.
Sum of digits= 5 + 9 = 14
Product of its digits = 5 x 9 =45
Sum of the sum of digits and product of digits = 14 + 45 = 59
Write a program to accept a two-digit number. Add the sum of its digits to the product
of its digits. If the value is equal to the number input, output the message “Special 2-
digit number” otherwise, output the message “Not a special 2-digit number”.

import [Link];

public class SpecialTwoDigit {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter a two-digit number: ");


int n = [Link]();

if (n >= 10 && n <= 99) {


int tens = n / 10;
int % 10;
int sum = tens + ones;
int prod = tens * ones;

if (sum + prod == n) {
[Link]("Special 2-digit number");
} else {
[Link]("Not a special 2-digit number");
}
} else {
[Link]("Not a two-digit number");
}
}
}
10. The 1st day of 2010 was Friday, write a program to input any day number within the
month of January and print which day was it. Also check whether the day number
entered is a valid date or not.

import [Link];

public class Jan2010DaySwitch {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter day number of January 2010 (1-31): ");


int d = [Link]();

if (d < 1 || d > 31) {


[Link]("Invalid date");
return;
}

int offset = (d - 1) % 7; // 0 -> Friday, 1 -> Saturday, ... 6 -> Thursday

switch (offset) {
case 0:
[Link]("It was: Friday");
break;
case 1:
[Link]("It was: Saturday");
break;
case 2:
[Link]("It was: Sunday");
break;
case 3:
[Link]("It was: Monday");
break;
case 4:
[Link]("It was: Tuesday");
break;
case 5:
[Link]("It was: Wednesday");
break;
case 6:
[Link]("It was: Thursday");
break;
default:
// This will never occur because offset is 0..6
[Link]("Error computing day");
}
}
}
11. Write a program to input the length of the 3 sides of a triangle (say a, b and c) and
calculate the area depending upon the following criteria. Use switch case:
i. If the sum of any two sides of the triangle is lesser than the third side then print “A
triangle cannot be formed”
ii. If a=b=c then print “It is an equilateral triangle” and calculate the area using
equilateral triangle formula
iii. If the sum of the squares of any two sides is equal to the square of the third side
then print “It is a right-angled triangle” and calculate the area following the formula
iv. otherwise calculate area using formula for scalene triangle

import [Link];

public class TriangleAreaSwitch {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

double a, b, c;

[Link]("Enter side a: ");

a = [Link]();

[Link]("Enter side b: ");

b = [Link]();

[Link]("Enter side c: ");

c = [Link]();

int typeCode = 0;

// 0 = cannot form triangle

// 1 = equilateral

// 2 = right-angled

// 3 = other/scalene/isosceles

// --- VALIDITY CHECK ---

if (a + b <= c || a + c <= b || b + c <= a || a <= 0 || b <= 0 || c <= 0) {

typeCode = 0;

}
else if (a == b && b == c) {

typeCode = 1; // equilateral

else {

// --- CHECK RIGHT-ANGLED USING [Link]() ---

double largest = [Link](a, [Link](b, c));

double x = 0, y = 0;

// Identify the other two sides

if (largest == a) {

x = b; y = c;

} else if (largest == b) {

x = a; y = c;

} else {

x = a; y = b;

// Pythagoras check

if ((x*x + y*y - largest*largest) ==0) {

typeCode = 2; // right-angled

} else {

typeCode = 3; // scalene or isosceles (non-right)

// --- SWITCH FOR AREA ---

switch (typeCode) {

case 0:

[Link]("A triangle cannot be formed");

break;
case 1:

[Link]("It is an equilateral triangle");

double area1 = ([Link](3) / 4.0) * a * a;

[Link]("Area = " + area1);

break;

case 2:

[Link]("It is a right-angled triangle");

// Compute area using half × product of legs

double largest = [Link](a, [Link](b, c));

double x = 0, y = 0;

if (largest == a) {

x = b; y = c;

} else if (largest == b) {

x = a; y = c;

} else {

x = a; y = b;

double area2 = 0.5 * x * y;

[Link]("Area = " + area2);

break;

case 3:

[Link]("Scalene/other valid triangle");

double s = (a + b + c) / 2.0;

double area3 = [Link](s * (s - a) * (s - b) * (s - c));

[Link]("Area = " + area3);


break;

}
12. Write a program to input an integer and print its factors.

import [Link];

public class Factors {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter an integer: ");

int n = [Link]();

[Link]("Factors of " + n + " are:");

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

if (n % i == 0) {

[Link](i + " ");

}
13. Write programs to find the sum of each of the following series:
i. s=1*2+2*3+3*4+…+9*10
ii. s=1*2+3*4+5*6+…+9*10
iii. s = 1 + ½ + 1/3 + ¼ …

iv.

i.

public class SeriesSum {

public static void main(String[] args) {

int sum = 0;

for (int i = 1; i <= 9; i++) {

sum = sum + (i * (i + 1));

[Link]("Sum = " + sum);

ii.

public class Series2 {

public static void main(String[] args) {

int sum = 0;

for (int i = 1; i <= 9; i += 2) {

sum = sum + (i * (i + 1));

[Link]("Sum = " + sum);

}
}

iii.

import [Link];

public class Series3 {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter number of terms: ");

int n = [Link]();

double sum = 0.0;

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

sum = sum + (1.0 / i);

[Link]("Sum = " + sum);

}
14. Write a program to input an integer and remove all the even digits from it.
For Example,
INPUT: Enter an integer: 1234
OUPUT: 13

import [Link];

public class removeeven {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter the number");

int n = [Link]();

int newn=0;

int i=0;

while(n>0){

if((n%10)%2!=0){

newn=newn+(int)([Link](10,i))*(n%10);

i++;

n=n/10;

[Link](newn);

15. Write a program to input two integers and find their Least Common Multiple(L.C.M).
For Example,
INPUT: Enter 2 integers:
12
8
OUTPUT: L.C.M. = 24
import [Link];

public class LCM {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter 2 integers:");
int a = [Link]();
int b = [Link]();

int hcf = 1;
int min = (a < b) ? a : b;

// Find HCF using simple loop


for (int i = 1; i <= min; i++) {
if (a % i == 0 && b % i == 0) {
hcf = i;
}
}

int lcm = (a * b) / hcf;

[Link]("L.C.M. = " + lcm);


}
}

iv.

import [Link];

public class SeriesX {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter value of x: ");


double x = [Link]();

[Link]("Enter value of n: ");


int n = [Link]();

double sum = 0;
double term;

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


term = ([Link](x, i) / i)*([Link](-1,i+1));
sum=sum+term;
}

[Link]("Sum of series = " + sum);


}
}

16. Write a program to input two integers and find their Highest Common Factor(H.C.F).
For Example,
INPUT: Enter 2 integers:
12
8
OUTPUT: H.C.F. = 4

import [Link];

public class HCF {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter 2 integers:");

int a = [Link]();

int b = [Link]();

int hcf = 1;

int min = (a < b) ? a : b; // find smaller number

for (int i = 1; i <= min; i++) {

if (a % i == 0 && b % i == 0) {

hcf = i;

[Link]("H.C.F. = " + hcf);

}
17. A game of dice is to be simulated for two players, each player gets a chance to throw
his dice, the player who throws 6 wins. Create this as a program.

import [Link];

public class DiceGame {

public static void main(String[] args) {

while(true){

// Player 1 throws the dice

int p1 = (int)([Link]() * 6) + 1; // generates 1 to 6

[Link]("Player 1 rolls: " + p1);

// Player 2 throws the dice

int p2 = (int)([Link]() * 6) + 1; // generates 1 to 6

[Link]("Player 2 rolls: " + p2);

// Decide the winner

if (p1 == 6 && p2 == 6) {

[Link]("Both rolled 6 — It's a tie!");

break;

else if (p1 == 6) {

[Link]("Player 1 wins!");

break;

else if (p2 == 6) {

[Link]("Player 2 wins!");

break;

else {
[Link]("No one rolled 6 — No winner! Try again");

18. Input an integer and check whether it is a special number or not. A special number is
such a number whose sum of the factorials of each digit is the number itself. For
example, 145 is a special number because 1! + 4! + 5! = 1 + 24 +120 = 145. Special
numbers are also called factorion.

import [Link];

public class SpecialNumber {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter an integer: ");

int n = [Link]();

int x = n; // store original number

int sum = 0;

// Compute sum of factorial of each digit

while (x > 0) {

int d = x % 10;

// factorial of digit d

int fact = 1;

for (int i = 1; i <= d; i++) {

fact = fact * i;

}
sum = sum + fact;

x /= 10;

// Check for special number

if (sum == n) {

[Link]("Special number");

} else {

[Link]("Not a special number");

19. Create the following:

public class Pattern {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

// Print leading spaces

for (int s = 1; s < i; s++) {

[Link](" "); // two spaces for alignment

}
// Print numbers from i to 5

for (int j = i; j <= 5; j++) {

[Link](j + " ");

[Link]();

public class VShape {

public static void main(String[] args) {

int n = 5; // height of the V

for(int j=1;j<=n;j++){

for(int i = 1;i<=(2*n-1);i++){

if(i==j || i==(2*n-1-j+1))

[Link]("*");

else

[Link](" ");

[Link]();

}
20. Write a menu driven class to accept a number from the user and check whether it is a
Palindrome or a Perfect number. Palindrome number- (a number is a Palindrome which
when read in reverse order is same as read in the right order) Example: 11, 101, 151, etc.
Perfect number- (a number is called Perfect if it is equal to the sum of its factors other
than the number itself.) Example: 6=1+2+3

import [Link];

public class NumberMenuNoFunc {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

while (true) {

[Link]("\n=== Number Checker Menu ===");

[Link]("1. Check Palindrome");

[Link]("2. Check Perfect");

[Link]("3. Exit");

[Link]("Enter your choice (1-3): ");

int choice = [Link]();

if (choice == 3) {

[Link]("Exiting... Goodbye!");

break;

if (choice != 1 && choice != 2) {

[Link]("Invalid choice. Try again.");

continue;

[Link]("Enter an integer: ");

int n = [Link]();
switch (choice) {

case 1: {

// ----- PALINDROME CHECK -----

if (n < 0) {

[Link]("Not a Palindrome number");

break;

int x = n;

int rev = 0;

while (x > 0) {

rev = rev * 10 + (x % 10);

x /= 10;

if (rev == n) {

[Link]("Palindrome number");

} else {

[Link]("Not a Palindrome number");

break;

case 2: {

// ----- PERFECT NUMBER CHECK -----

if (n <= 1) {

[Link]("Not a Perfect number");

break;

int sum = 1; // 1 is a proper divisor of any n>1

// Sum all proper divisors up to n/2

for (int i = 2; i <= n / 2; i++) {


if (n % i == 0) {

sum += i;

if (sum == n) {

[Link]("Perfect number");

} else {

[Link]("Not a Perfect number");

break;

You might also like