Data Type

Data Types in Java

In Java, data types define the type and size of values that can be stored in variables. Java is a statically-typed language, which means that you need to explicitly declare the data type of a variable before using it. Java provides two main categories of data types:

  • Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
  • Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types:

Java primitive data types are the basic building blocks for data manipulation in the Java programming language. They include byte, short, int, long, float, double, char, and boolean. These data types are used to store simple values directly, without referencing any other data structures.

Java Primitive Data Types Chart:

Byte Data Type:

In Java, the byte data type is one of the eight primitive data types, and it represents an 8-bit signed integer. This means that it can hold integer values ranging from -128 to 127. The byte data type is used when you need to conserve memory or when working with data that falls within the small range of values that it can represent.

  • The byte data type is one of the primitive data types in Java. It is an 8-bit signed two’s complement integer.
  • Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127.
  • Its default value is 0.
  • The byte data type is utilized to conserve memory in large arrays where memory efficiency is of utmost importance.
  • It conserves space as a byte occupies only 1/4th of the space taken by an integer.. It can also be used in place of “int” data type.
Example:
public class ByteDataTypeExample{
    public static void main(String[] args) {
       byte num1 = 120;
       byte num2 = -127;
       System.out.println("num1 = " + num1);
       System.out.println("num2 = " + num2)
    }
}
Output:

num1= 120

num2= -127

Explanation:
  • byte num1 = 120;: Here, a variable named num1 of type byte is declared and assigned the value 120. In Java, byte is an 8-bit signed integer data type that can hold values from -128 to 127. Since 120 is within this range, it is a valid value for a byte variable.
  • byte num2 = -127;: Here, another variable named num2 of type byte is declared and assigned the value –127. Since num2 is declared as a byte, it can hold values from -128 to 127. Hence, –127 is also a valid value for this variable.
  • The System.out.println() statements are used to print the values of num1 and num2 on the console:
  • This will print: num1 = 120
  • This will print: num2 = -127
  • The output will display the values assigned to num1 and num2 as strings concatenated with the corresponding variable names.
Short Data Type:

In Java, the short data type is a 16-bit signed integer data type. It can store whole numbers in the range from -32,768 to 32,767. The short data type is used to save memory when you know that the values you are working with will fall within this range.

  • The short data type represents a 16-bit signed two’s complement integer in Java. Its value-range lies between -32,768 to 32,767 (inclusive).
  • The short data type can have values as low as -32,768 and as high as 32,767. Its default value is 0.
  • The short data type, like the byte data type, can be utilized to save memory. It is half the size of an integer, aiding in efficient memory usage.
Example:
public class ShortDataTypeExapmle{
     public static void main(String[] args) {
         short n1 = 23575;
         short n2 = 13257;
         System.out.println(n1+n2);
     }
}
Output:
36832
Explanation:
  • short n1 = 23575;: In this line, a variable named n1 of type short is declared and initialized with the value 23575. Since n1 is of type short, it can store values in the range from -32,768 to 32,767, and 23575 is within this valid range.
  • short n2 = 13257;: In this line, another variable named n2 of type short is declared and initialized with the value 13257. Like n1, n2 can also store values within the range from -32,768 to 32,767, and 13257 is a valid value for a short variable.
  • System.out.println(n1 + n2);: In this line, you are performing the addition operation on n1 and n2. Since both n1 and n2 are of type short, the addition will be performed as a short arithmetic operation.
  • However, here comes the important part: The result 36832 exceeds the maximum value that a short data type can hold, which is 32767. When the result of the addition exceeds the valid range for a short, an overflow occurs.
  • In Java, when an overflow occurs for short, the value wraps around to the minimum value (-32,768) and continues from there. So, 36832 – 32768 is equal to 4074. The value 4074 is the result of the overflow.
  • This behavior is a consequence of how two’s complement representation works for signed integer types like short in Java. Always be cautious of potential overflows when working with data types that have limited ranges. If the result might exceed the valid range, consider using a larger data type, such as int or long, to avoid unexpected behavior.
Int Data Type:

In Java, the int data type is a 32-bit signed integer data type. It can store whole numbers in the range from -2,147,483,648 to 2,147,483,647. The int data type is one of the most commonly used data types for representing integers in Java due to its wide range of values.

  • The int data type is a 32-bit signed two’s complement integer. From -2147483648 to -2147483647, entire numbers can be stored in an int data type.
  • It’s minimum value is – 2,147,483,648 and maximum value is 2,147,483,647.
  • It’s default value is 0.
