aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting and shadowing questions. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting and shadowing questions." Watch "Casting and shadowing questions." New topic
Author

Casting and shadowing questions.

Jan Osykowski
Ranch Hand

Joined: Jul 15, 2010
Posts: 41
Hey guys,

I got some questions, first of all:



Why the 3rd line doesn't work?? I read that integer literals are ints by default and even though in the 2nd line there is no problem. So there is some kind of casting done automatically . But in the nearly the same situation in the 3rd line there is an error. Why does it happen like this?

Also would like to ask a question about scoping and shadowing.



There is an error that a identifiers are duplicated. But they are in different scopes, aren't they? So the shadowing should come in play, no?

Cheers,
Jan.
Mark Uppeteer
Ranch Hand

Joined: Mar 02, 2004
Posts: 159

an int is bigger in size (32 bit) than a short , so you can't put an int into a short (16 bit).

in the loop your problem is here



the second a is not in a different scope.
your third 'a' is in a different scope.

I know where my towel is. (SCJP 5, OCPJWCD)
[Free Quiz Tips for a fun night with friends or family] Flash games
Jan Osykowski
Ranch Hand

Joined: Jul 15, 2010
Posts: 41
But have a look at the second line. I assing to 'rr' an integer literal that is understood as an int. And in this is line there is no problem. It works. The problem is when I try a similar situation and assign and int to short but not as a literal but as a variable.

And for your answer to the second question. In the book there is written that there are 4 basic scopes and one of them is block variables (eg. in a for or an if) so I think my code should be fine but it's not. And also, if I change the name of an int in the for loop there is still an error inside an if. Why?

Cheers,
Jan.
Dieter Quickfend
Bartender

Joined: Aug 06, 2010
Posts: 543
    
    4

A variable is not a literal. The compiler will cast an int literal to a short if it's in range, but only if it's a literal. Not if it's a variable or if it's the result of an expression that contains a variable, or if you pass it to a method... Only if it's the literal.

so



Oracle Certified Professional: Java SE 6 Programmer && Oracle Certified Expert: (JEE 6 Web Component Developer && JEE 6 EJB Developer)
Jan Osykowski
Ranch Hand

Joined: Jul 15, 2010
Posts: 41
Alright, thanks, now I get it. Any clues about the second question?

Cheers,
Jan.
Gari Jain
Ranch Hand

Joined: Jun 29, 2009
Posts: 100
A QUESTION FROM KATHY SIERRA SCJP BOOK




What is the result? (Choose all that apply.)
A. An exception is thrown at runtime
B. The code compiles and runs with no output
C. Compilation fails with an error at line 8
D. Compilation fails with an error at line 9
E. Compilation fails with an error at line 12
F. Compilation fails with an error at line 13


Answer:
® A is correct, a ClassCastException will be thrown when the code attempts to downcast a
Tree to a Redwood.
® B, C, D, E, and F are incorrect based on the above information.
(Objective 5.2)
Please explain this question to me. I am unable to understand the casting concepts...











OCPJP 6-100%; Preparing for GATE11
Rodmar Conde
Greenhorn

Joined: Jul 09, 2010
Posts: 11
Hi Gari,

The error is in this line:



t1 is of type Tree, ¿right?

We hava that Redwood extends Tree.... in terms of hierachy, this means that Tree existed before Redwood did, in other words Tree class doesn't even know about the existence of class Redwood.

Then, t1 can't become a Redwood so that causes the error.

Cheers.


SCJA | SCJP Semi Study Guide in Spanish
Gari Jain
Ranch Hand

Joined: Jun 29, 2009
Posts: 100
Thanks for replying@Rodmar

But my doubt is not just about the answer. Please explain what is happenning in Line9 i.e.


Firstly we are creating a new Tree object and then casting it to Redwood..what does this actually mean?Ofcourse it wont get an extra field which was previously not present, but then what will actually happen?
We are then passing it to a tree reference when it is actually a Redwood object now, which was fine if the object was an actual Redwood object but it is not an actual Redwood object it's been typecasted to it.
And then the object is again type casted to Redwood???in line 12

I am just not getting what is exactly goin on in this code extract.
Please Elaborate
Thanks
Dieter Quickfend
Bartender

Joined: Aug 06, 2010
Posts: 543
    
    4

I'll take a stab at it

You just have to keep in mind the differences between an object and a reference variable

A Maple is not a Redwood and the compiler knows it, because nobody calls a Maple a Redwood. That would be silly. The compiler doesn't let you get away with it.

A Redwood is a Redwood and, though the compiler doesn't know it if you called it a Tree, it will let you call it a tree so you can still go back to calling it a Redwood. But you have to let the compiler know it's really a Redwood explicitly, by casting it. When casting, you're basically telling the compiler "hey C-diddy... I'm callin' this thang a tree, but it's really a Redwood, see?"

A Tree is not a Redwood, but the compiler can't be sure it's not a Redwood. Maybe it's a Redwood and you're just calling it a tree. So if you tell the compiler "Hey C-diddy...etc. etc." it will take your word for it, but at runtime, that stuff really doesn't fly and it will hurt your street cred.
Gari Jain
Ranch Hand

