VARIABLES IN JAVA


In Java, variables are used to store data of different types, such as numbers, characters, or objects. Here are the main types of variables in Java:

  1. Primitive Variables:
    • boolean: Stores either true or false.
    • byte: Stores whole numbers from -128 to 127.
    • short: Stores whole numbers from -32,768 to 32,767.
    • int: Stores whole numbers from -2,147,483,648 to 2,147,483,647.
    • long: Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
    • float: Stores fractional numbers with single-precision (32-bit).
    • double: Stores fractional numbers with double-precision (64-bit).
    • char: Stores a single character, such as ‘a’ or ‘$’.
  2. Reference Variables:
    • String: Stores a sequence of characters.
    • Arrays: Stores a fixed-size collection of elements of the same type.
    • Objects: Stores instances of user-defined classes.

Variables in Java have a specific type, which must be declared before they can be used. Here’s an example of declaring and initializing variables:

javaCopy codeint age = 25; // declaration and initialization of an integer variable
double pi = 3.14159; // declaration and initialization of a double variable
String name = "John"; // declaration and initialization of a string variable
boolean isStudent = true; // declaration and initialization of a boolean variable

Once a variable is declared, its value can be updated or reassigned using the assignment operator (=):

javaCopy codeage = 30; // updating the value of the age variable
name = "Jane"; // updating the value of the name variable
isStudent = false; // updating the value of the isStudent variable

It’s important to note that Java is a statically typed language, which means that variable types are explicitly declared and checked at compile-time.