Checking String Values in Java [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Im trying to find if the first two letters of a string are "hi". If it does it shold return true, and if not it should return false. I used substring to find the values of the given string, but when the condition comes up true it isn't returning true. I must not be understanding something about Java, which Im new to.
Here is my code:
class Main {
public boolean startHi(String str) {
String str1 = str.substring(0,1);
String str2 = str.substring(1,2);
if(str1=="h" && str2=="i"){
return true;
}
if(str!="hi" || str.length()<=2){
return false;
}
else{
return false;
}
}
public static void main(String[] args) {
System.out.println(new Main().startHi("hi ho"));
System.out.println(new Main().startHi("hi"));
System.out.println(new Main().startHi("howhi"));
}
}
The string starts with "hi" and it sees that, but it returns false.

You could use String.startsWith(String prefix)
public boolean startHi(String str) {
return str.startsWith("hi");
}
So after all you probably don't need your own startHi() method, but can use standard Java API.

It's not returning true because you have to compare strings with the equals() method.
if("h".equals(str1) && "i".equals(str2)){
return true;
}
If you use == to compare objects it will check if it's the same object so it checks if the memory addresses of the objects are the same.
The string class overrides the equals() method to check for content.
If you're creating a string like this
String s1 = "Hi";
Java will put "Hi" in the so called string literal pool
so if you are creating a second string
String s2 = "Hi";
Java will not create a second Object but will refer to the "Hi" in the string literal pool.
Now you could do compare the two strings like s1 == s2 and it would be true
because the two references s1 and s2 point to the same object.
But what the substring() method does is new String("xyz") and if you declare a string like this a new object will be created and the comparison with == will return false because the two references obviously don't point on the same object.

Try this...
if(str1.equals("h") && str2.equals("i")) //equals use instead of (==) Operator.
instead Of
if(str1 =="h" && str2 == "i")
OR
if(str.startsWith("hi") // this will also works

Related

String Concat With Same Reference? [duplicate]

This question already has answers here:
a confusion about java String literal pool and String's concatenation
(4 answers)
When should we use intern method of String on String literals
(14 answers)
Closed 6 years ago.
Here is my code and I am now quite confuse about String pool and
Heap storage by this output.
public class String1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "abcd";
String str1 = "" ;
str1=str1+"abcd";
if(str.equals(str1))
System.out.println("True");
else
System.out.println("False");
if(str == str1)
System.out.println("True");
else
System.out.println("False");
}
}
Now, I am creating String str and will be stored in string pool (Correct me if I am getting wrong!).
Now after concat str1 with string "abcd" they both have same value.
So, I think str and str1 should have same reference in String pool and So, 2nd if statement should print true but it prints false.
So, my question why str and str1 not getting same reference ?
Java automatically interns (means, puts them into the String pool) String literals, not newly created Strings. See also https://stackoverflow.com/a/1855183/1611055.
Remember that Strings are immutable, so the + operator must create a new String - it can not append to the existing one. Internally, the + operator uses a StringBuilder to concatenate the strings. The final result is retrieved through StringBuilder.toString() which essentially does return new String(value, 0, count);.
This newly created String is not automatically put into the String pool.
Hence the str1 reference is different from str even though the strings have the same content. str points to a location in the string pool, while str1 points to a location on the heap.
If you add
str1 = str1.intern();
after str1 = str1 + "abcd"; to explicitly intern the newly created String, your second if statement returns true.
Alternatively, str1 = (str1 + "abcd").intern(); would have the same effect.
In case of strings to compare the values we should use equals method as it compares values that are present in the string variables.
But when we choose to compare string variables using == it compares the addresses of the String object not the values so it will return false even if they have same values in it.
you are right that the strings get added to the string pool. but == checks if both the objects are pointing to the same reference (to make it simpler pointing to the same memory location) in the string pool or not. whereas .equals() method check if the value of the both the object are same or not.

Comparing Same Object of String with '==' and getting different result in both scenerio, where the String Object Value is same [duplicate]

