Hi, I have two Questions Question 1) This may be a trivial question but can somesome explain why below would work? (i thought 1 is int and since int is 32 bits, how can it fit without cast?) char c = 1; Question2) Also, explain below problem. String s = "hello"; long L = 99; double d = 1.11; int i = 1; int j = 0; which work and WHY?? 1. j=i << s; 2. j=i << j; 3. j=i << d; 4. j = i << L; ans was 1&4 but please explain someone, what general rules are needed in bit shifting different types?? Thank you so much =)
A1) char c = 1; works cause a char is 16 bits and will fit into a 32 bit int without the explicit cast. A smaller will automatically fit into a bigger, but you must explicitly (cast) a bigger into a smaller. Question 2 looks like one that I have to study. Some links: http://www.javaranch.com/campfire/StoryBits.jsp
Steven I think your mistaken, Kevin isn't putting a smaller char into an int he's putting the larger int into a smaller char. Kevin, the reason it works is because in the code you have you're using a literal int value so at compile time the compiler knows that this will fit into the char c. The same thing with final variables. Look at the code below and it'll show some other examples that might clear it up...
Check out this in the jls section 5.2
In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied: The expression is a constant expression of type byte, short, char or int. The type of the variable is byte, short, or char. The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.
hope that helps
Dave [This message has been edited by Dave Vick (edited June 14, 2001).]