menu

Java Basic Programs for Beginners


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

char[] arr = {'a', 'b', 'c'};

char[] arr = new char[]{'a', 'b', 'c'};

char[] arr = new char[3]{'a', 'b', 'c'};

char[] arr = new char[3]; arr[0] = 'a'; arr[1] = 'b'; arr[2] = 'c';


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 = 2;
System.out.println(x + y);
 }
}

2

3

5

7


4.

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.charAt(6));
 }
}

H

e

W

o


5.

What is the output of the following program?

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

2.5

2

3

5


6. Which of the following is a valid way to create a new object in Java?

Object obj = new Object();

Object obj = Object();

Object obj = new Object;

Object obj = Object;


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. Which of the following is a valid way to declare and initialize a double variable in Java?

double var = 3.14159;

double var = 3,14159;

double var = "3.14159";

double var = Double.parseDouble("3.14159");


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);
 }
}

2

3

5

-3


10.

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