Java Fundamentals
1. Question: Who invented the Java programming language?
○ Answer: James Gosling
2. Question: What company originally developed Java?
○ Answer: Sun Microsystems
3. Question: What is the current owner of Java?
○ Answer: Oracle Corporation
4. Question: What does JVM stand for?
○ Answer: Java Virtual Machine
5. Question: What does JDK stand for?
○ Answer: Java Development Kit
6. Question: What does JRE stand for?
○ Answer: Java Runtime Environment
7. Question: What is the primary feature that makes Java platform-independent?
○ Answer: Bytecode
8. Question: What type of programming paradigm does Java primarily follow?
○ Answer: Object-Oriented Programming (OOP)
9. Question: What is the extension of a Java source code file?
○ Answer: .java
10.Question: What is the extension of a compiled Java bytecode file?
○ Answer: .class
Keywords and Syntax
11.Question: Name three access modifiers in Java.
○ Answer: public, private, protected
12.Question: What keyword is used to create an object in Java?
○ Answer: new
13.Question: What keyword is used to define a constant in Java?
○ Answer: final
14.Question: What keyword is used to inherit a class in Java?
○ Answer: extends
15.Question: What keyword is used to implement an interface in Java?
○ Answer: implements
16.Question: What keyword is used to refer to the current object instance?
○ Answer: this
17.Question: What keyword is used to call the parent class's constructor?
○ Answer: super
18.Question: What keyword is used to define a method that cannot be overridden?
○ Answer: final
19.Question: What keyword is used to define a method that must be overridden in a subclass?
○ Answer: abstract
20.Question: What keyword is used to handle exceptions in Java?
○ Answer: try, catch, finally
21.Question: Name three primitive data types in Java.
○ Answer: int, double, boolean, char, byte, short, long, float
22.Question: What is the default value of a boolean variable in Java?
○ Answer: false
23.Question: What is the default value of an integer variable in Java?
○ Answer: 0
24.Question: What is the main method signature in Java?
○ Answer: public static void main(String[] args)
25.Question: What is the purpose of the static keyword in Java?
○ Answer: To indicate that a member belongs to the class itself, rather than to an instance of the class.
Object-Oriented Programming (OOP)
26.Question: What are the four pillars of OOP?
○ Answer: Encapsulation, Inheritance, Polymorphism, Abstraction
27.Question: What is encapsulation?
○ Answer: Bundling data and methods that operate on the data within a single unit (class).
28.Question: What is inheritance?
○ Answer: A mechanism where a new class inherits properties and behaviors from an existing class.
29.Question: What is polymorphism?
○ Answer: The ability of an object to take on many forms.
30.Question: What is abstraction?
○ Answer: Hiding complex implementation details and showing only essential information.
31.Question: What is a class in Java?
○ Answer: A blueprint or template for creating objects.
32.Question: What is an object in Java?
○ Answer: An instance of a class.
33.Question: What is a constructor in Java?
○ Answer: A special method that is called when an object is created.
34.Question: What is method overloading?
○ Answer: Having multiple methods with the same name but different parameters within the same class.
35.Question: What is method overriding?
○ Answer: Providing a new implementation for a method in a subclass that is already defined in its
superclass.
36.Question: What is an interface in Java?
○ Answer: A completely abstract class that contains only abstract methods and constants.
37.Question: What is an abstract class in Java?
○ Answer: A class that cannot be instantiated and may contain abstract methods.
Memory Management and Garbage Collection
38.Question: What is garbage collection in Java?
○ Answer: The automatic process of reclaiming memory occupied by objects that are no longer in use.
39.Question: What is the purpose of the finalize() method?
○ Answer: It is called by the garbage collector before an object is reclaimed. (However it is now
deprecated).
40.Question: Where are objects stored in Java memory?
○ Answer: Heap memory
Exception Handling
41.Question: What is an exception in Java?
○ Answer: An event that disrupts the normal flow of program execution.
42.Question: What is the difference between checked and unchecked exceptions?
○ Answer: Checked exceptions must be handled or declared, while unchecked exceptions are not required
to be handled.
43.Question: What is the purpose of the finally block in exception handling?
○ Answer: It contains code that is always executed, regardless of whether an exception is thrown or
caught.
Collections and Streams
44.Question: Name three common collection interfaces in Java.
○ Answer: List, Set, Map
45.Question: What is the difference between ArrayList and LinkedList?
○ Answer: ArrayList uses a dynamic array, while LinkedList uses a doubly linked list.
46.Question: What is a HashSet?
○ Answer: A collection that stores unique elements in no particular order.
47.Question: What is a HashMap?
○ Answer: A collection that stores key-value pairs.
48.Question: What are Java Streams?
○ Answer: A sequence of elements supporting sequential and parallel aggregate operations.
49.Question: What is the purpose of the forEach() method in Java Streams?
○ Answer: To perform an action for each element of the stream.
50.Question: What is the purpose of the map() method in Java Streams?
A - To filter elements of the stream based on a condition.
B - To sort the elements of the stream.
C - To transform each element of the stream using a function.
D - To reduce the stream to a single value.
Correct Answer: C - To transform each element of the stream using a function.
52.Question: Which of the following is not a valid access modifier in Java?
A - public
B - private
C - protected
D - internal
Correct Answer: D - internal
53.Question: What is the purpose of the 'super' keyword in Java?
A - To create a new instance of a class.
B - To call a method of the superclass.
C - To define a static variable.
D - To declare a final variable.
Correct Answer: B - To call a method of the superclass.
54.Question: Which exception is thrown when there is an attempt to access an array element with an illegal index?
A - ArrayIndexOutOfBoundsException
B - NullPointerException
C - IllegalArgumentException
D - IOException
Correct Answer: A - ArrayIndexOutOfBoundsException
55.Question: Which of the following is true about Java's garbage collection?
A - It is manually triggered by the programmer.
B - It reclaims the memory occupied by unused objects.
C - It is part of the operating system.
D - It is not available in Java.
Correct Answer: B - It reclaims the memory occupied by unused objects.
56.Question: What is the purpose of the 'this' keyword in Java?
A - To create a new object.
B - To refer to the current instance of the class.
C - To access static members.
D - To call a superclass constructor.
Correct Answer: B - To refer to the current instance of the class.
57.Question: Which of the following is a checked exception in Java?
A - NullPointerException
B - ArrayIndexOutOfBoundsException
C - IOException
D1 - RuntimeException
Correct Answer: C - IOException
58.Question: What is the purpose of the 'instanceof' operator in Java?
A - To compare two objects for equality.
B - To check if an object is an instance of a particular class or interface.
C - To create a new instance of a class.
D - To cast an object to a different type.
Correct Answer: B - To check if an object is an instance of a particular class or interface.
59.Question: Which of the following is true about interfaces in Java?
A - Interfaces can have instance variables.
B - Interfaces can have method implementations.
C - Interfaces can be instantiated.
D - Interfaces can have only abstract methods.
Correct Answer: D - Interfaces can have only abstract methods. (Prior to Java 8, now they can have default and static
methods)
60.Question: What is the purpose of the 'try-catch' block in Java?
A - To define a loop.
B - To handle exceptions.
C - To define a method.
D - To declare a variable.
Correct Answer: B - To handle exceptions.
Java MCQ’s :
https://www.placementpreparation.io/mcq/java
https://www.geeksforgeeks.org/quizzes/50-java-language-mcqs-with-answers-2
https://www.interviewbit.com/java-mcq
https://www.indiabix.com/java-programming/questions-and-answers
https://www.geeksforgeeks.org/java-multiple-choice-questions
https://www.scholarhat.com/tutorial/java/top-50-java-mcq-questions
https://www.examveda.com/mcq-question-on-java-program
Java Debugging:
1. What will the following code output?
public class DebuggingExample {
public static void main(String[] args) {
int x = 10;
System.out.println(x++); // Post-increment
}
A) 10
B) 11
C) Compilation error
D) Runtime error
2. What does the following code snippet print?
public class DebuggingExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(a < b ? a : b);
}
A) 10
B) 20
C) `a`
D) `b`
3. What will the following code output?
public class DebuggingExample {
public static void main(String[] args) {
String str = "hello";
System.out.println(str.toUpperCase().substring(1, 4));
}
A) `HEL`
B) `HELLO`
C) `ELL`
D) `EL`
4. What is the output of this code?
public class DebuggingExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr[5]);
}
A) 5
B) `ArrayIndexOutOfBoundsException`
C) `null`
D) 4
5. What will the following code output?
public class DebuggingExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
i++;
}
System.out.println(i);
}
A) 4
B) 5
C) 6
D) 0
6. What does the following code do?
public class DebuggingExample {
public static void main(String[] args) {
String str = "Java";
str = str.concat(" Programming");
System.out.println(str);
}
A) `Java`
B) `Java Programming`
C) `JavaProgramming`
D) Compilation error
7. What will this code print?
public class DebuggingExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.println("Error");
}
}
A) `Error`
B) `Infinity`
C) `10`
D) `0`
8. What is the output of the following code?
public class DebuggingExample {
public static void main(String[] args) {
String s = "123";
int num = Integer.parseInt(s);
System.out.println(num);
}
A) `123`
B) `12`
C) `null`
D) `Exception`
9. What will be the output of this code?
public class DebuggingExample {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
}
A) `0 1 2 3`
B) `0 1 2`
C) `1 2 3`
D) `0 1`
10. What does the following code snippet do?
public class DebuggingExample {
public static void main(String[] args) {
int a = 5;
int b = a++;
System.out.println(b);
}
A) `5`
B) `6`
C) `4`
D) `0`
11. What will this code output?
public class DebuggingExample {
public static void main(String[] args) {
String s = "hello";
s = s.replace('l', 'r');
System.out.println(s);
}
A) `herro`
B) `herro`
C) `herro`
D) `hello`
12. What does this code do?
public class DebuggingExample {
public static void main(String[] args) {
String[] arr = new String[5];
arr[0] = "one";
arr[1] = "two";
System.out.println(arr[2]);
}
A) `null`
B) `two`
C) `one`
D) `ArrayIndexOutOfBoundsException`
13. What will the following code output?
public class DebuggingExample {
public static void main(String[] args) {
String str = "Java";
System.out.println(str.substring(1, 4));
}
A) `Java`
B) `ava`
C) `ja`
D) `a`
14. What is the output of the following code?
public class DebuggingExample {
public static void main(String[] args) {
int i = 1;
System.out.println(i++ + ++i);
}
A) `4`
B) `5`
C) `6`
D) `7`
15. What does the following code print?
public class DebuggingExample {
public static void main(String[] args) {
System.out.println("Hello" + 1 + 2);
}
A) `Hello12`
B) `Hello3`
C) `Hello1 2`
D) `Hello`
16. What is the result of this code?
public class DebuggingExample {
public static void main(String[] args) {
String str = "Java";
System.out.println(str.charAt(2));
}
A) `J`
B) `a`
C) `v`
D) `a`
17. What will be the output of the following code?
public class DebuggingExample {
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 3
};
for (int i : nums) {
System.out.println(i);
}
}
A) `1 2 3`
B) `1`
`2`
`3`
C) `3 2 1`
D) `2 3 1`
18. What will this code output?
public class DebuggingExample {
public static void main(String[] args) {
String s = "abc";
s = s.toUpperCase();
System.out.println(s);
}
A) `ABC`
B) `abc`
C) `Abc`
D) `null`
19. What will be the result of the following code?
public class DebuggingExample {
public static void main(String[] args) {
String s = "123a";
int num = Integer.parseInt(s);
System.out.println(num);
}
A) `123`
B) `123a`
C) `Exception`
D) `null`
20. What does this code do?
public class DebuggingExample {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println(++a * b--);
}
A) `60`
B) `55`
C) `50`
D) `45`
21. What will be the output of this code?
public class DebuggingExample {
public static void main(String[] args) {
String str = "hello";
System.out.println(str.indexOf('l'));
}
A) `2`
B) `3`
C) `-1`
D) `4`
22. What is the result of this code?
public class DebuggingExample {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
System.out.println(nums[nums.length]);
}
A) `3`
B) `IndexOutOfBoundsException`
C) `2`
D) `null`
23. What does this code print?
public class DebuggingExample {
public static void main(String[] args) {
String str = "java";
System.out.println(str.concat(" programming").toUpperCase());
}
A) `java programming`
B) `JAVA PROGRAMMING`
C) `Java programming`
D) `JAVA PROGRAMMING.`
24. What is the output of this code?
public class DebuggingExample {
public static void main(String[] args) {
int a = 7;
int b = 3;
System.out.println(a % b);
}
A) `2`
B) `1`
C) `0`
D) `3`
25. What will this code output?
public class DebuggingExample {
public static void main(String[] args) {
String s = "hello";
System.out.println(s.equalsIgnoreCase("HELLO"));
}
A) `true`
B) `false`
C) `hello`
D) `HELLO`
26. What does the following code output?
public class DebuggingExample {
public static void main(String[] args) {
System.out.println("Hello".charAt(0));
}
A) `H`
B) `e`
C) `Hello`
D) `0`
27. What will be the output of this code?
public class DebuggingExample {
public static void main(String[] args) {
String str = "Java";
str = str.toLowerCase();
System.out.println(str.substring(2));
}
A) `java`
B) `va`
C) `ava`
D) `jav`
28. What does this code print?
public class DebuggingExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
}
System.out.println(Arrays.toString(arr));
}
A) `[2, 4, 6]`
B) `[1, 2, 3]`
C) `[2, 4, 6]`
D) `[2, 4, 6]`
29. What will the following code print?
public class DebuggingExample {
public static void main(String[] args) {
int x = 10;
System.out.println(x > 5 && x < 15);
}
A) `true`
B) `false`
C) `10`
D) `null`
30. What will this code output?
public class DebuggingExample {
public static void main(String[] args) {
System.out.println(2 + 3 * 4);
}
A) `14`
B) `20`
C) `24`
D) `5`
31. What does the following Java code snippet do?
public class DebuggingExample {
public static void main(String[] args) {
int x = 5;
int y = 0;
try {
System.out.println(x / y);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
A) The code prints "Cannot divide by zero."
B) The code throws an ArithmeticException.
C) The code results in a compile-time error.
D) The code prints "Infinity."
32. What will be the output of the following code?
public class DebuggingExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]);
}
}
A) The code will print all numbers in the array and then throw an ArrayIndexOutOfBoundsException.
B) The code will print all numbers in the array without error.
C) The code will throw an ArrayIndexOutOfBoundsException without printing any numbers.
D) The code will print "1 2 3 4 5" followed by an error message.
33. Given the following code, what will be the output?
public class DebuggingExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Before swap: a = " + a + ", b = " + b);
swap(a, b
); System.out.println("After swap: a = " + a + ", b = " + b);
}
public static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
A) Before swap: a = 10, b = 20
After swap: a = 20, b = 10
B) Before swap: a = 10, b = 20
After swap: a = 10, b = 20
C) The code will not compile.
D) The code will throw an exception.
34. What is the result of the following code snippet?
public class DebuggingExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length());
}
A) The code will print 0.
B) The code will print null.
C) The code will throw a NullPointerException.
D) The code will compile but not run.
35. Consider the following Java code. What will be the output?
public class DebuggingExample {
public static void main(String[] args) {
String str = "debugging";
System.out.println(str.substring(3, 10));
}
A) deb
B) ugging
C) bugging
D) debugg
1. Bug: Logical Error (Incorrect Condition)
Java
// Buggy Code
public class Bug1 {
public static boolean isEven(int num) {
return num / 2 == 1; // Incorrect condition
}
public static void main(String[] args) {
System.out.println(isEven(4)); // Should be true, but it's false
}
}
// Corrected Code
public class Bug1Corrected {
public static boolean isEven(int num) {
return num % 2 == 0; // Correct condition
}
public static void main(String[] args) {
System.out.println(isEven(4));
}
}
2. Bug: Array Index Out of Bounds
Java
// Buggy Code
public class Bug2 {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
for (int i = 0; i <= arr.length; i++) { // i <= arr.length is the problem
System.out.println(arr[i]);
}
}
}
// Corrected Code
public class Bug2Corrected {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
for (int i = 0; i < arr.length; i++) { // i < arr.length
System.out.println(arr[i]);
}
}
}
3. Bug: Null Pointer Exception
Java
// Buggy Code
public class Bug3 {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // NullPointerException
}
}
// Corrected Code
public class Bug3Corrected {
public static void main(String[] args) {
String str = null;
if (str != null) {
System.out.println(str.length());
} else {
System.out.println("String is null");
}
}
}
4. Bug: Integer Division (Truncation)
Java
// Buggy Code
public class Bug4 {
public static void main(String[] args) {
int a = 5;
int b = 2;
System.out.println(a / b); // Output: 2, should be 2.5
}
}
// Corrected Code
public class Bug4Corrected {
public static void main(String[] args) {
double a = 5;
double b = 2;
System.out.println(a / b);
}
}
5. Bug: Incorrect Loop Condition
Java
// Buggy Code
public class Bug5 {
public static void main(String[] args) {
for (int i = 10; i > 0; i++) {
i++; // Infinite loop
System.out.println(i);
}
}
}
// Corrected Code
public class Bug5Corrected {
public static void main(String[] args) {
for (int i = 10; i > 0; i--) { // i--
System.out.println(i);
}
}
}
6. Bug: Uninitialized Variable
Java
// Buggy Code
public class Bug6 {
public static void main(String[] args) {
int x;
System.out.println(x); // Error: variable x might not have been initialized
}
}
// Corrected Code
public class Bug6Corrected {
public static void main(String[] args) {
int x = 0; // Initialize x
System.out.println(x);
}
}
7. Bug: Incorrect String Comparison
Java
// Buggy Code
public class Bug7 {
public static void main(String[] args) {
String str1 = "hello";
String str2 = new String("hello");
System.out.println(str1 == str2); // False, should be true
}
}
// Corrected Code
public class Bug7Corrected {
public static void main(String[] args) {
String str1 = "hello";
String str2 = new String("hello");
System.out.println(str1.equals(str2)); // Use equals()
}
}
8. Bug: Incorrect Type Casting
Java
// Buggy Code
public class Bug8 {
public static void main(String[] args) {
double d = 10.5;
int i = (int) d;
System.out.println(i);
byte b = (byte) 200; // Value out of range of byte
System.out.println(b);
}
}
// Corrected Code
public class Bug8Corrected {
public static void main(String[] args) {
double d = 10.5;
int i = (int) d;
System.out.println(i);
byte b = (byte) 127; // value in range of byte
System.out.println(b);
}
}
9. Bug: Missing Break in Switch Statement
Java
// Buggy Code
public class Bug9 {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday"); // Fallthrough
case 3:
System.out.println("Wednesday");
}
}
}
// Corrected Code
public class Bug9Corrected {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
}
}
}
10. Bug: Incorrect Use of Logical Operators
Java
// Buggy Code
public class Bug10 {
public static void main(String[] args) {
int a = 5;
if (a > 10 & a < 20) { // & instead of &&
System.out.println("In range");
} else {
System.out.println("Out of range");
}
}
}
// Corrected Code
public class Bug10Corrected {
public static void main(String[] args) {
int a = 5;
if (a > 10 && a < 20) { // &&
System.out.println("In range");
} else {
System.out.println("Out of range");
}
}
}
11. Bug: Incorrect Loop Termination
Java
// Buggy Code
public class Bug11 {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
// i++; // Missing increment, infinite loop
}
}
}
// Corrected Code
public class Bug11Corrected {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
12. Bug: Incorrect Object Comparison
Java
// Buggy Code
public class Bug12 {
public static void main(String[] args) {
Integer num1 = 1000;
Integer num2 = 1000;
System.out.println(num1 == num2); // False, should be true
}
}
// Corrected Code
public class Bug12Corrected {
public static void main(String[] args) {
Integer num1 = 1000;
Integer num2 = 1000;
System.out.println(num1.equals(num2)); // Use equals() for Integer objects
}
}
13. Bug: Incorrect Method Signature
Java
// Buggy Code
public class Bug13 {
public static void main(String[] args) {
int result = add(5.5, 3.5); // Error: incompatible types
System.out.println(result);
}
public static int add(int a, int b) {
return a + b;
}
}
// Corrected Code
public class Bug13Corrected {
public static void main(String[] args) {
double result = add(5.5, 3.5);
System.out.println(result);
}
public static double add(double a, double b) {
return a + b;
}
}
14. Bug: Incorrect Scope of Variable
Java
// Buggy Code
public class Bug14 {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
int sum = 0;
sum += i;
}
System.out.println(sum); // Error: cannot find symbol sum
}
}
// Corrected Code
public class Bug14Corrected {
public static void main(String[] args) {
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += i;
}
System.out.println(sum);
}
}
15. Bug: Incorrect Use of Modulo Operator
Java
// Buggy Code
public class Bug15 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 1) { // Incorrect logic for even numbers
System.out.println(i);
}
}
}
}
// Corrected Code
public class Bug15Corrected {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) { // Correct logic for even numbers
System.out.println(i);
}
}
}
}
16. Bug: Incorrect File Handling (Missing Close)
Java
// Buggy Code
import java.io.*;
public class Bug16 {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("test.txt");
writer.write("Hello, World!");
// writer.close(); // Missing close()
}
}
// Corrected Code
import java.io.*;
public class Bug16Corrected {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("test.txt");
writer.write("Hello, World!");
writer.close();
}
}
17. Bug: Incorrect Exception Handling
Java
// Buggy Code
public class Bug17 {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArrayIndexOutOfBoundsException e) { // Incorrect exception type
System.out.println("Error");
}
}
}
// Corrected Code
public class Bug17Corrected {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) { // Correct exception type
System.out.println("Error");
}
}
}
18. Bug: Incorrect Array Initialization
Java
// Buggy Code
public class Bug18 {
public static void main(String[] args) {
int[] arr = new int[5];
arr[5] = 10; // ArrayIndexOutOfBoundsException
}
}
// Corrected Code
public class Bug18Corrected {
public static void main(String[] args) {
int[] arr = new int[5];
arr[4] = 10;
}
}
19. Bug: Incorrect Increment in For Loop
Java
// Buggy Code
public class Bug19 {
public static void main(String[] args) {
for (int i = 0; i < 5;) { // Missing increment
System.out.println(i);
}
}
}
// Corrected Code
public class Bug19Corrected {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
20. Bug: Incorrect use of static variables.
Java
// Buggy code
public class Bug20{
static int count = 0;
public Bug20(){
count++;
}
public static void main(String[] args){
Bug20 a = new Bug20();
Bug20 b = new Bug20();
System.out.println(a.count);
}
}
// Corrected code
public class Bug20Corrected{
int count = 0;
public Bug20Corrected(){
count++;
}
public int getCount(){
return count;
}
public static void main(String[] args){
Bug20Corrected a = new Bug20Corrected();
Bug20Corrected b = new Bug20Corrected();
System.out.println(a.getCount());
}
}
21. Bug: Incorrect use of += operator with String
Java
// Buggy Code
public class Bug21 {
public static void main(String[] args) {
String str = "Hello";
str += ' ';
str += 10; // Appends '10' as a string, not as a sum
System.out.println(str);
}
}
// Corrected Code
public class Bug21Corrected {
public static void main(String[] args) {
String str = "Hello";
str += ' ';
str += String.valueOf(10); // Converts 10 to a string
System.out.println(str);
}
}
22. Bug: Incorrect use of this keyword
Java
// Buggy Code
public class Bug22 {
int value;
public Bug22(int value) {
value = value; // Incorrect assignment
}
public static void main(String[] args) {
Bug22 obj = new Bug22(5);
System.out.println(obj.value); // Output: 0
}
}
// Corrected Code
public class Bug22Corrected {
int value;
public Bug22Corrected(int value) {
this.value = value; // Correct use of this
}
public static void main(String[] args) {
Bug22Corrected obj = new Bug22Corrected(5);
System.out.println(obj.value);
}
}
23. Bug: Incorrect use of instanceof
Java
// Buggy Code
public class Bug23 {
public static void main(String[] args) {
Object obj = "Hello";
if (obj instanceof Integer) { // Incorrect check
System.out.println("It's an Integer");
} else {
System.out.println("It's not an Integer");
}
}
}
// Corrected Code
public class Bug23Corrected {
public static void main(String[] args) {
Object obj = "Hello";
if (obj instanceof String) { // Correct check
System.out.println("It's a String");
} else {
System.out.println("It's not a String");
}
}
}
24. Bug: Incorrect use of final with Collections
Java
// Buggy Code
import java.util.ArrayList;
import java.util.List;
public class Bug24 {
public static void main(String[] args) {
final List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers = new ArrayList<>(); // Error: cannot assign a value to final variable numbers
}
}
// Corrected Code
import java.util.ArrayList;
import java.util.List;
public class Bug24Corrected {
public static void main(String[] args) {
final List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2); // Modifying the list is allowed
}
}
25. Bug: Incorrect use of nested loops
Java
// Buggy Code
public class Bug25{
public static void main(String[] args){
for(int i = 0; i < 5; i++){
for(int j = 0; i < 3; j++){ //Error i should be j
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
// Corrected code
public class Bug25Corrected{
public static void main(String[] args){
for(int i = 0; i < 5; i++){
for(int j = 0; j < 3; j++){
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
26. Bug: Incorrect use of Post/Pre increment operators
Java
// Buggy code
public class Bug26{
public static void main(String[] args){
int x = 5;
int y = x++;
System.out.println("x: " + x + " y: " + y); // x = 6, y = 5
y = ++x;
System.out.println("x: " + x + " y: " + y); // x = 7, y = 7
y = x--;
System.out.println("x: " + x + " y: " + y); // x = 6, y = 7
y = --x;
System.out.println("x: " + x + " y: " + y); // x = 5, y = 5
//Now to make the bug, lets do this.
y = x++ + x; //incorrect assumption that x will be incremented first.
System.out.println("x: " + x + " y: " + y);
}
}
//Corrected code
public class Bug26Corrected{
public static void main(String[] args){
int x = 5;
int y = x++;
System.out.println("x: " + x + " y: " + y);
y = ++x;
System.out.println("x: " + x + " y: " + y);
y = x--;
System.out.println("x: " + x + " y: " + y);
y = --x;
System.out.println("x: " + x + " y: " + y);
//Corrected code.
int temp = x;
x++;
y = temp + x;
System.out.println("x: " + x + " y: " + y);
}
}
27. Bug: Incorrect use of bitwise operators
Java
//Buggy code
public class Bug27{
public static void main(String[] args){
int a = 5;
int b = 3;
int c = a & b; // expecting logical and, but getting bitwise and.
System.out.println(c);
}
}
//Corrected Code
public class Bug27Corrected{
public static void main(String[] args){
boolean a = true;
boolean b = false;
boolean c = a && b;
System.out.println(c);
}
}
28. Bug: Incorrect use of compareTo
Java
//Buggy Code
public class Bug28{
public static void main(String[] args){
String a = "apple";
String b = "banana";
if(a.compareTo(b) > 0){ // Incorrect comparison, a is less than b
System.out.println("a is greater than b");
} else {
System.out.println("a is less than or equal to b");
}
}
}
//Corrected Code
public class Bug28Corrected{
public static void main(String[] args){
String a = "apple";
String b = "banana";
if(a.compareTo(b) < 0){
System.out.println("a is less than b");
} else {
System.out.println("a is greater than or equal to b");
}
}
}
29. Bug: Incorrect use of Math.random()
Java
//Buggy Code
public class Bug29{
public static void main(String[] args){
int random = (int)Math.random() * 10; // will always be 0
System.out.println(random);
}
}
//Corrected Code
public class Bug29Corrected{
public static void main(String[] args){
int random = (int)(Math.random() * 10); // Correct order of operations
System.out.println(random);
}
}
30. Bug: Incorrect use of nested try-catch
Java
//Buggy Code
public class Bug30{
public static void main(String[] args){
try{
try{
int a = 10/0;
} catch(ArrayIndexOutOfBoundsException e){ // incorrect exception.
System.out.println("Inner Catch");
}
Debugging Practice Links:
https://www.geeksforgeeks.org/java-tricky-output-questions
Basic Questions:
1. Write a program to print all odd,even numbers
2. Write a program to find the sum of all odd/even numbers from 1 to N.
3. Write a program to check if a given number is prime,composite.
4. Write a program to find the factorial of a given number.
5. Write a program to check if a given number is an Armstrong number.
6. Write a program to check if a given number is a palindrome.
7. Write a program to reverse a given number.
8. Write a program to find the sum of digits of a given number.
9. Write a program to find the largest digit in a given number.
10.Write a program to find the smallest digit in a given number.
11.Write a program to check if a given number is a perfect number.
12.Write a program to check if a given number is a happy number.
13.Write a program to find the greatest common divisor (GCD) /HCF (Highest Common Factor) of two numbers.
14.Write a program to find the least common multiple (LCM) of two numbers.
15.Write a program to generate the Fibonacci sequence up to a given number.
16.Write a program to check if a given year is a leap year.
17.Write a program to convert a decimal number to binary.
18.Write a program to convert a binary number to decimal.
19.Write a program to calculate the power of a number (x^y).
20.Write a program to find the square root of a number.
21.Write a program to find the largest element in an array.
22.Write a program to find the smallest element in an array.
23.Write a program to find the sum of all elements in an array.
24.Write a program to reverse an array.
25.Write a program to search for an element in an array.
26.Write a program to sort an array in ascending order.
27.Write a program to sort an array in descending order.
28.Write a program to find the frequency of each element in an array.
29.Write a program to check if a given string is a palindrome.
30.Write a program to reverse a given string.
31.Write a program to count the number of vowels,consonants in a string.
32.Write a program to convert upper case to lower case.
33.Write a program to count the number of words in a string.
34.Write a program to count the number of characters in a string.
35.Write a program to check if one string is a substring of another.
36.Write a program to find the longest word in a string.
37.Write a program to remove all spaces from a string.(left trim,right trim,specific character trim)
38.Write a program to compare two strings.
39.Write a program to concatenate two strings.
40.Write a program to check if a given number is positive, negative, or zero.
41.Write a program to swap two numbers without using a third variable.
42.Write a program to check if a number is a perfect square.
43.Write a program to check if a given number is even or odd using bitwise operations.
44.Write a program to find the XOR of two numbers.
45.Write a program to find the second largest element in an array.
46.Write a program to find the second smallest element in an array.
47.Write a program to remove duplicates from an array.
48.Write a program to find the intersection of two arrays.
49.Write a program to find the union of two arrays.
50.Write a program to find the sum of a geometric series.
51.Write a program to find the sum of an arithmetic series.
52.Write a program to find the roots of a quadratic equation.
53.Write a program to print the ASCII value of a character.
Algorithms:
1. Write a program for Linear Search.
2. Write a program for Binary Search.
3. Write a program for Bubble Sort.
4. Write a program for Merge Sort.
5. Write a program for Quick Sort.
6. Write a program for Recursive Fibonacci.
7. Write a program for Iterative Fibonacci.