Skip Top Navigation Bar

Exploring var with the Java Playground

Background on var

What is var used for?

  • We can declare a variable of type var when the actual type of the variable can be inferred based on what it is assigned to.
    • Local variables with initializers
    • Indexes in enhanced for-loops and traditional for-loops;
  • While you can use var when we are assigning the result of a method call. You may not want to where the type of the return is ambiguous. While the compiler will understand that type, this practice will make the code less readable.

When can we NOT use var?

  • We can not use var if the type of values being stored in the variable cannot be inferred.
    • Method returns or parameters
    • Constructor returns or parameters
    • Variable declarations

Exploring var with the Java Playground

  1. Run each example in the Java Playground.
  2. Record the result, if any and explain why this was the given result.
  3. If there is an error, explain the error and correct the code.
  4. If a result was provided, re-write the code segment with the proper data type instead of var and re-run the code.

Sample 1

Sample 2

Sample 3

Sample 4

Sample 5

Modify the enhanced-for loop to use a traditional for loop. Use var when declaring the loop control variable.

Sample 6

Sample 7

Using var, add another Dog object named finn and assign it to null.

Sample 8

Modify the Dog class by adding a bark method.

Follow Up Question

  1. While declaring sound of type var works, it isn't recommended. Explain why?

Sample 9

This code segment contains one improper use of var. On which line is var being used improperly? Modify the code by replacing one case of var with a data type.

Sample 10

This code segment contains one improper use of var. On which line is var being used improperly? Modify the code by replacing one case of var with a data type.

Sample 11

This code segment contains one improper use of var. On which line is var being used improperly? Modify the code by replacing one case of var with a data type.

Sample 12

This code segment contains one improper use of var. On which line is var being used improperly? Modify the code by replacing one case of var with a data type.

Sample 13

On which line is var being used improperly?

Sample 14

Modify Sample 13 so that numbers is declared var rather than var[] and assigned an int array of size 3.

Sample 15

Modify Sample 14 to also initialize numbers to 1, 2, 3 as follows: