Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Java Programs LAB SESSION

Uploaded by

tejasmuradi1
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java Programs LAB SESSION

Uploaded by

tejasmuradi1
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 38

-----------------------------------------------------------------JAVA

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;

System.out.println("cost price is :"+costprice);


System.out.println("profit:"+profit);
System.out.println("VAT :"+vat);
System.out.println("service charge : "+servicecharge);
System.out.println("Total selling price :"+total);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q2.Rohan purchased an old cycle for Rs. 1200 and spend Rs. 250 on repairs,
Rs. 350 in coloring and added new accessories worth Rs. 500. Rohan wants to make a
profit
of Rs. 1500 on selling the cycle. Find the selling price of the cycle. Write a java
program
to store all values and calculate and display the selling price.
Output:
Initial Cost: Rs. 1200.0
Repair Cost: Rs. 250.0
Coloring Cost: Rs. 350.0
Accessories Cost: Rs. 500.0
Total Cost: Rs. 2300.0
Desired Profit: Rs. 1500.0
Selling Price: Rs. 3800.0

ANS :
public class CycleSellingPriceCalculator {
public static void main(String[] args) {

// Define all the variables


double ic=1200.0;
double rc=250.0;
double cc=350.0;
double ac=500.0;
double dp=1500.0;

// Calculate the total cost


double totalcost=ic+rc+cc+ac;

// Calculate the selling price to make the desired profit


double sellingprice=totalcost+dp;

// Display the results


System.out.println("Initial Cost:"+ic);
System.out.println("repair Cost:"+rc);
System.out.println("coloring Cost:"+cc);
System.out.println("Accesories Cost:"+ac);
System.out.println("Total Cost:"+totalcost);
System.out.println("Desired Profit:"+dp);
System.out.println("Selling Price:"+sellingprice);

}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
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.

// Parse command-line arguments as doubles

// Calculate the sum


double num1=3.0,num2=2.2,num3=4.3;

double sum=num1+num2+num3;
// Calculate the average
double avg=sum/3;

// Display the results


System.out.println("Sum of three no is:"+sum);
System.out.println("Avg of three no is:"+avg);

}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
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) {

// write a logic to display error if arguments length is not equals to 2

// Parse command-line arguments as integers

// Display the original values


double num1=6,num2=7;
// Swap the values without using a third variable
num1=num1+num2;
num2=num1-num2;
num1=num1-num2;
// Display the swapped values
System.out.println("Swapped Values: num1 = " + num1 + ", num2 = " + num2);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q5.Write a program to calculate the tax for a taxable income of Rs. 9,90,000, if
the tax rate is fixed at 4.9%.
Output:
Taxable Income: Rs. 990000.0
Tax Rate: 4.9%
Tax Amount: Rs. 48510.0

ANS :
public class TaxCalculator {
public static void main(String[] args) {
// Define the taxable income
double taxableincome=990000.00;

// Define the tax rate (4.9% as a decimal)


double taxrate=4.9/100;

// Calculate the tax amount


double taxamount=taxableincome*taxrate;

// Display the tax amount


System.out.println("Taxable Income:"+taxableincome);
System.out.println("Taxable Rate:"+(taxrate*100));
System.out.println("Taxable Amount:"+taxamount);

}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
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);

System.out.println("The surface area of the cube is: " + surfaceArea);

}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
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;

public class CylinderSurfaceArea {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("enter the radius of the cylinder:");


double radius=scanner.nextDouble();

System.out.print("enter the height of cylinder:");


double height=scanner.nextDouble();

double pi=3.14;
double Area=pi*radius*radius;
double larea=2*pi*radius*height;
double totalarea=2*Area+larea;

System.out.print("the total surface area of cylinder is :"+totalarea);


}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q8.write a Java program to calculate compound interest for 3 year?
Formula-
Total amount=principle*((1+rate/100)*(1+rate/100)*(1+rate/100));
Compound intrest = amount – principle;
Output:
Enter the principal amount (P): 25000
Enter the annual interest rate (R): 24
The compound interest after 3 years is: 22665.6

