PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] Why Java did not check for type compatibility for byte as it does with int?

 July 20, 2022     byte, for-loop, integer, java, primitive     No comments   

Issue

I am trying to use byte as control loop variable in for loop. I used the condition as n < 128 (where 128 is out of range of byte)

for (byte n =0; n < 128 ; n++) System.out.println("I am in For loop. "+ n ); 

The loop is going infinitely from 0 to 127 and then -128 to 127.

When I tried to do the same with int, it gave an error.

for (int n = 0; n < 2147483648; n++)

The literal 2147483648 of type int is out of range

Why did Java not check the type compatibility with byte like it checked for int?


Solution

The type compatibility is not checked against the type of the loop's variable.

The type of an integer literal with no suffix is always int. 128 is a valid int, so the first loop passes compilation but results in numeric overflow leading to an infinite loop.

On the other hand, 2147483648 is not a valid int, so the second loop doesn't pass compilation. If you replace 2147483648 with a long literal (2147483648L), the second loop will also pass compilation.



Answered By - Eran
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing