首页 > 编程知识 正文

java中有哪些是赋值运算符,java中的赋值运算符怎么表示

时间:2023-05-04 18:53:39 阅读:241926 作者:2445

加法赋值运算符

It’s the Addition assignment operator. Let’s understand the += operator in Java and learn to use it for our day to day programming.

它是加法赋值运算符。 让我们了解Java中的+ =运算符,并学习如何将其用于日常编程。

x += y in Java is the same as x = x + y.

Java中的x + = yx = x + y相同

It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.

它是一个复合赋值运算符。 由于x ++仅将值增加1,因此最常用于递增变量的值。

使用+ =运算符递增值 (Incrementing Values With the += Operator)

This code will increase the value of a by 2. Let’s see the examples:

这段代码会将a的值增加2。让我们看一下示例:

int a = 1;a+=2;System.out.println(a); Output 输出量

On the other hand if we use a++:

另一方面,如果我们使用a ++

int a = 1;a++;System.out.println(a); Output 输出量

The value of a is increased by just 1.

a的值仅增加1。

在Java循环中使用+ = (Using += in Java Loops)

The += operator can also be used with for loop:

+ =运算符也可以与for循环一起使用:

for(int i=0;i<10;i+=2){ System.out.println(i);} Output 输出量

The value of i is incremented by 2 at each iteration.

i的值在每次迭代时增加2。

处理多种数据类型 (Working with multiple data types )

Another interesting thing to note is that adding int to double using the regular addition expression would give an error in Java.

要注意的另一件有趣的事情是,使用正则加法表达式将int加至double会在Java中产生错误。

int a = 1;a = a + 1.1; // Gives error a += 1.1;System.out.println(a);

The first line here gives an error as int can’t be added to a double.

第一行出现错误,因为int不能添加到double中。

Output:

输出:

error: incompatible types: possible lossy conversion from double to inta = a + 1.1; // Gives error

However, when using the += operator in Java, the addition works fine as Java now converts the double to an integer value and adds it as 1. Here’s the output when the code is run with only the += operator addition.

但是,在Java中使用+ =运算符时,加法效果很好,因为Java现在将double转换为整数值并将其加为1。这是仅使用+ =运算符加法运行代码时的输出。

Output 输出量

E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. This is Java doing typecasting to add the two numbers.

E1 op = E2等于E1 =(T)(((E1)op(E2))) ,其中T是E1的类型,只是E1仅被评估一次。 这是Java进行类型转换以将两个数字相加的方式。

字符串串联 (String Concatenation)

The += operator also works for string mutation.

+ =运算符还可用于字符串突变。

String a = "Hello";a+="World";System.out.println(a); Output 输出量

The string “Hello” has been mutated and the string “World” has been concatenated to it.

字符串“ Hello”已被更改,字符串“ World”已与其连接。

结论 (Conclusion )

The += is an important assignment operator. It is most commonly used with loops. The same assignment also works with other operators like -=, *=, /=.

+ =是重要的赋值运算符。 它最常与循环一起使用。 相同的赋值也可以与其他运算符(例如-=,* =,/ =)一起使用

翻译自: https://www.journaldev.com/41637/addition-assignment-operator-in-java

加法赋值运算符

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。