Data types in Java

Every variable in Java needs to be declared with the help of a data type. For example, whether a variable can store only numbers or can also store other symbols as its value.

Common data types

The following are the commonly used data types in Java:

  • int: Integer values (5, 0, -1, etc.)
  • char: Character values (a, 0, $, etc.)
  • double: Floating-point values (2.33333, -2500.001, 20.0, etc.)
  • boolean: Boolean values (true, false)
  • String: String values (educative, java, k2, etc.)

Variable declaration

The Java language requires the programmer to tell the data type of the variables used in a program. The following code demonstrates the declaration of variables to input their values with suitable prompts and to display them with suitable labels:

import java.util.Scanner; 
class Test
{
    public static void main(String[] args) 
    {
        Scanner myObj = new Scanner(System.in);
        String str; // Declaring a variable of type string
        int number; // Declaring a variable of type integer
        char alphabet='0';
        double real; // Declaring a variable of type double
        boolean isTrue; // Declaring a variable of type bool

        System.out.println("Please input a word: ");
        str = myObj.nextLine();

        System.out.println("Please input an alphabet: ");
        alphabet = myObj.nextLine().charAt(0);
        
        System.out.println("Please input an integer: ");
        number = myObj.nextInt();

        System.out.println("Please input a real number: ");
        real = myObj.nextDouble();

        System.out.println("Please input a boolean value true or false: ");
        isTrue = myObj.nextBoolean();

        System.out.println("The value of each variable is enclosed in brackets: ");
        System.out.println("str (" + str + ")");
        System.out.println("number (" + number + ")");
        System.out.println("alphabet (" + alphabet + ")");
        System.out.println("fraction (" + real + ")");
        System.out.println("isTrue (" + isTrue + ")");
    }
}
Variable declaration

Explanation

  • Lines 7–11: In these lines, the variables are declared so that they can be used to store values input by the user. There are different types of variables that are declared:
    • str is a variable of the string type.
    • number is a variable of the int type.
    • real is a variable of the double type.
    • isTrue is a variable of the bool type.
    • letter is a variable of the char type.
  • Lines 13–26: These lines output a prompt using System.out.println() and demand input from the user using nextLine() and then store them in the relevant variable.
  • Lines 28–33: These lines output the variable name as a label and print the value enclosed in a bracket.

The following code demonstrates the declaration of the variables without inputting their values from the user:

Press + to interact
class Test
{
public static void main(String[] args)
{
String str; // Declaring a variable of type string
int number; // Declaring a variable of type integer
char alphabet; // Declaring a variable of type char
double real; // Declaring a variable of type double
boolean isTrue; // Declaring a variable of type bool
System.out.println("The value of each variable is enclosed in brackets: ");
System.out.println("str (" + str + ")");
System.out.println("number (" + number + ")");
System.out.println("alphabet (" + alphabet + ")");
System.out.println("fraction (" + real + ")");
System.out.println("isTrue (" + isTrue + ")");
}
}

In the code above, lines 5–9 declare the variables str, number, alphabet, real, and isTrue, with the String, int, char, double, and boolean data types, respectively. When we execute the code, we see this error “variable might not have been initialized.” This shows that in Java programs, it is essential to assign some value to the variable before using it.

Variable initialization

Storing a value to a variable at the time of its declaration is called initialization. The following code demonstrates the initialization of the variables in Java:

Press + to interact
class Test
{
public static void main(String[] args)
{
int persons = 5; // Defining a variable of type int to store the number of persons
double totalWeight = 350.6; //Defining a variable of type float to store the total weight of 5 persons
char team = 'A'; // Defining a variable of type character
String status = "winner"; //Defining a variable of type str to store the team status
boolean flag = true; // Defining a variable of type boolean
System.out.println("Total weight of " + persons + " persons of the " + status + " team " + team + " is: " + totalWeight + ", and" +
" the value of flag is: " + flag);
}
}

In the code above, we have initialized all the variables to avoid the garbage values and to ensure that a known value is stored in them.

Operations depend on the data type

The data type also tells which operations are permissible on a specific piece of data and indicates the semantics (or meaning) of those operations. The following code demonstrates the semantics of the + operation on various data types along with declaring two or more variables in a single statement:

Press + to interact
class Test
{
public static void main(String args[])
{
int a = 5, b = 7, sum1 = 0; // Defining three variables on a single line
sum1 = a + b; // Sum of a and b
System.out.println("The sum of integers: " + sum1);
double e = 3.2, f = 1.5; // Defining two variables on a single line
double sum2 = e + f; // Sum of e and f
System.out.println("The sum of doubles: " + sum2);
String c = "5", d = "7"; // Defining two strings on a single line
String result = c + d; // Concatenates c and d, to store in result
System.out.println("The concatenation of strings: " + result);
}
}

