Java比较2个整数与等于或==? [英] Java Compare 2 integers with equals or ==?

查看:50
本文介绍了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个整数与等于或==?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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