Output is not as expected
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Output is not as expected

  1. #1
    Join Date
    Dec 2011
    Posts
    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?

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,474

    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 code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center