Java - Data Types and Variables

Data Types

A data type in Java is a type of data that can be stored in a variable. Java has two categories of data types:

1. Primitive Data Types:

Java has eight primitive data types that are built into the language. These include:

  • byte: A byte is an 8-bit signed integer, which has a minimum value of -128 and a maximum value of 127.
  • short: A short is a 16-bit signed integer, which has a minimum value of -32,768 and a maximum value of 32,767.
  • int: An int is a 32-bit signed integer, which has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647.
  • long: A long is a 64-bit signed integer, which has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807.
  • float: A float is a 32-bit floating-point number.
  • double: A double is a 64-bit floating-point number.
  • char: A char is a 16-bit Unicode character.
  • boolean: A boolean can have only two values: true or false.

2. Non-Primitive Types:

Non-primitive data types are also known as reference types. Unlike primitive data types, which hold the actual data values, non-primitive data types are used to store references to objects in memory.

  • Strings

    Strings are sequences of characters and are commonly used to represent text. They are considered non-primitive because they are implemented as objects in Java.

    
                        String name = "John Doe";
                    
  • Arrays

    Arrays are objects that can hold multiple values of the same type. They allow you to store and manipulate collections of data.

    
                        int[] numbers = {1, 2, 3, 4, 5};
                    
  • Classes

    Classes are user-defined data types that encapsulate variables (known as instance variables) and methods. They serve as blueprints for creating objects.

    
                        class Person {
                            String name;
                            int age;
                        }
                        
                        Person person1 = new Person();
                        person1.name = "John";
                        person1.age = 25;
                        
                    
  • Lists

    Lists are part of the Java Collection Framework and provide dynamic arrays, allowing you to store and manipulate a collection of elements. They are more flexible than arrays since they can grow or shrink dynamically.

    
                        import java.util.ArrayList;
    
                        ArrayList<String> fruits = new ArrayList<>();
                        fruits.add("Apple");
                        fruits.add("Orange");
                        fruits.add("Banana");
    
                        System.out.println(fruits);
                    
  • Map

    Maps are key-value pairs where each key is unique, and each key is associated with a value. They are useful for storing and retrieving data using a specific identifier or key.

    
                        import java.util.HashMap;
    
                        HashMap<String, Integer> studentScores = new HashMap<>();
                        studentScores.put("John", 85);
                        studentScores.put("Emily", 92);
                        studentScores.put("David", 78);
    
                        System.out.println(studentScores.get("John"));
                    

Variables

In Java, a variable is a named location in memory that is used to store data. A variable must be declared before it can be used. The syntax for declaring a variable in Java is as follows:


            data_type variable_name;
        

For example, to declare an integer variable called myNumber, we would use the following code:


            int myNumber;         
        

Once a variable is declared, it can be assigned a value using the assignment operator =. For example:


            myNumber = 42;         
        

We can also declare and initialize a variable in one line of code, like this:


            int myNumber = 42;         
        

Variables can be used in expressions, and their values can be updated as needed. For example:


            int x = 5;
            int y = 7;
            int sum = x + y; // sum is now 12
            x = 10;
            sum = x + y; // sum is now 17        
        

Java variables are case-sensitive, which means that myVariable and myvariable are two different variables.

Another example of declaring and initializing a variable:


            class Variables {
                public static void main(String[] args) {
                    String name = "John Doe";
                    int age = 30;
                    double height = 1.46;
                    char gender = 'M';
                    boolean member = true;

                    System.out.println("Name: " + name);
                    System.out.println("Age: " + age);
                    System.out.println("Height: " + height);
                    System.out.println("Gender: " + gender);
                    System.out.println("Member: " + member);
                }
            }
        

Output:


            Name: John Doe
            Age: 30
            Height: 1.46
            Gender: M
            Member: true
        

It's important to note that variables have a scope, which determines where they can be accessed in a program. Variables declared within a method are only visible within that method. Variables declared outside of a method (but within a class) are visible to all methods in the class.


Constants

A constant in Java is a value that cannot be changed during the execution of a program. It is also referred to as an immutable value. Constants are useful for storing values that are fixed and known in advance, such as mathematical constants or configuration settings.

In Java, constants are typically declared using the final keyword. The final keyword indicates that the value of the variable cannot be modified once it is assigned. By convention, constant names are written in uppercase letters, separated by underscores for readability.

Here's an example of declaring a constant in Java:


            final double PI = 3.14159;
            final int MAX_VALUE = 100;
            final String GREETING = "Hello";
        

In this example, PI, MAX_VALUE, and GREETING are constants with their respective data types.


Operators

Operators in Java are symbols or keywords that perform specific operations on operands (variables, constants, or expressions). They allow you to manipulate values and perform calculations in your programs. Java provides a wide range of operators, including arithmetic, assignment, comparison, logical, and more.

Let's take a closer look at some commonly used operators:

  1. Arithmetic Operators
    • + Addition
    • - Subtraction
    • * Multiplication
    • / Division
    • % Modulus (remainder)
  2. Assignment Operators:
    • = Assigns a value
    • += Adds and assigns a value
    • -= Subtracts and assigns a value
    • *= Multiplies and assigns a value
    • /= Divides and assigns a value
    • %= Modulus and assigns a value
  3. Comparison Operators:
    • == Equal to
    • != Not equal to
    • > Greater than
    • < Less than
    • >= Greater than or equal to
    • <= Less than or equal to
  4. Logical Operators:
    • && Logical AND
    • || Logical OR ! Logical NO
  5. Increment/Decrement Operators:
    • ++ Increment by 1
    • -- Decrement by 1

Now, let's see some examples of using operators in Java:


            class Operators{
                public static void main(String[] args){
                    int x = 10;
                    int y = 5;
                    int sum = x + y;
                    int difference = x - y;
                    int product = x * y;
                    int quotient = x / y;
                    int remainder = x % y;
                    
                    boolean isEqual = (x == y);
                    boolean isGreaterThan = (x > y);
                    
                    int incrementByOne = x++;
                    int decrementByOne = y--;
                    
                    boolean logicalResult = (x > y) && (y != 0);
                    boolean logicalNegation = !(x > y);
                    
                    System.out.println("The sum is :" + sum);
                    System.out.println("The difference is :" + difference);
                    System.out.println("The product is :" + product);
                    System.out.println("The quotient is :" + quotient);
                    System.out.println("The remainder is :" + remainder);
                    System.out.println("x is equal to y :" + isEqual);
                    System.out.println("x is greater than y :" + isGreaterThan);
                    System.out.println("x increment by one :" + incrementByOne);
                    System.out.println("y decrement by one :" + decrementByOne);
                }
              }
        

As you can see, operators play a vital role in performing computations, making decisions, and manipulating data in Java programs.

Constants and operators often go hand in hand in Java programming. You can use constants alongside operators to perform calculations, make comparisons, and control the flow of your programs. Constants provide fixed values, while operators allow you to manipulate those values to produce desired results.

Here's an example that demonstrates the use of constants and operators in Java:


            final double PI = 3.14159;
            int radius = 5;
            double area = PI * radius * radius;
            boolean isCircleLarge = (area > 50.0);
        

In this example, we declare the constant PI with a value of 3.14159. We then declare a variable radius and assign it a value of 5. We use the arithmetic operator * to multiply the value of PI, radius, and radius to calculate the area of a circle. Finally, we use the comparison operator > to check if the area is greater than 50.0 and store the result in the isCircleLarge variable.

Constants provide a way to give meaningful names to fixed values, making your code more readable and maintainable. Operators enable you to perform various computations and comparisons, allowing your programs to be dynamic and responsive.