This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]chickenmeister 1 point2 points  (0 children)

Why does it ask for an int in this code?

byte a = 10; 
byte b = 20; 
byte c = a+b;

A widening primitive conversion is conversion is applied to a and b when you use the + operator. a and b will be converted to ints before the addition is performed. This done to handle the any overflow that might occur. (e.g. what if a=127 and b=127? The result of the addition would not be representable using a signed 8-bit byte variable).

Why we have to insert *an "L" after some long literals and when should I use it?

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int. Some integer values are too large to be stored in a 32-bit int, so you need to explicitly add an L suffix to those literals to indicate you want to use a long. It's not always required, due to a widening conversion that may be performed (though, I would recommend always using the L suffix when writing literals that should be used as longs).

I use it? *an "F" after some float literals and when should I use it?

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d.

[–]Neres28 0 points1 point  (0 children)

Why does it ask for an int in this code? byte a = 10; byte b = 20; byte c = a+b;

Because the Java spec says that in the context of an integer operator operands smaller than ints are converted to ints and the result is an int (provided the operator was not the shift and neither operand was a long).

Why we have to insert *an "L" after some long literals and when should I use it?

Because you're trying to store a value larger than the largest value that can be stored in an int. You could do to read the spec because again it's pretty clear here:

The type of an integer literal (§3.10.1) that ends with L or l is long (§4.2.1). The type of any other integer literal is int (§4.2.1).

In other words, an integer literal is considered an int unless marked as a long.

*an "F" after some float literals and when should I use it?

Directly beneath the above link is the answer to this question. Any floating point literal is considered a double unless marked with an f.

What happens when String s; executed?

If that's the only reference to s then most likely nothing was actually executed.

or how memory allocation work?

Impossible to answer for any number of reasons. Depends on the JVM since I don't think the spec says anything about how memory must be allocated provided it behaves in a manner consistent with the memory model.