Example:
public class IntDataTypeExample{
     public static void main(String[] args) {
         int firstNumber;
         firstNumber = 12333468;
         int secondNumber;
         secondNumber = 27;
         System.out.println("secondNumber = " + secondNumber);

         System.out.println("firstNumber = " + firstNumber);
     }
}
Output:

secondNumber = 27

firstNumber = 12333468

Explanation:
  • int firstNumber;: In this line, a variable named firstNumber of type int is declared but not initialized. The variable is created and will be assigned a value later.
  • firstNumber = 12333468;: In this line, the variable firstNumber is assigned the value 12333468. This value is within the valid range for an int data type, which can store values from -2,147,483,648 to 2,147,483,647.
  • int secondNumber;: In this line, another variable named secondNumber of type int is declared but not initialized. Similar to firstNumber, it is created and will be assigned a value later.
  • secondNumber = 27;: In this line, the variable secondNumber is assigned the value 27. This value is well within the valid range for an int data type.
  • System.out.println(“secondNumber = ” + secondNumber);: This line prints the value of secondNumber on the console. The + operator is used for string concatenation, and it combines the string literal “secondNumber = “ with the value of the secondNumber variable (27). So, the output of this line will be: secondNumber = 27.
  • System.out.println(“firstNumber = ” + firstNumber);: This line prints the value of firstNumber on the console. It is similar to the previous line but with firstNumber. The output of this line will be: firstNumber = 12333468.
  • This output confirms that both variables, firstNumber and secondNumber, were correctly assigned their respective values and displayed using the System.out.println() statements.
Long Data Type:

A 64-bit signed integer data type is the Java equivalent of a long data type. It can store whole numbers in the range from approximately -9.2 quintillion (-9,223,372,036,854,775,808) to 9.2 quintillion (9,223,372,036,854,775,807). The long data type allows you to work with larger integer values than the int data type, but it uses more memory to store the values.

  • The long data type is a 64-bit two’s complement integer. It’s value-range lies between -9,223,372,036,854,775,808(-2^63)
  • To 9,223,372,036,854,775,807(2^63 -1)(inclusive).9,223,372,036,854,775,808 is its greatest value, while 9,223,372,036,854,775,808 is its minimum value.
  • It’s default value is 0.
  • The long data type is used when you need to store larger whole numbers than those provided by the int data type.
Example:
public class LongDataTypeExample{
     public static void main(String[] args) {
          long n1 = 23575234579800L;
          long n2 = 1325734567 ;
          System.out.println("Result is: " + (n1 -n2));
     }
}
Output:
Result is: 23573908845233
Explanation:
  • long n1 = 23575234579800L;: In this line, a variable named n1 of type long is declared and initialized with the value 23575234579800L. The ‘L’ at the end of the literal value indicates that it is of type long.
  • long n2 = 1325734567;: In this line, another variable named n2 of type long is declared and initialized with the value 1325734567. The absence of ‘L’ at the end of the literal value is acceptable because the value 1325734567 fits within the range of int as well as long.
  • System.out.println(“Result is: ” + (n1 – n2));: In this line, the subtraction operation (n1 – n2) is performed. Since both n1 and n2 are of type long, the subtraction will be carried out using long arithmetic.
  • The result of the subtraction, 23575233254033, is a long value. To print this result along with the message “Result is: “, the + operator is used for string concatenation. The numeric result is converted to a string, and then combined with the message to be displayed on the console.
  • This output represents the result of the subtraction of n2 from n1, with the result being a long value.
Float Data Type:

In Java, the float data type is a single-precision 32-bit floating-point data type. It is used to represent decimal numbers with fractional parts. The float data type provides a good balance between precision and memory usage, making it suitable for scenarios where a wider range of values with reasonable precision is required.

  • The float data type represents a single-precision 32-bit IEEE 754 floating point in Java.
  • It’s value range is unlimited. It is advisable to use a float (instead of double) when memory conservation is crucial in large arrays of floating-point numbers.
  • The float data type, however, should never be used for precise values, such as currency.
  • It’s default value is 0.0F.
