Java Compare 2 integers with equals or ==?

岁酱吖の 提交于 2020-02-11 14:14:32

问题


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

but for some reason this does not work.. i mean the Netbeans gives me an error: "int cannot be dereferenced" Why?


回答1:


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. The Kinds of Types and Values says (in part)

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).




回答2:


If you want to compare between

1-two integer 
If(5==5)
2- char
If('m'=='M')
3 string
String word="word"
word.equals("word")



回答3:


As int is primitive you can not use equals. What you can do Use Interger as wrapper

 void IntEquals(Integer original, Integer reverse) {
        Integer origianlNumber = original;
        Integer reverseNumber = reverse;

        if (origianlNumber.equals(reverse)) {
            System.out.println("Equals ");
        } else {
            System.out.println("Not Equal");
        }



回答4:


int is primitive type.This itself having value but Integer is object and it is having primitive int type inside to hold the value. You can do more operations like compare,longValue,..more by Using wrapper Integer.

== for Integer will not work the rang above -128 and 127. Integer hold cache value upto this range only in memory. More than this range you have to equals() method only to check Integer wrapper class.

equals() method will check the value stored in the reference location.



来源:https://stackoverflow.com/questions/28953805/java-compare-2-integers-with-equals-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!