Java Types and Type Conversion (Casting)

By Xah Lee. Date: . Last updated: .

In Java, there are primitive types: {short, int, double}. But there are also corresponding number classes, that wraps a class structure around these.

Technically, every variable and expression in Java is of some type.

Java data types are of two kinds: primitive and reference.

You can convert one data type to another, by a operation called “casting”. Converting from one type to another is necessary, because sometimes a function f accept type A, and your expression e has type B and you want to do f(e). So, you need to convert your e to type A.

The general syntax to do casting is this: (type) myExpression. For example, if “n” is a “int” and you want to cast it to “double”, do (double) n.

In the following example, java.lang.Math.pow() returns a “double”. It can be casted to “int” by including (int) in front. (if this is removed, the code won't compile.)

import java.lang.Math;

class T2 {
    public int square (int n) {
        return (int) java.lang.Math.pow(n,2);

class T1 {
    public static void main(String[] arg) {
        T2 x1 = new T2();
        double m =x1.square(3);


  1. Install
  2. javac java jar javadoc

Java Basics

  1. Print String
  2. Strings
  3. Power Function
  4. Java Types and Type Conversion
  5. Function
  6. Arrays

Class, Inheritance

  1. extends
  2. Constructor
  3. Constructor Return Type
  4. Extending a Class that has Explicit Constructors
  5. static
  6. this
  7. super
  8. Access Specifiers

Abstract class, Interface

  1. abstract
  2. Interface


  1. Package


  1. Collection, Map
  2. Read/Write File
  3. Convert File Encoding
  4. Complex Numbers in Java
  5. Unicode
  6. Number Literals