Example:
public class FloatDataTypeExample{
     public static void main(String[] args) {
          float salary1 = 45.98F;
          int salary2 = 789;
          System.out.println("total: " + (salary1 + salary2));
     }
}
Output:
total: 834.98
Explanation:
  • float salary1 = 45.98F;: In this line, a variable named salary1 of type float is declared and initialized with the value 45.98F. The ‘F’ at the end of the literal value indicates that it is of type float.
  • int salary2 = 789;: In this line, another variable named salary2 of type int is declared and initialized with the value 789. The value 789 is within the valid range for an int data type.
  • System.out.println(“total: ” + (salary1 + salary2));: In this line, the addition operation (salary1 + salary2) is performed. Since salary1 is of type float and salary2 is of type int, the addition will be performed as a floating-point addition.
  • The result of the addition, 834.98, is a float value. To print this result along with the message “total: “, the + operator is used for string concatenation. The numeric result is converted to a string, and then combined with the message to be displayed on the console.
  • This output represents the total sum of salary1 and salary2, with the result being a float value. The floating-point value 45.98 was added to the integer value 789, resulting in a floating-point value 834.98.
Double Data Type:

In Java, the double data type is a double-precision 64-bit floating-point data type. It is used to represent decimal numbers with a higher range and more significant digits of precision compared to the float data type. The double data type is suitable for scenarios where a wide range of values with increased precision is required.

  • The double data type can store fractional numbers from 1.7e−308 to 1.7e+308..
  • It’s value range is unlimited. It is typically employed for storing decimal values, similar to the float data type.
  • The double data type should also never be used for precise values, such as currency.
  • It’s default value is 0.0d.
Example:
public class DoubleDataTypeExample{
     public static void main(String[] args) {
          double saalry = 29.99d;
          System.out.println("salary  is: " + saalry);
     }
}
Output:
salary is: 29.99
Explanation:
  • double salary = 29.99d;: In this line, a variable named salary of type double is declared and initialized with the value 29.99d. The ‘d’ at the end of the literal value indicates that it is of type double. While the ‘d’ suffix is not strictly necessary for double literals, it is a good practice to include it to make the code more explicit and avoid any potential confusion.
  • System.out.println(“salary is: ” + salary);: In this line, the value of the salary variable is printed to the console. The + operator is used for string concatenation, which means the numeric value of salary will be converted to a string, and then combined with the message “salary is: “.
  • The value of the salary variable is 29.99. When this value is combined with the message “salary is: “, it forms the following string: salary is : 29.99.
  • This is the output that will be printed on the console. It displays the message “salary is: “ followed by the value of the salary variable, which is 29.99.
  • In summary, the code initializes a double variable named salary with the value 29.99 and then prints the message “salary is: “ along with the value of the salary variable on the console. The output will be the concatenation of the message and the value, displaying salary is: 29.99.
Char Data Type:

In Java, the char data type is used to represent single characters. It is a 16-bit unsigned data type that can store any single Unicode character. The char data type is used to handle individual characters, such as letters, digits, punctuation marks, and other special characters.

  • The char data type is used to store a single character.
  • It’s value-range lies between ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive).
  • The character needs to have single quotes, such as “A” or “c,” all around it.
Example:
public class calculation {
      public static void main(String[] args) {
        char ch1;
        char ch2;
          
        ch1 = 82;
        ch2 = 'H';
        System.out.println("The value of ch1 and ch2");
        System.out.println(ch1 + " " + ch2);
     }
}
Output:

the value of ch1 and ch2

R H

Explanation:
  • char ch1;: In this line, a variable named ch1 of type char is declared but not initialized. The variable is created but does not have any value assigned to it yet.
  • char ch2;: In this line, another variable named ch2 of type char is declared but not initialized. Similar to ch1, it is created but does not have any value assigned to it yet.
  • ch1 = 82;: In this line, the variable ch1 is assigned the decimal value 82. In Java, the char data type is a numeric data type that can be initialized using either a character literal or a numeric value representing the Unicode code point of the character. In this case, the decimal value 82 corresponds to the Unicode code point of the character ‘R’.
  • ch2 = ‘H’;: In this line, the variable ch2 is assigned the character literal ‘H’. In Java, character literals are enclosed in single quotes, and ‘H’ represents the character ‘H’.
  • System.out.println(“The value of ch1 and ch2”);: This line prints the message “The value of ch1 and ch2″ on the console.
  • System.out.println(ch1 + ” ” + ch2);: This line prints the values of ch1 and ch2 on the console, separated by a space. However, there’s a subtle issue with this line.
  • When you use the + operator between ch1 and the strings, it performs a numeric addition because ch1 is of type char, which is a numeric data type that represents Unicode code points. Therefore, the line is effectively performing the following numeric addition:
  • The numeric addition results in the decimal value 82, and then it is concatenated with the string ” H“. The decimal value 82 corresponds to the Unicode code point of the character ‘R’.
  • It displays the message “The value of ch1 and ch2” followed by the numeric value 82 and the character ‘H’, all separated by a space.
