Quiz – Using var in Java

To learn about the var reserved word, visit http://talks.skilltoz.com/local-variable-type-inference-var-java-10/

Java 11 Certification Practice Questions

Topic: Working with Java data types

Objective: Use local variable type inference, including as lambda parameters
Q1. Which of the following lines will compile without errors?
public class Example15 {
	var j=10; //line 2
	Example15() {
		var i=0;
		i ="one"; // line 6
	public static void main(String[] args) {
		var i = 1234;
		var s = ""+i;	// line 11
	public static void print(var a) { // line 14
		System.out.println("a is " + a);


A. Line 2
B. Line 6
C. Line 11
D. Line 14
E. None of these

Q2. Which of the following code fragments compile without errors?
A. var numberList = new ArrayList<Integer>();
   for (var num : numberList) {
	System.out.println("num is" + num);
B. var numberList = new ArrayList<Integer>();
   numberList = new LinkedList<>();
C. private var getModelName() {
      return “xyz”;
D. var list = new ArrayList<>();
   int i = list.get(0);


Q1. Choice C is correct. Line 11 will compile correctly because a string can be concatenated with various data types such as int, float, double, boolean,
etc. Line 2 will not compile because var cannot be used for instance variables. Line 6 will not compile because the type of variable i was inferred to be int first and hence cannot refer to a String. Line 14 will not compile because var cannot be used as a method parameter.

Q2. Choice A is the correct answer as only this code fragment compiles without errors. Choice B does not compile because var numberList is already inferred to be of type ArrayList<Integer> and LinkedList<> cannot be assigned to it. Choice C does not compile because var cannot be used as a return type. Choice D does not compile because the variable list is considered as ArrayList<Object> and Object cannot be simply assigned to an int.

For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/

Leave a Reply

Your email address will not be published. Required fields are marked *