• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to assign some numeric values like 1 ... to a short variable ?

 
raminaa niilian
Ranch Hand
Posts: 551
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Thank you for reading my post
I have a short value like :


somewhere in my code i tried to assign some values like



but it shows an error which say , you can not assing an int to a short variable

Also i tried to use java.lang.Short class like :


and it said that there is no constructor which can take an int value.


Thanks
 
Rusty Shackleford
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try casting 0 to a short. ie a = (short)0 or initializing it on the same line that you declared a.

Short only has 2 constructors:

Short(short value) and Short(String s). So either cast it to a short or pass it as a String if you wish to use this wrapper class.

I realize you just gave a simple example, but try to get in the habit of using meaningful names for variables. It helps self-document your code.
[ April 12, 2006: Message edited by: Rusty Shackleford ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
short a;
a = 0;

...should work, because you're assigning a literal value that's within range.

However, the Short constructor does require an explicit cast with an int literal...

Short s = new Short((short)10);
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code will work since it assigns a short to a constant value.
You might be referring to assigning to some non-constant value.

This will not compile because 'b' is not a constant.
Here, b is a constant:

...therefore, the code will compile.
JLS 15.28 2e defines a constant - it may have changed with the third edition.

A constant is not to be confused with a final
 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look just declare an int like...

int i = 0;

then do

short r = (short)i;

that should solve your question....just remember you can always downcast...

or maybe is would be better so say "upcast" like from an int to a float, or short, or long..

but you cant down cast..like from a float to an int...

justin
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic