Introduction to Java Programming.

Chapter 1: Introduction 

1.8 Storing Information: Java Data Types

In programming, a data type classifies the type of value a variable can hold. It specifies the size and type of values that can be stored in a memory location, as well as the operations that can be performed on those values. Understanding Java’s data types is fundamental to writing effective and efficient code. Java categorizes data types into two main groups: Primitive Data Types and Non-Primitive (or Reference) Data Types.

1.8.1 Primitive Data Types

Primitive data types are the most basic data types available in Java. They are predefined by the language and named by a keyword. Java’s primitive data types are stored directly in memory (on the stack for local variables, or within an object’s memory on the heap for instance/static variables) and contain the actual value.

Numeric Types |: These are used to store numerical values. They are further divided into integer types and floating-point types.

Integers: Used for whole numbers (numbers without a fractional component).

      byte:

      Size: 8-bit signed two’s complement integer.

      Range: From $-128$ to $127$.

      Memory Usage: 1 byte.

      Example: byte smallNumber = 50;

      short:

      Size: 16-bit signed two’s complement integer.

      Range: From $-32,768$ to $32,767$.

      Memory Usage: 2 bytes.

      Example: short quantity = 1000;

      int:

      Size: 32-bit signed two’s complement integer. This is the default integer data type in Java.

      Range: From $-2^{31}$ to $2^{31}-1$ (approx. $\pm 2$ billion).

      Memory Usage: 4 bytes.

      Example: int population = 1500000;

      long:

      Size: 64-bit signed two’s complement integer. Used for very large integer values.

      Range: From $-2^{63}$ to $2^{63}-1$ (approx. $\pm 9$ quintillion).

      Memory Usage: 8 bytes.

      Example: long worldPopulation = 7800000000L; (Note the L suffix for long literals).

Floating-Point: Used for numbers with a fractional component (decimal numbers).

      float:

      Size: Single-precision 32-bit IEEE 754 floating-point.

      Precision: Up to 7 decimal digits.

      Memory Usage: 4 bytes.

      Example: float temperature = 25.5f; (Note the f suffix for float literals).

      double:

      Size: Double-precision 64-bit IEEE 754 floating-point. This is the default floating-point data type in Java.

      Precision: Up to 15 decimal digits.

      Memory Usage: 8 bytes.

      Example: double pi = 3.1415926535;

Character Type |: Used to store single characters.

      char:

      Size: 16-bit Unicode character. This allows it to store characters from almost all human languages.

      Memory Usage: 2 bytes.

      Example: char grade = ‘A’;, char initial = ‘\u0041’;.

      Note: char literals are enclosed in single quotes (‘ ‘).

Boolean Type |: Used to store truth values.

      boolean:

      Size: Represents one bit of information, but its size is not precisely defined by the JVM specification. It effectively uses 1 byte for storage in arrays, but its individual storage might vary.

      Values: Can only be true or false.

      Example: boolean isJavaFun = true;, boolean isLoggedIn = false;

Declaration and Initialization |:
Before using a variable, you must declare it, which tells the compiler its type and name. You can also initialize it (assign an initial value) at the time of declaration or later.

      Syntax: dataType variableName;

      Syntax with Initialization: dataType variableName = value;

      Examples:

 // Variable Declaration

int count;              // Declaration only

count = 10;             // Initialization

// Declaration + Initialization in one step

double price = 99.99;   // Declaration and Initialization

char status = ‘P’;      // Declaration and Initialization

// Boolean Example

boolean isActive;       // Declaration only

isActive = true;        // Initialization

1.8.2 Non-Primitive Data Types

Non-primitive data types, also known as reference types, are not predefined by Java (except for String and Arrays, which are special cases). They are created by the programmer and are used to store references (addresses) to objects. When you declare a variable of a non-primitive type, it does not store the actual object but rather a reference to where the object is stored in memory (on the heap).

      String:

      String is a special non-primitive data type used to store sequences of characters (text). Although it’s a class in Java (java.lang.String), it’s so frequently used that it behaves somewhat like a primitive type in terms of literal representation.

      Immutability: String objects are immutable, meaning once a String object is created, its content cannot be changed. Any operation that appears to modify a String actually creates a new String object.

      Example:

 // Declaration and Initialization (using string literal)

String message = "Hello, Java!"; 

// Another way to create a String object (using ‘new’ keyword)

String name = new String("Parmeshwar");

Arrays:

      Arrays are non-primitive data types used to store a collection of fixed-size elements of the same data type in contiguous memory locations. We will cover arrays in detail in Section 1.11.

      Example:

 // An array of integers (declaration + initialization)

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

// An array that can hold 3 String objects (declaration + memory allocation)

String[] names = new String[3];

Classes and Interfaces:

      These are the most common non-primitive data types. When you define your own class or interface (which we will explore in later chapters on Object-Oriented Programming), you are essentially creating a new data type. Variables of these types hold references to objects created from those classes or implementations of those interfaces.

      Example:

 // Assuming you have defined a ‘Student’ class

Student s1 = new Student(); 

// Explanation:

// ‘s1’ is a variable (reference variable) of type ‘Student’

// It holds the memory address (reference) of a newly created ‘Student’ object

1.8.3 Default Values and Literals

      What are Literals?:
Literals are fixed values (constants) in a program. They are the direct representation of data.

      10: Integer literal (default int).

      3.14: Floating-point literal (default double).

      ‘A’: Character literal.

      "Hello": String literal.

      true, false: Boolean literals.

      100L: Long literal (note the L).

      2.5f: Float literal (note the f).

      Default Values for Primitive Types:
When an instance variable (a member of a class, not a local variable within a method) of a primitive type is declared but not explicitly initialized, Java automatically assigns it a default value. Local variables, however, do not get default values and must be explicitly initialized before use.

Data Type

Default Value

byte

$0$

short

$0$

int

$0$

long

$0L$

float

$0.0f$

double

$0.0d$ (or $0.0$)

char

‘\u0000’ (null character)

boolean

false

All Reference Types (String, Arrays, Classes, etc.)

null

            Example:

 class DefaultValueExample {

    // Instance variables (automatically initialized with default values)

    int defaultInt;           // Default = 0

    boolean defaultBoolean;   // Default = false

    String defaultString;     // Default = null

 

    public static void main(String[] args) {

        // Creating an object to access instance variables

        DefaultValueExample obj = new DefaultValueExample();

        // Printing default values

        System.out.println("Default int: " + obj.defaultInt);

        System.out.println("Default boolean: " + obj.defaultBoolean);

        System.out.println("Default String: " + obj.defaultString);

        // Local variables MUST be initialized before use

        // int localVariable;

        // System.out.println(localVariable); // Compile-time error: variable not initialized

    }

}

            Understanding data types is crucial as it directly impacts how you declare variables, store values, and perform operations in your Java programs.