- Java 11 and 12:New Features
- Mala Gupta
- 491字
- 2021-07-02 12:26:59
Using var with primitive data types
Using var with primitive data types seems to be the simplest scenario, but appearances can be deceptive. Try to execute the following code:
var counter = 9_009_998_992_887; // code doesn't compile
You might assume that an integer literal value (9_009_998_992_887, in this case) that doesn't fit into the range of primitive int types will be inferred to be a long type. However, this doesn't happen. Since the default type of an integer literal value is int, you'll have to append the preceding value with the suffix L or l, as follows:
var counter = 9_009_998_992_887L; // code compiles
Similarly, for an int literal value to be inferred as a char type, you must use an explicit cast, as follows:
var aChar = (char)91;
What is the result when you divide 5 by 2? Did you think it's 2.5? This isn't how it (always) works in Java! When integer values are used as operands in the division, the result is not a decimal number, but an integer value. The fraction part is dropped, to get the result as an integer. Though this is normal, it might seem weird when you expect the compiler to infer the type of your variable. The following is an example of this:
// type of result inferred as int; 'result' stores 2
var divResult = 5/2;
// result of (5/2), that is 2 casted to a double; divResult stores 2.0
var divResult = (double)(5/ 2);
// operation of a double and int results in a double; divResult stores
// 2.5
var divResult = (double)5/ 2;
Though these cases aren't specifically related to the var type, the developer's assumption that the compiler will infer a specific type results in a mismatch. Here's a quick diagram to help you remember this:

In arithmetic operation, if either of the operands is char, byte, short, or int, the result is at least promoted to int:
byte b1 = 10; char c1 = 9; var sum = b1 + c1; // inferred type of sum is int
Similarly, for an arithmetic operation that includes at least one operand as a long, float, or double value, the result is promoted to the type long, float, or double, respectively:
byte cupsOfCoffee = 10; long population = 10L; float weight = 79.8f; double distance = 198654.77; var total1 = cupsOfCoffee + population; // inferred type of total1
// is long var total2 = distance + population; // inferred type of total2
// is double var total3 = weight + population; // inferred type of total3 is
// float
- 從零構(gòu)建知識(shí)圖譜:技術(shù)、方法與案例
- 編程卓越之道(卷3):軟件工程化
- Android 9 Development Cookbook(Third Edition)
- 小程序,巧運(yùn)營(yíng):微信小程序運(yùn)營(yíng)招式大全
- The DevOps 2.4 Toolkit
- Python Data Structures and Algorithms
- Instant PHP Web Scraping
- Oracle實(shí)用教程
- OpenCV with Python Blueprints
- Fastdata Processing with Spark
- Oracle Data Guard 11gR2 Administration Beginner's Guide
- Python機(jī)器學(xué)習(xí)與量化投資
- 零基礎(chǔ)學(xué)Java第2版
- HTML5 Canvas核心技術(shù):圖形、動(dòng)畫與游戲開發(fā)
- RESTful Web API Design with Node.js