Data Types And Identifier In Java

Introduction

Every programming language comprises various elements such as keywords, data types, variables and identifiers etc. They are the fundamental elements of a programming language. 

You may be familiar with the terms like int, char, and so on. What exactly are these? They’re known as data types. How are they put to use? What about some other data types?

Stay with us, and this article will resolve all such queries around Java Data types and Identifier.


Data Types in Java

Data types are the foundation of every programming language. A programming language is used to write programs and applications to perform some tasks. And to perform a task, the program needs data. And here comes the crust, to store that data, we need an appropriate container. 

In simple words, to store a liquid material, we cannot use sacks. Similarly, for storing data, we need to understand its type. Once the type is known, we can put it in an appropriate container. So, to define the type of data, the concept of data type came into the picture.

Let’s first understand the types of programming languages.

What are Strongly-Typed Languages?

All the modern programming languages can be classified into two categories:

  • Strongly-Typed
  • Weakly-Typed languages.

Strongly-Typed languages are the programming languages in which:

  • Every variable and every expression has a type, and every type is strictly defined. 
  • Type compatibility is tested for all assignments, whether explicit or via parameter passing in function calls.
  • There are no automated conversions of types that are incompatible.

In layman’s terms, if a language specification vigorously enforces its typing rules. Allowing only those automatic type conversions in which no information is lost. This type of language is referred to as Strongly-typed. And if not, it is referred to as Weakly typed.

Java programming language is a strongly typed language. It means that every variable must have a declared type. It is an essential factor that contributes to the safety and robustness of Java

blog banner 1

The diagram below shows the various categories and subcategories of data types in Java:

Data types in Java are categorised as primitive and non-primitive. Let’s get to know the primitive data types first.

Primitive Types

In Java, every data must be declared with a type before it is used. In simpler words, we must declare what type of data is to be stored, before assigning the value.

A primitive type can be defined as:

  • They are predefined by the programming language. 
  • They can only store single values.
  • They do not share state with other primitive values. Two variables of the reference or non-primitive type can refer to the same object. But two primitive variables cannot affect one another.

Java supports the following eight primitive data types.

1. boolean:

The data type boolean is used to represent one bit of information. It can have value, either true or false. The size of the boolean data type is machine-dependent. The boolean data types are not typecasted into any other type implicitly or explicitly.

Declaration: boolean var;
Size: 1 bit
Range of Values: either 0 or 1

Programme:

public class BoolTest {
    public static void main(String args[])
    {
        boolean var = true;
        if (b == true)
            System.out.println("Testing Boolean Data Type!!");
    }
}// The default value of boolean data type is false or 0

Output:
Testing Boolean Data Type!!

2. int: 

The int data type is a 32-bit signed two’s complement integer. Unless there is no issue with memory, the int data type is usually chosen as the default data type for integral numbers.

Declaration: int var;
Size: 4 byte
Range of values: The range of its values is -2, 147, 483, 648 to 2, 147, 483, 647 (inclusive).

Note: After Java SE 8 and later, the int data type represents an unsigned 32-bit integer, whose value ranges from  0 to 2, 147, 483, 647 (inclusive). 

3. byte:

byte data type is an 8-bit signed integer. It is used in place of the int data type when we need to save memory.

Declaration: byte var;
Size: 1 byte
Range of values: The range of its values is -128 to 127 (inclusive).

Programme:

public class ByteTest {
    public static void main(String args[])
    {
        byte var = 117 ;
        System.out.println("Printing value of byte data type:"+var);
    }
}// Assigning value more than its range will lead to an overflow

Output:
Printing value of byte data type:117

4. short:

short data type is a 16-bit signed integer. Similar to bytes, short is also used to save memory in large arrays.

Declaration: short var;
Size: 2 bytes
Range of values: The range of its values is -32,768 to 32,767 (inclusive).

5. long:

When a program needs to store large integer values. Values that are out of the range of int, then a long data type is used. The default value of long data type in Java is 0. 

Declaration: long var;
Size: 8 bytes
Range of values: The range of its values is -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).

6. float:

This data type is used to store floating-point numbers associated with the single-precision 32-bit IEEE 754 values. The default value of the float data type is 0.0.

Note: IEEE 754 is IEEE Standard for Binary Floating-Point Arithmetic.

