Class LocalVariableTypeInferenceExamples

java.lang.Object
net.jrodolfo.java_evolution.java10.LocalVariableTypeInferenceExamples

public class LocalVariableTypeInferenceExamples extends Object
Demonstrates local variable type inference, introduced in Java 10 through the var reserved type name.

Before Java 10, local variables sometimes repeated long generic types that were already obvious from the initializer. That made code noisier without adding much information.

var solves that local readability problem. It does not make Java dynamically typed: the compiler still infers a specific static type from the initializer. In Java 10 it is limited to local variables, including variables in loops and try-with-resources blocks.

  • Constructor Details

    • LocalVariableTypeInferenceExamples

      public LocalVariableTypeInferenceExamples()
  • Method Details

    • countNames

      public int countNames(List<String> names)
      Uses var for a local variable whose constructor initializer makes a longer generic type obvious.
      Parameters:
      names - the names to count
      Returns:
      the number of names
    • wordLengths

      public Map<String,Integer> wordLengths(List<String> words)
      Uses var with a generic collection to avoid repeating the full type on both sides of the assignment.
      Parameters:
      words - the words to inspect
      Returns:
      a map from each word to its length
    • readFirstLine

      public String readFirstLine(String text) throws IOException
      Uses var in a try-with-resources declaration.
      Parameters:
      text - text read through a BufferedReader
      Returns:
      the first line of the text
      Throws:
      IOException - when reading fails
    • inferredTypeStillHasAConcreteClass

      public String inferredTypeStillHasAConcreteClass()
      Shows that a var variable still has a real compile-time type.
      Returns:
      the runtime class name of a variable inferred as String
    • whereVarCanBeUsed

      public String whereVarCanBeUsed()
      Keeps the explicit type in the method signature because Java 10 var is only for local variables.
      Returns:
      a sentence summarizing the scope of var