Click here to Skip to main content
15,939,853 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
My code is :
Java
int myInt = 56;
double myDouble = myInt;
System.out.println (myInt);
System.out.println (myDouble);


What I have tried:

Unable to undertake the mistake..
Posted
Updated 21-Jul-23 1:07am
v2
Comments
Richard MacCutchan 21-Jul-23 7:00am    
There is no mistake, that code compiles, runs, and produces the correct output.
CPallini 21-Jul-23 7:07am    
No type casting, no error :-D
Andre Oosthuizen 21-Jul-23 7:08am    
As Richard mentioned, the code is just fine, output is 56, 56.0. Check your code for an error at another line perhaps.

1 solution

Quote:
Java type casting error

It is a runtime exception that occurs when the application code attempts to cast an object of class type A into another class type B.

But, in your code above, I don't see that concern. We can convert int to double in java using assignment operator. Read[^].
Quote:
Java performs implicit conversion or widening conversion when both data types involved in conversion are compatible, or the value of a smaller data type is assigned to a bigger data type. Double is bigger than int as it requires more storage space; hence, int values are implicitly converted to double by Java.
Java
public static void main(String []args){
    System.out.println("Hello, World!");
    
    int myInt = 56;
    double myDouble = myInt;
    System.out.println (myInt);
    System.out.println (myDouble);

 }
// Output as below
// Hello, World!
// 56
// 56.0

If you reverse the datatypes, you would surely get a incompatible types error. Example:
Java
double myInt = 56;
int myDouble = myInt;
System.out.println (myInt);
// Errors as:
//error: incompatible types: possible lossy conversion from double to int 

Another example[^]:
Java
// creating an object
Object o = new Object();

// type casting the object o to string which give the classcasted exception because we
// type cast an parent type to its child type.
String s = (String)o;

// errors as
// java.lang.ClassCastException: class java.lang.Object cannot be cast to class java.lang.String (java.lang.Object and java.lang.String are in module java.base of loader 'bootstrap')
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900