Kazi Easrat
0
Q:

typecasting java

// You can typecast to convert a variable of one data type to another.
// Wide Casting converts small data types to larger ones.
// Narrow Casting converts large data types to smaller ones.
// Java can automatically Wide Cast.
// Java will throw an error when trying to automatically Narrow Cast.
// This is because data is often lost when Narrow Casting.
// Narrow Casting must be done manually.

//Wide Cast:
int SomeNumber = 5;
double WideCastedNumber = (double)SomeNumber;

//Narrow Cast:
double SomeNumber = 5.39;
int NarrowCastedNumber = (int)SomeNumber;
//Note: The data that holds the decimal places will be lost!
4
JAVA: Example of cast:

int SomeNumber = 5; //int 
double WideCastedNumber = (double)SomeNumber; //from int to double

double myDouble = 9.78;
int myInt = (int) myDouble; // from double to int
2
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
  }
}
1
Assigning a value of one type to a variable of another type is
known as Type Casting.
Auto-boxing; is a process when you take a primitive value and
assign into wrapper class object.
Un-boxing; is a process when you take Wrapper class object
and convert to primitive.
  
0

New to Communities?

Join the community