1

For some reason, my (basic) program always prints the text I reserved for my else statement. I am a newb when it comes to Java, so if I am making an obvious mistake I apologize. I also searched high and low for an answer, but couldn't find one. Could you take a look at this:

package test;

import java.util.Scanner;

public class tutorial_7 {

    private static Scanner x;

        public static void main(String args []) {
            x = new Scanner(System.in);

            System.out.print("Apples, or oranges: ");
            String bog = x.next();

            if (bog == "Apples") {
                System.out.print(1);
            }
            if (bog == "Oranges") {
                System.out.print(2);
            }
            else {
                System.out.print(3);
            }
        }
    }
}

Why is the text reserved for my if statements never being output? Everything seems to be fine.

Regards, JavaNoob

JavaNoob
  • 23
  • 3

2 Answers2

4

Don't use == to compare strings, it's for object identity.

Comparing strings should be done with the equals() method, such as:

if (bog.equals ("Oranges")) {
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Perfect. I will accept this answer when I can (9 minutes, the timer says). It seems I am too used to C++ and Python. – JavaNoob Sep 02 '13 at 02:19
1

How do I compare strings in Java?

 if (bog.equals("Apples")){
    System.out.print(1);
  }
  if (bog.equals("Oranges")){
      System.out.print(2);
  }
  else{
    System.out.print(3);
  }
Community
  • 1
  • 1
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64