Reintroduction to Java Data Types

Primarily “Data types” in java can be categorized into two types. That are, Primitive and Non Primitive or Reference data types.

Primitive data types can be classified into four groups boolean, character, floating point and Integers. Everything else other than primitive types are said to be reference types.

Following image shows hierarchy of data types in “Java Programming Language”

Complete set of Java DATA TYPES
Complete set of Java Data Types: Both Primitive and Reference Types

Primitive Data Types

Primitive data types are types that are self contained and holds atomic value. Primitive data types are types without any fields or methods. Primitive types do not inherit Object and are not part of Object hierarchy. Primitive data types are also called as simple types. Data types describe size, range and kind of values that are be stored. Java offers total 8 primitive data types boolean, char, byte, short, int, long, float and double .

Since primitive types are simple(not objects) they offer great performance for simple calculations as there will be no overhead of objects(instantiation and member lookup etc)

Java Primitive Data Types

Java is a static typed programming language. Where, types (data types) are associated with variables. On the other hand in dynamically typed languages types are associated with values, example: python. As a result in java we need to declare a variable prior using it with it’s type(data type).

In Java types are associated with variables. A variable is a identifier(name) given to unit of storage that stores values of specified type. that hold a value(literal) of specific type(primitive types). It is used to store values for later use in the program.

Variables are defined with combination of identifier, type and optional access and non-access modifiers. Variable can be optionally initialized.

If modifiers used are not compatible, following error will occur. Error: illegal combination of modifiers: ***
Example: final and volatile can’t be used together. If used, we will error
illegal combination of modifiers: final and volatile

Learn more about modifiers: TBA

Ideally data is not homogeneous it is available in different forms. What we can do, how we use it is driven by type of data it is. For example: if you take matrix how you perform addition is different from how you perform addition on two plain numbers, these two are totally different. Likewise programming languages offer different data types for different type of data.

These Primitive Data Types can be categorized into four groups

Let’s see java primitive data types in action

Data Type Boolean

Boolean data types is used to represent something which has only two possible answers for example Yes/No question. Boolean is used to represent true and false values. Thus boolean data type has only two literals which are true and false. Boolean types are default to false if it is not initialized.

Following image illustrates use of “Boolean” type

Java Boolean Data Type illustrated
Java Boolean Data Type illustrated

Following shows declaration of a variable of type boolean

