Data Types in Java

In this post, I am going to discuss Data Types in Java programming language.
Humans know the difference between “54321” and “zyxwv”. But a machine does not know it. We use Data Types in computer programming to dictate what a variable or object can hold. We use Data types in all programming languages including C, C++, Java.

In the previous post, I have told you that you have to declare the Data Type while declaring variables.

Example :
int mySalary = 50000; // number (whole number)
float mySalary = 50000.00f; // number (floating point number)
char firstLetter = 'A'; // character
boolean isOnline = true; // boolean
String channelName = "Programmer Kansabanik"; // String

We can divide Data Types into 2 groups. They are :

  • Primitive data types
  • Reference data types

Primitive Data Types :

Primitive types are the most basic data types available within the Java language. We can say that a primitive variable’s information is stored as the value of that variable.

A primitive data type specifies the size and type of variable values. We can classify them into 8 types. They are: 

  1. byte
  2. short
  3. int
  4. long
  5. float
  6. double
  7. boolean
  8. char
Data TypeSizeDescription
byte1 byteStore whole numbers
short2 bytesStore whole numbers
int4 bytesStore whole numbers
long8 bytesStore whole numbers
float4 bytesStore fractional numbers
double8 bytesStore fractional numbers
boolean1 bitStore true or false values
char2 bytesStore a single character/letter or ASCII values
This data is taken from w3school.com

Primitive Numbers :

We can divide primitive numbers into two types. They are:

  1. Integer types (stores whole numbers, positive or negative, without decimals. They are byte, short, int and long. You have to choose the correct data type based on the numeric value.).
  2. Floating point types (stores decimal or fractional numbers. They are : float and double.).

Note : int (for integer numbers) and double (for floating numbers) is the most used number variables in Java programming language.

Integer Types
Byte

All numbers in the interval (-128, 127) can be stored in a byte variable in Java programming language. The interval between -128 to 127 is smaller than the interval of an int variable. So we can say that the difference between a byte and int variable is the range of value.

Programmers use byte data type to save space in large arrays in Java programs. They take less space than int variables.

  • -2^7 = -128
  • 2^7 -1 = 127
Example :
byte exampleOne = -128; //Ok
byte exampleTwo = 127; //Ok
byte exampleThree = 100; //Ok

byte exampleFour = -129; //error
byte exampleFive = 128; //error

Short

All numbers in the interval (-32768 to 32767) can be stored in a short variable. A short data type is a 16-bit signed two’s complement integer.

A short variable takes space in memory less than int variable but more than a byte variable.

  • -2^15 = -32,768
  • 2^15 -1 = 32767
Example :
short exampleOne = -32768; //Ok
short exampleTwo = 32767; //Ok
short exampleThree = 4000; //Ok

short exampleFive = 32769; //error
short exampleSix = 32768; //error
Int

You can only store the binary value of an integer in it. Int data type is a 32-bit signed two’s complement integer.
The int data type can store whole numbers from – 2,147,483,648 to 2,147,483,647.

  • -2^31 = -2,147,483,648
  • 2^31 -1 = 2,147,483,647

Programmers generally use int as the default data type for integral values unless there is a concern about memory. The value of int is 0 in Java programming language.

Long :

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. A long data type is a 64-bit signed two’s complement integer.

programmers use the long data type for very large numbers where int is not sufficient for that value.

Note : Add a “L” to avoid any kind of errors in your program while using a long data type for a very long value.

Example :
long exampleOne = 15000000000L; // Ok
long exampleTwo =  15000000000; // error
long exampleThree = 15000; // Ok
/* 
Because 15000 is considered here as an int value
for the exampleThree variable.
*/

Floating Point Types

programmers use floating-point types whenever they store a number with decimal value or fractional value in Java.

Float :

You need to use float data type to store fractional numbers from 3.4e−038 to 3.4e+038.

Note : You should add an “f” at the end of the value in your Java program. Otherwise, you may face errors.

The float data type is a single-precision 32-bit IEEE 754 floating-point. Programmers use float to save memory in large arrays of floating-point numbers.

Example :
float myHeight = 5.2f;
//We have to add f at the end for decimal values.
System.out.println(myHeight);
Double :

The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Double data type is a double-precision 64-bit IEEE 754 floating point.

Note : We need to put “d” at the end of the value.

This data is taken from “www.w3school.com”.

We use double as the default data type for decimal values in java programs.

Example :
double myDouble = 19.99d;
System.out.println(myDouble);

Boolean :

A Boolean data type can only have a value of either true or false. This data type is only used for logical values.

