Java Programs LAB SESSION
Java Programs LAB SESSION
PROGRAMS-----------------------------------------------------
Q1.A shopkeeper buys a TV set for Rs. 32,500 and sells it at a profit of 27%.
Apart from this a VAT of 12.7% and Service Charge is 3.87% is charged.
Display total selling price, profit along with vat and service charge.
Output:
Cost Price: Rs. 32500.0
Profit: Rs. 8775.0
VAT: Rs. 5241.925
Service Charge: Rs. 1597.3425
Total Selling Price: Rs. 48114.2675
ANS :
public class TVSetProfitCalculator {
public static void main(String[] args) {
double costprice=32500.0;
double profitp=27.0;
double vatp=12.7;
double servicep=3.87;
double profit=(profitp/100)*costprice;
double sellingprice=costprice-profit;
double vat=(vatp/100)*sellingprice;
double servicecharge=(servicep/100)*sellingprice;
double total=sellingprice+vat+servicecharge;
ANS :
public class CycleSellingPriceCalculator {
public static void main(String[] args) {
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q3.Write a program to find the sum and average of three numbers where numbers must
be taken from command line argument.
Save the code to a file named SumAndAverageCalculator.java.
Open your command prompt or terminal and navigate to the directory where you saved
the file.
Compile the program using the javac command: javac SumAndAverageCalculator.java
Run the program with three numbers as command-line arguments:
Example 1:
Input:
java SumAndAverageCalculator 3.0 2.2 4.3
Output:
Sum of the three numbers: 9.5
Average of the three numbers: 3.1666666666666665
Example 2:
Input:
java SumAndAverageCalculator 3 1
Output:
Usage: java SumAndAverageCalculator <num1> <num2> <num3>
ANS :
public class SumAndAverageCalculator {
public static void main(String[] args) {
// Find arguments size. If it is not equal to 3 then print "Usage: java
SumAndAverageCalculator //<num1> <num2> <num3>" error message and exit from
the program.
double sum=num1+num2+num3;
// Calculate the average
double avg=sum/3;
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q4.Write a program to interchange the value of two numbers without using the third
variable where number must be taken from command line argument.
Write the program and Save the code to a file named
SwapNumbersWithoutTempVariable.java
Open your command prompt or terminal and navigate to the directory where you saved
the file.
Compile the program using the javac command: javac
SwapNumbersWithoutTempVariable.java
Run the program with two numbers as command-line arguments:
Example 1:
Input:
java SwapNumbersWithoutTempVariable 6 7
Output:
Original Values: num1 = 6, num2 = 7
Swapped Values: num1 = 7, num2 = 6
Example 2:
Input:
java SwapNumbersWithoutTempVariable 3
Output:
Usage: java SwapNumbersWithoutTempVariable <num1> <num2>
ANS :
public class SwapNumbersWithoutTempVariable {
public static void main(String[] args) {
ANS :
public class TaxCalculator {
public static void main(String[] args) {
// Define the taxable income
double taxableincome=990000.00;
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q6.Write a java program to calculate the curved surface area of a
cube?
Formula-6*side Square.
Output:
Enter the length of one side of the cube: 6
The surface area of the cube is: 216.0
ANS :
import java.util.Scanner;
public class CubeSurfaceArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of one side of the cube: ");
double side = scanner.nextDouble();
double surfaceArea = 6 * Math.pow(side, 2);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q7.write a java program to calculate the total surface area of a
cylinder?
Formula- Area = A=2πrh+2πr2 (take the π(pi) = 3.14).
r=Radius
h=Height
output:
Enter the radius of the cylinder: 5
Enter the height of the cylinder: 4
The total surface area of the cylinder is: 282.7433388230814
ANS :
import java.util.Scanner;
double pi=3.14;
double Area=pi*radius*radius;
double larea=2*pi*radius*height;
double totalarea=2*Area+larea;
ANS :
import java.util.Scanner;
double totalamount=Amount*((1+rate/100)*(1+rate/100)*(1+rate/100));
double CompoundIntrest=totalamount-Amount;
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q9.You're tasked with developing a Java program to manage student information.
To achieve this, you need to create a program that allows users to input a
student's name,
roll number, and marks for 5 subjects as command line arguments. The program
should then calculate
and display the student's average mark with the student name and roll number.
Output :
--------------
Student Details:
Name: Virat
Roll Number: 12345
Marks:
Subject 1: 90.5
Subject 2: 85.0
Subject 3: 78.5
Subject 4: 92.0
Subject 5: 88.5
Average Mark: 86.7
ANS :
public class MyProgram
{
public static void main(String[] args)
{
String name = args[0];
int roll = Integer.parseInt(args[1]);
float s1 = Float.parseFloat(args[2]);
float s2 = Float.parseFloat(args[3]);
float s3 = Float.parseFloat(args[4]);
float s4 = Float.parseFloat(args[5]);
float s5 = Float.parseFloat(args[6]);
calculateMarks(name,roll,s1,s2,s3,s4,s5);
}
public static void calculateMarks(String name,int roll,float s1,float s2,float
s3,float s4,float s5){
System.out.println("Student Details");
double avg = (s1+s2+s3+s4+s5)/5;
System.out.println("Student Name :"+name);
System.out.println("Student Roll :"+roll);
System.out.println("Marks :");
System.out.println("Subject 1 :"+s1);
System.out.println("Subject 2 :"+s2);
System.out.println("Subject 3 :"+s3);
System.out.println("Subject 4 :"+s4);
System.out.println("Subject 5 :"+s5);
System.out.println("Average Mark:"+avg);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q10.Create a java program for a bakery shop that takes user input for an item's
name,
quantity, and price, calculates the total cost, and then generates an invoice?
The program should welcome the user, collect this information, display the invoice
with the item details,
quantity, price per item, and the total cost, and finally thank the user for
shopping at the bakery shop.
------ Invoice ------
Item: Croissant
Quantity: 3
Price per item: Rs.2.50
Total cost: Rs.7.50
Thank you for shopping at My Bakery Shop! Have a nice day!
ANS :
public class MyProgram
{
public static void main(String[] args)
{
String item=args[0];
int quantity=Integer.parseInt(args[1]);
double price=Double.parseDouble(args[2]);
cost(item,quantity,price);
}
public static void cost (String item,int quantity,double price)
{
double total=quantity*price;
System.out.println("item :"+item);
System.out.println("Quantity :"+quantity);
System.out.println("Price per item :"+price);
System.out.println("Total Cost :"+total);
System.out.println("Thank you for shopping at My Bakery Shop!Have a nice
Day");
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q11.Write a java program to initialise two integers (Ex: a=10, b=15) and display
following details
1) addition of two integers
2) Subtraction of two integers
3) Multiplication of two integers
ANS :
public class MyProgram
{
public static void main(String[] args)
{
int a=8,b=4;
int add=a+b;
int sub=a-b;
int mul=a*b;
System.out.println("Addition is :"+add);
System.out.println("Subtraction is:"+sub);
System.out.println("multiplication is:"+mul);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q12.WAP in java to read a person age from command line and validate whether that
person is eligible for voting or not?
if age is greater than 18 then print "Eligible for voting".
else print "Not Eligible for voting".
ANS :
import java.util.Scanner;
public class MyProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ANS :
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
{
int max=0;
Scanner sc1 = new Scanner(System.in);
System.out.print("Enter your first number : ");
int a=sc1.nextInt();
System.out.print("enter your second number : ");
int b=sc1.nextInt();
if(a > 0 && b > 0)
{
if(a > b)max=a;
else max=b;
System.out.println("max = "+max);;
if(a%2==0)System.out.println("a = even");
else System.out.println("a = odd");
if(b%2==0)System.out.println("b = even");
else System.out.println("b is odd");
}
else System.out.println("negative number are not allowed");
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q14.Telangana Electricity Board charges from their consumers according to the units
consumed per month.
The amount to be paid is calculated as per given below:
Units Charges
upto 200 units Rs. 3.50 per unit
next 300 units Rs. 5.50 per unit
next 400 units Rs 6.00 per unit
more than 600 units Rs. 8.00 per unit
Design a class 'Customer' with a parameterised method to input the customer details
such as
Customer’s name, mobile no and amount of units consumed.
Design another class ‘BillCollector’ to receive the consumer details and call the
method
declared in Customer by passing the consumer details to generate the detailed bill.
[Use Command Line Argument to take the input]
Input:
Customer Name: Naresh
Customer Number: 9898989898
Customer Consumed Units: 429
Output:
Customer Name: Naresh
Customer Number: 9898989898
Customer Consumed Units: 429
Electricity Bill: 2082
ANS :
class Customer
{
public static void generateBill(String customerName,int customerNo,int
unitConsumed)
{
double bill = 0;
if (unitConsumed <=200)
{
bill=unitConsumed*3.50;
}
else if (unitConsumed <=300)
{
bill=unitConsumed*5.50;
}
else if (unitConsumed <=400)
{
bill=unitConsumed*6.00;
}
else
{
bill=unitConsumed*8.00;
}
System.out.println("Customer Name : "+customerName);
System.out.println("Customer Number : "+customerNo);
System.out.println("Customer Consumed units : "+unitConsumed);
}
}
public class MyProgram {
public static void main(String[] args)
{
String name = args[0];
int mobno = Integer.parseInt(args[1]);
int ConsumedUnits=Integer.parseInt(args[2]);
Customer.generateBill(name,mobno,ConsumedUnits);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q15.Punjab National Bank, Ameerpet declares new rate of interest on Saving Deposit
Interest Rate for their customers as given table:
Term Rate of Interest
Saving Fund Account Balance below 10 Lakhs 2.75%
Saving Fund Account Balance 10 Lakhs to 1 cr 2.90%
Saving Fund Account Balance more than 1cr to 10 cr 3.25%
Saving Fund Account Balance more than 10 cr 3.50%
The bank offers an extra 0.5% of Rate of Interest for senior citizens as compared
to the general citizens.
Design a class Bank with a method to receive the name, age, amount, time-period of
deposit for a customer.
Calculate and display the details for the customer with readable messages.
Design another class ‘PNB’ to call the method of Bank by passing the required
number of arguments,
order of arguments and type of arguments to generate the output from method.
[By using Command Line Argument]
Example 1:
Input:
Customer Name: Ramesh
Customer Age: 66
Customer amount: 20 Lakhs
Time period: 12 months
Output:
Customer Name: Ramesh
Customer Age: 66
Customer amount: 20 Lakhs
Time period: 12 months
ANS :
public class Bank
{
public static void customerDetails(String name, double amount, int age,int
time)
{
System.out.println("Customer name : "+name);
System.out.println("Customer age : "+age);
System.out.println("customer amount : "+amount);
System.out.println("time : "+time);
double intrest=0;
if (amount < 1000000)
{
intrest=amount*.0275;
}
else if ( amount <= 10000000 )
{
intrest=amount*.0290;
}
else if (amount <= 100000000)
{
intrest = amount*.0325;
}
else
{
intrest =amount*.0350;
}
if(age > 60)
{
intrest = intrest+(amount*.005);
}
System.out.println("savings account total intrest for time period of 12
months is ="+intrest);
}
}
class PNB {
public static void main (String [] args){
String name = args[0];
double amount = Double.parseDouble(args[1]);
int age=Integer.parseInt(args[2]);
int time=Integer.parseInt(args[3]);
Bank.customerDetails(name,amount,age,time);
}
}
Savings account total interest for the time period 12 months = 68000.
-----------------------------------------------------------------------------------
-----------------------------------------------
Q16.WAP to input three numbers and display them either in ascending order or
descending order as per the user’s choice.
If user passes 1 then display numbers in ascending order else display numbers in
descending order.
If user enters any other number than 1 and 2 then display an
Error message “Invalid Input. Try Again.
”(Use classes and methods as per your requirement)
[Use Command Line Argument to take the input]
Input:
Enter number 1: 23
Enter number 2: 34
Enter number 3: 16
Enter 1 for ascending 2 for descending: 2
Output:
Descending order of given numbers are: [34, 23, 16]
ANS :
import java.util.Arrays;
int o = Integer.parseInt(args[3]);
if (o != 1 && o != 2) {
System.out.println("Invalid Input. Try Again.");
return;
}
if (o == 1) {
ascendingOrder(numbers);
} else {
descendingOrder(numbers);
}
}
public static void ascendingOrder(int[] arr) {
Arrays.sort(arr);
System.out.println("Ascending order of given numbers are: " +
Arrays.toString(arr));
}
ANS :
public class NivenNumber
{
public static void main(String[] args)
{
int num=Integer.parseInt(args[0]);
check(num);
}
public static void check(int n)
{
int sum=0;
int t=n;
while(n!=0)
{
sum+=n%10;
n/=10;
}
if(t%sum==0)
{
System.out.println("it is a Niven Number");
}
else
{
System.out.println("it is not a Niven Number");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q18.WAP to design a method which accepts a number and check whether the
number is a perfect number or not.
Hint: A number is said to be perfect if the sum of the factors
is the same as the original number.
e.g: 6 is a perfect square
Factors of 6: 1,2,3 Sum is: 1+2+3=6
ANS :
public class MyProgram
{
public Static void main(String[] args)
{
int num=Integer.parseInt(args[0]);
check(num);
}
public static void check(int n)
{
int facsum=0;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
facsum+=i;
}
}
if(facsum==n)
{
System.out.print("it is a perfect number");
}
else
{
System.out.print("it is not a perfect number");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q19.WAP to design a method which takes a number as input and checK
whether the number is 'Neon' or not.
Hint: A number is said to be Neon if the sum of digits of the square
of the number is equal to the same number.
e.g: 9
Square: 9*9 = 81
Sum of digits of square : 8+1=9
ANS :
public class MyProgram
{
public static void main(String[] args)
{
int num=Integer.parseInt(args[0]);
check(num);
}
public static void check(int n)
{
int s=n*n;
int t=s;
int sum=0;
while(s!=0)
{
sum+=s%10;
s/=10;
}
if (n == sum)
{
System.out.println("it is a neon number");
}
else
{
System.out.println("it is not a neon number");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q20.After becoming the CM of Telangana, the new government has planned to
start digital services on buses where an application is required in which
the fare from each passenger is based on the distance travelled as per
the given tariff:
Distance Charges
1st 5 km Rs.30
Next 10 km Rs.20/km
More than 15km Rs.15/km
The application interface is such that as the passenger enters the bus,
the application prompts "Enter the distance you need to travel" and
"Enter the location name".At the end of the journey, the application
displays the following output in console:
1. number of passengers entered into bus
2. total fare received in the end of journey.
ANS :
public class MyProgram {
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: java MyProgram <passenger> <distance>
<location>");
return;
}
int charge;
if (d <= 5) {
charge = d * 30;
} else if (d <= 10) {
charge = 5 * 30 + (d - 5) * 20;
} else {
charge = 5 * 30 + 5 * 20 + (d - 10) * 15;
}
return fare;
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q21.WAP to design a method which generates a Floyd's Triangle:
1
2 3
4 5 6
7 8 9 10
11 12 13 12 15
ANS :
public class MyProgram {
public static void main(String[] args) {
int rows = 5; // Number of rows in the Floyd's Triangle
FloydTriangle(rows);
}
ANS :
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
{
double inputNumber = getInputNumber();
getRoundedValue(inputNumber);
squareRoot(inputNumber);
roundedValue(inputNumber);
}
public static double getInputNumber()
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Number :");
return scanner.nextDouble();
}
public static void getRoundedValue(double num)
{
double roundedValue = Math.round(num);
System.out.println("Rounded Value : "+roundedValue);
}
public static void squareRoot(double num)
{
double squareRoot= Math.sqrt(num);
System.out.println("Square Root : "+squareRoot);
}
public static void roundedValue(double num)
{
double roundedValue= Math.round(num);
System.out.print("Rounded down Value : "+roundedValue);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q23. WAP to input two integers and one character. The character must be any of
the arithmetical operator.
If not then display message “Invalid Arithmetic Operator”. If the character is an
arithmetic operator then perform its corresponding operation on the two integers
taken as input. And display readable message
ANS :
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number : ");
int num1=scanner.nextInt();
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q24.WAP to input a character and display whether it is a digit or whitespace.
WAP to input a character and display whether it is a vowel,special character or a
consonant
ANS :
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
switch(c)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : System.out.print("it s a vowel");break;
default : System.out.print("it is a consonant");
}
if (Character.isDigit(c) || Character.isWhitespace(c))
{
System.out.print("Entered character is not a letter");
}
else
{
System.out.print("Entered character is a special character");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q25.WAP to input the price and quantity of a product.
Calculate the total cost, discount 10% if the total is more than Rs.1200 otherwise
discount 5%.
Also find the total price to be paid after discount.
Write some readable messages with proper details to generate the output as in form
of a bill.
Input:
Enter Product price: 2200
Enter product quantity: 5
Output:
Total Price before discount: 11000
Discount amount: 1100
Total price to be paid after discount: 9900
ANS :
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
calculateDiscountPrice( price,quantity);
sc.close();
}
public static void calculateDiscountPrice(double price,double quantity)
{
double total = price*quantity;
double discount ;
if (total > 1200)
{
discount = total * 0.1;
} else
{
discount = total * 0.05;
}
double priceAfterDiscount = total - discount;
ANS :
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
amount( total);
sc.close();
}
public static void amount(double total)
{
double amount;
if (10000 < total)
{
amount = total * (1 - 0.05);
}
else if ( total >= 10000 && total < 50000)
{
amount = total * (1 - 0.15);
}
else if (total >= 50000 && total < 80000)
{
amount = total * (1 - 0.25);
}
else
{
amount = total * (1 - 0.35);
}
System.out.print("Total Amount to be paid after availing Discount :
"+amount);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q27.Define a method which returns the next multiple of 100 for the given number.
Write the method with the following specifications:
Name of the BLC class:NextMultipleOfHundred
Name of method: getNextMultipleOfHundred() Access Modifier:
public, static Arguments: one argument of type integer Return type: an integer
value
For example, If the given value is 123, return 200. if the given value is negative
or zero, return -1
Create an ELC class Main to test the application
ANS :
public class MyProgram
{
public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
int nextHundred = getNextMultipleOfHundred.nextMultiple(num);
System.out.println("Next Hundred : "+nextHundred);
}
}
class getNextMultipleOfHundred{
public static int nextMultiple(int n){
int next = ((n/100)+1)*100;
return next;
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q28.Define a method which returns the sum of three rounded numbers.
If the right most digit of the number is less than 5, then round off it's value to
the previous multiple of 10
otherwise if the right most digit of the number is greater or equal to 5, then
round off to the next multiple of 10.
Write the method with the following specifications:
Name of the BLC class:RoundedSum
Name of method: sumOfRoundedValues()
Access Modifier: public, static
Arguments: three argument of type integer
Return type: int
This method accepts three integer values as argument and return the sum of three
rounded numbers.
Example
if a = 23, b = 34, c = 66
20 + 30 + 70 = 120
if a = 23, b = 37, c = 55
20 + 40 + 60 = 120
Arguments: three argument of type integer
Return Type: an integer value
Specifications: The value returned by the method sumOfRoundedValues() is determined
by the following rules:
if any of the given number is negative or zero, return -1.
if any of the given numbers right most digit is of the number is less than 5, then
round off it's value to the previous
multiple of 10 otherwise if the right most digit of the number is greater or equal
to 5, then round off to the next multiple of 10.
ANS :
public class RoundOfNumber
{
public static void main(String[] args)
{
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int num3 = Integer.parseInt(args[2]);
RoundedSum.sumOfRoundedValues(num1,num2,num3);
}
}
class RoundedSum{
public static void sumOfRoundedValues(int n1,int n2,int n3){
int a1=(n1/10+(n1%10)/5)*10;
int a2=(n2/10+(n2%10)/5)*10;
int a3=(n3/10+(n3%10)/5)*10;
System.out.println("Round of Numbers are : "+a1+","+a2+","+a3);
int add = a1+a2+a3;
System.out.println("Addition is :"+add);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q29.Write a java program which print the given three-digit number is palindrome or
not
Class Name: CheckPalindrome
Method Name: isPalindrome()
Access Modifier: public, static
Arguments: one argument of type integer
Return type: boolean
Program is determined by the following rules:
if the given number is an three digit number, Example: if x = 232, print 1. if x =
345, print 0
if 1 then print a message that the number is palindrome
if 0 then print a message that the number is not a palindrome
if the given number is negative or zero, print -1
if -1 then print a message that the given number is -ve kindly provide the +ve
number only
if the given number is not an three digit number, print -2
if -2 then print the message that this program can check the operation for the 3
number only.
Create an ELC class Main to test the application
ANS :
public class MyProgram {
public static boolean isPalindrome(int num) {
if (num <= 0 || num >= 1000) {
return false;
}
int Num = num;
int rnum = 0;
while (num != 0) {
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
}
return Num == rnum;
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q30.class Palindrome:
1) create a BLC class called Palindrome
2) create a static method reverseNumber()
Method: reverseNumber
Parameters: int
Returns: int
Functionality:reverse a number and return it
3) create a static method isPlindrome()
Method: isPlindrome
Parameters: int num, int reverseNum
Returns: boolean
Functionality:compare num and reverseNum parameters and return true if they
are same else return false
class PalindromeTest
1) create a ELC class PalindromeTest
2) create a main method
i) read a number from user using scanner or command line
ii) call BLC class's reverseNumber() method and get the reverse number
iii) call BLC class's isPlindrome() in if condition and print appropriate
message like the number is Palindrome or not Palindrome
ANS :
import java.util.Scanner;
public class Palindrome {
public static int reverseNum(int n) {
int reverse = 0;
while (n != 0) {
int digit = n % 10;
reverse = reverse * 10 + digit;
n /= 10;
}
return reverse;
}
if (Palindrome.isPalindrome(n, reverseNum)) {
System.out.println("The number " + n + " is a Palindrome.");
} else {
System.out.println("The number " + n + " is not a Palindrome.");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q31.class FindPrimeNumbers
1) create a BLC class FindPrimeNumbers
2) create a static method findPrimeNumbers()
Method: findPrimeNumbers
Parameters: int
Returns: String
Functionality:find all the primenumbers from 2 to given number and append all
prime numbers to a String and return it.
class DisplayPrimeNumbers
1) create a ELC class DisplayPrimeNumbers
2) create a main method()
i) read a number from user using scanner or command line
ii) call BLC class's findPrimeNumbers() method in System.out.println();
ANS :
import java.util.Scanner;
public class DisplayPrimeNumbers
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int num =sc.nextInt();
System.out.println(FindPrimeNumbers.findPrimeNumbers(num));
}
}
public class FindPrimeNumbers {
public static String findPrimeNumbers(int num)
{
int i=0,j=0,c=1;
String s ="";
for(j=2;j<=num;j++) {
for(i=2,c=1;i<=j/2;i++) {
if(j%i==0) {
c=0;
break;
}
if(c==1)
{
s=s+" "+j;
}
}
return s;
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q32.class CreatePattern
1) create a BLC class CreatePattern
2) create a method createPattern()
Method: createPattern
Parameters: int
Returns: String
Functionality: append below pattern of *'s to a String and return it (below
pattern is for the number 11)
***********
*********
*******
*****
***
*
class PatternTest
1) create a ELC class PatternTest
2) create a main method()
i) read a number from user using scanner or command line
ii) call BLC class's findPrimeNumbers() method in System.out.println();
ANS :
import java.util.Scanner;
class CreatePattern {
ANS :
import java.util.Scanner;
public class SumAndAverageNumbers {
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q34.Write a program in Java to display the first n terms of odd natural number and
their sum.
Output:
Enter the value of 'n': 5
The first 5 odd natural numbers are:
1 3 5 7 9
The sum of the first 5 odd natural numbers is: 25
ANS :
import java.util.Scanner;
ANS :
import java.util.Scanner;
scanner.close();
}
ANS :
import java.util.Scanner;
scanner.close();
ANS :
import java.util.Scanner;
scanner.close();
ANS :
import java.util.Scanner;
scanner.close();
if (distance > 0) {
double fare = calculateFare(distance);
System.out.println("The fare to be paid is: Rs. " + fare);
} else {
System.out.println("Invalid distance. Distance should be a positive
value.");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q39.You have a saving account in a bank with some balance amount in your account.
Now, you want to perform the following tasks, as per your choice. The tasks are as
under:
1. Deposit Money
2. Withdraw Money
3. Check balance
0. Log Out
Write a menu driven program to take input from the user and perform the above
tasks.
The program checks the balance before withdrawal and finally displays the current
balance after transaction.
For an incorrect choice, an appropriate message should be displayed.
ANS :
import java.util.Scanner;
switch(ch) {
case 0:
System.out.println("Thank you");
break;
case 1:
System.out.print("Enter deposit amount : ");
amt = in.nextDouble();
bal += amt;
System.out.println("Money deposited.");
System.out.print("Total balance = " + bal);
break;
case 2:
System.out.print("Enter withdrawal amount : ");
amt = in.nextDouble();
if(amt > bal) {
System.out.println("Insufficient balance.");
}
else {
bal -= amt;
System.out.println("Money withdrawn.");
System.out.print("Total balance = " + bal);
}
break;
case 3:
System.out.print("Total balance = " + bal);
break;
default:
System.out.println("Invalid request.");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q40.Non-Static Calculator:
Implement a simple calculator class in Java with non-static/instance variables
for two operands 'num1','num2'. Include non-static methods for
addition, subtraction, multiplication, and division operations.
Method names: findSum(),findDifference(),findProduct(),findQuotient().
Create multiple instances of this class and perform different operations.
* Note:object is also called as instance of class.
* Take the input in the method using method parameters.
ANS:
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
findSum(num1,num2);
findDifference(num1,num2);
findProduct(num1,num2);
findQuotient(num1,num2);
}
public static void findSum(int num1,int num2)
{
int sum=num1+num2;
System.out.println("Sum = "+sum);
}
ANS :
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter num : ");
int num = scanner.nextInt();
findFactorial(num);
findCube(num);
}
public static void findFactorial(int num)
{
long f = 1;
for(int i=1;i<=num;i++)
{
f*=i;
}
System.out.println("Factorial is : "+f);
}
public static void findCube(int num)
{
int cube =num*num*num;
System.out.print("Cube is : "+cube);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q42.Static Constant:
Create a Java class representing a geometric shape, such as a
i).circle
ii).rectangle.
Define static final variables for common mathematical constants like PI .
Ensure these constants are accessible without creating an instance of
the class.
Create method to find the area of a circle.Here you have to use final
constant PI from Circle class.
Create method to find the area of rectangle.
Inputs will be provided to method during method calls.
ANS :
import java.util.Scanner;
public class MyProgram
{
static double pi = 3.14;
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Radius of circle : ");
int r = scanner.nextInt();
}
public static void findAreaOfTriangle(int l,int w)
{
int area = l * w;
System.out.println("area of rectangle is : "+area);
}
public static void findAreaOfCircle(int r,double pi)
{
double circleArea=2*pi*r;
System.out.print("area of circle is : "+circleArea);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q43.Non-Static Bank Account:
Implement a Java class for a bank account that has non-static/instance variables
for the account holder's name, account number, and balance.
Include non-static/instance methods to deposit, withdraw, and display the
current balance.
Test these methods with multiple account instances.
ANS :
import java.util.Scanner;
public class MyProgram
{
String name;
long accNo;
double balance;
public double deposite(double balance)
{
this.balance += balance;
return balance;
}
public void withdraw(double balance)
{
if(this.balance>balance){
this.balance -= balance;
System.out.println("After deposite current balance is :
"+this.balance);
}else{
System.out.println("Balance is low");
}
}
public void display()
{
System.out.println("Name of the account holder : "+name);
System.out.println("Account no of the account holder : "+accNo);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
MyProgram b = new MyProgram();
System.out.print("Enter account holder name : ");
b.name = sc.next();
System.out.print("Enter Account Number : ");
b.accNo = sc.nextLong();
System.out.print("Enter Account Balance : ");
b.balance = sc.nextDouble();
b.display();
System.out.print("Enter amount to deposit : ");
double bala = sc.nextDouble();
b.deposite(bala);
System.out.println("Total amount is : "+b.balance);
System.out.print("Enter amount to withdraw : ");
double balaa = sc.nextDouble();
b.withdraw(balaa);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q44.Non-Static Employee Class:
Create a Java class representing an employee with non-static variables
for employee ID, name, and salary. Include non-static methods to raise
the salary and display employee details. Instantiate multiple employee
objects and perform operations like giving raises.
ANS :
import java.util.Scanner;
public class MyProgram
{
int empId;
String name;
int sal;
public int raiseSalary(int sal)
{
this.sal += sal;
return sal;
}
public void display()
{
System.out.println("Employee id is : "+empId);
System.out.println("Employee Name is : "+name);
System.out.println("Employee salary is : "+sal);
}
}
-----------------------------------------------------------------------------------
-------------------------
Q45.Write all below programs in different classes and submit in codehs. Exceution
Process diagram can be drawn in notebook.
1. WAP for the following requirement:
Create a SV
Create a SM
Print the SV inside SM
Call the SM from the main method
---------------------------------------
2. WAP for the following requiremnet:
Create a SV
Create a NSM
Print the SV inside NSM
Call the NSM from the main method
-----------------------------------------
3. WAP for the following requirement:
Create a class
Create a SV
Create another class
Create a SM
Print the SV inside SM
Call the SM from the main method
-----------------------------------------
4. WAP for the following requirement:
Create a class
Create a SV
Create another class
Create a NSM
Print the SV inside NSM
Call the NSM from the main method
5. WAP for the following requirement:
Create a NSV
Create a SM
Print the NSV inside SM
Call the SM from the main method
---------------------------------------
6. WAP for the following requiremnet:
Create a NSV
Create a NSM
Print the NSV inside NSM
Call the NSM from the main method
-----------------------------------------
7. WAP for the following requirement:
Create a class
Create a NSV
Create another class
Create a SM
Print the NSV inside SM
Call the SM from the main method
-----------------------------------------
8. WAP for the following requirement:
Create a class
Create a NSV
Create another class
Create a NSM
Print the NSV inside NSM
Call the NSM from the main method
class First
{
static String name="Tejas";
}
class Second
{
public void displayMyName()
{
System.out.println("My name is "+First.name);
}
}
printingVariables();
}
}
class Test1
{
int age;
}
class DisplayAge
{
public static void display()
{
Test1 a=new Test1();
a.age=24;
System.out.println("Age is: "+a.age);
}
}