@@ -257,7 +257,52 @@ __different__ from the type of literal/object it's holding/referring, you may re
257
257
Casting can be done by the compiler _ (implicit cast)_ or by you _ (explicit cast)_ . Typically, an implicit cast happens
258
258
when you're doing a __ widening conversion__ , in other words, putting a smaller thing (say, a byte) into a bigger container
259
259
(such as an int). But when you try to put a large value into a small container (referred to as __ narrowing__ ), you should
260
- do an explicit cast, where you tell the compiler that you're aware of the danger and accept full responsibility.
260
+ do an explicit cast, where you tell the compiler that you're aware of the danger and accept full responsibility. Let's
261
+ for example consider the below program:
262
+
263
+ {% highlight java linenos %}
264
+ class Casting {
265
+ public static void main(String [ ] args) {
266
+ long a = 100; // literal '100' is implicitly an 'int'
267
+ //but the compiler does an implicit cast
268
+ int b = (int) 10.23; // literal '10.23' is implicitly a 'double'
269
+ // so we require an explicit cast
270
+ int x = 3957.229; // illegal, can't store a large value in a
271
+ // small container without explicit cast
272
+ }
273
+ }
274
+ {% endhighlight %}
275
+
276
+ There is another rule which you must be aware of, i.e, __ the result of an expression involving anything int-sized or
277
+ smaller is always an ` int ` __ . Check this out:
278
+
279
+ {% highlight java %}
280
+ byte a = 3; // No problem, 3 fits in a byte
281
+ byte b = 8; // No problem, 8 fits in a byte
282
+ byte c = a + b; // Should be no problem, sum of the two bytes
283
+ // fits in a byte
284
+ {% endhighlight %}
285
+
286
+ The last line won't compile! You'll get an error like this:
287
+
288
+ {% highlight java %}
289
+ TestBytes.java:5: possible loss of precision
290
+ found : int
291
+ required: byte
292
+ byte c = a + b;
293
+ ^
294
+ {% endhighlight %}
295
+
296
+ Doing an explicit cast like:
297
+
298
+ {% highlight java %}
299
+ byte c = (byte) (a + b);
300
+ {% endhighlight %}
301
+
302
+ solves the issue.
303
+
304
+ #### What happens when you cast a large value to store it in a small container
305
+
261
306
262
307
263
308
0 commit comments