-2

Below is the code:

package com.myprograms.test;

import java.util.Scanner;

public class MyProgram {

    public static void main(String[] args) {

        Scanner sIn = new Scanner(System.in);
        String name = "";

        System.out.print("Enter the name:");
        name = sIn.next();

        if (name.equals("somename")) {
            System.out.println("Success - Case 1");
        } else {
            System.out.println("Failed - Case 1");
        }

        if (name == "somename") {
            System.out.println("Success - Case 2");
        } else {
            System.out.println("Failed - Case 2");
        }

        sIn.close();
    }

}

Below is the output:

Enter the name: somename
Success - Case 1
Failed - Case 2

Here is the question:

Why one input behaves differently for the same condition in Java? Is it Java error?

DavidPostill
  • 7,734
  • 9
  • 41
  • 60
  • "*Why one input behaves differently for the same condition*" I don't see same conditions, `=="foo"` is not the same as `equals("foo")`. You can find many informations about differences between them on Stack Overflow, for instance : http://stackoverflow.com/questions/1643067/whats-the-difference-between-equals-and http://stackoverflow.com/questions/7520432/java-vs-equals-confusion http://stackoverflow.com/questions/971954/difference-between-equals-and (more at http://stackoverflow.com/search?q=%5Bjava%5D+equals+%22%3D%3D%22). – Pshemo Jul 20 '14 at 10:03

1 Answers1

0

"Java Error" - Really..??

This was explained many times, anyway here is a small explanation:

While comparing string in Java, use String.equals() or String.equlasIgnoreCase() methods.

Using == operator, compares the address.

While using equals() or equalsIgnoreCase() method compares the contents of the Strings.

Here is a good explanation (read "Meet Jorman" example):

An observation: You can close the Scanner after getting the inputs, instead of last line of the program, for better resource management.

Community
  • 1
  • 1
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126