Java Compare 2 integers with equal or ==?

I am very new to Java and I would like to know how can I compare 2 integers? I know this does the job ... but what about peers? Can this compare 2 integers? (when I say that integers mean "int" and 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, Netbeans gives me an error: "int cannot be dereferenced" Why?

+6
source share
3 answers

int is primitive. You can use an Integer wrapper, for example

 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), for example

 int first_int = 1; int second_int = 1; if(first_int == second_int){ // <-- int is a primitive. 

JLS-4.1. Types of species and values (partially)

There are two types of types in the Java programming language: primitive types ( Β§4.2 ) and reference types ( Β§4.3 ). There are, respectively, two types of data values ​​that can be stored in variables, passed as arguments, returned by methods, and work with: primitive values ​​( Β§4.2 ) and reference values ​​( Β§4.3 ).

+10
source

If you want to compare

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

Since int is primitive, you cannot use equals. What you can do Use Interger as a 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"); } 
+1
source

Source: https://habr.com/ru/post/983553/


All Articles