We can declare multiple variables as a comma-separated list in a single statement, as shown in line 5. Each variable can have a separate initial value.

Operators in Java

Like any other programming language, Java supports several types of operators. We have already seen the assignment operator, =, that assigns a value to a variable in our programs. The following are various forms of the assignment operator:

Press + to interact
class Test
{
public static void main(String args[])
{
int a, b;
a = b = 5; // Cascaded assignment
System.out.println("a = " + a + " \nb = " + b);
}
}

Explanation

  • Line 5: We declare two variables, a and b.
  • Line 6: We assign 5 to both a and b. This assignment syntax is called cascaded or chained assignment.
  • Line 7: We output a string, a = and then print the value stored in variable a i.e., 5. We output a string b = using \n so that it prints b on a new line and then the value stored in variable b, i.e., 5.

Commonly used operators

There are several other commonly used operators in Java, including:

  • Arithmetic operators: These are used for arithmetic operations (addition, subtraction, multiplication, etc.).

  • Comparison operators: These are used in conditional expressions (less than, greater than, etc.) .

  • Logical operators: These are used to combine conditional expressions (and, or, not).

  • Compound assignment operators: These are the combinations of arithmetic and assignment operators.

Arithmetic Operators

Operator

Description

Syntax

Results

x=7 and y=4

+

Addition: Adds two operands

x + y

11

-

Subtraction: Subtracts two operands

x - y

3

*

Multiplication: Multiplies two operands

x * y

28

/

Integer division: Divides the first operand by the second and gives an integer quotient because both operands are integers

x / y

1

/

Non-integer division: This divides the first operand by the second and gives a floating-point quotient. A quotient is a floating-point number when the dividend or the divisor, or both are floating-point numbers.

x / 4.0

1.75

%

Modulo: Returns the remainder when the first operand is divided by the second

x % y

3

++

Increment: Updates the variable with the value that is one more than the already stored value

x++

8

--

Decrement: Updates the variable with the value that is one less than the already stored value

x--

6

Comparison Operators

Operator

Description

Syntax

Results

x=7 and y=4

>

Greater than: True if the left operand is greater than the right

x > y

True

<

Less than: True if the left operand is less than the right

x < y

False

==

Equal to: True if both operands are equal

x == y

False

!=

Not equal to: True if both operands are not equal

x != y

True

>=

Greater than or equal to: True if the left operand is greater than or equal to the right

x >= y

True

<=

Less than or equal to: True if the left operand is less than or equal to the right

x <= y

False

Logical Operators

Operator

Description

Syntax

Results

x=7 and y=4

&&

Logical AND: True if both the operands are true

x > 4 && y > 4

False

||

Logical OR: True if either of the operands is true

x > 4 || y > 4

True

!

Logical NOT: True if the operand is false

! (x > 4)

False

Compound Assignment Operators

Operator

Description

Syntax

Results

x=7 and y=4

+=

Add and assign: Add the right-side operand with the left-side operand and then assign the result to the left operand (x = x + y)

x += y

x = 11

-=

Subtract and assign: Subtract the right-side operand from the left-side operand, and then assign the result to the left operand (x = x - y)

x -= y

x = 3

*=

Multiply and assign: Multiply the right-side operand with the left-side operand, and then assign the result to the left operand (x = x * y)

x *= y

x = 28

/=

Divide and assign: Divide the left operand with the right operand, and then assign it to the left operand (x = x / y)

x /= y

x = 1

%=

Modulo and assign: Take modulo after dividing the left operand with the right operand and, then assign the result to the left operand (x = x % y)

x %= y

x = 3

Square root and power

There are some operations in mathematics that are difficult to replicate in Java programs by using symbols, for example, calculating the power or the square root of a number. In math, the power of xx is represented as xnx^n and the square root is represented as x\sqrt x. However, Java enables its users to perform these operations in the following way:

Press + to interact
class Test
{
public static void main(String args[])
{
double a, b;
a = Math.pow(25, 2);
b = Math.sqrt(25);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}

Note: We have to add Math at line 6–7 to allow the use of Math operations, pow() and sqrt().

Explanation:

  • Line 5: We declare two variables of the double type.

  • Line 6: We performs the pow() operation and store 25225^2 as the result in a.

  • Line 7: We performs the sqrt() operation and store the square root of 25\sqrt {25} as the result in b.

  • Line 8: We output the string, a =, and then print the value stored in variable a, i.e., 625.

  • Line 9: We output the string, b =, and then print the value stored in the variable b, i.e., 5.

Get hands-on with 1300+ tech skills courses.