0% found this document useful (0 votes)
20 views19 pages

Java T-2

The document provides a comprehensive tutorial on control statements in Java, including control structures such as selection, iterative, and jump statements. It includes examples of Java programs for calculating electricity bills, displaying days of the week using switch statements, and computing gross salary based on employee status. Additionally, it discusses conditional statements and their applications in tax calculations based on age and income.

Uploaded by

dheeraj72006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views19 pages

Java T-2

The document provides a comprehensive tutorial on control statements in Java, including control structures such as selection, iterative, and jump statements. It includes examples of Java programs for calculating electricity bills, displaying days of the week using switch statements, and computing gross salary based on employee status. Additionally, it discusses conditional statements and their applications in tax calculations based on age and income.

Uploaded by

dheeraj72006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Tutorial 2: Control Statements

1. Control Structures and Electricity Bill

a) List various control structures available in Java. [R]

Control structures in Java can be categorized into three main types:

1. Selection (Decision-Making) Statements:

 if statement

 if-else statement

 if-else if ladder

 switch statement

2. Iterative (Looping) Statements:

 for loop

 while loop

 do-while loop

 Enhanced for loop (or for-each)

3. Jump (Transfer) Statements:

 break

 continue

 return

b) Interpret the control structure that can be used to solve the below program. [U]

The program requires checking a customer's total electricity consumption against


multiple distinct ranges (slabs) and calculating a cumulative bill based on which range
the consumption falls into.

The most suitable control structure for handling multiple, mutually exclusive conditions
based on numerical ranges is the if-else if-else ladder. This structure allows the
program to sequentially test the units consumed against each upper limit (e.g., if (units
<= 50), else if (units <= 100), etc.) until a condition is met, thus simplifying the complex
tiered calculation.
c) Develop a Java program to find the final electricity bill for a customer as per
below norms. [Ap]

Assuming a cumulative (tiered) billing slab system based on the most distinct ranges
provided:

 units: Rs. 1.45/unit

 units: Rs. 2.50/unit

 units: Rs. 3.30/unit

 units: Rs. 7.20/unit

 units: Rs. 8.50/unit

 units: Rs. 9.00/unit

 units: Rs. 9.50/unit

Java

import [Link];

