Java Compare 2 integers with equals or ==?

后端 未结 4 827
清歌不尽
清歌不尽 2020-12-19 04:55

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 s

4条回答
  •  抹茶落季
    2020-12-19 05:47

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

提交回复
热议问题