本文介绍了Java算术int与long的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在google上做了一些搜索,但我似乎无法找到我正在寻找的东西。我试图找出有关算术在Java中的工作方式的一些详细信息。例如,如果将两个long一起添加,这是使用在将两个int一起添加时使用的相同加法运算符吗?另外,当你在这样的算术表达式中混合long和int时,会发生什么:

I've done some searching on google, but I can't seem to find what I'm looking for. I'm trying to find out some detailed information on the way arithmetic works in Java. For example, if you add two longs together is this using the same addition operator that is used when adding two ints together? Also, what is going on under the hood when you mix longs and ints in arithmetic expressions like this:

long result;
long operand a = 1;
int operand b = 999999999;

result = a + b;

如果有人可以对此有所了解或发布相关文章的链接,那将是非常棒的。谢谢!

If anyone could shed some light on this or post links to relevant articles that would be awesome. Thanks!

编辑:感谢您的回复。另外,只要在表达式中指定最宽基元类型的变量,用不同的基元执行算术是否安全?

Thanks for the replies so far. Also, is it safe to perform arithmetic with different primitives so long as you are assigning into a variable of the widest primitive type in your expression?

推荐答案

当混合类型时,int会自动加宽为long,然后添加两个long以生成结果。 提供了很好的操作示例包含不同的主要类型。

when mixing types the int is automatically widened to a long and then the two longs are added to produce the result. The java language spec has good examples for operations containing different primative types.

具体来说,这些是每个主要扩展到不需要演员的类型:

Specifically, these are the types each primative will widening to without requiring a cast:


  • byte to short,int,long,float或double

  • short to int,long,float或double

  • char to int,long,float或double

  • int to long,float或double

  • long to float or double

  • 浮动加倍

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double
  • float to double

这篇关于Java算术int与long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:50
查看更多