public class ElectricityBill {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter total units consumed: ");

int units = [Link]();

double bill = 0.0;

int remainingUnits = units;

if (units <= 0) {

bill = 0.0;

} else {

// Slab 7: 801+ units @ Rs. 9.50

if (remainingUnits > 800) {

bill += (remainingUnits - 800) * 9.50;

remainingUnits = 800;
}

// Slab 6: 401 to 800 units @ Rs. 9.00

if (remainingUnits > 400) {

bill += (remainingUnits - 400) * 9.00;

remainingUnits = 400;

// Slab 5: 301 to 400 units @ Rs. 8.50

if (remainingUnits > 300) {

bill += (remainingUnits - 300) * 8.50;

remainingUnits = 300;

// Slab 4: 201 to 300 units @ Rs. 7.20

if (remainingUnits > 200) {

bill += (remainingUnits - 200) * 7.20;

remainingUnits = 200;

// Slab 3: 101 to 200 units @ Rs. 3.30

if (remainingUnits > 100) {

bill += (remainingUnits - 100) * 3.30;

remainingUnits = 100;

// Slab 2: 51 to 100 units @ Rs. 2.50

if (remainingUnits > 50) {


bill += (remainingUnits - 50) * 2.50;

remainingUnits = 50;

// Slab 1: 0 to 50 units @ Rs. 1.45

if (remainingUnits > 0) {

bill += remainingUnits * 1.45;

[Link]("Total Units Consumed: %d\n", units);

[Link]("Final Electricity Bill: Rs. %.2f\n", bill);

[Link]();

2. Switch Statement

a) What is the syntax of switch case statement in Java. [R]

The basic syntax of the traditional switch statement in Java is:

Java

switch (expression) {

case constant1:

// Statements to execute if expression == constant1

break; // Optional, to exit the switch block

case constant2:

case constant3: // Multiple case labels can share the same block

// Statements to execute if expression == constant2 or constant3

break;
default: // Optional, executes if no case matches

// Statements to execute

The expression must evaluate to a type that can be converted to an integer


(byte, short, char, int), an enum, or a String.

b) Compare switch case with else if ladder. [U]

Feature switch Statement if-else if-else Ladder

Usage Best for checking a variable Best for checking a variable against
against specific, discrete, constant a range of values or complex
values (e.g., matching a month conditions (e.g., checking if a score
number, an option string, or a menu is and ).
choice).

Expression Limited to integral types, String, Condition can be


Type or enum. any boolean expression.

Flow Uses break to exit the structure, Execution is sequential; once a


Control preventing fall-through to the condition is true, its block executes,
next case. and the rest of the ladder is skipped.

Readability Generally cleaner and more e icient Can become complex and less
for many specific checks on the same readable if there are many conditions
variable. checking the same variable.

c) Develop a Java program to display the day of the week when entered number
between 0 to 6 as follows using switch statement compulsory. [Ap]

The program must:

1. Read a number from to .

2. Use a switch statement to display the corresponding day.

3. Repeat the process until is entered, where it must display "SUNDAY" and then
exit.

Java

import [Link];
public class DayOfWeekSwitch {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

int dayNumber;

do {

[Link]("Enter a number (0-6) for the day of the week (0 to exit): ");

if ([Link]()) {

dayNumber = [Link]();

} else {

[Link]("Invalid input. Please enter a number.");

[Link](); // Consume the invalid input

dayNumber = -1; // Set to a non-exit value to continue loop

switch (dayNumber) {

case 0:

[Link]("SUNDAY");

return; // Exits the main method and the program

case 1:

[Link]("MONDAY");

break;

case 2:

[Link]("TUESDAY");

break;

case 3:

[Link]("WEDNESDAY");
break;

case 4:

[Link]("THURSDAY");

break;

case 5:

[Link]("FRIDAY");

break;

case 6:

[Link]("SATURDAY");

break;

default:

if (dayNumber != -1) {

[Link]("Invalid number. Please enter a number between 0 and


6.");

} while (true); // Loop runs indefinitely until 'return' on case 0

3. If-Else Comparison and Gross Salary

a) Compare if-else with nested if else. [U]

Feature if-else (Simple/Ladder) Nested if-else

Structure A sequence of conditions An if statement that is contained within the


checked at the same level. block of another if or else statement.

Use Case Used when only one condition Used when a condition's evaluation depends
from a set of mutually exclusive on the result of a previous condition (e.g.,
Feature if-else (Simple/Ladder) Nested if-else

possibilities needs to be true (e.g., checking if a person is over 18,


checking grades A, B, C, D). and then checking if they have a valid
license).

Complexity Simple and easy to follow. Can quickly become complex, di icult to
read, and error-prone (known as the "arrow
code" anti-pattern).

b) Develop a Java program for following: [Ap]

The gross salary is calculated as: .

The program accepts Basic Salary and Job Status (Regular/Contractual).

Basic Salary (BS) Range Status HRA DA

Any of BS of BS

Any of BS of BS

Regular of BS of BS

Contractual of BS Rs. (Fixed)

Java

import [Link];

public class GrossSalaryCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter employee's basic salary (Rs.): ");

double basicSalary = [Link]();


[Link]("Enter employee's status (R for Regular, C for Contractual): ");

char status = [Link]().toUpperCase().charAt(0);

double hra = 0.0;

double da = 0.0;

double grossSalary = 0.0;

if (basicSalary < 25000) {

// Category 1: BS < 25,000

hra = 0.10 * basicSalary;

da = 0.90 * basicSalary;

} else if (basicSalary < 50000) {

// Category 2: 25,000 <= BS < 50,000

hra = 0.15 * basicSalary;

da = 0.95 * basicSalary;

} else {

// Category 3: BS >= 50,000 (Requires nested if for status)

if (status == 'R') {

// Regular Employee

hra = 0.20 * basicSalary;

da = 0.98 * basicSalary;

} else if (status == 'C') {

// Contractual Employee

hra = 0.20 * basicSalary;

da = 75000.0; // Fixed DA for contractual assignment

} else {

[Link]("Invalid status entered. Assuming Regular.");

hra = 0.20 * basicSalary;


da = 0.98 * basicSalary;

grossSalary = basicSalary + hra + da;

[Link]("\nBasic Salary: Rs. %.2f\n", basicSalary);

[Link]("HRA: Rs. %.2f\n", hra);

[Link]("DA: Rs. %.2f\n", da);

[Link]("Gross Salary: Rs. %.2f\n", grossSalary);

[Link]();

4. Conditional Statements and Income Tax

a) List the conditional statements in Java. [R]

The primary conditional (selection/decision-making) statements in Java are:

1. if statement

2. if-else statement

3. if-else if-else ladder

4. switch statement

b) Write a program for finding total tax and net income for a person based on below
conditions. [Ap]

The program must handle age and sex to determine the tax table and then calculate tax
cumulatively across the slabs.
Category Age Tax Table
Range Condition

I (Normal) years Sex: M/F

II (Senior Citizen) to years Sex: M/F

III (Very Senior years Sex: M/F


Citizen)

The tax calculation for the example (Sex: M, Age: 50, Income: 800000) is:

 Category I (Normal).

 Taxable amount: .

 Tax: .

 Net Income: .

Java

import [Link];

public class IncomeTaxCalculator {

// Function to calculate tax based on category

private static double calculateTax(int age, double income) {

double tax = 0.0;

double taxableIncome = income;

// Determine the tax category thresholds

double slab1Limit, slab2Limit, slab3Limit;

if (age < 60) {

// Category I: Normal Citizens (< 60 years)


slab1Limit = 200000;

slab2Limit = 250000;

slab3Limit = 500000;

} else if (age >= 60 && age < 80) {

// Category II: Senior Citizens (60 to < 80 years)

slab1Limit = 250000; // Taxable starts at 2,50,001

slab2Limit = 250000; // Second Nil slab, e ectively

slab3Limit = 500000;

} else {

// Category III: Very Senior Citizens (>= 80 years)

slab1Limit = 500000; // Taxable starts at 5,00,001

slab2Limit = 500000; // Third Nil slab, e ectively

slab3Limit = 500000; // Third Nil slab, e ectively

// Ensure age is >= 18 for tax calculation (basic check as requested)

if (age < 18) {

[Link]("Warning: Income tax calculation typically assumes the


person is an adult (>= 18).");

// Slab 5: Above Rs. 10,00,000 (30%)

if (taxableIncome > 1000000) {

tax += (taxableIncome - 1000000) * 0.30;

taxableIncome = 1000000;

// Slab 4: Rs. 5,00,001 to Rs. 10,00,000 (20%)


if (taxableIncome > 500000) {

tax += (taxableIncome - 500000) * 0.20;

taxableIncome = 500000;

// Slab 3: Rs. 2,50,001 to Rs. 5,00,000 (10%)

if (taxableIncome > 250000) {

// For Category I, the tax slab is 10%.

// For Categories II and III, this slab is Nil (0%), so 10% rate is wrong.

// We must calculate the tax based on the specific table's rate for this range.

double slab3Rate = 0.0;

if (age < 60 || (age >= 60 && age < 80)) {

slab3Rate = 0.10; // 10% for Normal and Senior

} else {

slab3Rate = 0.0; // 0% for Very Senior

tax += (taxableIncome - 250000) * slab3Rate;

taxableIncome = 250000;

// Slab 2: Rs. 2,00,001 to Rs. 2,50,000 (Rate varies)

if (taxableIncome > 200000) {

double slab2Rate = 0.0;

if (age < 60) {

slab2Rate = 0.10; // 10% for Normal

} else {
slab2Rate = 0.0; // 0% for Senior/Very Senior

tax += (taxableIncome - 200000) * slab2Rate;

taxableIncome = 200000;

// Slab 1: Upto Rs. 2,00,000 (Nil)

// No tax is added here.

return tax;

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter Sex (M/F): ");

char sex = [Link]().toUpperCase().charAt(0);

[Link]("Enter Age: ");

int age = [Link]();

[Link]("Enter Income per Year (Rs.): ");

double income = [Link]();

if (age < 18) {

[Link]("\n--- TAX CALCULATION ABORTED ---");

[Link]("Person is below 18 years old. No tax liability calculated.");


[Link]();

return;

if (sex != 'M' && sex != 'F') {

[Link]("\n--- TAX CALCULATION ABORTED ---");

[Link]("Invalid sex entered. Must be M or F.");

[Link]();

return;

double totalTax = calculateTax(age, income);

double netIncome = income - totalTax;

[Link]("\n--- TAX CALCULATION RESULT ---");

[Link]("Sex: %c, Age: %d, Income: Rs. %,.2f\n", sex, age, income);

[Link]("Total Tax Payable: Rs. %,.2f\n", totalTax);

[Link]("Net Income (Income - Tax): Rs. %,.2f\n", netIncome);

[Link]();

5. Repetitive Statements and Apples

a) List the repetitive or iterative statements in Java. [R]

Iterative statements (or loops) in Java are used to execute a block of code repeatedly as
long as a certain condition remains true.

1. for loop
2. while loop

3. do-while loop

4. Enhanced for loop (or for-each loop)

b) A king wanted to give apples... Find the total number of apples the servant gets
by the end of the month July. [Ap]

The problem involves iterating over the days from to in July. The number of apples
received each day is cumulative: the amount increases by on even days and on odd
days, applied to the previous day's count.

 Start day: 20, Start apples: 10

 End day: 31

Total apples .

Java

public class ApplesCalculation {

public static void main(String[] args) {

int startDay = 20;

int endDay = 31;

int currentDayApples = 10;

long totalApples = 0; // Use long for safety in total sum

for (int day = startDay; day <= endDay; day++) {

// Add the apples received today to the total

totalApples += currentDayApples;

// Calculate the apples for the *next* day based on the current day's number

if (day % 2 == 0) {

// Even day: increasing the apples by 2

currentDayApples += 2;

} else {
// Odd day: increasing the apples by 3

currentDayApples += 3;

// Note: The loop runs from day 20 to 31. The last update to currentDayApples

// happens on day 31 and is not used, which is correct for finding the total up to the
end of July.

[Link]("Total number of apples the servant gets by the end of July: " +
totalApples);

6. Scanner Class and Commission

a) What is the use of scanner class in Java. [R]

The Scanner class in Java is primarily used to get user input. It belongs to
the [Link] package.

The Scanner class can parse primitive data types (like int, double) and strings from
various input sources, including the console ([Link]), files, strings, or streams. It is
highly useful for interactive console applications.

b) Write a program to calculate commission for the input value of sales amount.
[Ap]

The commission rules are:

1. Sales : Commission is Nil (0%)

2. : Commission is 2%

3. Sales : Commission is 5%

Java

import [Link];
public class CommissionCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the sales amount (Rs.): ");

double salesAmount = [Link]();

double commissionRate;

double commission;

if (salesAmount <= 5000) {

// Rule i: Commission is NIL for sales amount <= Rs. 5000

commissionRate = 0.0;

} else if (salesAmount < 10000) {

// Rule ii: Commission is 2% for sales when sales amount is > Rs. 5000 and < Rs.
10000

commissionRate = 0.02; // 2%

} else {

// Rule iii: Commission is 5% for sales amount >= Rs. 10000

commissionRate = 0.05; // 5%

commission = salesAmount * commissionRate;

[Link]("\nSales Amount: Rs. %.2f\n", salesAmount);

[Link]("Commission Rate: %.0f%%\n", commissionRate * 100);

[Link]("Total Commission: Rs. %.2f\n", commission);


[Link]();

You might also like