0% found this document useful (0 votes)
15 views3 pages

Java Practice Questions with Solutions

The document contains Java practice questions focused on basic programming concepts, including a Grade Calculator that assigns grades based on user input marks and an Even and Odd Counter that counts the number of even and odd integers from user input. Each section includes the logic behind the solution and the corresponding Java code. The document serves as a resource for practicing Java programming skills.

Uploaded by

MAlik Ibrahim
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)
15 views3 pages

Java Practice Questions with Solutions

The document contains Java practice questions focused on basic programming concepts, including a Grade Calculator that assigns grades based on user input marks and an Even and Odd Counter that counts the number of even and odd integers from user input. Each section includes the logic behind the solution and the corresponding Java code. The document serves as a resource for practicing Java programming skills.

Uploaded by

MAlik Ibrahim
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

Java Practice Questions with Solutions and Code

1. Grade Calculator

-------------------

Logic: Take the user's marks, check which range they fall into, and print the appropriate grade using

if-else conditions.

Code:

import [Link];

public class GradeCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter marks: ");

int marks = [Link]();

if (marks >= 90) {

[Link]("Grade: A");

} else if (marks >= 80) {

[Link]("Grade: B");

} else if (marks >= 70) {

[Link]("Grade: C");

} else if (marks >= 60) {

[Link]("Grade: D");

} else {

[Link]("Grade: F");
}

2. Even and Odd Counter

------------------------

Logic: Loop through 10 numbers, use num % 2 to check if even or odd, and keep count.

Code:

import [Link];

public class EvenOddCounter {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

int evenCount = 0, oddCount = 0;

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

[Link]("Enter number " + i + ": ");

int num = [Link]();

if (num % 2 == 0) {

evenCount++;

} else {

oddCount++;

[Link]("Even numbers: " + evenCount);

[Link]("Odd numbers: " + oddCount);


}

... (Truncated for brevity, but follows the same structure for other solutions.)

Common questions

Powered by AI

The EvenOddCounter program utilizes modular arithmetic (num % 2) to determine if a number is even or odd. When num % 2 equals 0, it signifies that the number is divisible by 2 and is therefore even. If the result is not 0, the number is odd. This simple modulus operation is efficient, providing a clear boolean evaluation to increment respective even or odd counters .

If the GradeCalculator uses only sequential if statements without the corresponding else-if structure, it may incorrectly check lower-grade conditions even if a higher one is met. For instance, if a student scores 85, without else-if, the program would output both 'Grade: B' and 'Grade: C', as both conditions would evaluate as true. The else-if structure ensures that once a true condition is met, subsequent conditions are not evaluated, preventing incorrect multiple outputs .

Using a for loop in the EvenOddCounter program is highly effective for managing a fixed set of 10 inputs, as it provides a concise, controlled iteration structure. The loop initialized with i = 1 and ending at i = 10 ensures precise processing of an exact count of inputs, aligning well with tasks that have a known number-throughput requirement. This implementation prevents the need for additional conditional termination checks that might be required in a while loop .

Closing the Scanner object is crucial for resource management as it releases system resources associated with it. Failing to close Scanner, which may be backed by System.in, can lead to resource leaks especially when a program runs for an extended duration or gets executed multiple times under certain loops. Properly closing it ensures efficient resource use and prevents performance issues or exhaustion of system file handles .

Initializing evenCount and oddCount variables before entering the loop is critical because it establishes a starting point for counting before any numbers are input. Without initialization, these variables would hold undefined values, potentially leading to incorrect counts and output. By starting the counters at zero, the program guarantees accurate calculation as it processes each number input through the loop .

The GradeCalculator uses a series of if-else conditions to evaluate the user's marks and print the appropriate grade. It starts by checking if the marks are greater than or equal to 90, resulting in a grade 'A'. If that condition is not met, it moves to the next conditional block (marks >= 80) and continues this pattern down to marks >= 60 for a 'D' grade and an else statement for an 'F'. This hierarchical check ensures that only the correct range condition applies, as each condition is mutually exclusive .

The primary strength of using if-else structures in the GradeCalculator is their straightforwardness and readability, easily mapping conditions to actions like assigning grades based on marks. However, the weakness lies in their linear scalability with complex conditions, which could become cumbersome with numerous conditions impacting maintainability and readability. Also, the lack of boundary handling within simple if-else structure may require additional checks for edge inputs like negative values not addressed in current logic .

In the GradeCalculator program, user interaction is facilitated using the Scanner class, allowing the program to capture user input from the console. The prompt 'Enter marks: ' informs the user when to enter data, ensuring that the program actively guides the user's actions. This interaction sequence supports program usability by providing clear instructions at a logical point, reducing user error and facilitating smooth data input operations .

The GradeCalculator does not explicitly handle edge cases such as negative marks, which could result in unexpected behavior under current logic. If negative marks are entered, the program will default to the else branch, outputting 'Grade: F'. However, this approach does not account for the logical issue that negative scores are invalid in most grading systems. Handling such cases would require additional checks to validate the input and ensure data falls within an acceptable range of 0-100 before grade assignment .

To modify the EvenOddCounter program to handle varying input sizes, replace the fixed for loop with a while loop that continues until a specific input indicates the end (e.g., entering zero, a blank input, or a predefined termination character). Additionally, the program would need to tally input counts dynamically, possibly by reading inputs into a List or adjusting the loop to monitor while a Scanner has next inputs, providing more flexibility in real-time without predetermined limits .

You might also like