-1
public class StringEqual
  {
 public static void main(String[] args)
   {
  String str1 = "abcd";
  String str2 = "abcdefg";
  String str3 = str1 + "efg";
  System.out.println("str2 = " + str2);
  System.out.println("str3 = " + str3);
  if (str2 == str3)
  {
     System.out.println("The strings are equal");
  }
  else
  {
     System.out.println("The strings are not equal");
  }
   }
  }

so far i've created this code. Now i am trying to figure out how do i make it so that str2 and str3 are equal when they are compared?

user3288334
  • 9
  • 1
  • 5

3 Answers3

1

If you ant compare strings you have to use equals method:

if (str2.equals(str3))
Jens
  • 67,715
  • 15
  • 98
  • 113
1

== compares the Object Reference

String#equals compares the content

So replace str2==str3 with

  String str2 = "abcdefg";
  String str3 = str1 + "efg";
  str2.equals(str2); // will return true
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

You know, you need to differentiate between string equality and object idendity. The other answers already told you that it would work with .equals().

But if you actually asking on how to get the same object by your string expressions: if it is a compile time constant expression it will be the same object. The str3 would come from the constant pool if it is a constant expression, and in order for that, you may only use final string variables or string literals:

public class FinalString
{
final static String fab  = "ab";
static String        ab  = "ab";
static String        abc = "abc";
static String     nonfin = ab  + "c"; // nonfinal+literal
static String        fin = fab + "c"; // final+literal

public static void main(String[] args)
{
    System.out.println(" nonfin: "  + (nonfin == abc));
    System.out.println("  final: " + (fin == abc));
    System.out.println(" equals? " + fin.equals(nonfin));
}
}

prints

 nonfin: false
  final: true
 equals? true
eckes
  • 10,103
  • 1
  • 59
  • 71