Java Final

Programming Foundations I Final Exam Practice Questions

Section 1: Introduction to Java (5 questions)

  • Q1. Compiling and Running a Java Program

    • The correct way to compile and run a Java program named HelloWorld.java is:
      Answer: B) javac HelloWorld.java then java HelloWorld

    • javac HelloWorld.java compiles the program.

    • java HelloWorld runs the compiled bytecode.

  • Q2. Basic Structure of a Java Program

    • The correct structure for a basic Java program is:
      Answer: A) public class Main { public static void main(String[] args) { } }

    • This structure contains the main method which serves as the entry point of the program.

    • public indicates the visibility of the class, and static allows the method to be executed without creating an instance of the class.

  • Q3. JVM

    • JVM stands for Java Virtual Machine.

    • Its purpose is to run Java bytecode, providing a platform-independent environment.

  • Q4. Case Sensitivity in Java

    • True or False: Java is case-sensitive, implying that myVariable and myvariable are considered different identifiers.
      Answer: True

    • Java distinguishes between uppercase and lowercase letters.

  • Q5. File Extension for Compiled Java Files

    • The file extension for compiled Java files is:
      Answer: B) .class

    • These .class files contain Java bytecode produced by the Java compiler.

Section 2: Variables and Assignments (7 questions)

  • Q6. Valid Variable Names

    • Which of the following is NOT a valid variable name in Java?
      Answer: B) 2ndPlace

    • Variable names cannot start with a digit.

  • Q7. Code Output

    • Given the code:
      java int x = 10; int y = 20; x = y; y = 15; System.out.println(x);

    • The output will be:
      Output: 20

    • x is assigned the value of y, which is 20.

  • Q8. Match Data Types

    • Data types and their ranges/usage:

    • byte: -128 to 127

    • int: -2,147,483,648 to 2,147,483,647

    • double: 15-17 decimal places

    • boolean: true or false

    • char: Single 16-bit Unicode character

  • Q9. Difference Between int and double

    • The difference is:

    • int is a 32-bit signed integer, whereas double is a 64-bit double-precision floating point.

    • Use int for whole numbers and double when decimal precision is required.

  • Q10. Code Output

    • Given the code:
      java int a = 5; int b = 2; double result = a / b; System.out.println(result);

    • The output will be:
      Output: 2.0

    • In Java, integer division truncates decimals, so 5 / 2 actually evaluates to 2 before being cast to double.

  • Q11. Declare a Constant

    • To declare and initialize a constant named PI with the value 3.14159:
      java final double PI = 3.14159;

  • Q12. String Concatenation

    • True or False: The statement String name = "John" + "Doe"; will concatenate the two strings.
      Answer: True

    • This results in name containing "JohnDoe".

Section 3: Branches (8 questions)

  • Q13. Code Output

    • Given the code:
      java int score = 75; if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else if (score >= 70) { System.out.println("C"); } else { System.out.println("F"); }

    • The output will be:
      Output: C

    • score is 75, which fits the condition for C.

  • Q14. Logical AND Operator

    • Which operator is used for logical AND in Java?
      Answer: B) &&

    • This operator evaluates to true only if both operands are true.

  • Q15. Code Error

    • What is wrong with this code?
      java int age = 20; if (age = 18) { System.out.println("Adult"); }

    • The error is attempting to use the assignment operator = instead of the equality operator ==.

  • Q16. If-Else Statement

    • Write an if-else statement that prints "Even" if a variable num is even, and "Odd" if it's odd:
      java if (num % 2 == 0) { System.out.println("Even"); } else { System.out.println("Odd"); }

  • Q17. Code Output

    • Given the code:
      java int x = 10; if (x > 5 && x < 15) { System.out.println("A"); } if (x > 8 || x < 3) { System.out.println("B"); }

    • The output will be:
      Output: A

    • The first condition is satisfied, while the second is not.

  • Q18. Convert If-Else to Switch

    • Convert the if-else statement to a switch statement:
      java int day = 3; switch(day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Other day"); }

  • Q19. Value of result

    • After executing the following code:
      java int a = 10, b = 20; boolean result = (a < b) && (b > 15);

    • The value of result will be:
      Value: true

    • Both conditions (a < b) and (b > 15) evaluate to true.

  • Q20. Switch Statement Fall Through

    • True or False: In a switch statement, if you forget the break statement, the code will "fall through" to the next case.
      Answer: True

    • This means subsequent cases will be executed until a break is encountered or the switch statement ends.

Section 4: Loops (10 questions)

  • Q21. Loop Execution Count

    • How many times will this loop execute?
      java for (int i = 0; i < 5; i++) { System.out.println(i); }

    • The loop will execute:
      Answer: 5 times

  • Q22. Code Output

    • Given the code:
      java int sum = 0; for (int i = 1; i <= 4; i++) { sum += i; } System.out.println(sum);

    • The output will be:
      Output: 10

    • This is the sum of the first four integers (1+2+3+4).

  • Q23. While Loop Error

    • Identify the error in this while loop:
      java int count = 0; while (count < 5) { System.out.println(count); }

    • The loop will cause an infinite loop as count is never incremented within the loop.

  • Q24. For Loop Example

    • Write a for loop that prints the numbers 10, 9, 8, 7, 6, 5:
      java for (int i = 10; i >= 5; i--) { System.out.println(i); }

  • Q25. Difference Between Loops

    • The difference between a while loop and a do-while loop is:

    • while loop: the condition is checked before the loop body executes.

    • do-while loop: the body executes at least once before the condition is checked.

  • Q26. Nested For Loop Output

    • Given the code:
      java for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { System.out.print("*"); } System.out.println(); }

    • The output will be:
      **Output:
      **
      **
      **

    • The inner loop prints 2 '*' characters, and the outer loop runs 3 times.

  • Q27. Break Statement in Loops

    • What does the break statement do in a loop?

    • It terminates the loop immediately and transfers control to the next statement following the loop.

  • Q28. Code Output with Continue

    • Given the code:
      java int i = 0; while (i < 5) { if (i == 3) { i++; continue; } System.out.print(i + " "); i++; }

    • The output will be:
      Output: 0 1 2 4

    • The number 3 is skipped due to the continue statement.

  • Q29. Factorial Calculation Loop

    • Write a loop that calculates the factorial of a number n (e.g., 5! = 5 × 4 × 3 × 2 × 1):
      java int factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; }

  • Q30. Infinite Loop Statement

    • True or False: An infinite loop is always a programming error.
      Answer: False

    • Infinite loops can be intentional (e.g., in server programs) to wait for an event or a condition.

