Type checking for assignments and casting - Java Language Basics

Java examples for Language Basics:Primitive Types

Description

Type checking for assignments and casting

Demo Code

public class Main {
  public static void main(String[] args) {
    double myFavoriteReal = 3.141592;
   //  int myFavoriteNat = 2.71;
  }/* w w  w  . java2s. c o  m*/
}

Casting types

In general, we can explicitly cast a type TypeExpr into a TypeVar using the following syntax:

TypeVar myVar=(TypeExpr)(Expression); 

We can eventually transform that real 2.71 by truncating it into the integer 2 by a casting operation.

Demo Code

public class Main {
  public static void main(String[] args) {
    int my=(int)2.71; 
    System.out.println(my);/*  ww  w. ja v a  2  s.  c  o  m*/
    
  }
}

Result


Related Tutorials