-
December 23rd, 2011, 08:14 AM
#1
Output is not as expected
Hi,
I am a newbie to Java and all new to programming.
Here I have a java program:
public class file_io {
public static void main (String args[]){
try{
String str;
System.out.println("Print this before exception\n");
str = args[0];
if (str == "abc"){
System.out.println("arg[0] value = "+str);
}
else{
System.out.println("Should not be printed if exception has occured in bove statement: str = args[0]");
}
}catch(Exception e){
System.out.println("Command Line Arguement is not passed");
System.out.println("Exception return value "+e+".");
}
}
}
I am compiling and running above program from CLI. I am passing parameter as abc through CLI. I am expecting my o/p as the print message inside if loop since I am passing parameter = abc which is matching str == "abc". But I get below o/p.
"Print this before exception
Should not be printed if exception has occured in bove statement: str = args[0]"
Can anyone please help me with the logic?
-
December 23rd, 2011, 08:34 AM
#2
Re: Output is not as expected
The == tests whether 2 primitives are the same value and/or whether 2 objects are the same object (and not whether they have the same content).
If you want to check if 2 objects have the same content (as defined by the class) you must use the objects equals method ie:
Code:
if ( str.equals("abc") )
The String class also has an equalsIgnoreCase() method to allow you to do a case insensitive equality test.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|