Java类型转换重要吗?它在初学阶段必须要了解吗?

huangapple go评论39阅读模式
英文:

Do java type casting matter? Does it necessarily need to know at the beginner stage?

问题

Sure, here's the translation of the provided content:

"Java中的类型转换是否重要?在初学阶段有必要了解吗?

double myDouble = 9.78;
int myInt = (int) myDouble;

这在初始阶段让我感到困惑。"

英文:

Do java type casting matter? Does it necessarily need to know at the beginner stage?

**double myDouble = 9.78;
int myInt = (int) myDouble;**   

This make me confuse at the first stage.

答案1

得分: 0

是的,它确实很重要。没有类型转换运算符,这将导致编译时错误。查看Java 语言规范的此章节以了解更多信息。

简单来说,可以将变量视为容器,例如,一个 int 类型的变量具有 4 个字节的容量,而 double 类型的值需要 8 个字节。因此,如果尝试将 double 类型的值赋给 int 类型的变量,它将不适合。类型转换运算符通过将 double 值修剪以适应 int 变量,使这种转换成为可能。另一方面,如果尝试将 int 类型的值赋给 double 类型的变量,无需任何类型转换,该值就可以容纳其中。

public class Main {
    public static void main(String[] args) {
        double myDouble = 9.78;
        int myInt = (int) myDouble; // 需要类型转换

        int x = 100;
        myDouble = 100; // 不需要类型转换
    }
}
英文:

> Do java type casting matter? Does it necessarily need to know at the
> beginner stage?

Yes, it does matter. Without the cast operator, this would be a compile-time error. Check this chapter of JLS to learn more about it.

In simple terms, consider variables as containers e.g. an int type of variable has a capacity of 4 bytes while a double type of value needs 8 bytes. Therefore, if you try to assign a double type of value to an int type of variable, it won't fit. The cast operator makes it possible by pruning the double value to fit into the int variable. On the other hand, if you try to assign an int type of value to a double type of variable, the value can be accommodated without requiring any casting.

public class Main {
	public static void main(String[] args) {
		double myDouble = 9.78;
		int myInt = (int) myDouble;// Casting is required

		int x = 100;
		myDouble = 100;// Casting is not required
	}
}

huangapple
  • 本文由 发表于 2020年8月1日 21:39:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63205831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定