ANS :
import java.util.Scanner;

public class CompoundInterestCalculator {


public static void main(String[] args) {
Scanner sc1= new Scanner(System.in);

System.out.print("Enter the Principal amount : ");


double Amount = sc1.nextDouble();

System.out.print("Enter the annual intrest : ");


double rate = sc1.nextDouble();

double totalamount=Amount*((1+rate/100)*(1+rate/100)*(1+rate/100));
double CompoundIntrest=totalamount-Amount;

System.out.print("The compound intrest is : "+CompoundIntrest);

}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
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);

System.out.print("Enter your age: ");


int age = sc.nextInt();
if (age >= 18) {
System.out.println("Eligible for voting");
} else {
System.out.println("Not Eligible for voting");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q13.WAP in java to read two integers from command line and perform below
validations.
1) verify whether the given numbers are positive or negative? if negative print
"Negative numbers are not allowed.
2) if both numbers are positive then print maximum number.
3) verify both numbers are even or odd

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;

public class MyProgram {


public static void main(String[] args) {
if (args.length != 4) {
System.out.println("Invalid number of arguments. Usage: java
SortNumbers <num1> <num2> <num3> <order>");
return;
}

int[] numbers = new int[3];


for (int i = 0; i < 3; i++) {
numbers[i] = Integer.parseInt(args[i]);
}

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));
}

public static void descendingOrder(int[] arr) {


Arrays.sort(arr);
int n = arr.length;
int[] descArr = new int[n];
for (int i = 0; i < n; i++) {
descArr[i] = arr[n - i - 1];
}
System.out.println("Descending order of given numbers are: " +
Arrays.toString(descArr));
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q17.WAP to declare a method to input a number. Check and display whether
its a Niven number or not.
Hint: A number is said to be niven if the number is divisible by
the sum of its digits.
e.g: 126 is Niven because 1+2+6=9
and 126 is divisible by 9.

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 passenger = Integer.parseInt(args[0]);


int distance = Integer.parseInt(args[1]);
String location = args[2];

int fare = tariff(passenger, distance, location);

System.out.println("Total fare received at the end of the journey: " +


fare);
}

public static int tariff(int p, int d, String l) {


System.out.println("Enter number of passengers entered into bus: " + p);

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;
}

int fare = charge * p;

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);
}

public static void FloydTriangle(int rows) {


int number = 1;

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


for (int j = 1; j <= i; j++) {
System.out.print(number + " ");
number++;
}
System.out.println();
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q22.1. WAP for the following requirement:
i. Create a method to input a number.
ii. Create another method to perform the following operations and
print
a. Print the rounded value of input
b. Print the square root of the number
c. Print the rounded down value of number
Here value returned from first method becomes the input for second method.

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();

System.out.print("Enter the Second number : ");


int num2=scanner.nextInt();

System.out.print("Enter operation you want to perform ");


char c = scanner.next().charAt(0);
double result;
switch(c)
{
case '+' : result = num1+num2;
System.out.print("Addition is "+result);
break;
case '-' : result = num1-num2;
System.out.print("Substraction is "+result);
break;
case '*' : result=num1*num2;
System.out.print("Mul is : "+result);
break;
case '%' : result=num1%num2;
System.out.print("Mod is : "+result);
break;
case '/' : result=num1/num2;
System.out.print("Div is : "+result);
break;
default : System.out.print("Invalid arithmetic operation");

}
}

}
-----------------------------------------------------------------------------------
-----------------------------------------------
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);

System.out.print("Enter a character : ");


char c = sc.next().charAt(0);

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);

System.out.print("Enter Product Price : ");


double price = sc.nextDouble();

System.out.print("Enter Product quantity : ");


double quantity = sc.nextDouble();

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;

