0% found this document useful (0 votes)
13 views3 pages

Widening Casting: Example

In Java, there are two types of casting between primitive data types: widening casting, which automatically converts a smaller type to a larger one; and narrowing casting, which requires manually placing the type in parentheses to convert a larger type to a smaller one. Widening casting occurs from byte to double, while narrowing casting goes the opposite direction.

Uploaded by

rent mark
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
13 views3 pages

Widening Casting: Example

In Java, there are two types of casting between primitive data types: widening casting, which automatically converts a smaller type to a larger one; and narrowing casting, which requires manually placing the type in parentheses to convert a larger type to a smaller one. Widening casting occurs from byte to double, while narrowing casting goes the opposite direction.

Uploaded by

rent mark
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 3

n Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a


larger type size
byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a


smaller size type
double -> float -> long -> int -> char -> short -> byte

Widening Casting
Widening casting is done automatically when passing a smaller size type to
a larger size type:

Example
public class MyClass {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}

Run example »

Narrowing Casting
Narrowing casting must be done manually by placing the type in
parantheses in front of the value:

Example
public class MyClass {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}

Run example »

❮ PreviousNext ❯

COLOR PICKER

HOW TO
Tabs
Dropdowns
Accordions
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax
Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow
Filter List
Sort List

SHARE
CERTIFICATES
HTML
CSS
JavaScript
SQL
Python
PHP
jQuery
Bootstrap
XML

Read More »

You might also like