How to Use the Cast on Java

Casting, in programming, is the process of converting from one primitive data type to another. Most numerical, and a few non-numerical, primitive data types in Java can be cast between each other using the C-style syntax of adding the name of the desired data type within parenthesis to an expression. Casting with objects is trickier, and involves reading the online Javadocs for the classes to find the appropriate methods (if they exist.)

Instructions

    • 1

      Open "NetBeans" and click "File" and "New Class."

    • 2

      Type "psvm" to create a main method.

    • 3

      Add the following code to the main method:

      double d = 83.45;

      // Cast d to float data type.

      float f = (float) d;

      // Cast d to int data type. The value will be truncated to just "83."

      int i = (int) d;

      // Cast to short

      short s = (short) d;

      // Cast to char. The result will be the letter with the ASCII value of 83: the letter 'S'

      char c = (char) d;

Tips & Warnings

  • In the case of strings of text, you can parse them into numerical values using the "parse" command of the appropriate data type. For example: 'double d = Double.parse("12.4");'

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured