devxlogo

Be Careful When You Cast

Be Careful When You Cast

Java allows you to cast variables, or change them from one variable type to another. However, it’s important to make sure that the final variable type can store all the information from the original variable type, as Java will discard any additional information.

For example, if you cast a variable with a value of 20 from short to byte, you won’t lose any information. However, if you make the same cast with an initial value of 20,000, you’ll get an incorrect result because a byte variable’s maximum value is 127.

devx-admin

Share the Post: