在 Java 中初始化 long

原始数据类型-oracle doc 表示 Java 中 long的范围是 -9,223,372,036,854,775,8089,223,372,036,854,775,807。 但是当我在日食时做这样的事

long i = 12345678910;

它显示了“ The literal 12345678910 of type int is out of range”错误。

有两个问题。

1)如何使用值 12345678910初始化 long

2)默认情况下所有的数值文字都是 int类型的吗?

505464 次浏览
  1. 你应该添加L: long i = 12345678910L;
  2. 是的。

顺便说一句:它不一定是大写的L,但小写经常与1混淆:)。

你需要像这样在结尾添加大写的L

long i = 12345678910L;

同样适用于带有3.0f的float

哪个能回答你的两个问题

  1. 你需要在数字的末尾添加L字符,以使Java识别它为长字符。

    long i = 12345678910L;
    
  2. Yes.

See Primitive Data Types which says "An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int."

要初始化long,您需要在末尾添加“L”。< br > 可以是大写,也可以是小写。< br > < / p >

所有数值默认为int。即使你对任何整数执行byte的任何操作,byte也会先升格为int,然后再执行任何操作。< br >

试试这个

byte a = 1; // declare a byte
a = a*2; //  you will get error here
你得到错误,因为2默认是int。< br > 因此,您正在尝试将byteint相乘。 因此result被类型转换为int,不能赋值回byte