Skip to content
This repository was archived by the owner on Feb 10, 2024. It is now read-only.

Commit a049cb0

Browse files
author
Ram swaroop
committed
added content
1 parent 6a1f962 commit a049cb0

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

_posts/2015-05-14-variables-and-literals.md

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,8 +303,27 @@ solves the issue.
303303

304304
#### What happens when you cast a large value to store it in a small container
305305

306+
When you do a explicit cast, the compiler just keeps __the number of bits (from right)__ that the variable type can hold
307+
and strips off the rest. Consider the below program to understand better:
306308

309+
{% highlight java linenos %}
310+
class Casting {
311+
public static void main(String [] args) {
312+
int i = 7;
313+
byte b = (byte) i;
314+
System.out.println("The 1st byte is " + b); // prints 7
315+
// now let's see another example
316+
int i = 128;
317+
byte b = (byte) i;
318+
System.out.println("The 2nd byte is " + b); // prints -128
319+
}
320+
}
321+
{% endhighlight %}
307322

308-
323+
So, in line 4, `i` is `7` i.e, `00000000000000000000000000000111` (32 bits) and when we do a explicit cast, the compiler
324+
just stores `00000111` (8 bits) in variable `b` (as `byte` can hold only 8 bits) which is also `7`. Therefore, it prints
325+
`7`. But in line 8, `i` is `128` i.e, `00000000000000000000000010000000` and after stripping off the extra bits we are
326+
left with `10000000` which is not `128` as the 1st bit is the sign bit. So, after computing the 2's compliment of it we
327+
get `-128` as the result.
309328

310329

0 commit comments

Comments
 (0)