boolean  isCat;
boolean b = true;  // Initialized to true 
// Use of different modifiers 
class Bar {
   public static volatile boolean b;  

Where, public is access modifier. static and volatile are non-access modifiers.

Data Type char

Character data type char is used to store single character where character should be enclosed within single quotes. Out of the box java supports unicode. Unicode is used to represent all human languages in the world it unifies all other characters set like ASCII, Latin etc into one. Java char data type is of size 16 bits which is used to store unsigned numbers from 0 to 65535 and Unicode character set is used to represent these numbers as characters. So, char can be classified as numeric data type where actual values are stored as numeric using character encoding, and character set(unicode) is used to represent to those numbers as character symbols. Java characters supports Unicode out of the box, ASCII still ranges from 0 to 127.

Hexadecimal Unicode characters can be represented with notation ‘\uXXXX’.
Characters can also be represented with octal code points as ‘\ddd’

Java offers different escape sequence characters (escape sequence) to represent non -printable and special characters

\’Single Quote
\”Double Quote
\nNew Line/Line Feed
\rCarriage Return
\fForm Feed
\tTab (Horizontal Tab)

Following code shows declaration and initialization of character variable using keyword char.

char c;
c = 'a'
char lineFeed = '\12'   //Octal character
char letter = '\u0061'  //Hexadecimal Unicode character

Integer Data Types

Java offers total 4 primitive integer data types byte, short, int and long. In java all integer data types are used to store signed numbers. Unlike other languages java doesn’t support unsigned integers .

Java doesn’t have support for unsigned integers. All integer types signed

Integer Literals

Literal is the notation to represent values of any data type. Any whole number is said to be integer literal. We can also represent integers in other number systems(bases). Following table describes different integer literals of different bases binary, octal and hexadecimal.

Prefix is used to specify integer literals in different bases described in following table

Base/RadixLiteral PrefixExample
2 (Binary)0b or 0B0b0101, 0B0110
7 (Octal)0010, 071
10 (Decimal)No leading zero0, 1, 2, 3, 8, 99, 32…
16 (Hexadecimal)0x or 0X0xf2, 0XFF

Using literals(digits) 8 and 9 in octal literals (when numbers prefixed with 0) gives error since literals in octal number system are 0 to 7

Optionally underscore(_) can be used in integer & floating point literals for readability. Example: 2_534_382

Data Type byte

The type byte is the smallest integer data type that java offers. It is used to store signed 8 bits (1 byte) ranging from -128 to 127. This data type is used when it is required to deal with binary data or binary network streams/files.

Following code shows declaration and initialization of byte variables using keyword byte.

byte a, b;
a = 0011   // Octal equivalent of Decimal 9 
byte flag = 0b0110; 
byte hb = 0x3F;  // Hexadecimal equivalent of 63

Data Type short

The type short is integer data type of size 16 bits(2 bytes) , stores signed integers ranging from -32,768 to 32767. It is declared using “short” keyword.

short age;
age = 23;
short speed = 120; 

Data Type int

The data type “int” is most commonly used type in java. It is of size 32 bits (4 bytes) stores values from -2,147,483,648 to 2,147,483,647 .

int elapsedtime; 
int distance = 5; 

Data Type long

Long is the data type which is used to store very numbers, really big number when data type int is not enough. Data type long is of size 64 bits(8 bytes) with range -9223372036854775808 (2 ** 63) to 9223372036854775807 ((2 ** 63) -1).

Long literals are suffixed with “l” or “L” example: 3828932L

long ld = 922337203685477580L

Floating Point Data Types

Floating point data types are used for real number where it is required to represent fractional Precision. Java supports two floating point types. Those are float (single precision) and double (double precision) where float is 32-bit and double is 64-bit.

Data Type float

Floating data type float is very common choice to represent a factional precision. The Data type float represents single precision numbers with 32-bit of storage. It’s values can range from ~4.9e-324 to ~3.4e+038 . Keyword float is used to denote float type

Float literal are suffixed with letter f . Example: 32.3f, 3.14f

float height;
float area;
float distance = 32.5f 
var weight = 69.5f

Data Type double

Double data type is use to represent double precision numbers. Double uses 64-bits to store values. It is useful especially when it is required to store very large or very small numbers with precision. Double types are declared using keyword double . Double types can store values ranging from ~4.9e-324 to ~1.8e+308 . By default double is used to represent decimal numbers.

double pi = 3.14;
var weight = 69.5;  //weight gets double type 

Java Primitive Data Types Size,Range and Defaults

Primitive data types are available in different sizes and support different range of values according to size. We have to choose the best possible data type as per requirement. Unlike other static typed languages C/C++ java data types size and range doesn’t change as per architecture of system(OS) to support portability and platform independence.

If you assign a value which is beyond the range supported by that data type, error will occur with message “incompatible types: possible lossy conversion“.

Java does type promotion automatically for integer & floating point types when computing expression to highest (size)preceded type in the expression

Java primitive data types size and ranges are explained in following image

Java Primitive Data Types Size and Range
Java Primitive Data Types Size and Range

Boxing and Unboxing of Primitive Types

The process of encapsulating primitive value within the wrapper type is called boxing. On the other hand, getting a primitive values from Wrapper type is called unboxing

Java compiler does autoboxing and autounboxing when ever it is required automatically. Where autoboxing is conversion of primitive to reference type (object of corresponding wrapper class), example: int to Integer. Auto-unboxing is conversion of Reference type(Object of wrapper class) to primitive, example: conversion of Integer to int.

Wrapper types(Reference Types) provided by java for corresponding Primitive Types


There wrapper types offer wide range of methods to work with related to corresponding primitives

Read In detail about Boxing, Unboxing, Autoboxing and Autounboxing: #TBA

Reference Data Types

Anything other than primitive type is said to be Non-Primitive or Reference type in java.

Following are Non-Primitive or Reference Types that java offers


Arrays are fixed length homogeneous data types. Arrays store fixed length different values of same type. Arrays can be of 1-dimensional, 2-dimensional or multi-dimensional.

Declaration of Arrays

byte[] buffer; 
int[][] matrix;    //2-Dimensional 
int matrix[][][];  // 3-Dimensional
double[] units[][];  //3-Dimensional equivalent to double[][][] units; 

Read More about java arrays at : #TBA


Unlike C/C++ we don’t have to use character arrays to define strings. Java offers Reference a built-in Reference Type to deal with strings. Strings are enclosed by double quotes.

Declaration and usage of strings

String msg = "Hello! Welcome to Java"; 
String name = new String("neotam"); 

Limitation of Java Strings

