Java 10 Flashcards

1
Q

What is Local Variable Type Inference in Java 10?

A

Local-Variable Type Inference is the biggest new feature in Java 10, you can uise var for local variables intead of typed name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does Local Variable Type Inference work?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Java 10 introduce Local Variable Type Inference, does this mean that now Java is a dynamically typed language?

A

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);
}   }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can we initialize var as null?

A

No, null is not a type and hence the compiler cannot infer the type of the RHS expression.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
Can we declare multiple variable var in single statement like
var x = 1, y = 2?
A

No, var is not allowed in a compound declaration

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can we create a var variable without initializer?

A

No, If there is no initializer then the compiler will not be able to infer the type and it will give compilation error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Which method we can use to create the new collection instances from existing instances?

A

We can use the copyOf (List.copyOf, Set.copyOf, and Map.copyOf) to create the new collection instances from existing instances.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the use of Optional.orElseThrow() method?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Which methods are added to the Collectors class in the Stream package

A

Below methods are added to the Collectors class in the Stream package

Collectors.toUnmodifiableList()
Collectors.toUnmodifiableSet()
Collectors.toUnmodifiableMap()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly