-5

I'm newbie in java and i need some help.I created a class;

public class asdd {
    String name;
    String Lastname;
    int age;

    public asdd(String value1,String value2,int value3){

        this.name=value1;
        this.Lastname=value2;
        this.age=value3;
    }

}

Then i wrote some code to do practic but i faced a problem with if control statement in below. Although input is "mike" my program bypasses if and runs else statement. Thanks.

import java.util.Scanner;

public class dd {

    public static void main(String[] arguments){

      asdd person=new asdd("mike","angel",21);
      Scanner input= new Scanner(System.in);
      String control=input.nextLine();

      if (control==person.name)
        System.out.println("hi baby");
      else
        System.out.println(person.Lastname);

   }    
}

Also i'm getting error after run program.

Carlos Robles
  • 10,828
  • 3
  • 41
  • 60
raider_
  • 135
  • 9

4 Answers4

4

As a quick search on this site would have quickly revealed, you should use the equals() method of String objects instead of ==. The former compares strings lexicographically, whereas the latter compares object references. So you want:

if (control.equals(person.name))

instead of:

if (control==person.name)

As an aside, class names should start with a capital letter, not lower case. And you should also explicitly specify the visibility of your Asdf class' variables: specifically, it's good practice to access them only through getters, as opposed to directly as you are doing.

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
1

Use String.equals() to compare String literals in Java, not == Change your code like this

if(control.equals(person.name))
Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
1

Sadly, java isn't javascript, or numerous other languages that use == sensibly.

== compares identity - true only if the two objects are the same object.

.equals() should be used to compare values:

if (control.equals(person.name))

It is generally considered a "mistake" that java doesn't use == as you expected it to work. For some other java "mistakes", see this answer.

Community
  • 1
  • 1
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

The == operator is for numeric values. For strings use the .equals method:

    String s1 = "value", s2 = "value";
    if (s1.equals(s2)) {
      // do your code here
    }
Froxx
  • 957
  • 4
  • 14
  • 27