  • Java Strings doesn’t support subscription operator or indexing
  • Java Strings are objects. So any two different string object of same values are not equal

Use equals() method of string object instead of operator == to compare strings for desired result


Classes play vital role in object oriented programming.IN Java code is written in the form of classes. Each java source file should contain atleast one class and atmost one public class

Classes are building blocks of object oriented programming in java. Classes act as blue print for objects(instances) instantiated from class.

Classes provide a way to create your own types

Objects are created(instantiated) from class by using new keyword

Anatomy of Class Definition in Java

Java Class Definition
Java Class Definition

By using classes we can represent real world problems, entities and concepts programmatically as objects. Classes contain fields and methods. Where fields represent the data and methods represent the behavior or functionality

Classes offer abstraction and encapsulation traits of object oriented programming languages. Code reusability, modularity and polymorphism can be achieved by using inheritance.

Class are blueprints for object which are created by instantiating a class. Each class can contain fields and methods. These fields and methods can be called as members. Visibility of these member(fields & methods) is controlled by access modifiers.

Class fields can be either class variable or instance variables.

Defining a class

Classes are defined using keyword class .

Each java source file should contain at least one public class. Java Source files are made up of classes

Above code describes the definition of a typical class. Here we have taken student as an example.

Constructor is a special kind of method with same name as name of the class and which doesn’t return anything

Defining a constructor is optional. if not defined java uses default constructor with no arguments

Instantiating the class

Purpose of creating class which is a blue print is to create objects from it. Words object and instance can be used interchangeably

The process of creating the instance is called instantiation. This is process through which we can create objects out of classes. Keyword new is used to instantiate(create instance).

We have defined class so that we can create instance for each student in a class/section or college. Each instance created will be independent and will have it’s own isolated data or memory.

Objects are constructed or instantiated using the keyword called new . Following code shows creating students named Bruce and Lois. When creating instance arguments to constructor are passed to initialize the object being created. If constructor is not defined or takes no arguments no need to pass any arguments when creating object.

Student bob = new Student(48, "Bruce", "Wayne", 3);
Student lois = new Student(49, "Lois", "Lane", 3);


Interfaces in java are used to write public API’s. Interfaces provide a way to achieve abstraction and provides a common ground for outside world to interact with objects through methods exposed (implemented).

Typically interfaces don’t contain any definition e but only declaration of methods and variables. As said interfaces are used to write public API’s through which objects expose methods to interact with outside code by hiding (complex) internals, which is in fact abstraction.

Classes implement interfaces. Any class that is said to be implementing a given interface must implement all methods declared in the interface. Otherwise it’s a compilation error. Implementing interface enforces definition of methods that are declared in the interface but not how they are implemented.

Since interfaces enforce implementation of methods it is also said to be contract programming. It can be put this way, the class that is implementing the interface is having a contract with interface to implement(define) each and every method that are declared in the interface.

Anatomy of Interface

Java Interface Definition
Java Interface Definition

Defining Interface

Interfaces in java are defined using keyword interface. Interfaces can inherit or extend other interfaces. Unlike classes java interfaces can extend or inherit multiple interfaces.

All methods declared in interface are implicitly public

Interface definition can contain abstract methods, static methods and default methods

Implementing Interface

Class can implement any interface by using keyword implements.

Following snippet shows implementing interface.

class Task implements Runnable {

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Running Task");
            // Other statements related to task  go here
Thread t1 = new Thread(new Task());

In the above example class Task is implementing Runnable interface . Which is very common way to create threads. Where, Thread constructor expects object of type Runnable (or object of class which implements Runnable). Here, accepting Runnable object would enforce and will make sure that passed object will have run method, which will be called by thread when thread is started using Thread.start .

Java supports multiple inheritance only using interfaces where as classes do not support multiple inheritance


Enumerations are special kind of classes to define a new data type with set of only values that data type can have. In other words, an enumeration(enum) is a set of named constants. An enumeration object holds any value that was declared in definition but not other values.

Named constants that are defined in enumeration are also called as enumeration constants

Each enum constant(member) is implicitly declared as public static final

All enumerations implicitly inherit java.lang.Enum

Anatomy of enumeration

Definition of simple Enum Type in Java
Java Enumeration Definition

Semicolon (;) at the end of enumeration constants is not required if defined enum contains only named constants

Enumeration are very powerful where they can have methods and fields like any other class. Following image illustrates an enumeration with fields, constructor and methods

Java Enumeration Definition with fields, constructor and methods
Java Enumeration with fields, constructor and methods

Defining and Enum Type

Following code shows defining typical simple enumeration

public enum Day {

As discussed above enumeration are very powerful than just being named constants. Following code shows defining enumeration type with fields and methods


Annotations are used to provide meta data in source file. Annotations do not effect operation and control flow of code they annotate. The information or meta data the is embedded into source file is formally called as annotation.

Annotations leave semantics intact. Thus, no affect on flow and execution of a program. Annotation are effectively used by external tools like documentation generator, compiler and build automation tools.

Annotation Anatomy

Java Annotation Definition Anatomy
Java Annotation Definition

Defining Annotation

Annotation are defined using @interface . Annotations don’t contain any logic but only members.

Applying Annotations

From JDK 8, annotations can be applied to all most anything like, class, type, methods and exceptions etc. Event annotations can be annotated.

class AnnoDemo {
    @Information(description = "Annotation Demo ", name="Constructor Annotation")
    static void AnnoDemo(){

Annotation are applied to any type by calling Annotation prefixing @ with arguments in the form of key value(member name and value). Default argument can be omitted unless it is required to override.

Annotations are deeper than they look, please check other article specific to annotations for more


Objects are key to understand object-oriented programming. Objects hold state and have functionality. State is represented by variables that are called as fields or member variables and functionality of object is defined by methods.

Objects are effectively used to represent any real work object, entity, concept, event or concept. For example : dog, mobile, car, student, instructor, college, marriage. In java everything that objects know is state/data (fields) and can do/perform functionality/behavior(methods). For example if you take dog , it’s characteristics are name, breed, color and owner and it’s behavior fetching, eating, sleeping and barking. In a program we write these characteristics of real work object(here in this example it’s dog) are translated into data or state formally called as fields (in some other OOP languages, member variables or instance variables or attributes) of object and behavior(fetching, eating, barking etc) is defined by methods.

Blueprint of objects is defined by classes

Each object has it’s own isolated state or data. Objects are created from classes using the process called instantiation using keyword new

Let’s take another example car. If car is defined as a class, car objects are created from class using new keyword. Fields (state) of car object will be color, brand, mileage, max_speed etc. and methods will be drive, stop, steer_right, steer_left, driveBack, changeGear etc.

Following image illustrates, as if car is a object what are it’s fields(in other languages called attributes or properties) and methods.

Object Oriented Programming - Objects, Fields and Methods Explained
Object Oriented Programming – Objects, Fields and Methods Explained

This phenomena of representing real word object’s characteristics and behavior in source program as fields(data) and methods is very effective. It enables us create direct analogy of real word tangible and intangible things in a program.

Default image
Leave a Reply