Java 10 Flashcards
What is Local Variable Type Inference in Java 10?
Local-Variable Type Inference is the biggest new feature in Java 10, you can uise var for local variables intead of typed name
How does Local Variable Type Inference work?
Parsing a var statement, the compiler looks at the right-hand side of the declaration / initializer, and it infers the type from the right-hand side (RHS) expression.
var i = 5; Here compiler will create a int variable i
Java 10 introduce Local Variable Type Inference, does this mean that now Java is a dynamically typed language?
No, it’s still a statically typed language.
Let’s take an below example
class LocalVariableTypeExample { public static void main(String args[]){ var i = 5; var s = "abc";
System.out.println("s:" + s); System.out.println("i:" + i); } } Now compile the code and check the decompiled file, it will look like
class LocalVariableTypeExample { public static void main(String args[]){ int i = 5; String s = "abc";
System.out.println("s:" + s); System.out.println("i:" + i); } }
Can we initialize var as null?
No, null is not a type and hence the compiler cannot infer the type of the RHS expression.
Can we declare multiple variable var in single statement like var x = 1, y = 2?
No, var is not allowed in a compound declaration
Can we create a var variable without initializer?
No, If there is no initializer then the compiler will not be able to infer the type and it will give compilation error
Which method we can use to create the new collection instances from existing instances?
We can use the copyOf (List.copyOf, Set.copyOf, and Map.copyOf) to create the new collection instances from existing instances.
What is the use of Optional.orElseThrow() method?
If value is present in the Optional instance the it will return the value, else if there is no value in the Optional instance then this method will throw an Exception
Which methods are added to the Collectors class in the Stream package
Below methods are added to the Collectors class in the Stream package
Collectors.toUnmodifiableList()
Collectors.toUnmodifiableSet()
Collectors.toUnmodifiableMap()