Java Debugging Questions2
Java Debugging Questions2
1.
public class OperatorExample {
public static void main(String[] args) {
int x = 1;
int y = 2;
int z = 5;
System.out.println(“x: “ +(x == 1));
System.out.println(“y: “ +(y == z));
if(x == 1 || x == y || x == z) {
System.out.println(“One”);
}
if(x == y || y == 2 || z == 5) {
System.out.println(“Two”);
}
if(x == y || y == z || z == x) {
System.out.println(“Three”);
}
}
}
Output:-
x: true
y: false
One
Two
Explanation:-
Three integer variables x, y, and z are initialized with the values 1, 2, and 5,
The
x==1,this will print true, y is not equal to z so false.x == 1 || x == y || x == z:
The OR
operator (||) checks if at least one of the conditions is true. x == 1 is true
because x is
1.similarly y==2 true so it prints Two.
=================================================================
2)
public class Example {
public static void main(String[] args) {
int x = 7;
int y = 10;
int z = (x > y) ? x & y : x | y;
System.out.println(“z:” + z);
}
}
Output:-
z:15
Explanation:-
x is initialized with 7, which is 0111 in binary. y is initialized with 10, which
is 1010
in binary.It checks the condition and it becomes false.so Bitwise OR is evaluated
between 0111 and 1010 the result is 1111, which is 15 in decimal.
3)
public class DivisionExample {
public static void main(String[] args) {
int a = 14;
int b = 5;
int c = (a / b) % 2 == 0 ? a : a % b + b;
System.out.println(“a:” + a);
System.out.println(“b” + b);
System.out.println(“c:” + c);
}
}
Output:-
a: 14
b: 5
c: 14
Explanation: -
a is initialized to 14.b is initialized to 5.(a / b) is 14 / 5 which gives 2.(a /
b) % 2
calculates 2 % 2, which is 0. Since the result is 0, the condition (a / b) % 2 == 0
is true
and c = a.
=================================================================
4)
public class TernaryExample {
public static void main(String[] args) {
int a = 3;
int b = 4;
int c = a++ * ++b;
int d = (a > b) ? a + b : a - b;
System.out.println(“a:” + a);
System.out.println(“b:” + b);
System.out.println(“c:” + c);
System.out.println(“d:” + d);
}
}
Output:-
a: 4
b: 5
c: 15
d: -1
Explanation:-
a and b is initialized with 3 , 4 respectively.a++ is the post-increment operation
so
it will increment after the multiplication ,++b is the pre-increment operation so
b=5 the
result a++*++b=3*5=15. after this a is incremented a=4 and b=5.The condition (a >
b)
evaluates to false(4>5).hence d = 4-5 =-1.
=================================================================
5)
public class TrickyStringOperators {
public static void main(String[] args) {
String str1 = “Hello”;
String str2 = “World”;
int result1 = 5 * 2 - 2;
int result2 = str2.length() % 3;
String result = str1 + result1 + result2;
System.out.println(“str1: “ + str1);
System.out.println(“str2: “ + str2);
System.out.println(“result: “ + result);
}
}
Output: -
str1: Hello
str2: World
result: Hello82
Explanation:-
str1 is initialized with “Hello” and str2 is initialized with “World”. The 5 * 2 -
2 = 8.
str2LengthModulus = str2.length() % 3 in which length of “World” is 5 and 5 % 3
equals
2. Hence Strings1,result1 and result2 are concatenated.
=================================================================
6)
public class Example {
public static void main(String[] args) {
int a = 10;
int b = 5;
int result = a / b * 2 - b / 0;
System.out.println(“result: “ + result);
}
}
Output:-
Error
Explanation:-
The expression b / 0 results in division by zero, which is an illegal operation in
Java. Division by zero causes an Arithmetic Exception at runtime. To fix this, add
a
check to ensure that the divisor is not zero.
=================================================================
7)
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b && a<c);
System.out.println(a);
System.out.println(a<b&a++<c);System.out.println(a);
}
}
Output:-
false
10
false
11
Explanation: -
For the first print statement 5<10=false and a + + is post increment so a value is
10<20 true both are connected by logic and so both input should be true otherwise
output is false ,here the first condition itself false so it never executes the
second
statement.
For the 2nd print statement a value is not incremented so output is 10.
For 3
rd print statement first condition is false so that second condition is checked is
true
(false and true) is false
For 4
th statement a is incremented because the second condition of 3
rd statement is
true.
=================================================================
8)
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
System.out.println(!d);
}
}
Output:-
-11
9
false
true
Explanation:-
”~” this is a bitwise complement; it will complement the digits in binary
digit.Binary
form of 10 is 1010 so complement of 10 is 0101 ,which is converted to its
corresponding
binary representation using 2’s complement is -11. In the 2
nd print statement, The binary
representation of -10 is 1001 which is binary in 9. For the 3rd and 4
th statement the
operator is logical not which gives the complement of inputs.
=================================================================
9)
class Animal{
}
class Dog extends Animal{
}
public class Test{
public static void main(String args[]){
Animal myAnimal=new Dog();
Animal another=null;
System.out.println(myAnimal Instanceof Dog);
System.out.println(myAnimal Instanceof Animal);
System.out.println(another Instanceof Animal);
}
}
Output :-
true
true
false
Explanation: -
The java instanceof operator is used to test whether the object is an instance of
the specified type (class or subclass ) if it is the instance of that class output
is true. If
we apply the instanceof operator with any variable that has null value, it returns
false.
=================================================================
10)
public class Code1{
public static void main(String[] args) {
int a = 10, b = 20;
int max = a >b ? a : b;
System.out.println(“Max:”+ max);
String result = a >b ? “a is greater”; :100;
}
}
Output:-
String result = a > b ? “a is greater”; : 100; (Incompatible types) ^ .iint cannot
be
converted to String
Explanation:-
Misuse: Assigning the result to the wrong type
=================================================================
11)
public class Code2 {
public static void main(String[] args) {
int a = 5;
int b = 2;
double result = a / b;
System.out.println(“Result:” + result);
}
}
Output:-
Result: 2.0
Explanation: -
The data type is double so output is in double;
=================================================================
12)
public class Incre {
public static void main(String[] args) {
int x = 5; int y = x++;
System.out.println(“x:” + x + “y:”; + y);
}
}
Output:-
x: 6, y: 5
Explanation:-
y is assigned 5, then x is incremented.
13)
public class StringComparisonError {
public static void main(String[] args) {
String s1 = “hello”;
String s2 = new String(“hello”);
if (s1 == s2) {
System.out.println(“Strings are equal”);
}
else {
System.out.println(“Strings are not equal”);
}
}
}
Error:-
The output is Strings are not equal .
Explanation:-
== compares object references, not content. Using .equals() to compare the
actual string values, it can be resolved.
14)
public class BitwiseOrError {
public static void main(String[] args) {
double a = 5.5;
double b = 2.0;
double result = a | b;
System.out.println(“Result:” + result);
}
}
Error: -
Operator |’; cannot be applied to the ‘double’ data type.
Explanation: -
Bitwise operators can only be applied to integer types. Changing the variables to
integers fixes the issue.
=================================================================
15)
public class LogicalAndError {
public static void main(String[] args) {
int a = 5;
int b = 10;
boolean result = (a = 5) && (b >a);
System.out.println(“Result:” + result);
}
}
Error: -
Operator “&&” cannot be applied to int;
Explanation:-
The && operator expects boolean operands. The original code uses
=(assignment) instead of == (equality).
=================================================================
16)
public class TernaryOperatorError {
public static void main(String[] args) {
int a = 10;
String result = (a > 5) ? 100 : "Less";
System.out.println(“Result:” + result);
}
}
Error:-
Incompatible types: int cannot be converted to String;
Explanation:-
The ternary operator should return the same type for both outcomes.
=================================================================
17)
public class Main {
public static void main(String[] args) {
double a = 0.1;
double b = 0.2;
if (a + b == 0.3) {
System.out.println("Equal");
}
else {
System.out.println("Not Equal");
}
}
}
Output:-
Error,incorrect comparison.
Explanation:-
Floating-point numbers should not be compared directly using `==` due to
precision issues. To fix this, use a tolerance level when comparing floating-point
numbers. It is corrected by assigning it with tolerance level if (Math.abs((a + b)
- 0.3) <
0.00001).
=================================================================
18)
public class Main {
public static void main(String[] args) {
int x = 4; // binary: 0100
int y = 1; // binary: 0001
if ((x & y) == 1) {
System.out.println("Condition true");
}
else {
System.out.println("Condition false");
}
}
}
Output:-
Error,incorrect comparison.
Explanation:-
The bitwise AND operator `&` is used incorrectly instead of the logical AND
operator `&&`. To fix this, replace `&` with `&&`.
=================================================================
19)
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 20;
int z = 5;
if (x > y && y < z || z == 5) {
System.out.println("Condition met");
}
else {
System.out.println("Condition not met");
}
}
}
Output:-
The issue is with the operator precedence. The expression (x > y && y < z || z
== 5) is evaluated from left to right, which may lead to unexpected results.
Corrected precedence with parentheses is by if ((x > y && y < z) || z == 5)
=================================================================
20)
Public class IncompatibleTypeCasting{
Public static void main(String args[]){
double a=10.5;
double b=3.5;
System.out.println(“a:”+a +”b:”+b);
int x=a;
int y=b;
System.out.println(“a:”+a +”b:”+b);
}
}
Output:-
a:10.5
b:3.5
Error;
Explanation:-
double datatype can’t be compatible with integer datatype. To rectify this we have
to explicitly type cast it but int can be compatible with double implicitly.
=================================================================
21)
class Person {
String name;
int age;
}
public class Main{
public static void main(String[] args) {
Person person = new Person();
person.name = "John";
person.age = 30;
System.out.println("Name: " + person.name);
System.out.println("Age: " + person.age);
}
}
Output:-
Name:John
Age:30;
Explanation:-
Dot operator is used to access the class properties and behaviors;
=================================================================
22)
public class Test {
public static void main(String args[]){
int i=20+ +9- -12+ +4- -13+ +19;
System.out.println(i);
}
}
Output:-
i=77
Explanation:-
In the program, the operators are just to puzzle someone. The operators are neither
pre or post increments. The statement can be written and solved as follows:
int i=20+ (+9)- (-12)+ (+4)- (-13)+ (+19);
i=20+9+12+4+13+19
=================================================================
23)
public class Main {
public static void main(String[] args) {
int i = 0;
while (i <10) {
System.out.println(i);
i = i++;
}
}
}
Output:-
0
Explanation:-
The issue is with the line i = i++;. This is a classic example of a “dangling
increment” that can be fixed by simply changing it to i + +;.
24)
public class Main {
public static void main(String[] args) {
boolean b = true;
if (b = false) {
System.out.println(“This should not print.”;);
}
}
}
Output:-
This should not print.
Explanation:-
The issue is with the line if (b = false). This is an assignment, not a comparison,
and sets b to false. To fix, change it to if (b == false) or simply if (!b).
=================================================================
25)
public class Main {
public static void main(String[] args) {
byte b = 10;
b += 10;
System.out.println(b);
}
}
Output:-
20
Explanation:-
The += operator promotes the byte value to an int before performing the
addition.
=================================================================
26)
import java.util.scanner;
class data{
public static void main(String args[]){
Scanner scan = new Scanner();
long x = scan.nextLong();
if (x < 9223372036854775807 && x > -9223372036854775808) {
System.out.println("* long");
}
}
}
Error:-
data.java:6: error: integer number too large
Explanation:-
Even Though the given number is specified as long in the given question the
numbers specified in the comparison are automatically considered as integers by the
compiler. This can be prevented by the use of adding long to the end of the given
number.
=================================================================
27)
class data{
public static void main(String args[]){
String str = "123x";
int number;
number = Integer.parseInt(str);
}
}
Error:-
Exception in thread "main" java.lang.NumberFormatException: For input string:
"123x"atjava.base/java.lang.NumberFormatException.
Explanation: -
In the given question the input string 123x is of incompatible method to be
converted into an integer due to the presence of the x using the function parseInt.
=================================================================
28)
class data{
public static void main(String args[]){
double str = 123.1;
int number = 5;
double num;
num=number + str;
}
}
Error:-
No error
Explanation:-
The given code is expected to give an error but results in the compiler giving no
errors due to the compiler automatically converting the integer to a double value.
=================================================================
29)
class data{
public static void main(String args[]){
var v1;
v1 = 10;
}
}
Error:-
data.java:12: error: cannot infer type for local variable v1
var v1;
Explanation:-
Var type variables need to be assigned a value during its creation since the
compiler has to identify and declare the type during its initialization
30)
public class OverflowError {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
int result = max + 1;
System.out.println("Result: " + result);
}
}
Error:-
The program runs but gives an incorrect result due to overflow
Explanation:-
Integer overflow happens when the value exceeds Integer.MAX_VALUE. Using
a larger data type (long) avoids overflow
=================================================================
31)
public class Test {
public static void main(String[] args) {
System.out.println('j' + 'a' + 'v' + 'a');
}
}
Output:-
418
Explanation:-
Each character is converted to its ASCII value and then summed up
(106 + 97 + 118 + 97)
=================================================================
32)
public class Test {
public static void main(String[] args) {
Integer num1 = 400;
Integer num2 = 400;
if (num1 == num2) {
System.out.println(0);
}
else {
System.out.println(1);
}
}
}
Output:-
1
Explanation:-
Integer caching only applies to values between -128 and 127
=================================================================
33)
class Main {
public static void main(String args[]) {
int t;
System.out.println(t);
}
}
Output:-
Compiler Error. This is because the local variables need to be assigned values
before accessing..
=================================================================
34)
class Test{
public static void main(String[] args){
Double object = new Double(\"2.4\");
int a = object.intValue();
byte b = object.byteValue();
float d = object.floatValue();
double c = object.doubleValue();
System.out.println(a + b + c + d );
}
}
Output:-
8.800000095367432
Explanation:-
Arithmetic conversions are implicitly performed to cast the values to a common
type.The compiler first performs integer promotion. If the operands still have
different
types, then they are converted to the type that appears highest in the hierarchy.
=================================================================
35)
public class WrapTest{
public static void main(String [] args){
int result = 0;
short s = 42;
Long x = new Long("42");
Long y = new Long(42);
Short z = new Short("42");
Short x2 = new Short(s);
Integer y2 = new Integer("42");
Integer z2 = new Integer(42);
if (x == y)
result = 1;
if (x.equals(y) )
result = result + 10;
if (x.equals(z) )
result = result + 100;
if (x.equals(x2) )
result = result + 1000;
if (x.equals(z2) )
result = result + 10000;
System.out.println("result = " + result);
}
}
Output:-
10
➢ x.equals(y) conditions works because it compares the value of a variable and not
the address value…
=================================================================
36)
class ByteAddition {
public static void main (String args []) {
byte value = 127;
value+=1;
System.out.println("Added Byte Value: "+value);
}
}
Output:-
Added Byte Value: -128
Explanation:-
Since we use a byte datatype, it holds values between -128 to 127. As we
increment 127, it overflows and wraps around to the minimum value of a byte which
is
-128
=================================================================
37)
class TypeMismatch {
public static void main (String args []) {
int iVal = 100;
double dVal = iVal;
int res = dVal;
System.out.println("Result: " +res);
}
}
Output:-
error: incompatible types: possible lossy conversion from double to int
Explanation:-
The code will not compile. The line (int res = dVal;) causes a compilation error
because we cannot directly assign a double value to an int variable without
explicit
typecasting. Lower order data types can be implicitly type casted to Higher order
datatypes but the inverse is not possible, rather we can explicitly typecast them.
=================================================================
38)
class PrecisionDemo {
public static void main (String args []) {
float fVal = 1.23456789f;
double dVal = 1.23456789;
System.out.println("Float value: " + fVal);
System.out.println("Double value: " + dVal);
}
}
Output:-
Float value: 1.2345679
Double value: 1.23456789
Explanation:-
Float values have less precision compared to double values. So the float value
1.23456789f is rounded to 1.2345679, whereas the double value retains more
precision.
=================================================================
39)
class DataLoss {
public static void main (String args []) {
long longVal = 12345678901L;
int intVal = (int) longVal;
System.out.println("Long value: " + longVal);
System.out.println("Int value: " + intVal);
}
}
Output:-
Long value: 12345678901
Int value: -539222987
Explanation:-
When casting a long to an int, the value may overflow because int has a smaller
range than long. In this case, 12345678901 cannot be represented accurately as an
int,
leading to data loss.
=================================================================
40)
class FloatComparison
{
public static void main (String args []) {
double a = (0.3 * 3) + 0.1;
double b = 1;
System.out.println("a: "+a);
if (a==b)
System.out.println("The numbers are equal!"+"\n");
else
System.out.println("The numbers are not equal!"+"\n");
}
}
Output:-
a: 0.9999999999999999
The numbers are not equal!
Explanation:-
Due to precision limitations of floating point data type, (0.9+0.1) may not be
exactly equal to (1.0).
=================================================================
41)
class IntDiv {
public static void main (String args []) {
int a = 9;
int b = 4;
double res = (double) a / b;
System.out.println("Result: " + res);
}
}
Output:-
Result: 2.25
Explanation:-
Casting ‘a’ to double ensures that the division is performed in floating-point
arithmetic, producing a result of 2.25 instead of 2 which would be the result of
integer
division.
=================================================================
42)
class CharArithmeticDemo {
public static void main (String args []) {
char ch = 'A';
char newCh = (char) (ch + 1);
System.out.println("Original char: " + ch);
System.out.println("New char: " + newCh);
}
}
Output:-
Original char: A
New char: B
Explanation:-
The char value 'A' is treated as its ASCII value (65) during arithmetic operations.
Adding 1 results in 66, which corresponds to the character 'B'.
=================================================================
43)
class CharArithmeticOverflow {
public static void main (String args []) {
char ch = 65535;
ch = (char) (ch + 1);
System.out.println("Char value: " +(int)ch);
}
}
Output:-
Char value: 0
Explanation:-
The char type in Java has a maximum value of 65535. Adding 1 causes an
overflow, wrapping around to 0. The cast to int displays the result (0) of the
overflow.
=================================================================
44)
class TypePromotion {
public static void main (String args []) {
byte bVal = 10;
bVal = bVal+5;
System.out.println("Byte value: " + bVal);
}
}
Output:-
error: incompatible types: possible lossy conversion from int to byte
Explanation:-
‘bVal + 5’ results in an int because of type promotion. Assigning an int directly
to
a byte results in a compilation error.
=================================================================
45)
class ByteOverflow {
public static void main (String args []) {
byte a = 100;
byte b = 50;
byte sum = (byte) (a + b);
System.out.println("Sum: "+sum);
}
}
Output:-
Sum: -106
Explanation:-
(a + b) results in 150, which exceeds the range of byte (-128 to 127). The result
wraps around due to overflow.
=================================================================
46)
public class Demo {
public static void main(String args[]){
int a = '2' - '0';
System.out.println(a);
}
}
Output:-
2
Explanation:-
In Java, char values are stored as Unicode values. The Unicode value of '2' is 50
and '0' is 48. Thus, 50 - 48 equals 2.
=================================================================
47)
public class Demo {
public static void main(String args[]){
double d1 = 0.1;
double d2 = 0.2;
double sum = d1 + d2;
System.out.println(sum);
}
}
Output:-
0.30000000000000004
Explanation:-
Floating-point arithmetic in Java can lead to precision errors. Here, adding 0.1
and 0.2 results in a minor precision error, producing 0.30000000000000004 instead
of
the exact 0.3.
=================================================================
48)
public class Demo {
public static void main(String args[]){
float f = 100.001f;
double d = f;
System.out.println(d);
}
}
Output:-
100.0009994506836
Explanation:-
When a float is assigned to a double, precision may be added. As float has less
precision than double, it will give the above OUTPUT.
=================================================================
49)
public class Demo {
public static void main(String[] args) {
double d = 9.78;
int i = (int) d;
System.out.println("Int value: " + i);
long l = 123456789012L;
float f = l; // Widening cast
System.out.println("Float value: " + f);
}
}
Output:-
Int value: 9
Float value: 1.2345679E11
Explanation:-
● The conversion from double to int is called Narrowing type cast in which a
large data type is reduced to smaller data type.In this conversion double
(large data type) is converted to int(small data type) and we get the result as
9.
● In the next conversion, the data type is converted from double to float and this
process is known as Widening type cast. In this process a comparatively
smaller data type is converted to a comparatively larger data type.
In this conversion a long (smaller data type) is converted to float(larger
data type) and we get the result as1.2345679E11.
=================================================================
50)
public class Demo {
public static void main(String[] args) {
String str = "12345";
int num = Integer.parseInt(str);
System.out.println(num);
}
}
Output:-
1234
Explanation:-
Integer.parseInt converts the String "12345" to the int 12345.
=================================================================
51)
public class PrecisionTest {
public static void main(String[] args) {
double largeValue = 123456.78901234;
float smallValue = (float) largeValue;
System.out.println("Original double value: " + largeValue);
System.out.println("Casted float value: " + smallValue);
}
}
Output:-
Original double value: 123456.78901234
Casted float value: 123456.79
Explanation:-
Casting a double to a float can cause precision loss because float has less
precision compared to double. The float value only shows up to 6-7 decimal digits,
leading to a loss of the exact value from the double.
=================================================================
52)
public class TypeConversionTest {
public static void main(String[] args) {
byte smallByte = 100;
int largerInt = smallByte;
byte resultByte = (byte) (largerInt + 200);
System.out.println("Resulting byte value: " + resultByte);
}
}
Output :-
Resulting byte value: -56
Explanation :
In this code, largerInt is promoted to int before the addition operation. Adding
200 to
largerInt results in a value of 300, which exceeds the range of a byte (-128 to
127).
When casting 300 back to byte, the value wraps around, resulting in -56 due to
overflow.
=================================================================
53)
import java.util.ArrayList;
public class AutoboxingTest {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(42);
list.add(null);
int firstValue = list.get(0); // This works fine
int secondValue = list.get(1); // This will throw an exception
System.out.println("First value: " + firstValue);
System.out.println("Second value: " + secondValue);
}
}
Output:-
First value: 42
Exception in thread "main" java.lang.NullPointerException
At AutoboxingTest.main(AutoboxingTest.java:8)
Explanation:-
In the code, list.get(1) retrieves a null value from the ArrayList of Integer. When
trying to unbox this null to a primitive int, a NullPointerException occurs because
primitive types cannot be null. To avoid this, always check for null values before
unboxing.
=================================================================
54)
public class NarrowingConversionTest {
public static void main(String[] args) {
Long largeValue = 9876543210L;
int narrowedValue = (int) largeValue;
System.out.println("Original long value: " + largeValue);
System.out.println("Narrowed int value: " + narrowedValue);
}
}
Output:-
Original long value: 9876543210
Narrowed int value: -1610517008 ^
Explanation:-
When casting a long to an int, Java performs a narrowing conversion, which
means the data might be truncated if it exceeds the range of the target type (int
in this
case). The long value 9876543210 is too large to fit in an int, which has a range
of
-2147483648 to 2147483647. As a result, the value wraps around and becomes
-1610517008 due to overflow.
=================================================================
55)
public class IncompatibleCastTest {
public static void main(String[] args) {
Object obj = "Hello, World!";
Integer number = (Integer) obj; // This will throw a ClassCastException
System.out.println("Number: " + number);
}
}
Output:-
Exception in thread "main" java.lang.ClassCastException: class java.lang.String
cannot
be cast to class java.lang.Integer..
Explanation:-
In this code, obj is an Object that actually references a String object. Attempting
to cast this String object to an Integer causes a ClassCastException because String
and
Integer are not related types and cannot be directly converted between each other.
This
illustrates the importance of ensuring that the types are compatible before
performing a
cast.
=================================================================
56)
public class GradeEvaluator {
public static void main(String[] args) {
int score = 85;
if (score > 90) {
System.out.println("Grade: A");
} else if (score > 80) {
System.out.println("Grade: B");
} else if (score > 70) {
System.out.println("Grade: C");
} else if (score > 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}
Output:-
Grade: B
Explanation:-
The current conditions will categorize a score of 85 as "Grade: B", which is
correct in this case.
=================================================================
57)
public class DayOfWeek {
public static void main(String[] args) {
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("The day is: " + dayName);
}
}
Output:-
The day is: Wednesday
=================================================================
58)
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}
}
}
Output:-
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
=================================================================
59)
public class BreakExample {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
if (sum > 20) {
break;
}
}
System.out.println("Sum is: " + sum);
}
}
Output:-
Sum is: 21
=================================================================
60)
public class NestedIfElse {
public static void main(String[] args) {
int x = 10;
int y = 20;
if (x > 5) {
if (y < 15) {
System.out.println("x is greater than 5 and y is less than 15.");
} else {
System.out.println("x is greater than 5 but y is not less than 15.");
}
} else {
System.out.println("x is not greater than 5.");
}
}
}
Output:-
x is greater than 5 but y is not less than 15.
=================================================================
61)
public class Test {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
if (i == 3) {
continue;
}
System.out.print(i + " ");
i++;
}
}
}
Output:-
Infinite loop.
When i is 3, the continue statement causes the loop to skip the i++ statement
and hence never progresses past 3. This results in an infinite loop. Fix this by
moving
the i++ before the continue statement.
62)
public class Test {
public static void main(String[] args) {
int i = 1;
do {
int j = 1;
do {
System.out.print(j + " ");
j++;
} while (j <= i);
System.out.println();
i++;
} while (i <= 3);
}
}
Output:-
1
1 2
1 2 3
When i = 1, the inner loop prints 1.
When i = 2, the inner loop prints 1 2.
When i = 3, the inner loop prints 1 2 3.
The outer loop continues while i is less than or equal to 3.
63)
public class Main {
public static void main(String[] args) {
String str = "hello";
for (char c : str.toCharArray()) {
if (c == 'l') {
continue;
}
System.out.print(c + " ");
}
}
}
Output:-
h e o
The continue statement skips the current iteration when c equals 'l'. Therefore,
'l'
characters are not printed, and all other characters are printed with a space
between
them.
=================================================================
64)
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
for (int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Output:-
ArrayIndexOutOfBoundsException
The loop condition i <= arr.length causes an attempt to access arr[3] when i
equals 3, which is out of bounds since valid indices are 0, 1, 2. Change the loop
condition to i < arr.length to fix the issue.
=================================================================
65)
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 0, j = 10; i < 5; i++, j -= 2) {
sum += i + j;
}
System.out.println("Sum: " + sum);
}
}
Output:-
Sum: 40
The for loop has two iterators: i starts at 0 and increments, while j starts at
10 and decrements by 2 each iteration.
sum = 0 + 10 = 10
sum = 1 + 8 = 9 (total 19)
sum = 2 + 6 = 8 (total 27)
sum = 3 + 4 = 7 (total 34)s
sum = 4 + 2 = 6 (total 40)
=================================================================
66)
public class ControlTest {
public static void main(String[] args) {
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else if (x == 10) {
System.out.println("x is 10");
} else {
System.out.println("x is less than 5");
}
}
}
Output:-
x is greater than 5
Explanation:-
This code demonstrates basic use of if, else if, and else statements. In this case,
x is 10, so the output will be "x is 10" because the else if condition x == 10 is
true.
=================================================================
67)
public class LoopTest {
public static void main(String[] args) {
for (int i = 0; i < 5; i--) {
System.out.println(i);
}
}
}
Output:-
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
Explanation:-
The issue is that the loop variable i is being decremented (i--), which will cause
an infinite loop since i will always be less than 5.
=================================================================
68)
public class WhileLoopTest {
public static void main(String[] args) {
int count = 0;
while (count < 10) {
System.out.println("Count: " + count);
}
}
}
Output:-
Count: 0
Count: 0
Count: 0
Count: 0
Count: 0
Count: 0
Count: 0…..
Explanation:-
The loop will run indefinitely because count is never incremented. To fix it, add
an
increment statement inside the while loop:
while (count < 10) {
System.out.println("Count: " + count);
Count++; }
=================================================================
69)
public class NestedLoopTest {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(i + "" + j + " ");
}
}
}
}
Output:-
00 01 02 10 11 12
Explanation:-
The outer loop iterates twice (i.e., i takes values 0 and 1), and for each value of
i,
the inner loop iterates three times (i.e., j takes values 0, 1, and 2).
=================================================================
70)
public class Main {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int index = 0; index < numbers; index++) {
System.out.print("value of item : " + numbers[index] );
System.out.print("\n");
}
}
}
Explanation : -
Loop Condition: index < numbers.length ensures that the loop iterates through all
valid indices of the numbers array. numbers.length returns the number of elements
in
the array, which is 5 in this case.
Corrected code:-
public class Main {
public static void main(String args[]) {
int[] numbers = {10, 20, 30, 40, 50};
for (int index = 0; index < numbers.length; index++) {
System.out.println("value of item: " + numbers[index]);
}
}
}
Output:-
value of item: 10
value of item: 20
value of item: 30
value of item: 40
value of item: 50
=================================================================
71)
Error code:-
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
System.out.println("Value of i: " + i);
}
}
}
Explanation:-
The while loop lacks an increment for i, leading to an infinite loop.
Corrected code:-
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
i++;
System.out.println("Value of i: " + i);
}
}
}
Output:-
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
Value of i: 10
=================================================================
72)
Error code:-
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j <= matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Explanation:-
Loop Condition: Changing j <= matrix[i].length to j < matrix[i].length ensures that
j
only takes values from 0 to matrix[i].length - 1. This avoids accessing out-of-
bounds
indices.
Corrected code:-
public class NestedLoopError {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Output:-
1 2 3
4 5 6
7 8 9
=================================================================
73)
Error code:-
public class Pattern{
public static void main(String args[]){
int n=4;
for(int i=1;i<=n;i++){
for(int j=0;j<n;j++){
if(j<i){
System.out.println(i);
}
else {
System.out.println(“ “);
}
}
System.out.println(“ “);
}
}
}
Explanation:-
The inner loop should iterate from ‘0’ to ‘i’ not ‘n’.This causes the loop to run
more times
than necessary and print extra spaces. The else block adds unnecessary spaces,which
disrupts the pattern.
Corrected code:-
public class Pattern{
public static void main(String args[]){
int n=4;
for(int i=1;i<=n;i++){
for(int j=0;j<i;j++){
if(j<i){
System.out.println(i);
}
System.out.println( );
}
}
}
}
Output:-
1
22
333
4444
=================================================================
74)
public class Test{
private String function(){
return (“GFG”);
}
public final static String function(int data){
return (“GeeksforGeeks”);
}
public static void main(String[] args){
Test obj = new Test();
System.out.println(obj.function());
}
}
Output:-
GFG
Explanation:-
Access modifiers associated with methods doesn’t determine the criteria for
overloading. The overloaded methods could also be declared as final or static
without
affecting the overloading criteria.
=================================================================
75)
class A{
private A(){}//private constructor
void msg(){
System.out.println(”Hello java”);}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
}
}
Explanation:-
A Constructor cannot be private or protected except nested classes.
=================================================================
76)
class A{
protected void msg(){
System.out.println(“Hello java);
}
}
public class Simple extends A{
void msg(){
System.out.println(“Hello;);
}
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
Error: -
Compile-time error
Explanation:-
If you are overriding any method, the overridden method (i.e.declared in
subclass) must not be more restrictive.The default modifier is more restrictive
than
protected.That is why, there is a compile-time error.
=================================================================
77)
public class OverLoadExample {
public void test(long a, int b){
System.out.println(“test one”);
}
public void test(int a, long b){
System.out.println(“;test two”);
}
public static void main(String[] args) {
OverLoadExample overLoadExample = new
OverLoadExample();
overLoadExample.test(1,2);
}
}
Explanation:-
Both method test(long,int) in OverLoadExample and method test(int,long) in
OverLoadExample are the same(compatible data type), ambiguous call.
=================================================================
78)
package pack1;
public class A{
private int x = 50;
protected int y = 100;
int z = 200;
}
package pack2;
import pack1.A;
public class B extends A {
}
import pack2.B;
public class Test {
public static void main(String[] args){
B b = new B();
System.out.println(b.x);
System.out.println(b.y);
System.out.println(b.z);
}
}
Explanation:-
First error is in line System.out.println(b.x); because private members cannot be
accessed in the subclass. Second error is in line System.out.println(b.y); because
default members of superclass can be accessed in the subclass within the same
package only. Also only one public class can be declared in a file.
=================================================================
79)
public class OverloadDebug3 {
public void display(int num) {
System.out.println("Integer: " + num);
}
public void display(int num1, int num2) {
System.out.println("Integers: " + num1 + ", " + num2);
}
public static void main(String[] args) {
OverloadDebug3 obj = new OverloadDebug3();
obj.display(1, 2, 3);
}
}
Explanation:-
The method called obj.display(1, 2, 3) does not match any existing overload
because there is no display(int, int, int) method.
=================================================================
80)
public class OverloadDebug4 {
public void process(Integer num) {
System.out.println("Wrapper Integer: " + num);
}
public void process(int num) {
System.out.println("Primitive int: " + num);
}
public static void main(String[] args) {
OverloadDebug4 obj = new OverloadDebug4();
obj.process(null);
}
}
Explanation:-
The call obj.process(null) is ambiguous because null could match both Integer
and int, making every call from process(int num) when num != null.
=================================================================
81)
public class OverloadPrimitive {
public void print(int num) {
System.out.println("Integer: " + num);
}
public void print(double num) {
System.out.println("Double: " + num);
}
public static void main(String[] args) {
OverloadPrimitive obj = new OverloadPrimitive();
obj.print(10);
obj.print(10.5);
}
}
Explanation:-
The print(int) method is called when passing an int argument.
The print double) method is called when passing a double argument.
No errors in this program. Both method overloads work as intended.
9.
=================================================================
82)
public class Parent {
private int privateValue = 100;
}
public class Child extends Parent {
public void showValue() {
System.out.println(privateValue);
}
}
Explanation:-
The line System.out.println(privateValue); in the Child class results in an error
because privateValue is private in the Parent class and cannot be accessed by
subclasses.
=================================================================
83)
class A {
private void display(int x) {
System.out.println("Class A: " + x);
}
public void display(double x) {
System.out.println("Class A: " + x);
}
}
class B extends A {
public void display(int x) {
System.out.println("Class B: " + x);
}
}
public class Main {
public static void main(String[] args) {
A obj = new B();
obj.display(5);
}
}
Output:-
Class A: 5.0
Explanation:-
The method display(int x) in class A is private, so it is not inherited by class B.
When obj.display(5) is called, Java looks for a method in A that can take an int
parameter. Since display(int x) in A is private, it is not accessible from B.The
only
accessible method in A that can handle an int is display(double x), so Java
implicitly
converts 5 to 5.0 and calls display(double x) in class A.
=================================================================
84)
class Test {
public void show(int x) {
System.out.println("Integer: " + x);
}
protected void show(double x) {
System.out.println("Double: " + x);
}
private void show(String x) {
System.out.println("String: " + x);
}
}
public class Main {
public static void main(String[] args) {
Test obj = new Test();
obj.show(5);
obj.show(5.0);
obj.show("Hello");
}
}
Output:-
Integer: 5
Double: 5.0
Error: Cannot resolve method 'show(java.lang.String)'
Explanation:-
The show(int x) and show(double x) methods are accessible because they are
public and protected respectively.The show(String x) method is private, so it is
not
accessible outside the Test class. The attempt to call obj.show("Hello"); will
result in a
compilation error, as the method is not visible.
=================================================================
85).
class Parent {
public static void print(String s) {
System.out.println("Parent: " + s);
}
}
class Child extends Parent {
private static void print(String s) {
System.out.println("Child: " + s);
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.print("Hello");
}
}
Output:-
Parent: Hello
Explanation:-
The reference type of obj is Parent, so the print(String s) method in the Parent
class is called, even though obj is an instance of Child.The print method in Child
is
private, so it is not accessible from outside the Child class, and it doesn’t
override the
print method in Parent.
=================================================================
86)
class Base {
void test(int a) {
System.out.println("Base class: " + a);
}
protected void test(String s) {
System.out.println("Base class: " + s);
}
}
class Derived extends Base {
private void test(int a) {
System.out.println("Derived class: " + a);
}
public void test(String s) {
System.out.println("Derived class: " + s);
}
}
public class Main {
public static void main(String[] args) {
Base obj = new Derived();
obj.test(10);
obj.test("Hello");
}
}
Explanation:-
When obj.test(10) is called, the method in Base is used because the private
method in Derived is not accessible because we are assigning a weaker access
privilege. When obj.test("Hello") is called, it is a compile-time error
=================================================================
87)
class Example {
public void calculate(int a, double b) {
System.out.println("Method 1: " + (a + b));
}
private void calculate(double a, int b) {
System.out.println("Method 2: " + (a + b));
}
}
public class Main {
public static void main(String[] args) {
Example ex = new Example();
ex.calculate(5, 10.0);
ex.calculate(10.0, 5);
}
}
Output:-
Method 1: 15.0 Error: Cannot resolve method 'calculate(double, int)'
Explanation:-
The calculate(int a, double b) method is public and accessible, so it will execute
and produce Method 1: 15.0.The calculate(double a, int b) method is private, so it
is not
accessible outside the Example class. The call ex.calculate(10.0, 5); will result
in a
compilation error because the method is not visible.
=================================================================
88)
class Test {
public void compute(int a, double b) {
System.out.println("Method 1: " + (a + b));
}
private void compute(int... a) {
System.out.println("Method 2: " + a.length);
}
public void compute(double a, double b) {
System.out.println("Method 3: " + (a + b));
}
}
public class Main {
public static void main(String[] args) {
Test obj = new Test();
obj.compute(5, 10);
obj.compute(5, 10.0);
obj.compute(10.0, 5.0);
}
}
Output:-
Method 1: 15.0
Method 1: 15.0
Method 3: 15.0
=================================================================
89)
class GFG {
public static void main(String args[]) {
final int[] numbers = {1, 2, 3};
int[] otherNumbers = {4, 5, 6};
numbers = otherNumbers;
System.out.println((numbers));
}
}
Explanation:-
The above program generates errors because as a final(keyword) array
means that the array variable which is actually a reference to an object, cannot be
changed to refer to anything else, but the members of the array can be modified.
=================================================================
90)
class Test {
public static void main(String args[]) {
int intArray[] = {1, 2, 3};
int cloneArray[] = intArray.clone();
System.out.println(intArray == cloneArray);
for (int i = 0; i < cloneArray.length; i++) {
System.out.print(cloneArray[i] + " ");
}
}
}
Output:-
False
1 2 3
Explanation:-
In the above Program,the intArray and cloneArray are not the same object
(intArray == cloneArray is false), but they share the same contents because
primitive
values are deeply copied.For arrays containing objects, the references are copied,
so
the objects themselves are not duplicated.
=================================================================
91)
public static void main(String args[]) {
final int arr[] = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 10;
System.out.println(arr[i]);
}
}
Output:-
10
20
30
40
50
Explanation:-
The array arr is declared as final, but the elements of an array are changed
without any problem. Arrays are objects and object variables are always references
in
Java. So, when we declare an object variable as final, it means that the variable
cannot
be changed to refer to anything else.
=================================================================
92)
public class JavaArrayExample{
public static void main(String[] args){
System.out.println(new int[]{1, 2, 3, 4, 5}.length);
System.out.println(new int[]{21, 14, 65, 24, 21}[1]);
}
}
Output:-
5
14
Explanation:-
The line creates a new integer array with the elements {1, 2, 3, 4, 5} and
directly accesses its length property and length is 5. The new integer array with
the
elements {21, 14, 65, 24, 21} creates an array and accesses the element at index 1
which is 14.
=================================================================
93)
public class TestArrayException {
public static void main(String args[]) {
int arr[] = {50, 60, 70, 80};
for (int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Explanation:-
In the Above code,The issue is in the loop condition i <= arr.length is
problematic. Array indices in Java are zero-based, meaning valid indices for an
array of
length 4 are 0 to 3. The arr.length is 4, so when i equals 4, it is out of bounds
for the
array.
=================================================================
94)
public class StackOverflowErrorExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
recursiveMethod(arr, 0);}
public static void recursiveMethod(int[] arr, int index) {
if (index < arr.length) {
System.out.println(arr[index]);
recursiveMethod(arr, index);
}
}
}
}
Explanation:-
The code calls a recursive method without incrementing the index, leading to
infinite recursion. This results in a StackOverflowError.
=================================================================
95)
public class OutOfMemoryErrorExample {
public static void main(String[] args) {
int[] arr = new int[Integer.MAX_VALUE];
}
}
Output:-
Error.
Explanation:-
The program tries to allocate an array arr of size Integer.MAX_VALUE, which
is the maximum positive value for a 32-bit signed integer (i.e., 2,147,483,647).The
code
tries to create an array with a size that exceeds the available memory.This results
in an
OutOfMemoryError.
=================================================================
96)
public class ArraySwap {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
swap(arr[0], arr[arr.length - 1]);
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
}
Output:-
1 2 3 4 5.
Explanation:-
It won't perform Swapping because, When we pass an array element like
arr[0] to a method, the value of that element is passed, not a reference to the
element
itself. Therefore, the swap method only works with copies of the values 1 and 5.
=================================================================
97)
public class ArrayWithNulls {
public static void main(String[] args) {
String[] names = {"Alice", null,"Bob","Charlie"};
for (int i = 0; i <names.length; i++) {
System.out.println(names[i].toUpperCase());
}
}
}
Output:-
Null Pointer Exception.
Explanation:-
To prevent the NullPointerException, check if the element is null before
calling toUpperCase().
=================================================================
98)
public class Arrayinitialization {
public static void main(String[] args) {
int[] array;
array[0]=10;
System.out.println(array[0]);
}
}
Explanation:-
The array must be initialized to allocate memory for the elements.
=================================================================
99)
public class Incorrect2DArrayLoop {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j <= matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Explanation:-
The inner loop uses j<=matrix[i].length which leads to out of bounds.
=================================================================
100)
public class array {
public static void main(String[] args) {
int sum=0;
for(int i=0;i<5;i++){
int[] numbers=new int[5];
numbers[i]=i;
sum+=numbers[i];
}
System.out.println("Sum:" +sum);
}
}
Output:-
Sum:10
Explanation:-
The array numbers is re-created in each iteration of the loop in which beginning
of each iteration, all elements of the array are reset to 0.Even Though it
reinitializing the
array in each iteration, the code still assigns the value i to the correct index
and sums it
up.But it is very efficient if we initialize the array out of loop to avoid
unnecessary error.
=================================================================
101)
public class ArrayDefaultValues {
public static void main(String[] args) {
int[] arr = new int[3];
for (int i : arr) {
System.out.println(i);
}
}
}
Output:-
0 0 0
Explanation:-
The array arr is initialized with a size of 3 and it has no value and each
element is automatically initialized to the default value for that type. For int,
the default
value is 0.
=================================================================
102)
public class ForEachTrap {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
num *= 2;
}
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
Output:-
1 2 3 4 5.
Explanation:-
The multiplication num *= 2 only affects the copy of the value stored in
num, not the actual elements in the numbers array. As a result, the original array
remains unchanged.
=================================================================
103)
public class StringArrayModification {
public static void main(String[] args) {
String[] words = {"Hello", "World", "Java"};
for (int i = 0; i < words.length; i++) {
words[i] = words[i] + " Modified";
}
for (String word : words) {
System.out.println(word);}
String test = words[1];
System.out.println("Test String: " + test);
}
}
}
Output:-
Hello Modified
World Modified
Java Modified
Test String: World Modified.
Explanation:-
The first loop appends "Modified" to each element of the words array. This
changes the original content of the array elements.after this loop the original
elements
get changed to test that "Test String " is used to check whether the string get
changed
or not.
=================================================================
104)
class Test {
public static void main(String[] args) {
int[ ][ ] x = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};
int[ ][ ] y = x;
System.out.println(y[2][1]);
}
}
Output:-
:7
Explanation:-
It initializes a 2D array x with three rows: First row: {1, 2},Second row: {3, 4,
5},Third row: {6, 7, 8, 9}. y[2] refers to the third row of the array, which is {6,
7, 8, 9}.and
y[2][1] is the second element which is 7.
=================================================================
105)
class Student {
int marks;
public static void main(String...args) {
Student[] studentArray=new Student[1];
studentArray[0].marks=100;
System.out.println("mark="+studentArray[0].marks);
}
}
Explanation:-
Student[] studentArray = new Student[1]; creates an array that can hold one
Student object, but initially, the element studentArray[0] is
null.studentArray[0].marks =
100; attempts to access the marks field of the Student object at index 0. However,
since
studentArray[0] is null, you are trying to access a field on a null reference,
which causes
a NullPointerException.
=================================================================
106)
class A{
public static void main(String[] args) {
String[] strings = new String[3];
Strings[0] = "hello";
Strings[1] = 123;
}
}
Explanation:-
The error in your code is a compilation error due to type mismatch.
Specifically, this line, strings[1] = 123; causes the problem because 123 is an int
and
strings is an array of String. Java does not allow you to assign an int to a String
variable
directly.
=================================================================
107)
class GFG {
public static void main(String[] args){
int arr[] = new int[3];
for(int i=0;i<arr.length();i++){
System.out.println(arr[i]);
}
}
}
Explanation:-
The issue in this code is the line for(int i=0;i<arr.length();i++).The method
length is a property, not a method, so you should not use parentheses.
=================================================================
108)
class Arrayreturn {
public static void main(String[] args) {
int[] numbers = getNumbers();
for (int number:numbers) {
System.out.println(number);
}
}
public static int getNumbers() {
int[] array = {1, 2, 3, 4, 5};
return array;
}
}
Explanation:-
The getNumbers method is returning an int[] array, but its return type is
declared as int. This mismatch will result in a compilation error because you
cannot
return an array where an int is expected.
=================================================================
109)
public class Simple {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
numbers = new int[]{1, 2, 3};
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
Output:-
1 2 3
Explanation:-
The line numbers = new int[ ]{1, 2, 3}; reassigns the numbers reference to a
new array with values 1, 2, 3.Hence original values 10, 20, 30 are lost and
replaced with
1, 2, 3.
=================================================================
110)
class Test{
public static void main (String[] args){
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (arr1 == arr2)
System.out.println("Same");
else
System.out.println("Not same");
}
}
Output:-
Not same
Explanation:-
In Java, the == operator is used to compare object references, not the
actual contents of the objects.Here, arr1 and arr2 are two different arrays with
the same
contents {1, 2, 3}. However, they are stored in different memory locations.if (arr1
==
arr2): This statement compares whether arr1 and arr2 point to the same memory
location. Since they are two separate arrays, the result of arr1 == arr2 is false.
=================================================================
111)
public class SimpleArray {
public static void main(String[] args) {
int[] intArray = new int[3];
String[] stringArray = new String[3];
System.out.println("Default values in intArray:");
for (int value : intArray) {
System.out.println(value);
}
System.out.println("Default values in stringArray:");
for (String value : stringArray) {
System.out.println(value);
}
}
}
Output:-
Default values in intArray: 0 0 0
Default values in stringArray: null null null.
Explanation:-
intArray is an array of int and is initialized with default values of 0.
stringArray is an array of String and is initialized with default values of null.
=================================================================
112)
class Test{
public void demo(String str){
String[] arr = str.split(";");
for (String s : arr){
System.out.println(s);
}
}
public static void main(String[] args){
char array[] = {'a', 'b', ' ', 'c', 'd', ';', 'e', 'f', ' ','g', 'h', ';', 'i',
'j'};
String str = new String(array);
Test obj = new Test();
obj.demo(str);
}
}
Output:-
ab cd
ef gh
ij
Explanation:-
The char array contains characters and delimiters ( ; ). new String(array)
converts the char array to a String, which will be "ab cd;ef gh;ij kl". In the demo
method,
str.split(";") splits the string "ab cd;ef gh;ij kl" into parts based on the ;
delimiter. The
resulting array will be ["ab cd", "ef gh", "ij “].
=================================================================
113)
public class PrintMatrixElement {
public static void main(String[] args) {
int [ ][ ] matrix = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
int value = matrix[2][2];
System.out.println(value);
}
}
Output:-
11
Explanation:-
matrix[2] refers to the 3rd row of the matrix: {9, 10, 11, 12} matrix[2][2] refers
to the 3rd element of the 3rd row, which is 11.
=================================================================
114)
class Test {
public static void main(String[] args) {
String[] str = {"Geeks", "for", "Geeks"};
System.out.println(str.length);
System.out.println(str[0].length);
}
}
Explanation:-
For arrays, length is a field (not a method). So, you use array.length.
For strings, length() is a method (note the parentheses). So, you use
string.length().
=================================================================
115)
public class Outer {
private static int data = 2;
private static int LocalClass() {
class Inner {
private int[] numbers = {5, 10, 15};
private int getFirstElement() {
return numbers[0];}
}
Inner inner = new Inner();
return inner.getFirstElement();
}
public static void main(String[] args) {
System.out.println(data * LocalClass());
}
}
Output:-
10
Explanation:-
The Inner class contains a array numbers with values {5, 10, 15}.The
getFirstElement method returns the first element of the array, which is 5 and
multiplies
with the static data (which is 2) by the result from LocalClass() (which is 5), and
prints
the result.
=================================================================
116)
public class Test {
int[] numbers;
Test(int size) {
numbers = new int[size];
}
public static void main(String[] args) {
Test test = new Test(3);
test.numbers[0] = 10;
test.numbers[1] = 20;
System.out.println(test.numbers[0] + " " + test.numbers[1] );
}
}
Output:-
10 20
Explanation:-
The Test constructor initializes the numbers array with a size of 3, so it can
hold three elements.(test.numbers[0] and test.numbers[1]) assigns values to the
first
two elements of the array.The third element (test.numbers[2]) is not explicitly
assigned a
value. In Java, uninitialized elements of an int array are automatically set to 0
by default.
=================================================================
117)
public class Output {
Static String[] words = {"Hello", "World"};
public static void main(String[] args) {
System.out.print("Word at index 2: " + words[2] + " ");
String a;
System.out.print("Uninitialized variable: " + a);
}
}
Explanation:-
The word array is initialized with two elements: "Hello" and "World".
Attempting to access words[2] will throw an ArrayIndexOutOfBoundsException.The
local variable a is declared but not initialized. In Java, local variables must be
initialized
before they can be used.
=================================================================
118)
public class Demo {
public static void main(String[] args) {
System.out.println("Standard main method:");
int[] numbers = {1, 2, 3};
main(numbers);
}
public static void main(int[] numbers) {
System.out.println("Overloaded main method with int array:");
for (int number : numbers) {
System.out.println(number);
}
}
}
Output:-
Standard main method:
Overloaded main method with int array:
1 2 3
Explanation:-
Standard main Method (String args[ ]) is the entry point for the application. It
initializes and passes an integer array to another main method. Overloaded main
Method: Takes an integer array as a parameter, processes it, and prints its
elements.
119)
class X{
//Class X Members
}
class Y{
//Class Y members
}
class Z extends X,Y{
//Class Z members
}
Output:-
Compile time error as only 1 class can be extended in Java
==================================================================
120)
class Animal {
static void sound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
static void sound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog();
Animal.sound();
}
}
Explanation:-
The animal makes a sound
~The expected output: The dog barks
~ When you call Animal.sound(), the Java compiler resolves the method
call to the sound() method of the Animal class, because the type of the reference
myAnimal is Animal, not Dog. Even though the object being referred to is a Dog
instance, the static method call is resolved based on the type of the reference,
not the type of the object.
==================================================================
121)
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
class AdvancedCalculator extends Calculator {
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
AdvancedCalculator myCalculator = new AdvancedCalculator();
System.out.println(myCalculator.add(1, 2)); }
}
Output:-
3
Explanation:-
~ the Java compiler looks for a method named add that takes two int parameters.
Since the Calculator class defines such a method, the compiler resolves the method
call
to that method, even though the AdvancedCalculator class defines a different method
named add with three int parameters.
==================================================================
122)
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
}
public class Main {
public static void main(String[] args) {
Circle myCircle = new Circle();
myCircle.draw(); }
}
Output: -
Error!
Explanation:-
~the Circle class does not provide an implementation for the draw() method, so it
must be declared as abstract. However, in the main() method, you are trying to
create
an instance of the Circle class, which is not allowed because it is abstract.
==================================================================
123)
class Bird {
void fly() {
System.out.println("The bird is flying.");
}
}
class Parrot extends Bird {
void fly() {
System.out.println("The parrot is flying high.");
}
void flyHigh() {
fly(); // Is this line correct?
super.fly(); // Is this line correct?
}
}
public class Main {
public static void main(String[] args) {
Bird myBird = new Parrot();
myBird.flyHigh(); // Output: ?
}
}
Output:-
Error!
~The flyHigh() method is not defined in the Bird class, so you can't call it on a
Bird
reference. ~The flyHigh() method is trying to call super.fly(), but super refers to
the
parent class, which is Bird. However, the flyHigh() method is not defined in the
Bird
class, so you can't call it using super.
==================================================================
124)
class Person {
final void eat() {
System.out.println("The person eats");
}
}
class Employee extends Person {
void eat() {
System.out.println("The employee eats");
}
}
public class Main {
public static void main(String[] args) {
Employee myEmployee = new Employee();
myEmployee.eat(); // Output: Error (Expected: The employee eats)
}
}
Output:-
Error!
~ when a method is declared as final, it means that it cannot be overridden by
any subclass
~ compiler will show an error because we are trying to override a final method
==================================================================
125)
class Parent {
protected void display() {
System.out.println("Parent display");
}
private void privateMethod() {
System.out.println("Parent private method");
}
}
class Child extends Parent {
protected void display() {
System.out.println("Child display");
}
void callPrivateMethod() {
System.out.println("Attempted to call Parent's private method");
}
}
public class TestAccessModifiers {
public static void main(String[] args) {
Child c = new Child();
c.display();
c.callPrivateMethod();
}
}
Output:-
Child display
Attempted to call Parent's private method
Explanation:-
Explanation:
The display method in Child overrides the display method in Parent, so "Child
display" is printed.
The callPrivateMethod method attempts to call privateMethod from Parent, but
this will cause a compilation error because privateMethod is private and cannot be
accessed or overridden by subclasses. The message in the method indicates the
failed
attempt to access the private method.
==================================================================
126)
class Parent {
void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
void display() {
System.out.println("Child display");
}
}
class AnotherChild extends Parent {
void display() {
System.out.println("AnotherChild display");
}
}
public class TestIncorrectUpcasting {
public static void main(String[] args) {
Parent p = new AnotherChild();
Child c = (Child) p; // Incorrect downcasting
c.display();
}
}
Output:
error!
Explanation:-
This code will throw a ClassCastException at runtime because p is actually an
instance of AnotherChild, which cannot be cast to Child.
==================================================================
127)
interface ParentInterface {
void display();
}
class Parent implements ParentInterface {
public void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
public void display() {
System.out.println("Child display");
}
}
public class TestInterfaceInheritance {
public static void main(String[] args) {
ParentInterface p = new Child();
p.display();
}
}
Output:-
Child display
Explanation:-
The display method in Child overrides the method in Parent. Since p references
an instance of Child, the overridden method in Child is called.
==================================================================
128)
class Parent {
Parent() {
System.out.println("Parent Constructor");
}
}
class Child extends Parent {
Child() {
System.out.println("Child Constructor");
}
}
public class TestConstructor {
public static void main(String[] args) {
new Child();
}
}
Output :-
Parent Constructor
Child Constructor
Explanation:-
When a Child object is created, the constructor of the Parent class is called
first,
followed by the constructor of the Child class.
==================================================================
129)
class Base {
public static void show() {
System.out.println("Base static show");
}
public void display() {
System.out.println("Base display");
}
}
class Derived extends Base {
public static void show() {
System.out.println("Derived static show");
}
public void display() {
System.out.println("Derived display");
}
}
public class Test {
public static void main(String[] args) {
Base b = new Derived();
b.show();
b.display();
}
}
Output:-
Base static show
Derived display
==================================================================
130)
class A {
public A(String s) {
System.out.print("A");
}
}
public class B extends A {
public B(String s) {
System.out.print("B");
}
public static void main(String[] args) {
new B("C");
System.out.println(" ");
}
}
Output: -
Compilation fails
Explanation:-
The implied super() call in B’s constructor cannot be satisfied because there isn’t
a no-arg constructor in A. A default, no-arg constructor is generated by the
compiler
only if the class has no constructor defined explicitly.
==================================================================
131)
public class A extends B {
public static String sing() {
return "fa";
}
public static void main(String[] args) {
A a = new A();
B b = new A();
System.out.println(a.sing() + " " + b.sing());
}
}
class B {
public static String sing() {
return "la";
}
}
Output:-
fa la
Explanation:-
The sing() method won’t be overridden because static methods didn’t support
that so when b.sing() executed only the sing() method present in Class B executed
because b is an object of type B; B b = new A(). if you want “fa fa” as the output
then
simply remove static in the method.
==================================================================
132)
class Base {
final public void show() {
System.out.println("Base::show() called");
}
}
class Derived extends Base {
public void show() {
System.out.println("Derived::show() called");
}
}
class Main {
public static void main(String[] args) {
Base b = new Derived();
b.show();
}
}
Output: -
Compiler error
Explanation:-
Final methods cannot be overridden. However, if we remove the keyword final
then, the output will be Derived::show() called
==================================================================
133)
class Parent {
static void staticMethod() {
System.out.println("Parent static");
}
}
class Child extends Parent {
static void staticMethod() {
System.out.println("Child static");
}
}
public class Main {
public static void main(String[] args) {
Parent p = new Child();
p.staticMethod();
}
}
Output:-
Parent static
Explanation:-
Static methods are resolved at compile-time based on reference type (‘Parent’),
not object type.
==================================================================
135)
class A {
void display() {
System.out.println("A display");
}
}
class B extends A {
void show() {
System.out.println("B show");
}
}
public class Main {
public static void main(String[] args) {
A a = new B();
B b = (B) a;
b.show();
}
}
Output:-
B show
Explanation:-
Casting ‘A’ to ‘B’ is valid here since ‘a’ actually refers to a ‘B’ instance. An
invalid
cast would cause a ‘ClassCastException’.
==================================================================
136)
public class Animal {
public void move() {
System.out.println("Animal moves");
}
}
public class Dog extends Animal {
public void move() {
System.out.println("Dog runs");
}
public void bark() {
System.out.println("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.bark(); // Error
}
}
Explanation:-
1.The bark() method is specific to Dog and not available in Animal.
2.Since a is of type Animal, it cannot access Dog-specific methods. Use proper
casting if needed.
==================================================================
137)
public class Example {
static {
System.out.println("Static block 1");
}
{
System.out.println("Instance block 1");
}
public Example() {
System.out.println("Constructor");
}
{
System.out.println("Instance block 2");
}
static {
System.out.println("Static block 2");
}
public static void main(String[] args) {
System.out.println("Main method");
new Example();
}
}
Output:-
Static block 1
Static block 2
Main method
Instance block 1
Instance block 2
Constructor
Reason:
Static blocks are executed when the class is first loaded, instance blocks are
executed in the order they appear when creating an instance, and the constructor
executes last.
==================================================================
138)
class Test {
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
static int x= 0;
return ++x;
}
}
Output:-
Compilation error
Reason:-
Static local members are not allowed.
==================================================================
139)
public class Myclass{
private int x = 10;
static int m1() {
int y = x;
return y;
}
public static void main(String[] args) {
m1();
}
}
Output:-
Error:
non-static variable x cannot be referenced from a static context
The above code will not be compiled because x is an instance
variable and instance members cannot be accessed from a static region.
==================================================================
140)
public class Test{
Test() {
m2();
}
void m1() {
System.out.println("Instance method");
}
static void m2() {
System.out.println("Static method");
m1();
}
public static void main(String[] args){
new Test();
}
}
Output:-
Error:-
non-static method m1() cannot be referenced from a static context
There is an error inside the static method because we cannot make a
static reference to the non-static method m1() from the type Test.
==================================================================
141)
class Test1 {
int x = 10;
Public static void main(String[] args){
System.out.println(Test1.x);
}
Static{
int x = 20;
System.out.print(x + " ");
}
}
Output:-
Error:-
non-static variable x cannot be referenced from a static context
==================================================================
142)
import java.util.*;
package Mypack;
public class Main {
public static void main(String args[]) {
System.out.println("Sastra");
}
}
Output:-
Error
Explanation:-
package must be declared initially before import statement.
==================================================================
143)
package mypack;
public class Hidden {
public static String message = "Hello from Hidden!";
static {
message = "Hello from Hidden (modified)!";
}
}
import mypack.Hidden;
public class Main {
public static void main(String[] args) {
System.out.println(Hidden.message);
}
}
Output: -
Hello from Hidden (modified)!
Explanation:-
Static block in the Hidden class changes the value of the message variable
before the main method accesses it. Thus, only the modified message is printed, and
the original value is never displayed.
==================================================================
144)
class MyClass {
static int count = 0;
public MyClass() {
Count++;
}
public void displayCount() {
System.out.println(“Count:” + count);
}
}
public class Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.displayCount();
obj2.displayCount();
}
}
Output:-
count : 2
count : 2
The explanation shows that a static variable is shared by all class instances.
When two objects are created, the variable is incremented twice, resulting in both
objects displaying “Count: 2”.
==================================================================
145)
class Example {
static void printMessage() {
System.out.println("Hello from static method");
}
}
public class Main {
public static void main(String[] args) {
Example obj = null;
obj.printMessage();
}
}
Output:-
The program doesn’t throw a NullPointerException because static methods
belong to the class itself, not individual instances. You can invoke a static
method
using the class name or even a null instance, as the method is tied to the class,
not the object.
==================================================================
146)
package com.example;
public class Main {
public static void main(String[] args) {
Helper helper = new Helper();
helper.displayMessage();
}
}
package com.util;
public class Helper {
public void displayMessage() {
System.out.println("Hello from Helper!");
}
}
Output:-
The code fails to compile because the Main class is in the com.example
package,and the Helper class is in the com.util package. To use Helper in Main, you
need to import it:import com.util.Helper.
==================================================================
147)
import p1.models.Model;
import p2.models.Model;
public class main {
public static void main(String[] args) {
Model obj = new Model();
}
}
Explanation:-
Ambiguous call, as there are two different classes with the same name from
different packages, hence the compiler cannot decide which one to use.
==================================================================
148)
public class Parent {
public static void printMessage() {
System.out.println("Parent class");
}
}
public class Child extends Parent {
public static void printMessage() {
System.out.println("Child class");
}
public static void main(String[] args) {
Parent obj = new Child();
obj.printMessage();
}
}
Output:-
Parent class
Explanation:-
We get the output as Parent class even though we are referencing Child class,
the static method cannot be overridden. In order to call the method in Child class,
we
need to have an object of Child class.
149)
class Test1 {
int x = 10;
Public static void main(String[] args){
System.out.println(x);
}
static{
System.out.print(x + " ");
}
}
Explanation:-
Error : non-static variable x cannot be referenced from a static context.If we are
trying to print the instance variable inside the static block or static method
without
creating a class instance then it will give error.
==================================================================
150)
package App.models;
class Model {
void display() {
System.out.println("Display method");
}
}
package App.main;
import App.models.Model;
public class MainApp {
public static void main(String[] args) {
Model model = new Model();
model.display();
}
}
Explanation:-
The Model class is package-private (default access level) and therefore cannot
be accessed from the myApp.main package. The class needs to be public to be
accessible outside its own package. Also we cannot declare two packages in the same
Java file.
==================================================================
151)
public class test {
public void A() {
System.out.println("This is a non-static method.");
}
public static void main(String[] args) {
nonStaticMethod();
}
}
Explanation:-
Non-static method A() cannot be referenced from a static context. However,
non-static methods can call upon static methods.
152)
class Test {
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
static int x= 0;
return ++x;
}
}
Output:-
Compilation error
Explanation:-
Static local members are not allowed.
==================================================================
153)
class Test {
int a = 1;
int b = 2;
Test func(Test obj) {
Test obj3 = new Test();
obj3 = obj;
obj3.a = obj.a++ + ++obj.b;
obj.b = obj.b;
return obj3;
}
public static void main(String[] args) {
Test obj1 = new Test();
Test obj2 = obj1.func(obj1);
System.out.println("obj1.a = " + obj1.a + " obj1.b = " + obj1.b);
System.out.println("obj2.a = " + obj2.a + " obj1.b = " + obj2.b);
}
}
Output:-
obj1.a = 4 obj1.b = 3
obj2.a = 4 obj2.b = 3
Explanation:-
obj1 and obj2 refer to the same memory address.
==================================================================
154)
class First {
void display() {
System.out.println("Inside First");
}
}
class Second extends First {
void display() {
System.out.println("Inside Second");
}
}
class Test {
public static void main(String[] args){
First obj1 = new First();
Second obj2 = new Second();
First ref;
ref = obj1;
ref.display();
ref = obj2;
ref.display();
}
}
Output:-
Inside First
Inside Second
Explanation:-
At line 15, ref is created with the Reference of the Class First, the next line
it is assigned with obj 1 which is allocated with the memory of the Class First,
therefore
the display function of the first class is called. At line 18, it is assigned with
obj 2 which
has the memory of the Class Second hence the display function of the Second class
is
called.
==================================================================
155)
class Circle {
double radius;
Circle(double r) {
radius = r;
}
double calculateArea () {
return 3.14 * radius * radius;
}
}
class Test {
public static void main(String[] args) {
Circle c = new Circle ();
System.out.println("Area: " + c.calculateArea());
}
}
Output:-
Error at line 12, the circle c is declared with no argument constructor but in the
Circle class, it is defined as a Parameterized Constructor.
==================================================================
156)
class DemoClass {
int a = 1;
void func() {
Demo obj = new Demo();
obj.display();
}
class Demo {
int b = 2;
void display() {
System.out.println("\na = " + a);
}
}
void get() {
System.out.println("\nb = " + b);
}
}
class Test {
public static void main(String[] args) {
DemoClass obj = new DemoClass();
obj.func();
obj.get();
}
}
Output:-
Error at line 14.
Explanation:-
Variable b belongs to the class Demo which is nested inside the class
Democlass. Therefore the data members declared in the Class Democlass can be
accessed inside the class Demo but the data members declared in the Class Demo
cannot be accessed outside the class Democlass.
==================================================================
157)
class A {
int i;
static {
System.out.println(i);
}
}
Output:-
compilation error
Explanation:-
It gives a compile time error (Line 7). Because, you can’t refer to a
non-static field inside a static initialization block.
==================================================================
158)
class Car {
private String model;
private int year;
Car(String m, int y) {
model = m;
year = y;
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2020);
// Error: model has private access in Car
System.out.println("Model:"+myCar.model+" Year: " + myCar.year);
}
}
Explanation:-
The model and year fields in the Car class are private, so they cannot be
accessed directly outside the class. This results in a compilation error.
==================================================================
159)
class Calculator {
int result;
void add(int a, int b) {
result = a + b;
}
static void printResult() {
System.out.println("Result: " + result);
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(5, 10);
Calculator.printResult();
}
}
Explanation:-
The printResult method is static and is trying to access the non-static field
result.
This leads to a compilation error since static methods cannot directly access non-
static
fields.
==================================================================
160)
class MathOperations {
int multiply(int a, int b) {
if (a > 0 && b > 0) {
System.out.println("Multiplying two positive numbers.");
}
}
}
public class Main {
public static void main(String[] args) {
MathOperations mathOps = new MathOperations();
int result = mathOps.multiply(3, 4);
System.out.println("Result: " + result);
}
}
Explanation:-
The multiply method has a return type of int, but it does not return any value in
some execution paths, which will result in a compilation error.
==================================================================
161)
class Printer {
void print(String text) {
System.out.println(text);
}
void print(String message) {
System.out.println(message);
}
}
public class Main {
public static void main(String[] args) {
Printer printer = new Printer();
printer.print("Hello, World!");
}
}
Explanation:-
The print method is incorrectly overloaded with the same parameter type
and name, which is not allowed. Java does not allow two methods with the same
signature (name and parameter list) within a class.
==================================================================
162)
class A {
void sum(int x, int y) {
System.out.println(“Sum of two numbers: “ +(x+y));
}
void sum(int y, int x) {
System.out.println(“Sum of three numbers: “+(x+y));
}
public static void main(String[] args){
A a = new A();
a.sum(20, 30);
}
}
Output:-
Error
Explanation:-
The sum function in Class A is defined twice with the same return type
which violates the static polymorphism and confuses the Compiler, therfore the
error is
produced.
==================================================================
163)
class Helper{
private int data;
private Helper(){
data = 5;
}
}
public class Test{
public static void main(String[] args){
Helper help = new Helper();
System.out.println(help.data);
}
}
Output:-
Compilation error
error: Helper() has private access in Helper
Helper help = new Helper();
Explanation:-
A private constructor cannot be used to initialize an object outside the
class that it is defined within because it is no longer visible to the external
class.
==================================================================
164)
class Person {
String name;
}
public class Test {
public static void main(String[] args) {
Person p;
p.name = "Alice";
System.out.println(p.name);
}
}
Explanation:-
Initialization:
Person p = new Person(); creates a new instance of the Person class and
assigns it to the variable p. This ensures that p is no longer null but references
a valid
Person object.
Setting and Accessing Fields: After initialization, p.name = "Alice"; correctly
sets the
name field of the Person object.System.out.println(p.name); will print "Alice"
because p
is properly initialized and refers to an actual object.
==================================================================
165)
class Employee {
private double salary;
public void setSalary(double amount) {
salary = amount;
}
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee();
emp.salary = 50000;
System.out.println(emp.salary);
}
}
Explanation:-
Private Field Access:
The salary field in the Employee class is declared as private. This
means it cannot be accessed directly from outside the Employee class, including
from
within the Main class.
Compilation Error: -
Attempting to access emp.salary directly from the Main class will result in a
compilation error because the salary field is not accessible due to its private
access
modifier.
==================================================================
166)
public class GFG {
static String sw_name;
static float sw_price;
static void set(String n, float p)
{
sw_name = n;
sw_price = p;
}
static void get()
{
System.out.println("Software name is: " + sw_name);
System.out.println("Software price is: " + sw_price);
}
public static void main(String args[])
{
GFG.set("Visual studio", 0.0f);
GFG.get();
}
}
Output:-
Software name is: Visual studio
Software price is: 0.0
==================================================================
167)
class GFG {
public static int ctr = 0;
public GFG() { ctr++; }
public static void main(String[] args)
{
GFG obj1 = new GFG();
GFG obj2 = new GFG();
GFG obj3 = new GFG();
System.out.println("Number of objects created are “+ GFG.ctr);
}
}
Output:-
Number of objects created are 3.
==================================================================
168)
public class Demo{
public static void main(String[] arr){
}
public static void main(String arr){ }
}
Output:-
No
Explanation:-
We can overload main() too. But JVM will always call main() that has String[]
argument.
==================================================================
169)
public class Demo{
public static void main(String[] arr){
Int num1 = 100;
Int num2 = 100;
Int num3 = 500;
Int num4 = 500;
if(num1==num2){
System.out.println(“num1 == num2”;);
}
else{
System.out.println(“num1 != num2”);
}
if(num3 == num4){
System.out.println(“;num3 == num4”);
}
else{
System.out.println(“num3 != num4”);
}
}
}
Output:-
num1 == num2
num3 != num4
Explanation:-
We always thought that whenever two object references are compared
using “==”, it always evaluates to “false”. But here Integer caching changes the
results.Integer class has a caching range of -128 to 127. Whenever a number is
between this range and autoboxing is used, it assigns the same reference. That’s
why
for value 100, both num1 and num2 will have the same reference, but for the value
500
(not in the range of -128 to 127), num3 and num4 will have different references.
==================================================================
170)
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void printName() {
System.out.println(name.toUpperCase());
}
public static void main(String[] args) {
Person person = null;
person.printName();
}
}
Output:-
ERROR!
Exception in thread “main”
java.lang.NullPointerException: Cannot invoke Person.printName()” because
“;lt;local1” is null at Person.main(Person.java:14)
Explanation:-
A NullPointerException in Java is one of the most common errors. It means that
you are trying to access a part of something that doesn’t exist. Here,In this code,
the
person object is null, so calling person.printName() results in a
NullPointerException.
You can fix this by ensuring that your object is not null before calling the
method.
==================================================================
171)
public class Test {
public static void main(String[] args) {
my_method;
}
public static void my_method() {
System.out.println(“Hello, world!”);
}
}
Output:-
1 error found:
File: Test.java [line: 7]
Error: Test.java:7: cannot find symbol symbol : variable my_method location:
class Test
Explanation:-
Here, the compiler is looking for a variable called my_method in the main
method;instead, you want to initiate a method call to my_method.
==================================================================
172)
class Demo{
public Demo(int i){
System.out.println(“int”);
}
public void Demo(short s) {
System.out.println(“short”);
}
}
public class Test{
public static void main(String[] args){
short s = 10;
Demo demo = new Demo(s);
}
}
Output:-
int
Explanation:-
The class Demo has one constructor i.e. with int argument. The short value is
automatically promoted to an int value during object creation so the constructor
with
the int argument will be called and it will print “int”.
==================================================================
173)
class Person {
String name;
int age;
// Constructor with parameters
Person(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
// Error: The constructor Person() is undefined
Person p = new Person();
System.out.println("Name: " + p.name + ", Age: " + p.age);
}
}
Explanation:-
The Person class only has a parameterized constructor, but in the main method,
an attempt is made to create a Person object using a no-argument constructor which
does not exist. will be uninitialized, leading to null for make and model, and 0
for year
when you print them.
==================================================================
174)
class Parent {
static void display() {
System.out.println("Static method in Parent");
}
}
class Child extends Parent {
static void display() {
System.out.println("Static method in Child");
}
}
public class Test {
public static void main(String[] args) {
Parent obj = new Child();
obj.display();
}
}
Output:-
Static method in Parent
Explanation:-
In Java, static methods are not overridden; they are hidden. The type of the
reference (Parent in this case) determines which static method is called, not the
type of
the actual object. Therefore, Parent.display( ) is called instead of Child.display(
).
==================================================================
175)
class Parent {
protected void show() {
System.out.println("Show in Parent");
}
}
class Child extends Parent {
private void show() {
System.out.println("Show in Child");
}
}
public class Test {
public static void main(String[] args) {
Parent obj = new Child();
obj.show();
}
}
Output:-
Test.java:16: error: show() has private access in Child
Explanation:-
The method show( ) in the Child class cannot override the show( ) method in the
Parent class because it has a more restrictive access modifier (Private). In Java,
the
the overriding method must have the same or a less restrictive access level.
==================================================================
176)
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
@Override
void draw() {
// Implementation needed
}
}
public class Test {
public static void main(String[] args) {
Shape s = new Circle();
s.draw();
}
}
Output:-
error
Explanation:-
Circle is not abstract and does not override abstract method draw() in Shape.The
Circle class must provide an implementation for the abstract method drawn( )
defined in
the Shape class.
==================================================================
177)
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
void makeSound(String sound) {
System.out.println(sound);
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.makeSound();
}
}
Output:-
Error
Explanation:-
The Dog class defines a method makeSound(String sound), which does not
override the makeSound( ) method from the Animal class because the number of
arguments is different.this changes the signature of the function.
==================================================================
178)
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void Sound() {
System.out.println("Bark");
}
}
public class Test {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound();
}
}
Output:-
Some sound
Explanation:-
The method Sound( ) in the Dog class does not override the sound( ) method in
the Animal class because method names are case-sensitive in Java. Therefore, the
Dog
class does not actually override the sound( ) method.
==================================================================
179)
abstract class Calculate {
abstract int add(int a, int b);
}
public class Main {
public static void main(String[] args) {
System.out.println(new Calculate() {
int add(int a, int b) {
return a + b;
}
}.add(11010, 022011));
}
}
Output:-
20235
Explanation:-
As Calculate is abstract,the definition of add is defined in Main class.Also here
022011
is octal as it is started with 0,So it is converted into decimal and then added to
decimal
11010.
==================================================================
180)
abstract class AbstractClass {
private abstract int abstractMethod();
}
Output:-
Error
Explanation:-
abstract methods can’t be private.
==================================================================
181)
abstract class A {
abstract int add(int a, int b);
}
class B extends A {
@Override
int add(int a, int b) {
return a + b;
}
}
Output:-
Error
Explanation:-
As A is abstract ,the member function add must be defined in subclass B or else it
must
be declared abstract as well.
==================================================================
182)
public class PumpkinDemo {
public static void main(String[] args) {
Shape s = new Circle();
System.out.println(s.name);
}
}
class Shape {
String name = "Shape";
}
class Circle extends Shape {
String name = "Circle";
}
Output:-
Error
Explanation:-
Shape.Member variables cannot be overridden.
==================================================================
183)
class Parent {
final void show() {}
}
class Child extends Parent {
void show() {} // This line will cause a compilation error
}
Output:-
Error
Explanation:-
Final methods can not be overridden
==================================================================
184)
class SuperClass {
protected void display() {
System.out.println("Display method in SuperClass");
}
}
class SubClass extends SuperClass {
private void display() {
System.out.println("Display method in SubClass");
}
}
public class Main {
public static void main(String[] args) {
SubClass obj = new SubClass();
obj.display();
}
}
Output:-
Error
Explanation:-
You cannot override a protected method and make it private because you're
decreasing the access level, which is not allowed.
==================================================================
185)
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Sleeping...");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
myAnimal.sound();
}
}
Output:-
Error
Explanation:-
Abstract classes cannot have objects.
==================================================================
186)
abstract class Helper {
static void demofun() {
System.out.println("Geeks for Geeks");
}
}
public class Main extends Helper {
public static void main(String[] args) {
Helper.demofun();
}
}
Output:-
Error
Explanation:-
Abstract class member functions can be called without creating instances for
that class.
==================================================================
187)
abstract class A {
abstract int x();
abstract int y();
abstract int z();
}
abstract class B extends A {
public int x() {
return 2;
}
}
class C extends B {
public int y() {
return 3;
}
public int z() {
return 4;
}
}
class Main {
public static void main(String[] args) {
C s = new C();
System.out.println(s.x());
System.out.println(s.y());
System.out.println(s.z());
}
}
Explanation:-
As A is abstract it's member functions must be defined in the subclasses.As we
are not declaring all definitions of A in subclass B we are declaring it as
abstract.We can
also derive another class C for B to declare the abstract functions of A.
==================================================================
188)
class Parent {
public void display() {
System.out.println("Parent Display");
}
}
class Child extends Parent {
public int display() {
return 0;
}
}
Output:-
Error
Explanation:-
The return type must be the same for the overridden functions.
==================================================================
189)
interface FinalMethodExample {
public void display();
}
class Final implements FinalMethodExample {
public void display() {
System.out.println("Hello child class");
}
}
class Main {
public static void main(String[] args) {
new Final().display();
}
}
Output:-
error
Explanation:-
In interfaces the functions should be defaultly abstract, so it doesn’t take a
function
body.
================================================================
190)
interface demo {
int x = 10;
}
class DB1 implements demo {
public static void main(String[] args) {
System.out.println(new DB1().x);
}
}
Output:-
error
Explanation:-
Since interface is abstract in nature we can’t create an object or anonymous
object so by removing newdemo() while print x, we can get the output as 10.
================================================================
191)
class A {
// Class A
}
interface B extends A {
// Interface B extending Class A
}
Output:-
error
Explanation:-
An interface can extend another interface, not the class.
================================================================
192)
public class Myclass {
private final int x = 10;
void m1() {
final int x = 20;
System.out.println(x);
}
public static void main(String[] args) {
Myclass obj = new Myclass();
obj.m1();
}
}
Output:-
20
Explanation:-
local variable x in the m1() hides the class variable x, so it prints the local
variable's
value.
================================================================
193)
public final class Inheritance {
class Program {
String s = "Class Program";
}
class Print extends Program {
void display() {
System.out.println(s);
}
}
public static void main(String[] args) {
Inheritance i = new Inheritance();
Inheritance.Print j = i.new Print();
j.display();
}
}
Output:-
Class Program
Explanation:-
final keyword when given to classes makes them uninheritable, but
subclasses of a final class can inherit other classes within the final class, hence
class B inherits String s from class Program and prints it.
==================================================================
194)
interface A {
default void method() {
helper();
}
private void helper() {
System.out.println("Helper in A");
}
}
class B implements A {
}
public class Test {
public static void main(String[] args) {
A obj = new B();
obj.method();
}
}
Output:-
Helper in A
Explanation:-
The hepler() method in interface ‘’A’ is private and only accessible within the
interface. The default method() in interface ‘A’ calls the helper(). When method()
is
called by object it invokes the method().
================================================================
195)
interface A {
default void method() {
System.out.println("Method in A");
}
}
interface B {
default void method() {
System.out.println("Method in B");
}
}
class C implements A, B {
public void method() {
super.method();
}
}
public class Test {
public static void main(String[] args) {
C obj = new C();
obj.method();
}
}
Output:-
Error
Justification:-
In class C, there is an ambiguity in calling super.method() because method() is
defined in both interfaces A and B. The compiler does not know which interface's
method() to call. To resolve this, invoke the function by A.super.method().
================================================================
196)
public final interface MyInterface {
void myMethod();
}
public class MyClass implements MyInterface {
public void myMethod() {
System.out.println("Method implemented in MyClass.");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myMethod();
}
}
Output:-
error
Explanation:-
Interface as final doesn’t allow .If we use it as final it would prevent any class
from
implementing it.
================================================================
197)
public class Myclass {
final static int x;
static {
x = 10;
}
public static void main(String[] args) {
System.out.println(x);
}
}
Output:-
10
Justification:-
If static and final are both used then the value being initialized in the static
block
is allowed.
================================================================
198)
interface MyInterface {
static void myMethod() {
System.out.println("Hello");
}
}
class MyClass implements MyInterface {
public void myMethod() {
System.out.println("World");
}
}
Explanation:-
Static methods in interfaces cannot be overridden by implementing classes.
Static methods belong to the interface itself, not the instance of the class.
================================================================
199)
interface MyInterface {
private void myMethod() {
System.out.println("Hello");
}
}
class MyClass implements MyInterface {
public void myMethod() {
System.out.println("World");
}
}
Explanation:-
Private methods in interfaces cannot be accessed by implementing classes.
The code fails because MyClass tries to override a private method, which is
not allowed.
Solution:-
interface MyInterface {
private void myMethod() {
System.out.println(“Hello”);
}
default void callMyMethod() {
myMethod();
}
}
================================================================
200.
interface A {
private int i;
}
Output:-
ERROR
Explanation:-
In an interface declaring a variable as private is meaningless .... in order to use
it
inside the classes by implementing keywords it must be public.
================================================================
201)
interface I {
void methodI(int i);
class C implements I {
public void methodI(int i) {
System.out.println(i);
}
}
}
Output:-
NO ERRORS
Explanation:-
Semantically class c is static and final and cannot be overridden in any other
blocks and it is not erroneous.
================================================================
202)
class ParentClass {
public final void displayMessage() {
System.out.println("This is a final method");
}
}
class ChildClass extends ParentClass {
public void displayMessage() {
System.out.println("Attempting to override a final method.");
}
}
Output:-
ERROR
Explanation:-
The final method displayMessage() is not able to override and overriding it will
raise errors.
================================================================
203)
class Data {
int value = 0;
}
public class FinalReferenceTest {
public static void main(String[] args) {
final Data data = new Data();
data.value = 10;
data = new Data();
}
}
Output:-
ERROR
Explanation:-
Final data object already created and unable to reassign an object with same name
since it is final
================================================================
204)
interface A {
void m1();
default void m2() {
System.out.println("Two");
}
}
class B implements A {
public void m1() {
System.out.println("Three");
}
}
public class Main {
public static void main(String[] args) {
A a = new B();
a.m1();
a.m2();
}
}
Output:-
error
Explanation:-
Default method cannot be abstract.
================================================================
205)
interface A {
void m1();
interface B {
void m2();
}
}
class C implements A, A.B {
public void m1() {
System.out.println("Green");
}
public void m2() {
}
}
Output:-
error
Explanation:-
Class C must implement an inherited abstract method from inner interface A.B.
================================================================
206)
interface A {
void m1();
interface B {
void m1();
}
}
class C implements A.B {
public void m1() {
System.out.println("Green");
}
}
public class Test {
public static void main(String[] args) {
A a = new C();
a.m1();
}
}
Output:-
error
Explanation:-
Class C is implementing an inner interface, not outer interface. But the reference
of a is
a type of outer interface. The correct code is A.B ab = new C();
================================================================
207)
interface A {
A();
void m1();
}
public abstract class B implements A {
public void m1() {
System.out.println("One");
}
}
Explanation:-
An interface cannot have a constructor.
================================================================
208)
final class MyClass {
static final void myMethod() {
System.out.println("Hello");
}
}
class MySubClass extends MyClass {
// override
static void myMethod() {
System.out.println("World");
}
}
Explanation:-
MyClass is marked as final, so it cannot be inherited. Additionally, myMethod
is both final and static, so it cannot be overridden. Attempting to override a
static method also leads to compilation errors.Also final method can only be
inherited but not overridden.
================================================================
209)
public class A {
public static void main(String[] args){
System.out.println('j' + 'a' + 'v' + 'a');
}
}
Output:-
Instead of string concatenation. Sum is given as output as single quotes are used
instead of double quotes (double quotes is used for String).
=================================================================
210)
class B{
public static String sing(){
return "la";
}
}
public class C extends B
{
public static String sing(){
return "fa";
}
public static void main(String[] args){
C a = new C();
B b = new C();
System.out.println(a.sing() + " " + b.sing());
}
}
Output:-
➢ fa la
This is because as the sing() method is static, it cannot be overridden to give "fa
fa" and hence gives "fa la".
==================================================================
211)
class Base {
public void Print(){
System.out.println("Base");
}
}
class Derived extends Base {
public void Print(){
System.out.println("Derived");
}
}
class Main {
public static void DoPrint(Base o){
o.Print();
}
public static void main(String[] args){
Base x = new Base();
Base y = new Derived();
Derived z = new Derived();
DoPrint(x);
DoPrint(y);
DoPrint(z);
}
}
Output:-
Base
Derived
Derived
This is because object y of type Base is overridden to point to class Derived due
to polymorphism.
==================================================================
212)
public class Demo{
public static void main(String[] arr){
Integer num1 = 100;
Integer num2 = 100;
Integer num3 = 500;
Integer num4 = 500;
If(num1==num2){
System.out.println("num1 == num2");
}
else{
System.out.println("num1 != num2");
}
if(num3 == num4){
System.out.println("num3 == num4");
}
else{
System.out.println("num3 != num4");
}
}
}
Output:-
➢ num1 == num2
num3 != num4
Since the Integer datatype is used, it has a caching range of -128 to 127. So
“num1 == num2” and “num3 != num4” will be printed.
==================================================================
213)
public class Switch2{
final static short x = 2;
public static int y = 0;
public static void main(String [] args){
for (int z=0; z < 3; z++){
switch (z){
case x: System.out.print("0 ");
case x-1: System.out.print("1 ");
case x-2: System.out.print("2 ");
}
}
}
}
Output:-
2 1 2 0 1 2
because the case expressions are all legal because x is marked final, which
means the expressions can be evaluated at compile time. In the first iteration of
the for
loop case x-2 matches, so 2 is printed. In the second iteration, x-1 is matched so
1 and
2 are printed (remember, once a match is found all remaining statements are
executed
until a break statement is encountered). In the third iteration, x is matched. So 0
1 and 2
are printed.
==================================================================
214)
public class Test{
Test() {
super();
this();
System.out.println("Test class object is created");
}
public static void main(String []args){
Test t = new Test();
}
}
Output:-
Error:-call to this must be first statement in constructor
Both this() and super() must be the first statement in the class constructor. They
cannot be called together in the same constructor.
=================================================================
215)
public final class FinalClass {
}
public class ExtendedClass extends FinalClass {
}
class Test{
public static void main(String args[]) {
FinalClass E = new ExtendedClass();
}
}
Output:-
You cannot extend a final class; it will cause a compilation error. Also, only one
class can have a public access specifier in one file.
==================================================================
216)
class Base{
protected final void getInfo(){
System.out.println("method of Base class");
}
}
public class Derived extends Base {
protected final void getInfo(){
System.out.println("method of Derived class");
}
public static void main(String[] args){
Base obj = new Base();
obj.getInfo();
}
}
Output:-
Error:-getInfo() in Derived cannot override getInfo() in Base Overriding is not
allowed -
when using the final keyword.
==================================================================
217)
class Writer{
public static void write(){
System.out.println(“Writing...”);
}
}
class Author extends Writer{
public static void write(){
System.out.println(“Writing book”);
}
}
public class Programmer extends Author{
public static void write(){
System.out.println(“Writing code”);
}
public static void main(String[] args){
Author a = new Programmer();
a.write();
}
}
Output:-
➢ Writing book
Explanation:-
The write method is static so it is independent of the object as the static method
can’t be overridden; it doesn't matter which class object is created.
Here we created a reference for Author class and write() is called even though we
create an object for Programmer output is Writing book.
==================================================================
218)
public class Simplilearn {
public static void main (String args[]) {
System.out.println(100 + 100 + “Simplilearn”);
System.out.println(“E-Learning Company” + 100 + 100);
}
}
Output:-
200 Simplilearn
E-Learning Company100100
Explanation:-‘
+’ operator will concatenate ,the statement will contain at least one String.
==================================================================
219)
class Grandparent{
public void Print(){
System.out.println(“Grandparent”);
}
}
class Parent extends Grandparent{
public void Print(){
System.out.println(“Parent”);
}
}
class Child extends Parent{
public void Print(){
super.super.Print();
System.out.println(“Child”);
}
public class Main{
public static void main(String args[ ]){
Child c= new Child();
c.print();
}
}
Output:-
Compiler Error in super.super.Print()
Explanation: -
In Java, it is not allowed to do super.super. We can only access Grandparent’s
members using Parent.
==================================================================
220)
public class DebugExercise1 {
public static void main(String[] args) {
String str = null;
int length = str.length();
System.out.println("Length: " + length);
}
}
Output:-
NULL POINTER EXCEPTION
Explanation:-
In java calling a method on a null reference leads to a Null pointer exception.
==================================================================
221)
static class A{
Static int b;
A(){
b=2;
}
Static void display(){
Return “B:”+b;
}
Output:-
compilation error;
Explanation: -
we can’t initialize static data members inside the constructor because static is
initialized before the very first object created.
==================================================================
222)
class Test{
public void gfg(){
System.out.println("GeeksforGeeks");
}
}
public class Derived extends Test{
public void gfg(){
System.out.println("GFG");
}
public static void main(String[] args){
Derived obj = new Test();
obj.gfg();
}
}
Output:-
Compilation error
Explanation:-
A child class reference variable cannot be used to store an instance of parent
class.
==================================================================
223)
public class ArrayTest {
public static void main(String[] args) {
int[] array = {1, 2, 3};
modifyArray(array);
System.out.println(array[0] + " " + array[1] + " " + array[2]);
}
public static void modifyArray(int[] arr) {
arr = new int[] {4, 5, 6};
}
}
Output:-
1 2 3
Explanation:-
The modifyArray method assigns a new array to the parameter arr. This
changes the reference inside the method but does not affect the original array
reference in main. Thus, the original array remains unchanged.
==================================================================
224)
abstract class Animal {
abstract void sound();
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Woof");
}
void eat() {
System.out.println("Dog eats bones");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
}
public class Test {
public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.sound();
myAnimal.eat();
myAnimal = new Cat();
myAnimal.sound();
myAnimal.eat();
}
}
Output:-
Woof Dog eats bones Meow Animal eats
Explanation:-
The Dog class overrides sound and eat, while Cat only overrides sound.
When myAnimal is assigned a Cat instance, it will only call sound specific to Cat.
The eat() method, not overridden in Cat, uses the implementation from Animal.
==================================================================
225)
public class Test{
private static int value = 20;
public int s = 15;
public static int temp = 10;
public static class Nested{
private void display(){
System.out.println(temp + s + value);
}
}
public static void main(String args[]){
Test.Nested inner = new Test.Nested();
inner.display();
}
}
Output:-
The static class Nested cannot access non static data member.error:
non-static variable s cannot be referenced from a static context
System.out.println(temp + s + value);
==================================================================
226)
public class RuntimePolymorphism{
public static void main(String[] args){
A a = new B();
B b = new B();
System.out.println(a.c + “ “+ a.getValue()+” “ + b.getValue() + “
“+b.getSuperValue());
}
}
class A{
protected char c = ‘A’;
char getValue(){
return c;
}
}
class B extends A{
protected char c = ‘B’;
char getValue(){
return c;
}
char getSuperValue(){
return super.c;
}
}
Output:-
➢ A B B A
Explanation:-
a.c is A the variable c from A is simply hidden in class
B.a.getvalue(),b.getvalue()
are from class B.super is used to call c from class A.
==================================================================
227)
final class Vehicle {
protected String brand = (“Ford”);
public void honk() {
System.out.println(“Tutu, tutu”);
}
}
class Main extends Vehicle {
private String modelName = “Mustang”;
public static void main(String[] args) {
Main myFastCar = new Main();
myFastCar.honk();
System.out.println(myFastCar.brand + “ ” +
myFastCar.modelName);
}
}
Output:-
Error
Explanation :-
● The main class is trying to inherit the final class.
● When a class is defined as final, it will not be possible to inherit or
redefine.
==================================================================
228)
class Main {
public static void main(String args[]) {
System.out.println(fun());
}
int fun() {
return 20;
}
}
Output: -
Compiler Error. In Java, non-static methods cannot be called in a static
method without creating an object.We make fun() static OR we can create an
object of the Main class and then call the method on that object then the program
==================================================================
229)
class Superclass {
protected void show() {
System.out.println("Superclass");
}
}
class Subclass extends Superclass {
private void show() {
System.out.println("Subclass");
}
}
public class Test {
public static void main(String[] args) {
Superclass obj = new Subclass();
obj.show();
}
}
Output:-
error
Explanation:-
The show method in Subclass is more restrictive than the show method in
Superclass. In Java,overridden methods must have the same or less restrictive
access
level.
==================================================================
230)
class Main {
void process(int... numbers) {
System.out.println("Varargs");
}
void process(int number) {
System.out.println("Single int");
}
void process(String text) {
System.out.println("String");
}
public static void main(String[] args) {
Main obj = new Main();
obj.process(10);
obj.process("Hello");
obj.process(1, 2, 3);
}
}
Output:-
➢ Single int
String
Varargs
Explanation: -
Single int: Matches the exact method signature void process(int number).
String: Matches the exact method signature void process(String text).
Varargs: Matches the varargs method void process(int... numbers)
because it can handle multiple integers.
==================================================================
231)
class DivByZero {
public static void main(String args[]){
int var1 = 15;
int var2 = 5;
int var3 = 0;
int ans1 = var1 / var2;
int ans2 = var1 / var3;
System.out.println( "Division of va1"+ " by var2 is: "+ ans1);
System.out.println("Division of va1"+ " by var3 is: "+ ans2);
}
}
Output:-
runtime error
Explanation:-
caused by dividing by zero
==================================================================
232)
public class DebugExercise10 {
public static void main(String[] args) {
int x = 10;
if (x > 5) {
int y = x * 2;
}
System.out.println("Y: " + y);
}
}
Output:-
error: cannot find symbol
Explanation:-
scope issue y has been declared inside the if statement . hence the scope of y is
restricted till there.
==================================================================
233)
class X{
public X(int i){
System.out.println(1);
}
}
class Y extends X{
public Y(){
System.out.println(2);
}
}
Output:-
Compilation error
Explanation :-
because the constructor of class Y is trying to invoke the constructor of its super
class X,but there is no default constructor in class X.
==================================================================
234)
public class WhatIsWrong {
public static void main(String[] args) {
double i = 2;
switch (i) {
case 1: System.out.println(“First class”);
break;
case 2: System.out.println(“Second class”);
break;
default:
break;
}
}
}
Explanation:-
Compilation-error at switch(i) as switch works only with “int” and“String”.
incompatible types: possible lossy conversion from double to int.
==================================================================
235)
public class Demo {
static int x=1111;
static {
x=x-- - --x;
}
{
x=x++ + ++x;
}
public static void main(String args[]){
System.out.println(x);
}
}
Output:-
➢ 2
Explanation:-
We know that the static block executed first. Therefore, the post decrement value
of x will be 1111 and the pre decrement value will be 1109 and the difference
between
the values is 2 and the same will print on the console.
Note:- that the block after the static block will never get executed.
==================================================================
236)
import java.lang.Math;
public class Example
{
public static void main(String args[])
{
String computerMove;
switch ( (int)(3*Math.random()) )
{
case 0:
computerMove = "Rock";
break;
case 1:
computerMove = "Scissors";
break;
case 2:
computerMove = "Paper";
break;
}
System.out.println("Computer's move is " + computerMove);
}
}
Explanation:-
Since math.random() gives only values 0 and 1 and 2 can’t be formed, an
exception will be thrown at the last line.
To fix the error case 2 should be changed to default or Initialize the computermove
variable as Null.
==================================================================
237)
class A {
void sum(int x, int y) {
System.out.println(”Sum of two numbers: “ +(x+y));
}
void sum(int y, int x) {
System.out.println(“Sum of three numbers: “ +(x+y));
}
public static void main(String[] args){
A a = new A();
a.sum(20, 30);
}
}
Output:-
➢ Error
Explanation:-
The sum function in Class A is defined twice with the same return type which
violates
the static polymorphism and confuses the Compiler, therefore the error is produced.
==================================================================
238)
class Grandparent {
public void Print() {
System.out.println(“Grandparent’s Print()”);
}
}
Class Parent extends Grandparent {
public void Print() {
System.out.println(“Parent’s Print()”):
}
}
class Child extends Parent {
public void Print() {
super.super.Print();
System.out.println(“Child’s Print()”);
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.Print();
}
}
Output:-
➢ Error – Compilation error on line 14
Explanation:-
There is no such identifier named super.super used in the child class,
instead to print all 3 print functions on the child class, use separate super
identifiers in
the parent class and child class.
==================================================================
239)
class Base {
final public void show() {
System.out.println("Base::show() called");
}
}
class Derived extends Base {
public void show() {
System.out.println("Derived::show() called");
}
}
class Main {
public static void main(String[] args) {
Base b = new Derived();
b.show();
}
}
Output:-
Compilation Error at line 7 - In the base class, the show() function is defined as
final, hence its inherited class named Derived cannot override the show() function.
==================================================================
240)
public class B{
public static void main(String[] args) {
System.out.println(“Original main”);
}
public static void main(String args){
System.out.println(“overloaded main “);
}
}
Output:-
➢ Original main
Explanation:-
Main functions can be overloaded in java but it is simply never called, the
actual main function with String [] is displayed.
==================================================================
241)
public class StaticExample {
private static int count = 0;
public static void increment() {
count++;
}
public void printCount() {
System.out.println(count);
}
public static void main(String[] args) {
StaticExample obj = new StaticExample();
obj.increment();
obj.printCount();
}
}
Output:-
➢ 1
==================================================================
242)
public class Test{
public static void main(String[] args){
int temp = null;
Integer data = null;
System.out.println(temp + " " + data);
}
}
Output:-
Error - Null value cannot be converted into integer data type.
Explanation:-
Temp variable is a primitive data type. Primitive data types cannot be
assigned null values but data is an instance of class Integer and therefore can
hold null
values.
==================================================================
243)
public class Test{
public static void main(String[] args){
int temp = 40;
if(temp == 30 && temp/0 == 4){
System.out.println(1);
}
else{
System.out.println(2);
}
}
}
Output:-
➢ 2
Explanation:-
&& operator is evaluated from left to right. If the first expression of &&
operator evaluates to false, then the second operator is not evaluated. There is no
compilation error because divide by 0 is a runtime exception.
==================================================================