[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: ok..one of those..I RTFM...but..I'm dumb...what can I say..



For some resons, my responses to this thread are lost in the ether somewhere.
I apologize if they all show up at the same time in the near future. My
comments were basically:
 
The compiler is warning you for a reason. Narrowing casts are most likely to
have a loss of precision. The best solution would be to assign the result of
the operation into an int, rather than manually cast it back to a byte.
 
Strange fact, this statement compiles and runs:     b *= b1
 
The Java specification states that the compound arithmetic assignment
operator be interpreted by the compiler like this:     b = (byte)((b)*(b1))
 
Again, this is a narrowing cast, so it's not recommended, but you get no
warnings either :)
 
Lance England

	-----Original Message----- 
	From: Miller, Tory P 
	Sent: Tue 10/9/2001 8:12 AM 
	To: 'ajug-members@www.ajug.org' 
	Cc: 
	Subject: RE: ok..one of those..I RTFM...but..I'm dumb...what can I
say..
	
	


	Fido,
	
	Before any arithmetic operation all operands are promoted in Java to
at least an int.
	This is why you have to cast it back -- using (byte) -- to rid
yourself of the compiler error. Check out www.javaranch.com for a bunch of
good tutorials for fundamentals and getting certified.
	
	Hope this helps!
	Tory Miller
	-----Original Message-----
	From: Fido [mailto:pinudwn@swbell.net]
	Sent: Tuesday, October 09, 2001 12:27 AM
	To: ajug
	Subject: ok..one of those..I RTFM...but..I'm dumb...what can I say..
	
	
	     I'm trying to understand a key concept of implicit conversion in
	Java.  Explain to me if you have the following code:
	
	//  file Wannaknow.java =)
	
	class Wannaknow
	{
	   public static void main(String[] args)
	   {
	       byte b = 2;
	       byte b1 = 3;
	       b = b * b1;
	       System.out.println(b);
	   }
	}
	
	
	----
	
	....how in the world you get a compile error that says this:
	
	Wannaknow.java:7: possible loss of precision
	found   : int
	required: byte
	               b = b * b1;
	                     ^
	1 error
	
	----
	
	   Apparently, I'm not understanding something...yet...can't a byte
hold
	a value from -2^7 through 2^7-1?  Which would equals -128 through 127
	right? Why is this requiring an int, a value of -2^31 to 2^31-1?
	
	   From my math experience (be it I only passed 5th grade math -
	addition, subtraction, multiplication, and division of 2-digit
numbers),
	2*3 is 6 and 6 > 127.  So, where's my reasoning wrong?  I know my
	infinite stupidity is greater than someone's infinite knowledge of
Java,
	who could be classified as a 'god of Java,' but, I do think one of
you
	Herculean characters can help this meager Sysiphus.
	
	Thanks.
	Fido - a wannabe man from a distant place...far far away...