Hi

Can someone explain to me why when i compare the array values for my code below,if i use "==",it will only compare 1 time.
However,if i use ".equals", it will work correctly.

import java.util.Scanner;
import java.util.Arrays;

class normalsorting
{
   public static void main(String args[])
   {

      String input;
      System.out.print("Enter Jumbled Up Number(Eg:2,6,8,4):");
      Scanner sc = new Scanner(System.in);
      input = sc.nextLine();
      String store [] = input.split(",");

      for(int i=0; i < store.length; i++)
      {
         int counter = 0;
         for(int j=0; j < store.length; j++)
         {
            if (store[i] == store[j])
            {
               counter++;
               System.out.println(counter);

            }
         }
      }

== means "refers to exactly the same object (same address in memory)"
equals(...) usually means "may be a different object, but the two objects have equivalent values, so I will treat them as equal"

which basically means:

if i use "==",it will only compare 1 time

no. that is not so. you are just getting only once two reference objects that point to the same object.

You only get one == on each run of the inner loop because that's the special case where j happens to be the same as i so you are comparing an array element with itself. Ie if j==i then array[i] == array[j]

Are u checking for the counter value?
It will be always 1, irrespective of the input you provide.
As the condition in the inner for loop will satisfy only once,
to get the exact value of the counter, initialize the value of counter above the outer loop, as the counter is getting reset when it comes out of the inner loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.