- Java 11 and 12:New Features
- Mala Gupta
- 280字
- 2021-07-02 12:27:00
Explicit casting with inferred variables
Imagine that a co-programmer assigned 29 to an inferred local variable (let's say age), assuming that the compiler would infer the type of the variable age as byte:
var age = 29; // inferred type of age is int
However, the compiler would infer the type of the variable age as int, since the default type of an integer literal value is int. To fix the preceding assumption, you can either use the explicit data type or override the compiler's default inference mechanism by using explicit casting, as follows:
byte age = 29; // Option 1 - no type inference
var age = (byte)29; // Option 2 - explicit casting
Similarly, you can use explicit casting with other primitive data types, like char and float:
var letter = (char)97; // inferred type of letter is char var debit = (float)17.9; // inferred type of debit is float
Without the explicit casting in the preceding examples, variables that are assigned integer literal values would be inferred as int, and decimal as double.
The following example shows explicit casting with reference variables:
class Automobile {} class Car extends Automobile { void check() {} } class Test{ public static void main(String[] args) { var obj = (Automobile)new Car(); obj.check(); // Won't compile; type of obj is Automobile } }
- Interactive Data Visualization with Python
- Dependency Injection in .NET Core 2.0
- 三維圖形化C++趣味編程
- Spring Boot Cookbook
- Mastering JBoss Enterprise Application Platform 7
- Bootstrap 4 Cookbook
- 常用工具軟件立體化教程(微課版)
- Sails.js Essentials
- Java設(shè)計模式深入研究
- ANSYS FLUENT 16.0超級學習手冊
- 歐姆龍PLC編程指令與梯形圖快速入門
- Mastering Swift 4(Fourth Edition)
- Access 2010數(shù)據(jù)庫教程(微課版)
- HTML5與CSS3權(quán)威指南(第2版·下冊)
- AVR單片機C語言應(yīng)用100例