The Artima Developer Community
Sponsored Link

Java Answers Forum
Q about type conversion in Java 5

2 replies on 1 page. Most recent reply: May 11, 2006 11:14 PM by Patrick He

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Paul Reiners

Posts: 8
Nickname: reiners
Registered: Mar, 2003

Q about type conversion in Java 5 Posted: May 11, 2006 12:33 PM
Reply to this message Reply
Advertisement
In Java 5, I can implicitly convert a short to an Integer in two steps like this:
	List<Integer> list = new ArrayList<Integer>();
	short s = 5;
 
	// Lines below do compile.
	int shortFromInt = s;
	list.add(shortFromInt);

However, I can't combine those two steps into one step like this:
	// Line below doesn't compile.
	list.add(s);

It seems like type conversion should be transitive. So, what is the philosophical reasoning for not allowing the second example, while allowing the first?


James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Q about type conversion in Java 5 Posted: May 11, 2006 1:07 PM
Reply to this message Reply
> It seems like type conversion should be transitive. So,
> what is the philosophical reasoning for not allowing the
> second example, while allowing the first?

I don't think there is a philisophical reason, rather, there is a technical reason.
list.add(s);


The above is equivalent to this:
list.add(Short.valueOf(s))

which returns a Short. There is no conversion from Short to Integer.

I think this will work:
list.add((int) s);

Patrick He

Posts: 2
Nickname: patrickhe
Registered: Sep, 2005

Re: Q about type conversion in Java 5 Posted: May 11, 2006 11:14 PM
Reply to this message Reply
There is no type convesion between primitive types and objects in Java language. Your code shows the new autoboxing feature in Java 5.
	List<Integer> list = new ArrayList<Integer>();
	short s = 5;
 
	int shortFromInt = s; // short type is converted to int type implicitly
	list.add(shortFromInt); // int type is autoboxed to Integer type.
	list.add(s); // short type is autoboxed to Short type, but "list" can only contain Integer type elements. 

Flat View: This topic has 2 replies on 1 page
Topic: adding Previous Topic   Next Topic Topic: system properties vs environment variables

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use