Java Comparing Values in Arrays

Java Comparing Values in Arrays

Wasn't sure whether to make a new thread or not. but i'll post it here. I figured my explanation was not very good.

i have a class below

lets say int[] = 1204, 1205

public class Job {

 private  int[] serviceCode =;     

 public Job (int[] jobCode) {


serviceCode = jobCode;

}

  public  int[] getJobCode() {
    return serviceCode;
 }

and this is the main program

public class MainProgram { 

public static void main {



}

}

how do i put the values of the array into separate integers?

4

4 Answers

You can't directly compare an int[] to an int. You need to access a value in the array and then compare.

int[] myArray = {1, 2, 3};
int value = 1;
if (myArray[0] == value) {/*do something*/}

You cannot compare an array with a variable that holds just one data.

You know, array is a data structure.

You must loop through the array and then compare each value of the array with t.

for(int i = 0; i < h.length; i++) {

    if( t == h[i] ) // Or any other comparison operator
        /* Perform some action.*/;
}

Your int[] h is an array of integers while int t is just a integer variable. So comparison is not at all possible. As per your question's title java comparing values in arrays here is an answer.

Either you can check whether this value exist in an array in for loop.

int val = 1;
int[] valArray = {1,2,3,4,5};
for(int i = 0; i < valArray.length ; i++)
{
     if (valArray[i] == val)
       {// Matched
       }
     else
      { // Not matched
      }

}

Array is contiguous memory location, in order to get the specific values from the each addressable unit you have to access that addressable location. Suppose you declare an array like this.

int[] array = {10,20,30};

This will do the memory allocation like this: ( lets 0th element is at address 100 and assuming int size is of 4 byte)

index        0      1      2
         -----------------------
         |  10  |  20   |  30   |
         -----------------------
address:    100    104    108

Array array name is basically base address form where the array starts in this case it is 100, next element will be present at 104 and 108.

Now lets say we have an integer variable : int temp=100. Now to compare array element with integer variable temp, we have to access the each element of array of type integer situated at specific index. You have to compare like following:

for(int i=0; i<array.length; i++){
    if(temp>array[i])  /*array[i] is accessing the value at index i"*/ 
           //do something
    else
          //do something.
}  
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.