3

I had a look to this post Java instantiate Short object in Java but did not exactly respond to what I am looking for.

Does anybody know why the first line (//1) gives an error whereas the second line (//2) does not

  Short s = new Short(4);//1

    short s1 = 4;//2 Here I know why it works it gets
 //implicitly narrow converted into a short. 

As stated in the code, I understand why the second line works fine, but what about the first line? Where is the sense of writing Short s = new Short((short)4); Bottom line: why does it not cast it implicitly? It is a constant not a variable.

Thanks in advance.

Community
  • 1
  • 1
Rollerball
  • 12,618
  • 23
  • 92
  • 161

5 Answers5

3

You could define a constructor taking a 'short' and another taking an 'int' and language semantics would make your call to the constructor ambiguous. So you need to use strict type. Also, since Short is final, try using Short.valueOf((short) 4) to avoid unnecessary object allocation.

Marcin
  • 2,399
  • 3
  • 17
  • 15
2

This is caused because Java use "search mechanizm" to find a constructor for int type. When you assing value to varialbe its type is defined and compiler can optimize the code. With constructor (or any other method) this is not possible.

2

When you say

Short s = new Short(4);

you are specifying an integer literal 4, not a short literal, and this is not permitted under the Java language specification for Method Invocation Conversion.

However, when you say

short s1 = 4;

this is subject to what the Java Language Specification calls a Narrowing Primitive Conversion, which is permitted even if it would lose precision.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

You should do like below :

 Short s = new Short((short) 4);

Reason : Type of 4 is Integer/int and NOT Short. So you need to do explicit typecast to ensure that Short constructor takes compatible type.

rai.skumar
  • 10,309
  • 6
  • 39
  • 55
0

It's just not supported.

With the other number object types, there is a literal for the value, numbers are int by default, but for long you have the L suffix, double has d and so on.

If you were to have new Short(int) throw an exception, then the constructor would be inconsistent with the other number constructors.

Trying to create a short primitive that is too big is tested at compile time, the same with byte.

If you did this:

byte b = 1000000;

Your code would not compile, rather than throw an exception.

So the behaviour is consistent when you take the compiler into account.

Chris Cooper
  • 4,982
  • 1
  • 17
  • 27