0% found this document useful (0 votes)
29 views9 pages

Story Based Java Coding Questions - Solutions

The document presents a series of beginner-friendly Java coding questions and their solutions, covering various topics such as bank balance calculations, electricity bills, shopping discounts, and more. Each question includes a Java class with a main method demonstrating the solution through simple programs. The examples are designed to be easy to understand and suitable for exam preparation.

Uploaded by

parnikadesk
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)
29 views9 pages

Story Based Java Coding Questions - Solutions

The document presents a series of beginner-friendly Java coding questions and their solutions, covering various topics such as bank balance calculations, electricity bills, shopping discounts, and more. Each question includes a Java class with a main method demonstrating the solution through simple programs. The examples are designed to be easy to understand and suitable for exam preparation.

Uploaded by

parnikadesk
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

Story Based Java Coding Questions – Solutions

(Simple Java Programs | Beginner Friendly | Exam Ready)

Q1. Bank Balance Story

class BankBalance {
public static void main(String[] args) {
int balance = 5000;
int deposit = 2000;
int withdraw = 1500;

balance = balance + deposit - withdraw;


[Link]("Final Balance = " + balance);
}
}

Q2. Electricity Bill Story

class ElectricityBill {
public static void main(String[] args) {
int units = 150;
int bill;

if (units <= 100)


bill = units * 5;
else
bill = (100 * 5) + (units - 100) * 7;

[Link]("Electricity Bill = Rs." + bill);


}
}

Q3. Shopping Discount Story

class ShoppingDiscount {
public static void main(String[] args) {

1
int amount = 6000;
double finalAmount;

if (amount > 5000)


finalAmount = amount - (amount * 0.10);
else
finalAmount = amount;

[Link]("Amount to Pay = " + finalAmount);


}
}

Q4. Exam Result Story

class ExamResult {
public static void main(String[] args) {
int marks = 78;

if (marks >= 90)


[Link]("Grade A");
else if (marks >= 75)
[Link]("Grade B");
else if (marks >= 50)
[Link]("Grade C");
else
[Link]("Fail");
}
}

Q5. Traffic Signal Story

class TrafficSignal {
public static void main(String[] args) {
String signal = "Red";

switch (signal) {
case "Red":
[Link]("Stop");
break;
case "Yellow":
[Link]("Ready");

2
break;
case "Green":
[Link]("Go");
break;
default:
[Link]("Invalid Signal");
}
}
}

Q6. Library Fine Story

class LibraryFine {
public static void main(String[] args) {
int days = 5;
int fine = 0;

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


fine = fine + 2;
}

[Link]("Total Fine = Rs." + fine);


}
}

Q7. Water Tank Story

class WaterTank {
public static void main(String[] args) {
int minutes = 10;
int water = 0;

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


water = water + 5;
}

[Link]("Total Water Filled = " + water + " liters");


}
}

3
Q8. Festival Lights Story

class FestivalLights {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
[Link]("House " + i + " lights ON");
}
}
}

Q9. Bus Ticket Story (Command Line Arguments)

class BusTicket {
public static void main(String[] args) {
int price = [Link](args[0]);
int passengers = [Link](args[1]);

int total = price * passengers;


[Link]("Total Fare = Rs." + total);
}
}

Q10. Student Marks Story (1D Array)

class StudentMarks {
public static void main(String[] args) {
int[] marks = {70, 80, 65, 90, 75};
int total = 0;

for (int i = 0; i < [Link]; i++) {


total += marks[i];
}

double average = total / 5.0;


[Link]("Total = " + total);
[Link]("Average = " + average);
}
}

4
Q11. School Classroom Story (2D Array)

class SchoolClassroom {
public static void main(String[] args) {
int[][] marks = {
{70, 80, 65, 90},
{60, 75, 85, 95},
{55, 68, 72, 88}
};

int max = marks[0][0];

for (int i = 0; i < [Link]; i++) {


for (int j = 0; j < marks[i].length; j++) {
if (marks[i][j] > max)
max = marks[i][j];
}
}

[Link]("Highest Mark = " + max);


}
}

Q12. Cricket Match Story (Jagged Array)

class CricketMatch {
public static void main(String[] args) {
int[][] runs = {
{45, 30, 25},
{60, 40, 35, 20},
{50, 10}
};

for (int i = 0; i < [Link]; i++) {


int total = 0;
for (int j = 0; j < runs[i].length; j++) {
total += runs[i][j];
}
[Link]("Total runs in Match " + (i + 1) + " = " +
total);
}
}
}

5
Q13. Student Information Story

class Student {
String name;
int roll;
int marks;

void display() {
[Link](name + " " + roll + " " + marks);
}

public static void main(String[] args) {


Student s1 = new Student();
[Link] = "Rahul";
[Link] = 1;
[Link] = 85;
[Link]();
}
}

Q14. Car Showroom Story (Constructor)

