Variables In Java | Declare, Initialise & Types (+Code Examples)
In programming, variables are essential for managing data during execution, making them fundamental to any project, big or small. Naturally, variables are like the backbone of any Java program. Just as data types define what kind of information a program can handle, variables determine how that information is stored and manipulated. In this article, we will explore different types of variables in Java, their applications, scope, and behavior with examples.
What Are Variables In Java Language?
Variables in Java programming are named memory locations or placeholders used to store data values. They act like containers that hold values, which can be changed or manipulated throughout the program.
Picture this: you have a box labelled "age,” and you can place different values (like 25, 30, or 42) into this box as needed. Similarly, in Java programming language, you can declare a variable called age (name of the memory location) and assign it a specific value, like so:
int age = 25;
Here:
- The keyword int indicates that age is an integer variable, meaning it will hold integer values.
- Value 25 is the initial value assigned to it.
The key thing to understand is that variables allow us to refer to data by name, and this is essential for writing reusable, flexible code. In the following sections, we will discuss how to declare and initialize variables in Java in detail, along with examples.
How To Declare Variables In Java Programs?
Variable declaration in Java means introducing it to the program by specifying the data type and the variable name/ identifier but not necessarily giving it a value at that point.
Key Steps To Declare A Variable In Java:
- Data Type Selection: Choose the type of data the variable will hold. The Java data types include many primitive types (e.g., int, double, String) and non-primitive types (arrays, enum, interface, etc).
- Variable Name: Use a meaningful, descriptive name that reflects the purpose or type of data. We generally use the camelCase convention in variable names.
- End with a Semicolon: Don’t forget to terminate the statement!
Syntax For Declaration Of Variables In Java:
dataType variableName;
Here,
- The dataType represents the type of data the variable will hold (e.g., int, double, String).
- The variableName refers to the name/ identifier we give to the variable, which we can use to access it across the program.
Example:
int age; // Declaration only, no value assigned
String name; // Declaration of a String variable
Here, we have simply declared one integer variable and a string variable without assigning values. The program now knows about these variables and their declaration type but doesn’t yet know what values they hold.
How To Initialize Variables In Java?
Variable initialization in Java involves assigning an initial value during or after the declaration. Doing so ensures that the variable has a meaningful value and is ready for use in the program. Once a variable has been declared, you can set its value using the simple assignment operator (=).
Syntax For Initialization Of Variables In Java:
dataType variableName = initialValue;
Here, the first part of the syntax (before =) is the same as in the declaration. After that, we use the assignment operator represented by an equals sign (=) and assign it a value given by initialValue. The simple Java program example below illustrates how to declare, initialize and print variables.
Code Example:
Output:
Number: 9
Price: 29.99
Name: Unstop
Code Explanation:
In the simple Java code example,
- We begin by declaring a public class named Main. Every Java program must have at least one class, which serves as the blueprint for objects, encapsulating variables and methods that perform actions within the program.
- Inside Main, we define a public method called static void main(), which is the entry point of any Java application/ the first method that gets executed.
- The public keyword means that it is accessible from outside of the class, and the static keyword means that the method belongs to the class itself and not an instance. So, it can be called without creating a class object.
- It is of type void, meaning there is no return value, and the parameter String[] args allows it to accept command-line arguments as an array of strings.
- Inside main(), we declare three variables—number, price, and name—using different data types.
- Variable number is an integer variable which we initialize with the value 9.
- Then, we have the double variable price, initialized with the value 29.99.
- And the String variable called name is assigned the value "Unstop".
- As you can see, the data type used for each variable corresponds to the kind of value we want to store in it.
- Initialization is important because variables in Java must be assigned values before they are used. If we tried to use a variable without assigning it a value, the program would not compile.
- After that, we use the System.out.println() method to print their values to the console. Here, we use the addition/ concatenation operator (+) for string concatenation. It combines the text (inside the quotes) with the value of the variable, allowing us to print both in one statement.
- The program terminates once the main() method finishes executing.
Naming Conventions For Variables In Java
There are well-defined naming conventions for variables in Java to ensure code clarity and consistency. Following these conventions helps in making code more readable and easier to maintain. In the table below, we have listed the key naming rules, along with examples and explanations:
Naming Convention | Example | Permissible? | Explanation |
---|---|---|---|
CamelCase | myVariableName | Yes | Used for naming variables and methods. Start with a lowercase letter, and capitalize each subsequent word. |
Descriptive Names | studentAge | Yes | Variable names should be meaningful and describe their purpose (e.g., studentAge indicates the age of a student). |
Underscores | my_variable | Yes, but discouraged | Although allowed, the use of underscores in Java variable names is discouraged. Use camelCase instead for better readability. |
Numbers | number1 | Yes |
Avoid using numbers in variable names unless absolutely necessary. Use more meaningful names like studentCount rather than student1. |
PascalCase | MyClass | Yes (for classes and interfaces) |
Used for naming classes and interfaces. Each word starts with an uppercase letter. If the name consists of multiple words, each subsequent word is capitalized (e.g., MyClass). |
UPPER_CASE | MAX_SIZE | Yes (for constants) |
Used for constants and final static variables. Words are separated by underscores and are all uppercase. |
Abbreviations | numStudents | Yes | Use abbreviations only if they are widely understood and clear (e.g., num for numbers in numStudents). |
Package Naming | com.example.project | yes | Packages are named in lowercase, often prefixed with a reversed domain name to ensure uniqueness. |
Types Of Variables In Java
In Java, variables can be categorized based on their scope and usage within a program. Understanding these types is essential for managing data effectively and writing clean code. The four main types of variables in Java are:
- Local Variables: Variables declared within a method, constructor, or block of code and exist only in that context.
- Instance Variables: Variables defined at the class level that belong to an instance of the class.
- Static Variables: Variables shared among all instances of a class, defined with the static keyword.
- Final Variables: Variables whose values cannot be changed once assigned, making them constants.
Want to expand your knowledge of Java programming? Check out this amazing course and become the best version of Java developer you can be.
Local Variables In Java
As mentioned above, local variables are those that are declared within a method, constructor, or any block of code. Their characteristics and behaviors make them essential for managing data specific to a particular execution context.
- Scope: Local variables in Java are accessible only within the method, constructor, or block in which they are declared. They cannot be accessed from outside this scope, ensuring that they are used only for their intended purpose.
- Lifetime: Local variables are created when the method, constructor, or block is entered and destroyed when it exits. This means they exist only during the execution of that particular block of code.
- Initialization: Unlike instance or static variables, local variables in Java must be explicitly initialized before they can be used. If you try to access a local variable without initializing it, the compiler will throw an error.
- Memory Management: Because local variables are created and destroyed dynamically, they are typically stored on the stack. This leads to efficient memory usage, especially in recursive functions.
Syntax For Local Variables In Java:
dataType variableName;
dataType variableName = initial_value
This is the same as the processes of declaration and initialization we discussed in the sections above. We revisit the declaration and initialization of local variables in the Java program example below.
Code Example:
Output:
Number: 10
Code Explanation:
In this Java code example,
- We declare a variable number (of type int) inside the main() method and assign the value 10 to it. This is the local variable inside main().
- We then print its value to the console using the System.out.println() method. Since number is a local variable, it is created when the main() method is called and destroyed when the method completes execution.
Instance Variables In Java
Instance variables are those class variables defined outside of any method, constructor, or block. They are associated with instances (or objects) of the class and provide a way to store object-specific data. Each instance of a class has its own copy of the instance variables, making them unique to each object.
- Scope: Instance variables in Java have class-level scope and are accessible throughout the class in which they are declared. This means they can be used in any method of the class, allowing for easy data management related to the object's state.
- Lifetime: The lifetime of instance class variables is tied to the lifespan of the object they belong to. They are created when the object is instantiated and are destroyed when the object is no longer referenced, usually when it is garbage collected.
- Initialization: If not explicitly initialized, instance variables in Java are automatically assigned default values. For example, numeric types (e.g., int, double) default to 0, boolean types default to false, and object references default to null.
Syntax For Instance Variables In Java:
accessModifier dataType variableName;
Here,
- The accessModifier controls the accessibility of the variable, which can be public, private, or protected.
- The dataType specifies the type of data the variable whose name is given by variableName will hold (e.g., int, double, String).
Code Example:
Output:
Model: Toyota
Year: 2022
Code Explanation:
In the example Java code,
- We declare two instance variables: model of type String and year of type int, inside the Main class. These variables are associated with instances (objects) of the Main class, meaning that each object of the Main class has its own copy of these variables, allowing different instances to hold different values.
- Then, we define a constructor Main() that initializes the instance variables with the values provided as arguments when an object is created. The this keyword is used to differentiate between the instance variables and the parameters.
- Next, we define displayDetails() method to print the details of the car. It accesses the instance variables model and year to display their values using System.out.println().
- After that, we define the main() method and create an instance of the Main class named myCar using the constructor. We pass arguments "Toyota" and 2022 to the constructor to initialize the model and year instance variables of the myCar object, respectively.
- Then, we call the displayDetails() method on the myCar object to print its details. This method call results in the output displaying the model as "Toyota" and the year as 2022.
This example shows how we can use an instance/ object of the class to initialize and access the instance variables in the class.
Static Variables In Java
Static variables are those that are defined at the class level and are shared among all instances of the class. Unlike instance variables, static variables belong to the class itself rather than to any individual object. This means that there is only one copy of a static variable, regardless of how many instances of the class are created.
- Scope: Static variables have class-level scope and are accessible throughout the class in which they are declared. They can also be accessed from outside the class using the class name, making them visible across all instances of that class.
- Lifetime: The lifetime of static variables in Java extends throughout the execution of the program. They are created when the class is loaded into memory and exist until the program terminates. Static variables retain their values across method calls and instances.
- Initialization: Static variables in Java are initialized only once, either explicitly (with a value) or implicitly (to their default values). If not explicitly initialized, static variables take on default values: numeric types default to 0, boolean types default to false, and object references default to null.
Syntax For Static Variables In Java:
static dataType variableName;
The syntax for declaration remains the same as local variables, only here we use the static keyword to indicate that the variable belongs to the class itself, rather than to any particular instance.
Code Example:
Output:
Count: 3
Code Explanation:
In the Java example code,
- We create a class called Counter and then declare a static integer variable count inside. Since count is static, all instances of Counter class will share the same variable, allowing it to keep track of the total number of times it has been incremented across all instances.
- Then, we define a static method increment() that increases the value of the static variable count by 1 each time it is called. This method can be invoked without creating an instance of the class, demonstrating the class-level nature of static variables.
- Next, we define the displayCount() method that outputs the current value of the static variable count to the console using System.out.println().
- In the main() method, we call the increment() method three times, causing the count to increase from its default value of 0 to 3.
- After that, we call the displayCount() to print the final value of the count, which results in the output displaying "Count: 3."
Final Variables In Java
In Java, final variables are variables that can only be assigned once. Once a final variable is initialized, its value cannot be changed, making it act like a constant throughout the program. These variables are typically used when you want to create constants or ensure that a particular variable's value remains the same after initialization.
- Immutability: Once initialized, the value of a final variable cannot be altered. Trying to reassign a value to a final variable will result in a compilation error.
- Initialization: A final variable must be initialized either at the time of declaration or within the constructor of the class. This ensures that the variable has a value before it's used, but once assigned, that value is locked.
- Usage: The final variables in Java are commonly used to define constants (e.g., PI, MAX_VALUE) or to mark variables whose values should remain constant throughout the program’s execution. These variables are often used in mathematical calculations or when dealing with fixed configurations.
Syntax For Final Variables In Java:
final dataType variableName = initialValue;
The general syntax for declaration and initialization remains the same as variables in Java. The difference is, here we use the final keyword to indicate that the variable is constant and its value cannot be changed.
Also, the name for such variables must follow the naming convention for constants, i.e., all caps with words connected using underscore, like MAX_VALUE.
Code Example:
Output:
Area of the circle: 78.5
Code Explanation:
In this Java code sample,
- Inside the Main class, we declare a final variable named PI of type double and initialized with the value 3.14. Since PI is marked as final, its value cannot be modified anywhere else in the program.
- Then, we define a calculateArea() method to compute the area of a circle based on its radius. It uses the formula PI * radius * radius, where PI is the final variable representing the mathematical constant π.
- In the main() method, we create an instance of the Main class named circle using the new keyword.
- Next, we call the calculateArea() method using the circle object and passing a radius of 5 as an argument. The function calculates and prints the area.
The key point here is that the value of PI remains unchanged throughout the program, reinforcing the concept of immutability that comes with the final variables. Even if the program attempted to modify the value of PI, it would result in a compilation error, ensuring the integrity of the constant value.
Scope and Lifetime of Variables In Java
In Java, variables have both scope and lifetime, which determine where they can be accessed and how long they exist during program execution. Understanding these concepts is essential to manage memory effectively and avoid errors.
Scope: It defines the region of the program where a variable is visible and can be accessed.
- Local Variables: These have a narrow scope and are only accessible within the block of code (like a method or a loop) where they are declared. Once the program exits this block, the local variables are no longer accessible.
- Instance Variables: These variables in Java are associated with a specific instance (or object) of a class. They have class-level scope, meaning they can be accessed anywhere within the class in which they are declared. However, each instance of the class has its own copy of the instance variables.
- Static Variables: These variables in Java also have a class-level scope, but they are shared among all instances of the class. They can be accessed anywhere within the class and across all objects of that class without needing an object reference.
Lifetime: It refers to how long a variable exists in memory during the execution of the program.
- Local Variables: These are created when the block of code (method or loop) in which they are declared is entered and are destroyed when the block is exited. They only live as long as the block of code runs.
- Instance Variables: These are created when an object of the class is instantiated. They exist for as long as the object exists, and they are destroyed when the object is no longer in use and gets garbage collected by the Java Virtual Machine (JVM).
- Static Variables: These are initialized when the class is loaded into memory (even before any objects are created). Static variables persist for as long as the class remains loaded and are destroyed only when the class is unloaded, typically when the program ends.
Real-life Example:
Imagine you're in a classroom, and your teacher (the Java program) gives you a piece of paper (a variable) to write down answers to a quiz.
- Local Variable: If the paper is only passed around within your small group during the quiz, it’s like a local variable. It can only be accessed by those in the group (block of code), and it disappears when the quiz ends (when the block finishes executing).
- Instance Variable: If each student in the class receives their own sheet of paper, it’s like an instance variable. Each student (instance) has their own copy, and they can keep using it until the class ends (until the object is garbage collected).
- Static Variable: If the teacher posts the paper on the classroom wall for everyone to see, it’s like a static variable. It’s accessible to all students (all instances), and it stays on the wall for the entire school year (for the lifetime of the class).
Data Types Of Variables In Java (Primitive & Non-primitive)
Data types in Java define the kind of data a variable can hold and the operations that can be performed on it. They are broadly classified into two categories: Primitive and Non-primitive data types.
Primitive Data Types: These are the most basic types of data and store simple values. For example:
- int (e.g., int age = 25;) for integers,
- double (e.g., double price = 19.99;) for decimal numbers,
- char (e.g., char grade = 'A';) for characters,
- boolean (e.g., boolean isAvailable = true;) for true/false values.
Non-primitive (Reference) Data Types: These reference objects rather than storing data directly. For example:
- Arrays (e.g., int[] numbers = {1, 2, 3};) for collections of similar types,
- Classes (e.g., Scanner input = new Scanner(System.in);) for user-defined or built-in objects.
Understanding these types is essential for effectively working with variables in Java. For more, read: Data Types In Java | Primitive & Non-Primitive With Code Examples
Java Variable Type Conversion & Type Casting
In Java, converting variables from one data type to another is a common operation. This process can happen either automatically (type conversion) or manually (type casting).
Type Conversion (Implicit): Also known as type coercion, this is automatically handled by the compiler when performing operations involving different data types. For example, if you add an int and a double, the int is automatically converted to a double before the operation.
Type Casting (Explicit): Type casting is when the Java programmer explicitly converts a variable from one data type to another. It’s necessary when narrowing (converting a larger type to a smaller type), as there’s potential for data loss. There are two kinds of casting:
- Widening (implicit): Converts smaller data types to larger ones, automatically handled by the compiler.
- Narrowing (explicit): Converts larger data types to smaller ones, requiring manual casting by the programmer.
Here is your chance to top the leaderboard while practising your coding skills: Particiapte in the 100-Day Coding Sprint at Unstop.
Working With Variables In Java (Examples)
In this section, we'll explore how to access, change, and read values of variables in Java through practical examples.
Accessing Variables In Java
To access a variable means to retrieve its value and use it in expressions or statements. Variables can be accessed within their scope using their names.
Code Example:
Output:
Number: 10
Message: Hello, Unstoppable!
Code Explanation:
- In the sample Java code, we declare and initialize two variables: number of type int with value 10 and message of type String with value "Hello, Unstoppable".
- We then access the values of these variables using their names (number and message) and print them to the console using the System.out.println() method.
Changing The Value Of A Variable In Java
Variables can be updated during program execution to reflect new data.
Code Example:
Output:
Number: 10
Code Explanation:
- In this example, we first declare and initialize an integer variable number with the value 5. Then, we reassign the value 10 to it using the simple assignment operator.
- We then print the value to the console, highlighting how variable values can be modified during program execution.
Reading User Input For Different Types Of Variables In Java
Java allows us to read different types of input from users, such as integers, doubles, and strings, using the Scanner class.
Code Example:
Output:
Enter an integer: 5
Enter a double: 3.14
Enter a string: Hello, Unstoppable!User Input:
Integer: 5
Double: 3.14
String: Hello, Unstoppable!
Code Explanation:
- In this example, we create a Scanner object named scanner to read user input from the console.
- We prompt the user to enter an integer, a double, and a string using the System.out.print() method individually.
- As use provides input, we use the nextInt(), nextDouble(), and nextLine() methods of the Scanner class to read integer, double, and string input. We also store them in the respective variables (intValue, doubleValue, stringValue) for further processing or display.
- After that, we use the System.out.println() method to display the values to the console.
- It is important to close the Scanner object using the close() method to release system resources after use.
This example demonstrates reading different types of input from the user using a Scanner. It reads an integer, a double, and a string, stores them in variables, and then prints them. The key takeaway is how Java handles user input for various data types.
Access Modifiers & Variables In Java
Access modifiers in Java are keywords that define the accessibility of classes, methods, and variables within a program. They play a crucial role in encapsulation and security by controlling which parts of the program can access certain elements.
Access Specifiers:
- public: Allows access from any other class. Use this when you want a variable to be universally accessible.
- private: Restricts access to within the same class. This is ideal for variables that should not be exposed outside the class.
- protected: Allows access within the same class and its subclasses. This is useful for allowing inheritance while maintaining some level of encapsulation.
- Default (no modifier specified): Restricts access to within the same package. This is useful for package-private access, allowing classes within the same package to interact while hiding variables from classes in other packages.
Syntax:
accessModifier dataType variableName;
Here, the accessModifier refers to the specifier we use, and the rest of the syntax remains the same for variable declaration. You must have seen the use of public modifiers in the examples above.
Need more guidance on how to become a Java developer? You can now select an expert to be your mentor here.
Conclusion
In this article, we explored the fundamental concepts of variables in Java. Variables serve as containers that store various data types, enabling us to manipulate and manage information effectively. When declaring variables, we must specify both the data type and the variable name, and we can initialize them by assigning a value using the assignment operator.
There are three primary types of variables: local variables that are defined within a function/ block of code, instance variables that belong to an instance of a class, and static variables that belong to the whole class. It is important to understand the difference between these variable types, as well as the nuances of data types. In addition, we discussed access modifiers, whose main role is to control the visibility and accessibility of variables, enhancing encapsulation and security in our code. By mastering these concepts, we lay a strong foundation for building sophisticated software that is both functional and adaptable to user needs.
Also read: Top 100+ Java Interview Questions And Answers (2024)
Frequently Asked Questions
Q. Difference between the instance and static variables In Java.
Instance Variables |
Static Variables |
|
Association |
Associated with instances (objects) of a class. |
Associated with the class itself rather than instances. |
Number of Copies |
Each instance has its own copy of instance variables. |
Only one copy is shared among all instances of the class. |
Initialization |
Initialized when an object is created. |
Initialized only once when the class is loaded into memory. |
Accessing |
Accessed using object references. |
Accessed using the class name. |
Q. What is the difference between public, private, protected, and default access modifiers?
Access Modifier | Visibility | Description |
---|---|---|
public | Any class | Accessible from any class. Used for methods and variables that need to be widely available. |
private | Same class | Restricted to the same class. Used for encapsulating implementation details. |
protected | Same class and subclasses | Accessible within the same class and subclasses. Allows inheritance while enforcing encapsulation. |
Default | Same package | Accessible only within the same package. Useful for package-level encapsulation. |
Q. What are the benefits of using different data types in Java variables?
- Efficient Memory Allocation: Different data types occupy varying amounts of memory, allowing for optimal storage.
- Precision and Accuracy: Using specific types, like
double
for floating-point calculations, ensures higher precision. - Type Safety: Enforces compatibility between operations and data types, preventing runtime errors.
Q. What is the difference between local variables and instance variables?
- Local Variables: Declared within a method and exist only within that method's scope. It must be initialized before use.
- Instance Variables: Declared within a class but outside any method. Initialized when an object is created and exists as long as the object exists.
Q. How do you read user input of different data types in Java?
User input can be read using the Scanner class. For example:
- To read an integer: int num = scanner.nextInt();
- To read a double: double value = scanner.nextDouble();
- To read a string: String text = scanner.nextLine();
Q. How do variables with different access modifiers impact code organization and security in Java?
Variables with different access modifiers significantly influence code organization and security in Java:
- Encapsulation and Information Hiding: Access modifiers such as private restrict access to variables within the same class, promoting encapsulation and information hiding. This prevents external classes from being directly able to access or modify the internal state of an object, enhancing data integrity and security.
- Code Maintainability and Readability: By using appropriate access modifiers with variables in Java programs, developers can clearly define their scope and visibility, making the codebase easier to understand and maintain. For example, using public for variables intended to be accessed by other classes and private for internal implementation details enhances code readability and maintainability.
By now, you must know all about variables in Java and how to use them appropriately. Here are a few more topics you must explore:
- Key Features Of Java, Java 8 & Java 11 Explained (+Code Examples)
- Advantages And Disadvantages of Java Programming Language
- List Of 50 Core Java Interview Questions With Answers (2022)
- Top 15+ Difference Between C++ And Java Explained! (+Similarities)
- Difference Between Java And JavaScript Explained In Detail