Please disable adblock to view this page.

← Go home

Java Data Types

java-display

April 30, 2017
Published By : Pratik Kataria
Categorised in:

Java has 2 data types

  1. Primitives
  2. Objects

Primitive Data Type

  • Numbers, characters and booleans.
  • Stored in fastest available memory — for faster access to data.
  • Names given are all in lowercase — so you can distinguish them from complex objects.
  • One exception data type that is not a primitive: String

Declaring Primitive Variables

  • Java is statically typed language unlike JavaScript or Python which are dynamic languages.
  • All variables must have their types declared.
  • Example:
    • int aVar = 5;
  • Example elaborated:
    • int -> data type which stays fixed once assigned as Java allocated memory for you depending on the data type. You cannot change this at run-time.
    • aVar -> Identifier which starts with lowercase and later we use Camel casing.
    • 5 -> value

Numeric Primitive Data Types

  • byte
    • Bits: 8
    • Minimum: -128
    • Maximum: 127
  • short
    • Bits: 16
    • Minimum: -32,768
    • Maximum: 32,767
  • int
    • Bits: 32
    • Minimum: -2,147,483,648
    • Maximum: 2,147,483,647
  • long
    • Bits: 64
    • Minimum: -9.22337E+18
    • Maximum: 9.22337E+18
  • float (32 bits)
  • double (64 bits)

Helper Classes in Java

  • Java has helper classes for each primitive.
  • These classes support conversion and formatting.
  • Data Type — Helper Class (Take note of lowercase and uppercase)
    • byte — Byte
    • short — Short
    • int — Integer
    • long — Long
    • float — Float
  • Example of usage:
    • java.lang.Double supports double values
      double doubleVal = 134.6d; //d is alpha character to explicitly set the value as double and not float
      Double doubleObject = new Double(doubleVal); //helper object
      byte byteVal = doubleObject.byteValue();    //convert to byte
      int intVal = doubleObject.intValue();       //convert to int
      float floatVal = doubleObject.floatValue(); //convert to float
      String stringVal = doubleOject.toString();  //convert to string

Primitive Defaults

  • Primitive numeric values default to 0.
  • Example:
    • int someInt;
    • System.out.println(“Value of unassigned int is: ” +someInt);
    • //OUTPUT: Value of unassigned int is: 0

Guess the output

byte b = 127;
b++;
System.out.println("Value of b: " + b);

OUTPUT ?

Value of b: 128

Wrong! Real Output:

Value of b: -128

Why?

Maximum of byte is 127. So incrementing on 127 will wrap around the value.

Solution?

byte b = 127;

/*
Byte helper class has a constant MAX_VALUE field that represents the largest 
value the data type can have
*/
if( b < Byte.MAX_VALUE) { 
    b++;
}

System.out.println("Value of b: " + b);

//OUTPUT:
//Value of b: 127