This question already has answers here:
What is 'var' in Java 10, and is it comparable to JavaScript?
(3 answers)
Closed 3 years ago.
Is there a difference between declaring var x and int x?
//Java 8
int x = 10;
//Java 10
var x = 10;
There is no run-time difference. var is compile-time syntactical sugar. If you replace var with the inferred type (int) you get identical results.
Related
This question already has answers here:
Java: Why can't I cast int to Long
(3 answers)
Wrapper classes - why integer literals fail for Long but work for anything smaller
(2 answers)
Closed 1 year ago.
Why it's correct:
Long l = new Long(10);
but it's not correct:
Long l2 = 10;
I understand that int is substituted here, but why is new Long(10) correct?
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Integer division: How do you produce a double?
(11 answers)
Int division: Why is the result of 1/3 == 0?
(19 answers)
Why does integer division code give the wrong answer? [duplicate]
(4 answers)
Closed 4 years ago.
So it is obvious that
int x = 3/4; // x is 0 here
But i do not understand why the following is also the case:
double x = 3/4; // x is also 0 here
With the following i am able to get the result i want:
double x = (double) 3/4; // x is 0.75 here, but why do i have to cast?
This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 6 years ago.
I have below code
int i = 5;
long j = 5;
1. i = i + j; // Throwing an exception "Type mismatch: cannot convert from long to int"
2. i += j; // This working fine
As you can see 1st case throwing an exception but 2nd case working fine.
Why 2nd case working fine without throwing an any exception?
+= is a compound statement and Compiler internally casts it. Where as in first case direct statement and compiler cries.
This question already has answers here:
Double is not converting to an int
(4 answers)
Closed 8 years ago.
int k=(int)10.0;
Integer j = (Integer ) 10.0;//compile time error
In the second line of code i am getting incompatible types error.my question is why it is not possible to cast wrapper classes in java?As i am able to cast primitives in java.
incompatible types: double cannot be converted to Integer
Integer j = (Integer ) 10.0;
no, you cannot cast primitives to the wrong wrapper class, use int k = Double.valueOf(10.0).intValue() instead or int k=(int)10.0; Integer i = k;
This question already has answers here:
Is Integer Immutable
(12 answers)
Closed 9 years ago.
I know Integer is immutable in Java. But I tried this:
Integer i = 4;
i++;
System.out.println(i); // output is 5
Why the self-increment is still working? Did Java create a new Integer object?
i++;
is equivalent to:
i = i + 1;
which i now refers to a different Integer object (5).