0

Operator "==" doesn't work if I make one array manually and other from string using split method. Why?

import java.util.*;

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

//first array

      String[] arr1={"Ram", "Shyam"};

//starting second array by scanning

      Scanner sc=new Scanner(System.in);
      String s=sc.nextLine();

//input String provided is: Ram Shyam
      
      String [] arr2=s.split(" ");

//so now two exact same arrays created
//so now I tried to compare but ans false

      if(arr1[0]==arr2[0])
      {
      System.out.println("true");
      }

      else 
      {
      System.out.println("false");
      }
    }
}
//ans comes false why?
Slaw
  • 30,631
  • 6
  • 43
  • 69
Netrapal
  • 1
  • 1
  • 1
    What I think may not be explained in the duplicate link is that `==` does work if the strings are constants in the code, as you have said. If you have `"Ram"` in your code in more than one place, the Java specification requires that they are collected into one single object. Therefore their references are equal (it's the same reference, after all), and `==` will return true. This works across multiple classes and multiple files, as long as it's a constant (literal) string. – markspace May 12 '22 at 23:41

0 Answers0