dsa

Java Data Types

In this tutorial, you will learn about variables, how to create them, and different data types that Java programming language supports for creating variables.


Java Variables

A Java variable is a piece of memory that can contain a data value. It is the basic unit of storage in a program. A variable is a name given to a memory location. A variable thus has a data type.

How to declare variables in Java?

The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.
In Java, all the variables must be declared before use.

In the code example below,
the main() method contains the declaration of a single integer variable named number. The value of the integer variable is first set to 10, and then 20 is added to the variable afterwards.

// Program                
public class MyClass {
    public static void main(String[] args) {
        int number = 10;
        number = number + 20;
        System.out.println( number ); 
    }
}
Types of variables

A Class Variables(static field)is a variable that belongs to a class. A static field has the same value for all objects that access it. Static fields are also called class variables. Static fields are also covered in more detail in the text on Java fields.

A Instance Variables(non-static field) is a variable that belongs to an object. Objects keep their internal state in non-static fields. Non-static fields are also called instance variables, because they belong to instances (objects) of a class. Non-static fields are covered in more detail in the text on Java fields.

A Local Variable is a variable declared inside a method. A local variable is only accessible inside the method that declared it. Local variables are covered in more detail in the text on Java methods.

A Parametes is a variable that is passed to a method when the method is called. Parameters are also only accessible inside the method that declares them, although a value is assigned to them when the method is called. Parameters are also covered in more detail in the text on Java methods.


Rules for Naming Variables in Java

Java programming language has its own set of rules and conventions for naming variables. Here's what you need to know:

  • Variables in Java are case-sensitive.
  • A variable's name is a sequence of Unicode letters and digits. It can begin with a letter,$ or _. However, it's a convention to begin a variable name with a letter. Also, variable names cannot use whitespace in Java.
  • When creating variables, choose a name that makes sense. For example, score, number, level makes more sense than variable names such as s, n, and l.
  • If you choose one-word variable names, use all lowercase letters. For example, it's better to use number rather than NUMBER, or nUMBER.
  • If you choose variable names having more than one word, use all lowercase letters for the first word and capitalize the first letter of each subsequent word. For example, smallNumber.


  • Java Data Types

    A variable takes up a certain amount of space in memory. How much memory a variable takes depends on its data type. As explained in the text about Java variables, each variable in Java has a data type. Data types into two groups:
    Primitive data types
    Object references


    A variable of a primitive data type contains the value of the variable directly in the memory allocated to the variable. For instance, a number or a character.
    A variable of an object reference type is different from a variable of a primitive type. A variable of an object type is also called a reference. The variable itself does not contain the object, but contains a reference to the object. The reference points to somewhere else in memory where the whole object is stored. Via the reference stored in the variable you can access fields and methods of the referenced object. It is possible to have many different variables reference the same object. This is not possible with primitive data types.


    Java Primitive Data Types

    Primitive data are only single values and have no special capabilities.
    There are 8 primitive data types:

    1. BOOLEAN : boolean data type represents only one bit of information either true or false, but the size of boolean data type is virtual machine-dependent. Values of type boolean are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.
       
      // Java program to demonstrate boolean data type 
      class Codemistic { 
          public static void main(String args[]) 
          { 
              boolean b = true; 
              if (b == true) 
                  System.out.println("Codemistic"); 
          } 
      }
                         
      Output:Codemistic
                   
    2. BYTE: The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving memory in large arrays.
    3. SHORT: The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually matters.
    4. INT: It is a 32-bit signed two’s complement integer.
    5. LONG: The long data type is a 64-bit two’s complement integer.
    6. FLOAT: The float data type is a single-precision 32-bit IEEE 754 floating point. Use a float (instead of double) if you need to save memory in large arrays of floating point numbers.
    7. DOUBLE: The double data type is a double-precision 64-bit IEEE 754 floating point. For decimal values, this data type is generally the default choice.
    8. CHAR: The char data type is a single 16-bit Unicode character.

    EXAMPLE:

    
    // Java program to demonstrate 
    // primitive data types in Java 
      
    class Codemistic { 
        public static void main(String args[]) 
        { 
            char a = G; // declaring character                              
            // Integer data type is generally 
            // used for numeric values 
            int i = 89; 
            // use byte and short 
            // if memory is a constraint
            byte b = 4;
            // this will give error as number is 
            // larger than byte range 
            // byte b1 = 7888888955; 
    
            short s = 56; 
    
            // this will give error as number is 
            // larger than short range 
            // short s1 = 87878787878; 
    
            // by default fraction value 
            // is double in java 
            double d = 4.355453532; 
      
            // for float use 'f' as suffix 
            float f = 4.7333434f; 
      
            System.out.println("char: " + a); 
            System.out.println("integer: " + i); 
            System.out.println("byte: " + b); 
            System.out.println("short: " + s); 
            System.out.println("float: " + f); 
            System.out.println("double: " + d);
            }
        }
                                       
                       
    Output:
                char: G
                integer: 89
                byte: 4
                short: 56
                float: 4.7333436
                double: 4.3554535326 
    Non-primitive data types

    Non-primitive data types are called reference types because they refer to objects. It will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. They are strings, objects, arrays, etc.
    Non-primitive, or reference data types, are the more sophisticated members of the data type family. They don't store the value, but store a reference to that value. Instead of partNumber 4030023, Java keeps the reference, also called address, to that value, not the value itself.

    Reference types can be a class, interface, or array variable. Remember that a class is a set of plans for a given object. There are thousands of tree objects, but the parent set of plans would belong in the tree class. Variables can exist inside the tree class, such as height or tree type. These are reference variables.
    An array is a single object that contains multiple values of the same type. We could have declared our integer for partNumbers as an array to hold a given number of partNumbers in a single object


    Table of primitive data types
    Type Descripton Default Size Examplem Literals Range of value
    boolean true or false false 1 bit true,false true,false
    byte twos complement integer 0 8 bits none -128 to 127
    char unicode character \u0000 16 bits 'a','ond7nk','\76gtbs' char representationof ASCll value 0 to 255
    short twos complement integer 0 16 bits (none) -32,768 to 32,767
    int twos complement integer 0 32 bits -2,-1,0,1,2 -2,147,483,648 to 2,147,483,648
    long twos complement integer 0 64 bits -2L,-1L,0L,1L,2L -9,223,372,036,854,776,808 to 9,223,372,036,854,776,808
    float IEEE 754 floating point 0.0 32 bits 1.23e100f upto 7 decimal digits
    double IEEE 754 floating point 0.0 64 bits 1e1d upto 18 decimal digits