gpt4 book ai didi

java - Java 中的类型转换是否也会导致内存字节的转换?

转载 作者:行者123 更新时间:2023-12-04 09:30:57 26 4
gpt4 key购买 nike

如果我转换 intdouble通过做这个:

int x = 5; 
double y = x;
我知道 y将具有 5.0 的值,但是当 x变量设置为 double y变量,在Java中是通过自动类型转换来转换的,内存中的字节数是否也被Java间接自动转换为我们?
int是 4 个字节,而 double是 8 个字节,所以在这种情况下,值来自变量 x设置变量 y 的值时, 会被语言间接转换为内存字节吗?如果我进行强制转换或使用某种方法来转换数据类型而不是自动类型转换,我想这种内存转换将保持不变?

最佳答案

我不确定我是否正确理解了你的问题,但我认为你在这里有问题:

If I convert an int to a double by doing this: int x = 5; double y = x;


您不是从 int 转换而来的到 double .您正在创建 double来自 int值(value)。这也意味着为 double 分配了内存值和原来的 int完好无损。
请参阅以下示例:
@Test
void testPrimitive() {
int x = 5;
double y = x;
log.info("x:{}", x);
log.info("y:{}", y);
x += 1;
log.info("x:{}", x);
log.info("y:{}", y);
// This is the way to assign a value double to an int:
// You need to cast so strip the decimal part explicitly!
// This changes the value of int but does not alter bytes or so just drops bytes
x = (int)y;
y += 5;
log.info("x:{}", x);
log.info("y:{}", y);
}
以及它打印出来的内容:

11:16:11.368 [main] INFO org.example.type.PrimitiveTest - x:5
11:16:11.373 [main] INFO org.example.type.PrimitiveTest - y:5.0
11:16:11.375 [main] INFO org.example.type.PrimitiveTest - x:6
11:16:11.375 [main] INFO org.example.type.PrimitiveTest - y:5.0
11:16:11.375 [main] INFO org.example.type.PrimitiveTest - x:5
11:16:11.375 [main] INFO org.example.type.PrimitiveTest - y:10.0


x & y 有自己的内存空间,即使是强制转换,你也不会改变它们的字节数。

关于java - Java 中的类型转换是否也会导致内存字节的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62845735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com