Boolean Data Type:

In Java, the boolean data type represents a single bit of information that can have one of two values: true or false. It is used to store boolean values, which are used in conditional expressions and logical operations. The boolean data type is fundamental for controlling the flow of a program based on certain conditions.

  • We know that java has eight data types. Boolean is one of them. This data type returns only true or false.
  • Boolean values are mostly used for conditional testing.
Example:
public class BooleanDataTypeExample{
     public static void main(String[] args) {
          boolean isJavaFun = true;
          boolean isJavaHard = false;
          System.out.println("is java fun? " +isJavaFun);
          System.out.println("is java hard? " +isJavaHard);
     }
}
Output:

is java fun? true

is java hard? false

Explanation:
  • boolean isJavaFun = true;: In this line, a variable named isJavaFun of type boolean is declared and initialized with the value true. The variable isJavaFun represents a boolean condition, and its value is set to true, indicating that “Java is fun.”
  • boolean isJavaHard = false;: In this line, another variable named isJavaHard of type boolean is declared and initialized with the value false. The variable isJavaHard represents a boolean condition, and its value is set to false, indicating that “Java is not hard.”
  • System.out.println(“is java fun? ” + isJavaFun);: This line prints the message “is java fun? ” on the console, followed by the value of the isJavaFun variable. The + operator is used for string concatenation, which combines the message with the boolean value. Since the value of isJavaFun is true, it will be converted to the string “true“, and the final output will be “is java fun? true“.
  • System.out.println(“is java hard? ” + isJavaHard);: This line prints the message “is java hard? ” on the console, followed by the value of the isJavaHard variable. Like before, the + operator is used for string concatenation, and since the value of isJavaHard is false, it will be converted to the string “false“. The final output will be “is java hard? false”.
  • This output displays the results of the boolean conditions stored in the variables isJavaFun and isJavaHard, along with the corresponding messages. It tells us that “Java is fun” (isJavaFun is true) and “Java is not hard” (isJavaHard is false).

Java Non-Primitive Data Types:

Non-primitive data types, also known as reference data types or object types, are data types in programming languages that do not directly store values but instead store references (memory addresses) to objects or instances of classes. These data types are used to create complex data structures and represent more sophisticated data, as they can hold a collection of values or a combination of different data types.

In contrast to primitive data types, which are built-in and represent simple values, non-primitive data types are defined by the programmer through classes or interfaces. Instances of non-primitive data types are objects, and they have methods and properties associated with them.

Common examples of non-primitive data types:
  1. Arrays: A collection of elements of the same data type, indexed by integers.
  2. Strings: A group of characters used to represent text in most cases.
  3. Classes: Custom data types created by the programmer to encapsulate data and behavior.
  4. Interfaces: A set of method signatures that define a contract for implementing classes.
  5. Collections: Data structures that store and manage groups of objects, like lists, sets, maps, etc.

Here’s an example in Java to demonstrate a non-primitive data type, which is an array:

Example:
public class NonPrimitiveDataTypesExample {
    public static void main(String[] args) {
        // Array (Non-primitive data type)
        int[] numbers = {1, 2, 3, 4, 5};

        // String (Non-primitive data type)
        String message = "Hello, Java";

        // Accessing and printing array and string elements
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        System.out.println();
        System.out.println(message);
    }
}
Output:

1 2 3 4 5

Hello, Java

Explanation:
  • In this example, numbers is an array of integers, and message is a string. These are non-primitive data types because they are not directly storing the values themselves but instead are holding references to objects (the array and the string objects).
  • Non-primitive data types are essential for building complex data structures and implementing object-oriented programming concepts. They allow programmers to create custom data types, encapsulate data and behavior within objects, and design more sophisticated and flexible applications.
Visited 1 times, 1 visit(s) today

Comments are closed.

Close