0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Casting in Java

Posted at

What is cast?

Casting in Java is the process of converting a variable from one data type to another. There are two main types of casting:

1. Widening Casting (Implicit Casting)
2. Narrow Casting (Explicit Casting)

1. Widening Casting (Implicit Casting)

Widening casting occurs when a smaller data type is converted into a larger data type. This is done automatically by Java, so no explicit cast is needed.

int num = 10;
double d = num;  // int → double (automatic conversion)
System.out.println(d);  // Output: 10.0

2. Narrow Casting (Explicit Casting)

Narrowing casting occurs when a larger data type is converted into a smaller data type. This requires explicit casting because data loss may occur.

double d = 9.78;
int num = (int) d;  // double → int (explicit casting)
System.out.println(num);  // Output: 9 (decimal part is truncated)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?