|
-
Jan 4th, 2003, 06:45 AM
#1
Thread Starter
Addicted Member
Casting in Java
What is the way how to casting data type in Java?
-
Jan 4th, 2003, 10:21 AM
#2
C-style
Object o = new String("Hello");
String s = (String)o;
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Jan 5th, 2003, 08:12 PM
#3
Dazed Member
Wideing conversions are permitted with primative data types as well as object types as well as narrowing conversions which must be expliciltly specified.
class castExamples{
public static void main(String[] args){
/*
if a integer value falls with in the range of the destination type
then no cast is required.
*/
byte b = 88; // int value in range. No cast required
byte b1 = (byte)128; // int value not in range. cast required
short s = 678; // int value in range. No cast required
char c = 33; // int value in range. No cast required
/*
Impilcit widening conversions
*/
long l = 2000; //Implicit wideing: int to long;
double d = l; //Implicit wideing: double to long
/*
narrowing conversions between char, byte (or short) always require
an explicit cast even if the source value is in range of the
destination type
*/
byte b2 = 33; // no cast required
short s1 = (short) 'a'; // value in range of short but explicit cast required
char c1 = (char) b2; // byte to char but explicit cast required
}
}
Last edited by Dilenger4; Jan 5th, 2003 at 08:19 PM.
-
Jan 5th, 2003, 08:26 PM
#4
One typo:
double d = l; //Implicit wideing: double to long
should be
double d = l; //Implicit wideing: long to double
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Jan 5th, 2003, 08:37 PM
#5
Dazed Member
Yeah i saw that. Thanks CornedBee. I was too lazy to change it though. You can do the Object casting example now.
-
Jan 6th, 2003, 07:35 AM
#6
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|