menu

Java Basic Programs for Beginners


1. Which of the following is a method of the String class?

length()

size()

count()

amount()


2.

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


3.

What is the output of the following program?

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

1

0

Compile error

Runtime error


4. 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


5. 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};


6. Which of the following is not a valid way to declare and initialize an integer array in Java?

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

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

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

int[] arr = new int[3]; arr[0] = 1; arr[1] = 2; arr[2] = 3;


7.

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


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

char var = 'a';

char var = "a";

char var = 97;

char var = 'a'.toUpperCase();


9. Which of the following operators has the highest precedence in Java?

*

++

&&

+


10.

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.substring(7, 12));
 }
}

Hello

world

Hello,

, wor