menu

Java Basic Programs for Beginners


1. Which of the following is a valid way to declare and initialize an array of integers in Java?

int[] arr = new int[5];

int arr[5] = {1, 2, 3, 4, 5};

int[] arr = {1, 2, 3, 4, 5};

int arr[] = new int[]{1, 2, 3, 4, 5};


2. Which of the following is not a valid way to declare and initialize a String variable in Java?

String var = "hello";

String var = new String("hello");

String var = 'hello';

String var = "hello".toUpperCase();


3.

What is the output of the following program?

public class Main {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println(x / y);
 }
}

2.5

2

3

1


4.

What is the output of the following program?

public class Main {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println(x - y);
 }
}

2

3

5

-3


5.

What is the output of the following program?

public class Main {
public static void main(String[] args) {
String str = "Hello, world!";
System.out.println(str.toUpperCase());
 }
}

HELLO, WORLD!

Hello, world!

hello, world!

hELLO, WORLD!


6.

What is the output of the following program?

public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
  }
 }
}

1 2 3 4 5

5 4 3 2 1

1 3 5

2 4


7. Which of the following is a valid way to declare a constant in Java?

final int var = 5;

int const var = 5;

const int var = 5;

int var = 5; final


8.

What is the output of the following program?

public class Main {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println(x > y && y < x);
 }
}

1

0

Compile error

Runtime error


9.

What is the output of the following program?

public class Main {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println(x >= y);
 }
}

1

0

Compile error

Runtime error


10. Which of the following is a valid way to declare and initialize a boolean variable in Java?

boolean var = "true";

boolean var = 1;

boolean var = true;

boolean var = True;