Section 5: User-Defined Methods (8 questions)

  • Q31. Method Signature

    • What is the correct method signature for a method that takes two integers and returns their sum?
      Answer: B) public static int sum(int a, int b)

    • This method signature indicates it is accessible from other classes, is static, and returns an integer.

  • Q32. Code Output

    • Given the code:
      java public static int multiply(int x, int y) { return x * y; } public static void main(String[] args) { int result = multiply(4, 5); System.out.println(result); }

    • The output will be:
      Output: 20

    • The result of multiplying 4 and 5 is 20.

  • Q33. Method Overloading

    • What is method overloading? Provide an example:

    • Method overloading occurs when multiple methods have the same name but different parameters (types or numbers).
      java public void display(int a) {} public void display(String b) {}

  • Q34. Code Error in Method

    • What is wrong with this method?
      java public static int calculate(int a, int b) { int sum = a + b; }

    • The method lacks a return statement, making it invalid as it is defined to return an integer.

  • Q35. isEven Method

    • Write a method named isEven that takes an integer parameter and returns true if the number is even, false otherwise:
      java public static boolean isEven(int num) { return num % 2 == 0; }

  • Q36. Parameters vs Arguments

    • The difference between parameters and arguments is:

    • Parameters are variables defined in the method signature, while arguments are the actual values passed to the method when it is invoked.

  • Q37. Output of Modify Value Method

    • Given the code:
      java public static void modifyValue(int num) { num = 100; } public static void main(String[] args) { int value = 50; modifyValue(value); System.out.println(value); }

    • The output will be:
      Output: 50

    • Primitive types are passed by value, so changes within the method do not affect the original variable.

  • Q38. Recursive Method Call

    • Can a method call itself? What is this called?

    • Yes, a method can call itself, which is known as recursion.

Section 6: Arrays (7 questions)

  • Q39. Declaring Integer Array

    • Which of the following correctly declares and initializes an integer array with 5 elements?
      Answer: D) All of the above

    • All options correctly declare and initialize the array in different ways.

  • Q40. Output of Array Access

    • Given the code:
      java int[] numbers = {10, 20, 30, 40, 50}; System.out.println(numbers[2]);

    • The output will be:
      Output: 30

    • The element at index 2 of the array is 30.

  • Q41. Out of Bounds in Array Access

    • What happens if you try to access numbers[5] in an array of size 5?

    • It will throw an ArrayIndexOutOfBoundsException because valid indices range from 0 to 4.

  • Q42. Sum of Array Elements

    • Write a loop to calculate the sum of all elements in an array named scores:
      java int sum = 0; for (int score : scores) { sum += score; }

  • Q43. Array Length Output

    • Given the code:
      java String[] names = {"Alice", "Bob", "Charlie"}; System.out.println(names.length);

    • The output will be:
      Output: 3

    • The length of the array is determined by the number of elements defined.

  • Q44. Maximum Value in Array

    • Write code to find the maximum value in an integer array:
      java int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } }

  • Q45. Array Indices in Java

    • True or False: Array indices in Java start at 1.
      Answer: False

    • Array indices start at 0.

Section 7: Objects and Classes (5 questions)

  • Q46. Complete Class Definition

    • Complete the class definition:
      java public class Student { private String name; private int grade; public Student(String name, int grade) { this.name = name; this.grade = grade; } public int getGrade() { return grade; } }

  • Q47. Class vs Object

    • The difference between a class and an object is:

    • A class is a blueprint for creating objects, describing properties and methods.

    • An object is an instance of a class, containing actual values.

  • Q48. Code Output for Class

    • Given the code:
      java public class Counter { private int count = 0; public void increment() { count++; } public int getCount() { return count; } } public static void main(String[] args) { Counter c1 = new Counter(); c1.increment(); c1.increment(); System.out.println(c1.getCount()); }

    • The output will be:
      Output: 2

    • Two increments were called on the instance of Counter.

  • Q49. Use of Access Modifiers

    • Why do we use access modifiers like private for instance variables?

    • Access modifiers control the visibility of class members.

    • private restricts access to the class itself, thus enforcing encapsulation and protecting the integrity of the data.

  • Q50. Complete Class Definition for Rectangle

    • Write a complete class named Rectangle:
      java public class Rectangle { private double width; private double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } public double calculateArea() { return width * height; } }