Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Data Types

We have seen a variable is used to hold a value. Be it a number or a name or even a sentence. But how will java come to know, if the value is a number or a name?

And thus Data Types comes into picture.


Data Types

Data Types tells the variable that what kind of values it can contain.


Example :

int x;


In the above statement

'x' is a variable

and

'int' is the Data Type. Which is saying 'x' can only hold numbers. If you want to assign anything other than a number, it will end up with an error.


int x = 5; // Valid

int x = 5.6; // Invalid as it is holding a decimal value.

int x = John; // Invalid as John is a name.


What is the valid way to store a decimal value or a name?

Java provides us with a set of Data Types used to hold all type of values.

There are two types of Data Types in Java :

1. Primitive Data Types : They are the widely used datatypes and which is easy to write.
2. Object Data Types : Object Data Types are created from classes. They can be custom defined or could be predefined by java.


Below are the set of Primitive Data Types :

  1. byte:

byte data type is of 8-bit.

It can hold values from -128 to 127.


Example:

byte a = 104;
byte b = -10

  1. short:

short data type is of 16-bit.

It can hold values from -32,768 to 32,767.


Example:

short s = 21900;
short r = -12400;

  1. int:

int data type is of 32-bit.

It can hold values from -2,147,483,648 to 2,147,483,647.


Example:

int a = 23445;
int b = -657767;

  1. long:

long data type is of 64-bit.

It can hold values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.


Example:

long a = 100000L;
long b = -200000L;

  1. float:

float data type is of 32-bit.


Example:

float f1 = 19.5f;

  1. double:

double data type is of 64-bit.


Example:

double d1 = 563.456;

  1. boolean:

boolean data type only contains true or false

If we do not specify anything the default value is false.


Example:

boolean flag = true;

  1. char:

char data type is of 16-bit.

Char data type can hold a letter/character.


Example:

char test ='c';

Note :For every Primitive Data Type, There is an equivalent Object Data Type available. They are called Wrapper Classes. Say for 'int' it is 'Integer', for 'float' it is 'Float' and so on.

Although we have seen how to hold a letter (Say the letter 'a') using 'char' data type. But we have not yet seen, how can we store a name? No worries, we will be looking at it next.