Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
34 lines (32 loc) · 1016 Bytes

File metadata and controls

34 lines (32 loc) · 1016 Bytes
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package chapter11;
// TypeCastingEx3.java
public class TypeCastingEx3{
/**
* Upcasting and downcasting with Number, Integer, Float etc.
*
* @param args
*/
public static void main(String[] args) {
Number n, n1;
Integer i = 5;
Double d = 2.5;
// Upcasting, putting Double and Integer to Number. No issues. Compiler
// does this automatically.
n = i;
n1 = d;
// Now its time for downcasting. The following code segment will not
// compile. Although we did the reverse in the upper segment, compiler
// throws an error while doing this. Try this by uncommenting.
/*
* i = n; d = n1;
*/
// So, to downcast properly, we need to explicitly cast it
// appropriately.
//i = n; // Type mismatch: cannot convert from Number to Integer
//d = n1; // Type mismatch: cannot convert from Number to Double
i = (Integer) n;
d = (Double) n1;
System.out.println("Here i = " + i + " (Integer) n : " + (Integer) n );
System.out.println("Here d = " + d + " d = (Double) n1: " + (Double) n1 );
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.