Joined: Jun 29, 2009
Posts: 100
Thankyou for replying.
I have understood the reason, why the exception is thrown. But when I run the Redwood and Tree code it shows that the Exception is thrown at line 12, i.e. at:



But my doubt is, Why is the exception not thrown on the line 9,i.e.



in the line above too..we are trying to cast Tree to Redwood explicitly when it cannot be cast.....??!!


Apart from what is happening above,
When I am trying to run this short code:




It's throwing
an exception at line 7,i.e.




Here too the same thing is happening a superclass object is being cast to a subclass...and in this code an exception is thrown here itself while in the Tree and Redwood code the exception gets thrown later!!
Dieter Quickfend
Bartender

Joined: Aug 06, 2010
Posts: 543
    
    4

Ah. This problem is simpler than I anticipated.

This is not procedural code. Check which code runs first. It's a runtime exception, and runtime will throw an exception when it can't RUN something. When it runs line 12, it hasn't run line 9 yet.
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

here the compiler know only about first argument not second.So it cannot able to predict the complete behavior.As second
type passes is object.

why not you try in your above by passing code only refernce type.and then see the output.

that is try replacing the above line with this
and then tell what is the output

NOW SECOND CODE



see compiler check for refernce type only as the objects are created at runtime.
here in this code.compiler is able to detect that method which contain second class as refernce is calling a method
which contain First class as refernce.so it will say no matching argument.
so throws Compile time error.


SCJP6.0,My blog Ranchers from Delhi
Jan Osykowski
Ranch Hand

Joined: Jul 15, 2010
Posts: 41
I'm popping up my second question.

Jan Osykowski wrote:

Also would like to ask a question about scoping and shadowing.



There is an error that a identifiers are duplicated. But they are in different scopes, aren't they? So the shadowing should come in play, no?

Cheers,
Jan.
Dieter Quickfend
Bartender

Joined: Aug 06, 2010
Posts: 543
    
    4

From the Java Language Specification:

If a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs.
Thus the following example does not compile:
class Test {
public static void main(String[] args) {
int i;
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}

It's fine to shadow instance variables with a local variable. Local variables, not so much, unless they're already out of scope.
Mark Uppeteer
Ranch Hand

Joined: Mar 02, 2004
Posts: 159

@Gari Jain

hijacking a thread is rather rude. Please start a new one for your questions!

@Jan Osykowski

do you understand now ? the declaration in the for loop can not shadow the previous declaration of 'a'.
if it were between {} it could...
Avishkar Nikale
Ranch Hand

Joined: Aug 06, 2010
Posts: 173
Can we say that local variables cannot have the same identifiers as method parameters in any inner scope ,
in any case.

When you are shadowing an instance variable the above rule still applies.

Regards,
Avishkar Nikale
Mark Uppeteer
Ranch Hand

Joined: Mar 02, 2004
Posts: 159

huh?

there's no method with parameters,...its a for loop.

Jan Osykowski
Ranch Hand

Joined: Jul 15, 2010
Posts: 41
Yes, now it's more clear. Thanks. I have one more question regarding casting though.
Why does this code work?



Long is 64 bits and float is 32 bits. So I think the explicit cast should be needed but this code compiles. Can anyone explain?

Cheers,
Jan.
Avishkar Nikale
Ranch Hand

Joined: Aug 06, 2010
Posts: 173
Mark Uppeteer wrote:huh?

there's no method with parameters,...its a for loop.



Mark,

I was referring to the very first code piece which Jan shared.



My post lost the race and ended up somewhere it is hard to relate to.
Avishkar Nikale
Ranch Hand

Joined: Aug 06, 2010
Posts: 173
Jan Osykowski wrote:
Long is 64 bits and float is 32 bits. So I think the explicit cast should be needed but this code compiles. Can anyone explain?

Cheers,
Jan.


Jan,

If you see the actual range of numbers then a long can easily fit into a float.

This would have been applicable if the code used double where a 64 to 32 bit truncation was necessary.


Divyeshh Patel
Ranch Hand

Joined: Aug 03, 2010
Posts: 37
Avishkar Nikale wrote:
Jan Osykowski wrote:
Long is 64 bits and float is 32 bits. So I think the explicit cast should be needed but this code compiles. Can anyone explain?

Cheers,
Jan.


Jan,

If you see the actual range of numbers then a long can easily fit into a float.

This would have been applicable if the code used double where a 64 to 32 bit truncation was necessary.




Avishkar,
Considering the float and long range, I think long cannot fit into float range without loss of precision.

Jan,

Regarding your doubt, here is what JLS says,
Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

Given these specs, I think we need to live with the loss of precision unless you use other Objects to store big numbers.
Hope you are clear now.


Cheers,
Divyesh.
Avishkar Nikale
Ranch Hand

Joined: Aug 06, 2010
Posts: 173
Divyeshh Patel wrote:
Avishkar,
Considering the float and long range, I think long cannot fit into float range without loss of precision.


Divyeshh,

My bad. I did not mention about loss of precision.

Thanks for the clarification.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting and shadowing questions.