We may not have the course you’re looking for. If you enquire or give us a call on +1 6474932992 and speak to our training experts, we may still be able to help with your training requirements.
Training Outcomes Within Your Budget!
We ensure quality, budget-alignment, and timely delivery by our expert instructors.
Java programming offers a dynamic and versatile environment for Developers. Variables are a fundamental part of this environment. But what exactly is a Java Variables? How do we declare, initialise, and use these variables in our programs? Read on to find out!
Have you ever wondered how data is stored and managed in a Java program? The answer is through variables. Without understanding the different types of Java Variables, you might end up with inefficient code or unexpected errors. Let's explore the world of Java Variables and learn how to use them effectively.
Table of Contents
1) Learn about Variable Declaration
2) Know About the Types of Variables in Java
3) Differences Between the Instance Variables and the Static Variables
4) Understanding Type Conversion and Type Casting
5) Conclusion
Learn About Variable Declaration
A variable declaration in Java happens once you mention the data type and give a unique name to the variable. By data type, we mean the type of data stored in this variable. Further, this variable also carries a name. An example of Syntax, as shown below, can be used to help better understand:
Syntax:
type variable_Name = value;
Example:
int myNum = “the knowledge academy”
Where int is the data type in Java, and myNum is the variable's name, and the knowledge academy is a value. In this way, a name can be allotted to a memory location. Values can be assigned to this variable in two ways:
1) Initialisation
2) Assignment
Initialisation (During Declaration)
Initialisation is the process of declaring a variable and assigning it a value in a single statement. This helps in making the code more concise and readable.
Syntax:
dataType variableName = value;
Example:
int age = 25;
Here, ‘int’ is the data type, ‘age’ is the variable name, and ‘25’ is the value assigned to the variable at the time of declaration.
Assignment (After Declaration)
Assignment is the process of assigning a value to a variable after it has already been declared. This can be useful when the value to be assigned is determined later in the program.
Syntax:
variableName = value;
Example:
int age;
age = 25;
Here, ‘age’ is first declared as an ‘int’ variable without an initial value. Later, ‘25’ is assigned to the variable age.
Know About the Types of Variables in Java
In Java, there exist different types of variables, whose characteristics are discussed in detail below:
Local Variables
a) A local variable is defined within a block, method, or constructor.
b) These variables are generated when the block begins or a function is called, and they disappear when the block leaves or the call to the function returns.
c) The scope of local variables is confined to the block in which they are declared, meaning they can only be accessed within that block.
d) It is mandatory to initialise local variables before using them within their defined scope.
Example:
public class LocalVariableExample { public static void main(String[] args) { // Local variable declaration and initialisation int sum = 0; // Block where local variable is used for (int i = 1; i <= 5; i++) { sum += i; } // Printing the local variable System.out.println("Sum: " + sum); } } |
Output:
Sum: 15
Instance Variables
a) Instance variables are non-static variables that are defined in a class outside of a method, constructor, or block.
b) When a class object is created, these variables are generated and eliminated.
c) Unlike local variables, instance variables can have access specifiers. If no access specifier is provided, the default access specifier is used.
d) Initialisation of instance variables is not mandatory. They have default values based on their data type.
public class Car { // Instance variables String model; int year; // Constructor to initialise instance variables public Car(String model, int year) { this.model = model; this.year = year; } // Method to display car details public void displayDetails() { System.out.println("Model: " + model); System.out.println("Year: " + year); } public static void main(String[] args) { // Creating objects of Car class Car car1 = new Car("Toyota Corolla", 2020); Car car2 = new Car("Honda Civic", 2019); // Displaying details of car1 car1.displayDetails(); // Displaying details of car2 car2.displayDetails(); } } |
Output:
Model: Toyota Corolla Year: 2020 Model: Honda Civic Year: 2019 |
Static Variables
a) Static variables, often known as class variables, are defined with the static keyword within a class but not in any function, constructor, or block.
b) Static variables are generated at the beginning of program execution and removed at the end.
c) Initialisation is not mandatory; default values depend on the data type (e.g., `null` for `String`, `0.0f` for `float`, `0` for `int`).
public class Counter { // Static variable static int count = 0; // Constructor that increments the static variable public Counter() { count++; } // Method to display the count public void displayCount() { System.out.println("Count: " + count); } public static void main(String[] args) { // Creating objects of Counter class Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); // Displaying the count using one of the objects c1.displayCount(); // Output: Count: 3 } } |
Output:
Count: 3
Learn how to develop a web application using Java programming by signing up for our Web Development Using Java Training now!
Differences Between the Instance Variables and the Static Variables
Following is the comparison between instance variables and static variables:
Aspect |
Instance Variables |
Static Variables |
Copies |
Each object has its own copy |
Only one copy per class, shared by all objects |
Memory Management |
Not efficient for memory management |
Good for memory management |
Effect of Changes |
Changes in one object do not affect others |
Changes are reflected in all objects |
Access |
Accessed through object references |
Accessed directly using the class name |
Creation and Destruction |
Created with the 'new' keyword and destroyed with the object |
Created when the program starts and destroyed when it stops |
Kickstart your coding journey with our JavaScript For Beginners Course and become a proficient Java Developer!
Understanding Type Conversion and Type Casting
Type Conversion
Type conversion is the process of converting one data type into another. This can happen either implicitly (automatically by the compiler) or explicitly (manually by the programmer).
Implicit Type Conversion (Widening Conversion):
a) When converting a smaller data type to a larger data type.
b) Done automatically by the Java compiler.
c) No data loss occurs.
int num = 10; double d = num; // Implicit type conversion from int to double System.out.println(d); // Output: 10.0 |
Here, the integer ‘num’ is automatically converted to a double ‘d’ without any data loss.
Type Casting
Type casting is the process of converting one data type into another explicitly. This is required when converting a larger data type to a smaller data type or when we need specific conversion logic.
Explicit Type Casting (Narrowing Conversion):
a) When converting a larger data type to a smaller data type.
b) The programmer must manually do it.
c) It might result in data loss or truncation.
double d = 10.5; int num = (int) d; // Explicit type casting from double to int System.out.println(num); // Output: 10 |
Here, the double ‘d’ is explicitly cast to an integer ‘num’, resulting in the truncation of the decimal part.
Join our Java Programming Course and become a proficient Java Developer - sign up to start learning!
Conclusion
Mastering Java Variables unlocks a new level of coding brilliance. By perfecting the art of declaring, initialising, and using local, instance, and static variables, you'll transform your code into a seamless, efficient masterpiece. Embrace these core concepts and let your Java programming skills shine!
Unlock your potential with comprehensive Java Courses – join now and become a coding master!
Frequently Asked Questions
In Java, there are eight basic data types: byte, long, float, short, int, double, char, and boolean. These types serve as the building blocks for data manipulation and storage, offering various ranges and precision.
Variables are named storage locations in memory that hold a value, while a data type specifies the kind of value a variable can store (e.g., int, float, String). Variables utilise data types to define their content.
The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.
Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.
The Knowledge Academy offers various Java Courses, including Java Programming, JavaScript For Beginners, Java Engineer Training and Web Development Using Java Training. These courses cater to different skill levels, providing comprehensive insights into Career in Java.
Our Programming & DevOps Blogs cover a range of topics related to Java, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Programming skills, The Knowledge Academy's diverse courses and informative blogs have got you covered.
Upcoming Programming & DevOps Resources Batches & Dates
Date
Mon 13th Jan 2025
Mon 10th Mar 2025
Mon 19th May 2025
Mon 21st Jul 2025
Mon 15th Sep 2025
Mon 17th Nov 2025
Mon 15th Dec 2025