Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Where did I do a mistake ?  RSS feed

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a piece of code, which is not working as intended. I'm not able to figure out, where I might have made a miskake. Please have a look at the code below.

public class MyEquals
{
public static void main(String[] args)
{
String s1 = "Ravi";
String s2 = "Ravi";
if (s1==s2)
System.out.println("Equal");
if (s1==args[0])
System.out.println("Equal");
}
}

after compiling, I ran
java MyEquals Ravi @ command prompt.

My output is
Equal
where as I'm expecting
Equal
Equal

I know that there is something silly I missed out there about command line arguements...but not able to figure out what.. If I'm not wrong args[0] should be of String. Then what is stopping a String to be compared with an another String.

Also, I have another question not related to the above one. I have seen a new for () syntax for iterating over arrays and collections. This question is related to that.

say
String[] s = {"abc","bcd","cde"};

Now, assume I need to display say s[1] all the time while navigating thru the array ... to put in code
for(int i=0,i<s.length;i++) System.out.println(s[1]);

How do I achieve this using hte new for (String a : s)

Thanks
 
Srikanth Ramu
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To compare the values of string use equals() method. For more details refer below post:

http://www.coderanch.com/t/262929/java-programmer-SCJP/certification/equals

Refer below link for Enhanced for loop

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also see Strings, Literally to understand why == behaves as it does for Strings.
 
Anita Singh
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Here you are comparing String literal to array of String Object,by using ==,it is not possible.
If you want to do this,then write
if(s1.equals(args[0])
{
System.out.println("equal");
}

Thanks & Regards
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!