Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Marcus exam question

kevin goon
Ranch Hand
Posts: 62
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 =)

Steven YaegerII
Ranch Hand
Posts: 182
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

http://janeg.ca/scjp/oper/shift.html
http://www.duke.edu/~twf/cps104/twoscomp.html

http://www.software.u-net.com/applets/BitShift/BitShiftAr.html

[This message has been edited by Steven YaegerII (edited June 14, 2001).]
[This message has been edited by Steven YaegerII (edited June 14, 2001).]

Dave Vick
Ranch Hand
Posts: 3244
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).]

Bin Wang
Ranch Hand
Posts: 82
Kevin,
The answer for you second question is: 2 & 4.
String can not be the operand of bitshift operator.

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
And a double must be cast to an int for (3) to work.