In Java program to store true and false, we must use the boolean variable as shown below.

Example :
boolean bol1 = true;
boolean bol2 = false;

System.out.println(bol1);
System.out.println(bol2);

The function of the boolean data type is different from other primitive data types in Java. The boolean data type is used in the validations/verifications/checking purposes.

Char :

You can store a single character using a char variable. You need to surround them with single quotes.

char firstLetter = 'A';
System.out.println(firstLetter);

char data type is a single 16-bit Unicode character.

Reference Data Types :

We can say that a reference variable holds a reference to information related to that variable. A reference variable contains the reference ( address ) of dynamically created objects. These kinds of variables (non-primitive) are not predefined like primitive data types and they refer to objects.

A reference type is based on a class. They are used to access objects.

When you will declare a reference type variable, use the class name as the data type of that variable.

Example (Print a String variable):
String myChannel = "Programmer Kansabanik";
System.out.println(myChannel);

Types of Variables in Java

In this post, I am going to talk about the types of Java variableS. In Java language, we normally see three kinds of variables.

The three types of variables in Java are :

  1. Instance Variable
  2. Static Variable (Class variable)
  3. Local Variable

Instance Variables

An instance variable is a variable declared inside a class, but outside a method. In object-oriented programming with classes, an instance variable is a variable defined in a class for which each object of the class has a separate copy.

In object-oriented programming, objects store their individual states in the “non-static fields” that are declared without the static keyword.

We programmers can mark them as final variables if we want. We can use instance variables without initialization in our program because they have default value.

Instance variable Syntax :

data_type variable_name;

Example (Declare an Instance variable):
package testJavaPrograms;
/*
 * Here I am going to discuss about instance variable in Java
 */
public class InstanceVariableExample {
/*
 * Below variable is INSTANCE VARIABLE as it is outside any method and it is
 * not using STATIC modifier with it. It is using default access modifier.
*/

	String instVar = "Example of Instance Variable.";

	public static void main(String[] args) {

		InstanceVariableExample obj = new InstanceVariableExample();
		/*
		 * Instance variable can only be accessed by Object of the class only as below.
		 */

		System.out.println("Example = " + obj.instVar);

	}
}

Static Variables

In Java programming language , static variables are preceded by static keyword.
When we create a variable as a static variable in our Java program, then a single copy of the variable is created and shared among all objects.

We can create static variables at class-level only. The static variable is like a global variable and is available to all methods.
Always the same set of values is shared among different objects of the same class.

Static variables can be directly called with the variable name. No object reference is needed to be created to call a static variable.

Programmers use static variables for memory management. Static keywords are used with variables, methods, blocks, and nested classes.

Static variable Syntax :

static data_type variable_name;

Example (Declare a Static Variable) :
package testJavaPrograms;
/*
Here I am going to discuss about static variable in Java
*/
public class StaticVariableExample {

	/*
	 * Below variable is STATIC variable as it is outside any method and it is
	 * using STATIC modifier with it. It is using default access modifier.
	 */
	static String stcVar = "I am an example of Static Variable."; 

	public static void main(String[] args) {
		
		System.out.println("Example = " + stcVar);
	}

}

The key concept of static variable :

A static variable is used to declare constants. Constants are those which have certain fixed values.

Example : There are 7 days in a week. This is fixed.

A static variable can be called with a static or non-static method.

Local Variables

A class contains methods, blocks, and inner classes.

We always declare local variables within the body of a method. Then we use that variable within that method. We can declare a method even inside a block (the area between opening and closing curly brace) or constructor. Then we use that variable within that method.

We should always initialize the value of a variable before using it because there is no default value for local variables.

Local variables are created when the method, constructor, or block is entered. The local variable will be destroyed once it exits the method, block, or constructor. Local variables are visible only within the declared method, constructor, or block. Other methods of the same class don’t have any idea about these variables.

Local variable Syntax :

data_type variable_Name = value;

Example (Local Variable):
package testJavaPrograms;
// here I am going discuss about Local Variable in Java
public class LocalvariableExample {

	public static void main(String[] args) {
                /*
		 * Below variable is LOCAL VARIABLE as it is defined inside method in
		 * class. Only modifier that can be applied on local variable is FINAL.
		 * Note* : Local variable needs to initialize before they can be used.
		 * Which is not true for Static or Instance variable.
		 */

		String lclVar = "I am a local variable of this method.";
		System.out.println("Example = " + lclVar);

	}
}

Variables in Java

What is a Variable?