Declaration: float var;
SIze: 4 bytes
Range of Values: float variable can hold values up to 7 decimal digits.`

7. double:

This data type is used to store floating-point numbers associated with the double-precision 64-bit IEEE 754 values. The default value of the double data type is 0.0.

Declaration: double var;
Size: 8 bytes
Range of Values: double variables can hold a value up to 16 decimal digits.

Note: The precision of a floating-point value indicates the number of digits a value can have after the decimal point.

Program to demonstrate the use of int, long, short, float, double.

public class DataTypeTest {
	public static void main(String args[])
    {
        // declaration
        int i = 100000;
        
        long l = 15000000000L;
  
        short s = 5000;
        
        // All the fractional values are by default double...
        float f = 5.75f;
  
        // for float 'f' suffix is used...
        double d = 19.99d;

        System.out.println("integer: " + i);
        System.out.println("long: " + l);
        System.out.println("short: " + s);
        System.out.println("float: " + f);
        System.out.println("double: " + d);
        
    }
}

Output:

integer: 100000
long: 15000000000
byte: 100
short: 5000
float: 5.75
double: 19.99

8. char:

The char data type is used to store a single character, letter or ASCII value. The character must be inside single quotes, like ‘A’ or ‘X’.

Declaration: char var;
Size: 2 bytes
Range of values: The range of its values is ‘\u0000’ (0) to ‘\uffff’ (65535).

Programme

public class CharTest {
    public static void main(String args[])
    {
        char var = 'B';
        System.out.println("Testing Character Data Type: "+var);
    }
}

Output:
Testing Character Data Type: B

Size of char data type in Java: 

Java uses the Unicode system, and 8 bits is insufficient to represent all Unicode characters. Hence Java uses 2 bytes for characters. In languages like C or C++, the ASCII system is used, and 8 bits represent all ASCII characters.

Non-Primitive Types

  • Unlike primitive data types, non-primitive data types are not predefined in the Java language. 
  • These data types are used to store a group of values. Examples of non-primitive data types are strings, objects, arrays, etc.  
  • When we define a variable of a non-primitive data type, it refers to a memory location where an object is stored. That’s why non-primitive data types are also known as Referenced Data types.
  • The Java programming language provides exceptional support for character strings via the java.lang.String class. By enclosing your character string in double quotes, a new String object will be created automatically.
  • The String class is not a primitive data type. We’ll probably think of it as such because of the specific support it gets from the language. 

Type Casting in Java

Typecasting is the process of assigning a value of one primitive data type to another type.

In Java, typecasting is of two types:

Widening Primitive Casting:

Converting lower data types into higher data types is called widening casting. No loss of information because we are passing a smaller size type to a larger size type.

byte ->short ->char ->int ->long ->float ->double

Program to demonstrate widening casting:

The conversion from numeric to char or Boolean data types is not done automatically. The char and Boolean data types are incompatible. In the program below, int is typecast into long and long into a float data type.

public class WideningCastingExample 
{
	public static void main(String[] args) 
	{
		int x = 7;
		//Converting the integer type into long type  
		long y = x;
		//Converting the long type into float type  
		float z = y;
		
	System.out.println("Before conversion, int value " + x);
	System.out.println("After conversion, long value " + y);
	System.out.println("After conversion, float value " + z);
	}
}

Output:
Before conversion, int value 7
After conversion, long value 7
After conversion, float value 7.0

Narrowing Primitive Casting:

Converting higher data types into lower data types is called narrowing casting. Loss of information may occur. It must be done manually by specifying the type in parentheses in front of the value.

double->float ->long ->int ->char ->short ->byte

Program to demonstrate narrowing casting:

In the following example, we have converted the double type into a long data type after that long data type is converted into the int data type.

public class NarrowingCastingExample 
{
	public static void main(String args[]) 
	{
		double d = 195.67;
		//converting double data type into long data type  
		long l = (long) d;
		//converting long data type into int data type  
		int i = (int) l;
	System.out.println("Before conversion: " + d);
		//fractional part lost  
	System.out.println("After conversion into long type: " + l);
		//fractional part lost  
	System.out.println("After conversion into int type: " + i);
	}
}

Output
Before conversion: 195.67
After conversion into long type: 195
After conversion into int type: 195

Java Tokens

Tokens are the smallest units in a program that the compiler recognises. Tokens are divided into five categories in the Java language:

  • Keywords
  • Identifiers
  • Literals or Constants
  • Operator
  • Separator

This blog will discuss keywords and identifiers.

Identifiers

A class name, method name, variable name, or label is known as identifiers in Java. Identifiers are used to identify names in programming languages.

Consider the following program:

public class Test
{
    public static void main(String[] args)
    {
        int num = 10;
    }
}

Identifiers present in the given program are

Test: The name of the class.
main: The name of a method.
String: A predefined class name.
args: A variable name.
num: A variable name.

Rules for defining identifiers

A valid java identifier must follow specific guidelines. If we don’t follow these guidelines, we’ll get a compile-time error. These rules apply to other languages as well, such as C and C++.

  1. The characters allowed for identifiers are all alphanumeric characters such as [A-Z], [a-z], [0-9]. In special characters, only $ (dollar) and _ (underscore) can be used. For example, num@ is not a valid Java identifier as it contains @ special character.
  1. Identifiers should not start with digits i.e [0-9]. For example, 7num is not a valid Java identifier.
  1. Identifiers in Java are case-sensitive. For example, num is not the same as Num identifier.
  1. There is no hard and fast rule for the length of the identifier. But to use an identifier of the optimum length (4 – 15 letters) is considered a good practice.
  1. Reserved words or Keywords can’t be used as an identifier. For example, int final = 9;  is an invalid statement as final is a reserved word. Note: There are 53 keywords in Java.
  1. There should not be any space in the identifier. For example, roll no is an invalid identifier.
  1. Using SQL keyword as an identifier is also not recommended in Java. For example, SELECT, COUNT, FROM cannot be used as identifiers.

Keywords

 Keywords are known as reserved words in programming languages. They are used to indicate predefined terms and actions in a program. As a result, these words are not permissible to be used as variable names or objects.

Java contains a list of keywords which includes the following:

abstractassert booleanbreakbyte 
casecatchcharclasscontinue
defaultdodoubleelseenum
extendsfinalfinallyfloatfor
ifimplementsimportinstanceofint
interfacelongnativenewnull
packageprivateprotectedpublicreturn
shortstaticstrictfpsuperswitch
synchronisedthisthrowthrowstransient
tryvoidvolatilewhileconst/goto*
  • Some of the keywords are obsolete in Java but still come under reserved words. For example, const and goto.
  • Some of the literals look like keywords in general but they are literals having a constant value. For example: true, false and null. Note: A Literal is a constant value that can be assigned to a variable in a program.
  • SQL keywords are also treated as reserved words, but they are not added to the list of keywords yet. 

Difference between Keywords and identifiers

Some of the differences between keywords and identifiers are given in the table below:

KeywordsIdentifiers
Keywords are predefined reserved words in programming languages.Identifiers are the names used to define terms such as variables, integers etc.
Start with a lowercase letter.It can start with an uppercase, lowercase letter or underscore.
Contains only alphabetical characters.Contains digits, alphabetical characters and special symbols.
Help in the identification of a specific property inside a program.They assist in locating the entity’s name.
No special symbol, punctuation is used.No punctuation or special symbols except underscores are used.
int, char, if, while, do, class etc. are examples of Keywordsnum1, count2, speed_car1, etc. are examples of identifier

Frequently Asked Questions

What are variables and identifiers in Java?

A variable is a container to store various types of data. And identifiers are used to identify names in programming languages. A class name, method name, variable name, or label is known as identifiers in Java.

What are data types in Java?

Data types are used to specify the type of data in programming languages.

What are the types of identifiers in Java?

Identifiers can be the name of any user-defined or built-in class, methods, variables in a program.

What are data types and variables?

Data types are used to specify the type of data stored in a variable or the parameter passed inside a function and the return value of methods in a program.

How can data be classified?

The two main categories of data types in Java are primitive or pre-defined and non-primitive or user-defined.

What are the three types of variables?

The three types of variables in Java are: Local variable, instance variable and static variable.

Key Takeaways

This article covers the basic tokens or building blocks of any programming language. Keywords, Identifiers, and Data types are the essential components of Java. 

Having read this blog on Java Data types and Identifier, you can learn more about various keywords such as static keywords or super keywords in Java.

Happy learning!

By Vaishnavi Pandey