Java中的文字分配 [英] Literal Assignment in Java

查看:61
本文介绍了Java中的文字分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义

double example = 23.1d

double example = 23.1

为什么long,float和double可以以l,f,d结尾?

Why long, float and double can end with l, f, d?

推荐答案

double example = 23.1d;double example = 23.1;之间没有区别,因为没有 type后缀的浮点文字总是被解释为

There is no difference between double example = 23.1d; and double example = 23.1; because a floating point literal without a type suffix is always interpreted as a double.

为了避免在某些情况下产生歧义,必须使用类型后缀.

The type suffixes are necessary in order to avoid ambiguities in certain scenarios.

例如,java支持方法重载.这意味着您可以同时具有void x( float f );void x( double d );两种方法都称为x;这两种方法都称为x.将选择哪一个取决于您通过的类型;如果您传递一个已知为float或double的变量,那么事情就很清楚了;但是如果要传递文字,例如:x( 5 );,则必须能够指定将5表示为float还是double,以便选择正确的方法.

For example, java supports method overloading. This means that you can have void x( float f ); and void x( double d ); Both methods are called x; which one will be selected depends on the type that you pass; if you pass a variable which is already known to be either float or double, things are clear; but if you want to pass a literal, like this: x( 5 ); then you have to be able to specify whether you mean this 5 to be a float or a double, so as to select the right method.

在其他一些非常细微的情况下,文字的类型也很重要.例如,以下代码:

There are a few other very nuanced situations where the type of the literal matters. For example, the following code:

System.out.println( "" + (2/3.3333) );
System.out.println( "" + (2/3.3333f) );

产生以下输出:

0.6000060000600006
0.600006

...因为第一个数字是双精度数,而第二个数字是浮点数.

...because the first number is a double, while the second number is a float.

类似的歧义问题使长整数文字必须具有"L"类型后缀.

Similar disambiguation concerns make the "L" type suffix necessary for long integer literals.

这篇关于Java中的文字分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