class Car {
String brand;
int price;

Car(String b, int p) {
brand = b;
price = p;
}

void display() {
[Link](brand + " " + price);
}

public static void main(String[] args) {


Car c = new Car("Toyota", 1000000);
[Link]();
}
}

6
Q15. Mobile Battery Story (Method Overloading)

class Mobile {
void battery(int percent) {
[Link]("Battery: " + percent + "%");
}

void battery(int percent, String status) {


[Link]("Battery: " + percent + "% " + status);
}

public static void main(String[] args) {


Mobile m = new Mobile();
[Link](80);
[Link](90, "Charging");
}
}

Q16. Employee Details Story ( this keyword)

class Employee {
int id;
String name;

Employee(int id, String name) {


[Link] = id;
[Link] = name;
}

void display() {
[Link](id + " " + name);
}

public static void main(String[] args) {


Employee e = new Employee(101, "Amit");
[Link]();
}
}

7
Q17. College Registration Story ( static keyword)

class CollegeStudent {
static String college = "ABC College";
int roll;
String name;

CollegeStudent(int r, String n) {
roll = r;
name = n;
}

void display() {
[Link](name + " " + roll + " " + college);
}

public static void main(String[] args) {


CollegeStudent s1 = new CollegeStudent(1, "Neha");
CollegeStudent s2 = new CollegeStudent(2, "Ravi");
[Link]();
[Link]();
}
}

Q18. ATM Machine Story

import [Link];

class ATM {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int balance = 5000;
int choice;

do {
[Link]("[Link] [Link] [Link] Balance [Link]");
choice = [Link]();

switch (choice) {
case 1:
[Link]("Enter amount: ");
balance += [Link]();
break;

8
case 2:
[Link]("Enter amount: ");
balance -= [Link]();
break;
case 3:
[Link]("Balance = " + balance);
break;
case 4:
[Link]("Thank You");
break;
default:
[Link]("Invalid Choice");
}
} while (choice != 4);
}
}

✔ Clean ✔ Simple ✔ Lab-exam safe

Common questions

Powered by AI

The 'this' keyword in the Employee class is crucial in disambiguating instance variables from local variables with the same names. It clarifies that the variable being referred to is the instance variable, enhancing code readability, reducing errors from variable shadowing, and ensuring that the correct variables are modified when initializing objects .

Method overloading in the Mobile class demonstrates polymorphism by allowing multiple methods with the same name but different parameters to exist. This provides the advantage of using a unified interface while enabling the implementation of variations in processing. It enhances code clarity and usability, allowing a method to behave differently based on input, which is practical for adapting functionality without altering client code .

Creating a Student class with fields for name, roll number, and marks allows for effective management of student information by providing a structured way to encapsulate student data. It enables easy data management, retrieval, and display which can be extended for further functionalities like sorting or statistical operations. Additionally, it promotes code reusability and organization making the system scalable for future alterations and additions .

Providing a default case in a switch statement, as shown in the TrafficSignal class, is beneficial for user experience and error reduction because it handles unexpected inputs gracefully. The default case acts as a catch-all, ensuring that the program delivers a clear response even when the input doesn't match any predefined case. This prevents undefined behavior, aids in debugging by highlighting incorrect inputs, and provides feedback to correct them, thus enhancing program robustness .

In the WaterTank class example, the use of a loop is central to accumulating the total water filled over a series of minutes. The loop iterates a set number of times, incrementing the water amount by a fixed quantity (5 liters) each time, reflecting continuous filling over each minute. This iterative accumulation effectively models time-based processes, offering a straightforward solution to problems involving gradual change .

The use of the 'static' keyword for the college variable in the CollegeStudent class means that this variable is shared across all instances of the class. Consequently, any changes to the college variable affect all objects of the class. This centralizes shared information that is common to all instances, ensuring consistency and reducing redundancy in data representation, but can limit flexibility if different instances need to represent different college names .

Using a jagged array in the CricketMatch class allows for a flexible data representation where each sub-array can differ in length. This is particularly effective when handling data of varying sizes, such as cricket match innings with different numbers of scores. It provides efficient storage by using memory only for the required number of elements per sub-array, but also involves increased complexity in operations as developers must handle uneven row lengths explicitly in their logic .

The logic for calculating the electricity bill in the given program varies based on the units consumed. If the units are less than or equal to 100, the cost is calculated at a rate of 5 per unit. For units greater than 100, the first 100 units are charged at 5 per unit, while the additional units beyond 100 are charged at 7 per unit .

Using a constructor in the Car class allows for object initialization with specific attributes such as brand and price, ensuring that each object starts its existence fully set up with all necessary data. This enhances code readability and reliability by enforcing mandatory initialization, minimizing the chances of objects being used before all their properties are meaningfully defined .

The ATM class utilizes a do-while loop to facilitate user interaction by continuously prompting the user to perform transactions until an exit condition is met. This loop ensures that the menu is displayed at least once, allowing users to choose and execute actions such as deposit, withdraw, check balance, or exit. It effectively supports multiple, consecutive operations in a single session, improving user convenience and interaction effectiveness .

You might also like