System.out.println("Total Price Before discount : "+total);


System.out.print("Total price to be paid after Discount :
"+priceAfterDiscount);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q26.A clothing brand Louis Phillips has announced the following discounts on
purchase of any of its products,
based on the M.R.P of the product
Total Cost Discount
Less than 10k 5%
More than 10k but less than 50k 15%
More than 50k but less than 80K 25%
More than 80k 35%
WAP to input the total cost to calculate and display the amount to be paid by the

costumer after availing the discount from the table.

ANS :
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.print("Enter total cost : ");


double total = sc.nextDouble();

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;
}

public class Main {


public static void main(String[] args) {
int number = 232;
if (MyProgram.isPalindrome(number)) {
System.out.println("The number " + number + " is a palindrome.");
} else {
System.out.println("The number " + number + " is not a palindrome.");
}

}
-----------------------------------------------------------------------------------
-----------------------------------------------
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;
}

public static boolean isPalindrome(int n, int reverse) {


return n == reverse;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number: ");
int n = sc.nextInt();

int reverseNum = Palindrome.reverseNum(n);

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 {

public static String createPattern(int n) {


String pattern = "";
for (int i = n; i >= 1; i--) {
for (int j = n- i; j > 0; j--) {
pattern += " ";
}
for (int k = 1; k <= 2 * i - 1; k++) {
pattern += "*";
}
pattern += "\n";
}
return pattern;
}
}
public class PatternTest {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
scanner.close();

String pattern = CreatePattern.createPattern(n);


System.out.println(pattern);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q33.Write a program in Java to input 5 numbers from keyboard and find their sum and
average.
Output:
please enter 5 numbers
Enter number 1
3
Enter number 2
232
Enter number 3
33
Enter number 4
545
Enter number 5
3
Sum of the numbers: 816.0
Average of the numbers: 163.2

ANS :
import java.util.Scanner;
public class SumAndAverageNumbers {

public static void main(String args[]) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter number 1 ");
int num1 = sc.nextInt();
System.out.println("Enter number 2 ");
int num2 = sc.nextInt();
System.out.println("Enter number 3 ");
int num3 = sc.nextInt();
System.out.println("Enter number 4 ");
int num4 = sc.nextInt();
System.out.println("Enter number 5 ");
int num5 = sc.nextInt();
int sum = num1 + num2 + num3 + num4 + num5;
double avg = sum/5.0;
System.out.println("Sum of the numbers: "+sum);
System.out.println("Average of the numbers: "+avg);

}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
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;

public class SumOfOddNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n,sum = 0;
System.out.print("Enter the value of n : ");
n = sc.nextInt();
System.out.println("The first "+n+" odd natural numbers are:");
for(int i = 1; i<=n*2; i++){
if(i%2!=0){
sum += i;
System.out.print(i+" ");
}
}
System.out.println();
System.out.println("The sum of the first "+n+ " odd natural numbers is:
"+sum);
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q35.Write a program to input three numbers (positive or negative) using Scanner.
Numbers must be initialised to instance variables.
Create user defined method to pass the numbers as input and if they are unequal
then display the
greatest number otherwise, display they are equal.
The method also displays whether the numbers entered
by the user are "All positive", "All negative" or "Mixed numbers".
Sample Input: 56, -15, 12
Sample Output: The greatest number is 56
Entered numbers are mixed numbers.

ANS :
import java.util.Scanner;

public class MyProgram {


private int num1, num2, num3;

public void inputNumbers() {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");


num1 = scanner.nextInt();

System.out.print("Enter the second number: ");


num2 = scanner.nextInt();

System.out.print("Enter the third number: ");


num3 = scanner.nextInt();

scanner.close();
}

public void analyzeNumbers() {


int greatest = num1;

if (num2 > greatest) {


greatest = num2;
}

if (num3 > greatest) {


greatest = num3;
}

if (num1 == num2 && num2 == num3) {


System.out.println("The numbers are equal.");
} else {
System.out.println("The greatest number is " + greatest + ".");
}

if (num1 > 0 && num2 > 0 && num3 > 0) {


System.out.println("Entered numbers are all positive.");
} else if (num1 < 0 && num2 < 0 && num3 < 0) {
System.out.println("Entered numbers are all negative.");
} else {
System.out.println("Entered numbers are mixed numbers.");
}
}

public static void main(String[] args) {


MyProgram analyzer = new MyProgram();
analyzer.inputNumbers();
analyzer.analyzeNumbers();
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q36.A triangle is said to be an "Equable Triangle', if the area of the triangle is
equal to its perimeter.
Write a program to enter three sides of a triangle. Create user defined method.
Check and print whether the triangle is equable or not.
For example, a right angled triangle with sides 5, 12 and 13 has its area and
perimeter
both equal to 30.

ANS :
import java.util.Scanner;

public class MyProgram {

public static double calculateArea(double s1, double s2, double s3) {


double s = (s1 + s2 + s3) / 2;
double area = Math.sqrt(s * (s - s1) * (s - s2) * (s - s3));
return area;
}

public static boolean checkEquableTriangle(double s1, double s2, double s3) {


double perimeter = s1 + s2 + s3;
double area = calculateArea(s1, s2, s3);
return area == perimeter;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the length of the first side: ");


double s1 = scanner.nextDouble();

System.out.print("Enter the length of the second side: ");


double s2 = scanner.nextDouble();

System.out.print("Enter the length of the third side: ");


double s3 = scanner.nextDouble();

scanner.close();

if (checkEquableTriangle(s1, s2, s3)) {


System.out.println("The triangle is equable.");
} else {
System.out.println("The triangle is not equable.");
}}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q37.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.
For Example, Consider the number 59.
Sum of digits: 5+9=14
Product of digits: 5*9=45
Total of the sum of digits and product of digits 14+45 = 59.
Write a program to create UDM that 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, display the message "Special 2-digit
number"
otherwise, display the message "Not a special two-digit number".

ANS :
import java.util.Scanner;

public class MyProgram {

public static boolean isSpecialNumber(int number) {


int sumOfDigits = number / 10 + number % 10;
int productOfDigits = (number / 10) * (number % 10);
return (sumOfDigits + productOfDigits) == number;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a two-digit number: ");


int number = scanner.nextInt();

scanner.close();

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


if (isSpecialNumber(number)) {
System.out.println("Special 2-digit number");
} else {
System.out.println("Not a special two-digit number");
}
} else {
System.out.println("Invalid input. Please enter a two-digit number.");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q38.The TSRTC Pushpak (Airport Electric Buses) is a service that operates air-
conditioned,
pollution-free, electric buses from and to Rajiv Gandhi International Airport
(R.G.I.A.)
in Hyderabad, Telangana. The buses have luxury seats, digital destination boards,
cell phone charging, and a wheelchair ramp. The service runs 24 hours a day,
with an average gap of 30 minutes between rides.
It has base fare based on the distance travelled as per the tariff given below:
Distance travelled Fare
upto 15km Fixed Charge Rs.70
16 km to 21km Rs 6/km
22km to 35km Rs 5/km
31km and above Rs 4/km
Develop an application with user defined method to input the distance travelled by
the passenger.
The method calculates and display the fare to be paid.

ANS :
import java.util.Scanner;

public class MyProgram {

public static double calculateFare(int distance) {


double fare;
if (distance <= 15) {
fare = 70;
} else if (distance <= 21) {
fare = 70 + (distance - 15) * 6;
} else if (distance <= 35) {
fare = 70 + 6 * (21 - 15) + (distance - 21) * 5;
} else {
fare = 70 + 6 * (21 - 15) + 5 * (35 - 21) + (distance - 35) * 4;
}
return fare;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the distance travelled (in km): ");


int distance = scanner.nextInt();

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;

public class MyProgram


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);

System.out.println("Enter 1 to deposit money");


System.out.println("Enter 2 to withdraw money");
System.out.println("Enter 3 to check balance");
System.out.println("Enter 0 to quit");

System.out.print("Enter your choice: ");


int ch = in.nextInt();
double amt = 0.0;
double bal = 5000.0; //Initial balance of account

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);

System.out.print("Enter Num1 : ");


int num1 = scanner.nextInt();

System.out.print("Enter Num2 : ");


int num2 = scanner.nextInt();

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);
}

public static void findDifference(int num1,int num2)


{
int difference = num2 - num1;
System.out.println("Differnce = "+difference);
}
public static void findProduct(int num1,int num2)
{
int product = num1*num2;
System.out.println("Product = "+product);
}
public static void findQuotient(int num1,int num2)
{
int quotient = 0;
if(num2!=0)
{
quotient = num1/num2;
System.out.println("Quotient = "+quotient);
}
else
{
System.out.println("operation cannot be performed");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
Q41.Static Utility Class:
Design a utility class in Java that contains only static methods for
various mathematical operations such as taking input and finding factorial,
calculating cube.
Method Name: findFactorial(), findCube()
Demonstrate the usage of these static methods in another class.

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();

System.out.print("Enter Length of Rectangle : ");


int l = scanner.nextInt();

System.out.print("Enter Width of Rectangle : ");


int w = scanner.nextInt();
findAreaOfTriangle(l,w);
findAreaOfCircle(r,pi);

}
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);

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
MyProgram e = new MyProgram();
System.out.print("Enter the Employee Id : ");
e.empId = sc.nextInt();
System.out.print("Enter the Employee Name :");
e.name = sc.next();
System.out.print("Enter the Employee salary : ");
e.sal = sc.nextInt();
e.display();
System.out.println("Salary of the Employee is : "+e.raiseSalary(e.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

public class TestVariable1 {


static int n=800;
public static void test()
{
System.out.println("Value of Static variable: "+n);
}
public static void main(String[] args) {
test();
}
}

public class TestVariable2 {


static String name="Tejas";
public void displayName()
{
System.out.println("My name is "+name);
}
public static void main(String[] args) {
TestVariable2 t=new TestVariable2();
t.displayName();
}
}

public class TestVariable3 {


public static void main(String[] args) {
Display d=new Display();
d.displayRollNo();
}
}
class Check
{
static int rollNo=56;
}
class Display
{
public static void displayRollNo()
{
System.out.println(Check.rollNo);
}
}

public class TestVariable4 {


public static void main(String[] args) {
Second p=new Second();
p.displayMyName();
}
}

class First
{
static String name="Tejas";
}

class Second
{
public void displayMyName()
{
System.out.println("My name is "+First.name);
}
}

public class TestVariable5 {


double price=350;
public static void printingVariables()
{
System.out.println(" Price of the item: "+new TestVariable5().price);
}
public static void main(String[] args) {

printingVariables();
}
}

public class TestVariable6 {


String name;
public void displaynames()
{
TestVariable6 x =new TestVariable6();
x.name="tejas";
System.out.println("Name: "+x.name);
}
public static void main(String[] args) {
TestVariable6 t=new TestVariable6();
t.displaynames();
}
}

public class TestVariable7 {


public static void main(String[] args) {
DisplayAge.display();
}
}

class Test1
{
int age;
}

class DisplayAge
{
public static void display()
{
Test1 a=new Test1();
a.age=24;
System.out.println("Age is: "+a.age);
}
}

public class TestVariable8 {


public static void main(String[] args) {
DisplayBalance d=new DisplayBalance();
d.balanceDisplay();
}
}
class Test2
{
int balance;
}
class DisplayBalance
{
public void balanceDisplay()
{
Test2 t=new Test2();
t.balance=24000;
System.out.println("Balance : "+t.balance);
}
}

You might also like