Java Compare 2 integers with equals or ==?(Java比较2个整数与等于或==?)
问题描述
我对 Java 非常陌生,我想知道如何比较 2 个整数?我知道 == 完成了工作.. 但是等于呢?这可以比较2个整数吗?(当我说整数时,我的意思是int"而不是整数").我的代码是:
i am very very new to Java and i would like to know how can i compare 2 integers? I know == gets the job done.. but what about equals? Can this compare 2 integers? (when i say integers i mean "int" not "Integer"). My code is:
import java.lang.*;
import java.util.Scanner;
//i read 2 integers the first_int and second_int
//Code above
if(first_int.equals(second_int)){
//do smth
}
//Other Code
但由于某种原因,这不起作用..我的意思是 Netbeans 给了我一个错误:int cannot be dereferenced"为什么?
but for some reason this does not work.. i mean the Netbeans gives me an error: "int cannot be dereferenced" Why?
推荐答案
int
是一个原语.您可以使用包装器 Integer
喜欢
int
is a primitive. You can use the wrapper Integer
like
Integer first_int = 1;
Integer second_int = 1;
if(first_int.equals(second_int)){ // <-- Integer is a wrapper.
或者您可以按值比较(因为它是原始类型),例如
or you can compare by value (since it is a primitive type) like
int first_int = 1;
int second_int = 1;
if(first_int == second_int){ // <-- int is a primitive.
JLS-4.1.类型和值的种类(部分)说
Java 编程语言中有两种类型:原始类型(§4.2) 和引用类型 (§4.3).相应地,有两种数据值可以存储在变量中、作为参数传递、由方法返回和操作:原始值(§4.2) 和参考值 (§4.3).
There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).
这篇关于Java比较2个整数与等于或==?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java比较2个整数与等于或==?


- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01