Variable plays an important role when you are coding in java. We use Java variables to store information to be referenced and manipulated in our java programs. Variables can store data value in our programs like a container.

Variable is the name of a memory location. We use variable names in our program instead of using use memory locations directly in our code.

In Java programming language, you have to learn about different types of variables, for example:

  • int (for integer values : 50, -50)
  • float (for decimal values : 50.25, -50.25)
  • String (for text values : “Programmer Kansabanik”, “@12H ello World”)

You can see three types of variables in the above example. But there are more than three types available in Java. I am going to explain them in this series.
For now, just focus on how can you declare a variable in Java programming language. You need to declare the variables first before using them to avoid errors in your programs.

How to Declare a Variable in Java?

Now you are going to learn how can you create a variable in your Java program.

  • First, you have to declare the Data Type of your variable (such as char, int, String).
  • Second, you have to write the name of your variable (such as a , firstName, lastName, myAge).
  • Now you need to assign it value. Generally, we use an equal sign (=) to assign values to a variable.

Data_Type variable_name = value;

Note :

Choosing a variable name is not a few seconds of work. You have to choose your variable name wisely. They must accurately describe their purpose in your program.

Your co-programmers should understand the purpose of your variable in your code. Sometimes you need to check your old code. If you don’t write the variable names properly, you will not be able to understand.

Example (store a String value):

Declare a variable name called channelName of type String. Then assign it the value “Programmer Kansabanik“. Then print the variable.

String channelName; // we have declared the variable
channelName = "Programmer Kansabanik"; // we have assigned value
System.out.println(channelName); // this line will print the value of your variable
You may follow another process to create a variable :
String channelName = "Programmer Kansabanik"; // we can do this directly
System.out.println(channelName); // this line will print the value of your variable.
Example (store a int value) :

Create a variable in your program to store a number value. Declare the variable called studentAge of type int and assign it the value 22. Then print the variable in your Java program.

int studentAge = 22;
System.out.println(studentAge);
Overwrite the value :

When you will assign a new value to an existing variable in your code, the new value will overwrite the previous value :

Example( change existing the value of myAge to 25 ):
int studentAge = 22; // declare the int type variable and assign a value
studentAge = 25; // overwrite the previous value
System.out.println(studentAge); // this line will print 25 instead of 22

If you don’t want others to overwrite your existing values, you can use final variables to prevent the overwriting existing values.

How to Display Variable?

We can use the println() method to display variables. Look at the code below :

int mySalary = 50000;
System.out.println(mySalary);

What is Java Identifiers?

In a Java program, we should identify all variables with unique names. These unique names are called identifiers in Java programming language.

They can be short names such as a, b, c. They can be more descriptive names such as myage , mySalary etc.

int s = 50000;
int mySalary = 50000; // this one is easy to understand

How to add variables ?

We can use plus sign (+) to add multiple variables of the same Data Type.

Example(Add two variables) :
int a = 5;
int b = 10;
int c = 20;
System.out.println(a + b + c) // Thus we can add 3 variables

Note :

I recommend you to use descriptive variable names because its easy to read and understandable. It is maintainable too.

Use of final variable in Java program

final keyword is used in different contexts. But in this post we will use final keyword to create constant variables.

If you put final keyword before declaring the variable, you can assign value only once. Its value can not be modified later in the code.

You can initialize a final variable when it is declared.

final data_type variable_name = value;

You or your co-programmers can not change the value of that variable in code. Thus it will be constant.

Look at the following code:

Example (Using a final variable):
final int studentAge = 25;
studentAge = 15; // this line will produce an error : cannot assign a value to a final variable

Example (without a final variable):
int studentAge = 25;
System.out.println(studentAge); // it'll print 25
studentAge = 15;
System.out.println(studentAge); // it'll print 15

How to Declare Many Variables

In this case, You can use a comma-separated list to declare multiple variables (more than one) of the same Data Type.

Example (Assign 3 values in the same line):
int a = 10, b = 20, c = 30; // 3 values are assigned in one line
System.out.println(a + b + c); // it will print the sum

The general rules for constructing names for variables (unique identifiers) are:

  • Variable names must begin with a letter.
  • Variable names should start with a lowercase letter and it cannot contain whitespace.
  • Variable names are case sensitive (“myVar” and “myvar” are different variables).
  • Variable names can contain letters, digits, underscores ( _ ), and dollar ( $ )signs.
  • You can not use “reserved words” (like Java keywords, such as int or boolean) as variable names.
  • Variable names can also begin with $ and _ .

In the next post I am going to talk about types of Java Variables.

Design a site like this with WordPress.com
Get started