Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

simple question regarding strings

 
Chaitali Deshpande
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
from marcus mock exam#1
Given the following code, what test would you need to put in place of the comment line?
//place test here
to result in an output of
Equal
public class EqTest{
public static void main(String argv[]){
EqTest e=new EqTest();
}
EqTest(){
String s="Java";
String s2="java";
//place test here {
System.out.println("Equal");
}else
{
System.out.println("Not equal");
}
}
}
1) if(s==s2)
2) if(s.equals(s2)
3) if(s.equalsIgnoreCase(s2))
4)if(s.noCaseMatch(s2))
If i use if(s==s2) i get o/p as Not Equal
my query is, == operator checks the memory reference so the
o/p should be Equals.
Does it mean that it also checks the value in strings
or is there any other explanation.
Thanks in advance
 
Val Dra
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use equalsIgnoreCase method .
 
Chaitali Deshpande
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Val Dra for ur reply but my query has not been resolved
does == sign also check contents of string
 
Tom Pridham
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== checks to see if the two references point to the same object:
String a = "Hello";
String b = a;
if(a == b)
{
// these two references point to the same string literal
}
.equals checks the contents of the strings:
String a = new String("Hello");
String b = new String("Hello");
if(a.equals(b))
{
// this is true, both string contents are the same
}
if(a == b)
{
// this is false because the references point to
// different objects
}
Hope this helps....
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chaitali,
You have two different String objects. One with an uppercase 'J' for "Java" and the other a lowercase 'j' for "java". This will create two different String objects in the String pool, so using == will give you "Not Equal".
-Peter
 
Sandeep Nachane
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have a set of self review questions on object equivalence concept on my homepages at the following link. http://www.tipsmart.com/javacert/selfreview/objequiv.htm
The questions mainly deal with the concept of "referenec equivalence" and "reference identity" .
You may find it useful !!
Thanks
Sandeep Nachane
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic