Java Datatypes


Java Datatypes

Data types are divided into two groups:

         Primitive data types - includes byte, short, int, long, float, double, boolean and char

         Non-primitive data types - such as String, Arrays and Classes

Data Type

Size

byte

1 byte

short

2 bytes

int

4 bytes

long

8 bytes

float

4 bytes

double

8 bytes

Boolean

1 bit

char

2 bytes


Byte

The byte data type can store whole numbers from -128 to 127

byte myNum = 100;

System.out.println(myNum);

 

Short

The short data type can store whole numbers from -32768 to 32767:

 Example

short myNum = 5000;

System.out.println(myNum);

 

Integer

The int data type can store whole numbers from -2147483648 to 2147483647. It can store whole numbers.

Example: int a = 10;

Long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an "L":

 Example

long myNum = 15000000000L;

System.out.println(myNum);

 

Floating Point Types

You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.

 The float and double data types can store fractional numbers. Note that you should end the value with an "f" for floats and "d" for doubles:

 Float Example

float myNum = 5.75f;

System.out.println(myNum);

 

Double Example

double myNum = 19.99d;

System.out.println(myNum);

 

Boolean:

Java has a boolean data type, which can only take the values true or false:

 Example Get your own Java Server

boolean isJavaFun = true;

boolean isFishTasty = false;

System.out.println(isJavaFun);     // Outputs true

System.out.println(isFishTasty);   // Outputs false

 

Characters

The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c':

 Example Get your own Java Server

char myGrade = 'B';

System.out.println(myGrade);


Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to objects.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

Post a Comment

0 Comments