From the course: Java 8+ Essential Training: Syntax and Structure

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Convert values between numeric types

Convert values between numeric types - Java Tutorial

From the course: Java 8+ Essential Training: Syntax and Structure

Start my 1-month free trial

Convert values between numeric types

- [Teacher] You can make copies of and convert numbers to different types. Certain conversions from one type to another are automatic. Let's start with a short value. I'll name it sh, and I'll give it a value of 100. Now I want to create an integer value and assign it the same value. I'll set the type as int, I'll give it an identifier of i, and I will assign a value of sh, and that works perfectly. The conversion from one type to another happens automatically. This is called widening the value. The integer variable uses twice the amount of memory than the short version does, even though functionally they represent the same value. As long as you're going from a smaller amount of memory to a larger amount of memory, you don't need any special syntax. But if you go in the other direction you'll have a problem. Let's say, for example, that I want to declare another short value that I'll call sh2, and I'll assign it the value of i, and I get the message error, incompatible types. Lossy…

Contents