BlueJ Error: "Incompatible types: int cannot be converted java.lang.String" AND "Incompatible types: java.lang.String cannot be converted to int"

Ann picture Ann · May 5, 2017 · Viewed 20.2k times · Source

I'm very new to coding and after trying multiple solutions I came up with, I still can't figure out why what I'm doing is wrong. This is my full code:

public class Student {
  private String name;
  private String grade;
  private String gender;
  private int number;

  public Student( String name,  String grade, String gender, int number ) {
    this.name = name;
    this.grade = grade;
    this.gender = gender;
    this.number = number;
  }

  public String getName() {
    return name;
  }

  public void setName( String name ) {
    this.name = name;
  }

  public String getGrade() {
   return grade;
  }

  public void setGrade( String grade ) {
    this.grade = grade;
  }

  public String getGender() {
    return gender;
  }

  public void setGender( String gender ) {
    this.gender = gender;
  }

  public String getNumber() {
    return number;
  }

  public void setNumber( String number ) {
    this.number = number;
  }
}

As you can probably see, I'm trying to not only be able to add a new name/grade/gender/int number when I first use an object, but also by using methods.

The problem I'm getting seems to be caused in this part:

public String getNumber() {
  return number;
}

public void setNumber( String number ) {
  this.number = number;
}

When I hover over "number" in the second line, BlueJ gives the following error: "Incompatible types: int cannot be converted to java.lang.String".

Though when I hover over "number" in the fifth line, BlueJ gives the error: "Incompatible types: java.lang.String cannot be converted to int".

I've tried searching on this website for similar problems, but haven't found any where they tried to use an int number to be filled in by the use of methods.

Answer

GhostCat picture GhostCat · May 5, 2017

String and int are two different types, and in contrast to Integer and int, there is no compiler-magic to turn the one into the other automatically.

But there are various helper methods to work around this, like:

String asString = Integer.toString(123);

which turns int into String; and

int number = Integer.parseInt("123"); 

for the other way round.

And just for the record: the fact that you can write

Integer integerObject = 5;

is called auto-boxing.