Skip to content
క
kagitha
/
quiz
/
java-var
Subscribe
Index
⌘K
JAVA NOTEBOOK · QUIZ 05 · BEGINNER
Java var
QUESTION 01 / 06
var count = 0; count = "ten"; What happens?
A
count becomes a String
B
Compile error: String cannot be converted to int
C
Runtime ClassCastException
D
count becomes an Object
SCORE SO FAR · 0 / 0
Share this quiz ↗
var count = 0; count = "ten"; What happens?
— Compile error: String cannot be converted to int. var is still static typing. The type is fixed as int at compile time and can never change.
var n = 10; What is the type of n?
— int. The literal decides the type. 10 is an int, 10L a long, 10.0 a double. If you need an Integer, use Integer.valueOf(10).
Where can you NOT use var?
— A class field. var is only for local variables (plus lambda parameters). Fields, method parameters and return types must spell out their types.
var list = new ArrayList<>(); What is the type of list?
— ArrayList<Object>. The diamond infers from the left-hand side, and with var there isn't one, so Java falls back to Object. Write new ArrayList<String>() instead.
Which of these compiles?
— var names = new ArrayList<String>();. The right-hand side must tell the compiler the type on its own. null, a bare array initializer and a lambda don't.
Does using var change the bytecode or slow your program down?
— No, the compiler writes the real type, so the bytecode is identical. var exists only in source code. The compiler replaces it with the inferred type, so there is no runtime difference.
kagitha
Close
✕
Search everything — articles, videos, chapters, agents, books
01
AI
02
Java
03
System Design
04
Series
05
Manga
06
The Lab
07
Videos
08
Quizzes
09
Books
10
Resume