1

Greatings there from the absolutely beginning of the coding way, I'm talking, less than a week (than 4 days, if to be correct). So, here's my problem. I made a class User and then gave it some variables (sorry if the way I'm writing is very casual and not programming-like).

public class User 
{
    String name;
    short age;
    int height;

Then I created some constructors. That's one of them:

public User(String name,short age,int height) {
    this.name=name;
    this.age=age;
    this.height=height;
    System.out.println(name);
    System.out.println("Age: "+age);
    System.out.println("Height: "+height);
    System.out.println();
}

Afterwards, in the main method I made a subject of the class User with indicated aomounts of variables:

public static void main(String[] args) {
    User user1=new User("Dan",20,190);
}

But when I run the programm, I get an error saying that there arent any constructor of (String,int,int) type. Meanwhile, if write (short),that is, specify the datatype, programm works. Why do Java see the the number matching the type of amount which short requires as int?

IQbrod
  • 2,060
  • 1
  • 6
  • 28
DEADy
  • 24
  • 1
  • 3
  • 2
    Because 20 really is an `int` (meaning that immediate number values are `int`s by default, because that's how the language is defined) and since it could be an `int` that does not fit a `short` the compiler wants you to be explicit about it. – Federico klez Culloca Sep 03 '20 at 10:00
  • 1
    Also, what you're doing is not called "specifying the data type". The correct term for future reference is "casting". – Federico klez Culloca Sep 03 '20 at 10:03
  • [A quick read](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) on the topic :) – dbl Sep 03 '20 at 10:07

2 Answers2

1

Java number literals are at ints, so 20 is an int which is not converted to short implicitely (except in some initialisations).

The compiler is then looking for a method that takes at least an int as second parameter. Your definition accept at most shorts (shorts are strict subset of ints). Then compiler rejects the call as unresolved.

When you write (short)20 then you order the compiler to shorter down the 32 bits int to a 16 bits short value. It is too dangerous (some ints values can be represented as shorts) to make it implicitly thus you need to write it by yourself and enforce the conversion (provided that you know what you are doing).

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

The compiler error is telling you that age is not of type short, (it automatically takes it as int unless you tell him otherwise)

Try this, this way you're telling the compiler your age is type short

public static void main(String[] args)
    {

        String name = "Dan";
        short age = 20;
        int height = 190;
        User user1=new User(name,age,height);
}
Mario Codes
  • 689
  • 8
  • 15
Casareafer
  • 145
  • 8