This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
In Program 1 I have declared two String and initialized them as "MADAM". When running I am checking the equality of their reference variable (by '==' operator') then I am getting a "true" response.
But in Program 2 I am declaring a String 'S' and initialize it as "MADAM". After that i am running a reverse loop and storing the characters of 'S' in reverse order in other String variable. Now i have again tried to check the equality of reference variable (by '==' operator') and am getting the response as 'false'. As both the String objects are of same value and are stored in constant Pool Area so both the variable should equate and the output in both the scenario should be 'true'. But WHY it is not same?
Program 1:
class Reverse {
public static void main(String[] args) {
String s="MADAM"; String rev="MADAM"; System.out.println(s==rev);
}
}
Output - true
Program 2:
class Reverse {
public static void main(String[] args) {
String s="MADAM"; String rev="";
for(int x=s.length()-1;x>=0;x--) { rev+=s.charAt(x); }
System.out.println(s==rev);
}
}
Output- false
In program 1 java compiler saves "MADAM" string in one memory location and assigns both "s" and "rev" to that location hence "s==rev" returns true because they both refer to the same address.
you should use "equals()" method to compare two strings. e.equals(rev);
have a look at this question:
Java String.equals versus ==
In your first class both strings are initialize to same object. So both are pointing to same memory location.
Next class, Rev is intilialized to "" value and see to madam so both have got different memory location. So false.
In essence,
if you use == for comparison, you are comparing their identity.
If you want to compare the object's value, use .equals()
String s="MADAM"; String rev="MADAM"; System.out.println(s==rev);
The above code will return true, because both Strings will be stored in the same memory location.
However, you can try the following, it will return you false:
String s1 = "aaa";
String s2 = new String("aaa");
System.out.println(s1 == s2); //false (comparing memory location)
System.out.println(s1.equals(s2)); //true (comparing value)
Side note: It is generally a bad practice to create Strings using new String(""). It was only used for demonstration purposes only.

Equal return False. What's wrong with this code? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have java syntax. Sory I'm still not figure out why this happen.
public class TestString {
public static void main(String [] args){
int i=-1;
String a=((Object)i).toString();
if(a=="-1"){
System.out.println("Same");
}else{
System.out.println("Not");
}
}
}
And then the result is "Not" what the problems why -1 string different with -1 int in object?
You have to use .equals() on string to compare.
String's equal method overridden in such a way.
Try
public class TestString {
public static void main(String [] args){
int i=-1;
String a=((Object)i).toString();
if(a.equals("-1")){
System.out.println("Same");
}else{
System.out.println("Not");
}
}
}
Strings have to be compared with the .equals() method.
You are using reference equality instead of object equality.
Since "-1" in the literal table has a different heap address than a newly allocated a, it returns false.
If for some reason you find yourself allocating a lot of String objects that share the same value(s) and want to test them by reference instead, consider using String#intern():
final String a = [...].intern(); // allocated
if (a == SOME_INTERNED_STRING_1) {
[...]
else if (a == SOME_INTERNED_STRING_2) {
[...]
}
==
compares reference which is not same in your case so if you want to compare string values then use
.equals() method
The == operator checks to see if two objects are exactly the same object . You can go for equals method to check if the value are equal or not

String is a substring of the second? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I probably made a logical error somewhere but I do not know where.
The output is always FALSE even though the condition seem to be TRUE
public class Test {
public static void main(String[] args) {
String str1 ="Hello world";
String str2 ="Hello world";
if (checkSubstring(str1,str2)){
System.out.println("Cool");
}
else
System.out.println("Not cool");
}
static boolean checkSubstring(String str1, String str2) {
String s1 = str1;
String s2 = str2;
if (s1.substring(4)== s2.substring(4)){
return true;
}
else
return false;
}
}
You should always use equals method to test for the content of string.
== operator checks whether two reference are pointing to same object or different ones. And since s1.substring() and s2.substring() will generate two different string objects, so comparing their reference will give you false boolean value.
So, in checkSubstring method, you should compare your substring like this: -
if (s1.substring(4).equals(s2.substring(4))) {
return true;
} else {
return false;
}
s1.substring(4)== s2.substring(4)
In the above Change it to s1.substring(4).equals( s2.substring(4))
- Objects in Java are compared using the equals() method.
- As String is an Object in Java, it must be treated in the same way.
- Moreover if you are trying to compare 2 String irrespective of their Case, then use equalsIgnoreCase().
- "==" is used for comparing the primitive types, and also to check whether 2 Object Reference Variables are pointing on the same object on the heap or not.
Eg:
Dog d1 = new Dog();
Dog d2 = d1;
if (d1 == d2){}
you need equals function
static boolean checkSubstring(String str1, String str2) {
String s1 = str1;
String s2 = str2;
if (s1.substring(4).equals(s2.substring(4))){
return true;
}
else
return false;
}

String comparison in Java: what is wrong with "=="? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java String.equals versus ==
public class S_eaqual {
public static void main(String[] args) {
String s1 = "one", s2 = "two";
if (s1 + s2 == "onetwo") {
System.out.println("Yes..equal");
}
}
}
This type of comparison shows errors. Is this not the right way of comparing strings?
Two String objects can be compared using == operator. So why this is showing error?
String should be compared using equals method.
String s1 = "one", s2 = "two";
if("onetwo".equals(s1+s2)) {
System.out.println("Yes..equal");
}
Try this...
String s3 = s1 + s2
if(s3.equals("onetwo")) {
...
== compares if they refer to the same object, and the result of s1+s2 isn't in this case, and the .equals() method on string compares that the values are the same. In general, you only use == for primitive value comparisons. Although you can do it for objects iff you intend to check to make sure that two references point to the same object.
use (s1+s2).equals("onetwo"); instead
Use equals:
if (s1.concat(s2).equals("onetwo")) System.out.println("Yes..equal");

Categories

Resources