Variable:
In Java, a variable is a storage location for a value. A variable has a name, a type, and a value. The type of a variable determines the kind of value it can hold, such as an integer, a floating-point number, or a string.- We use a name, so we can distinguish one variable from another.
- A variable's type determines the kinds of values/data that can be stored in it.
- The value is the specific object, data, or information stored in the variable.
How to Work with Variables in Java
To work with different kinds of data in Java, you can create variables of different types. For example, if you want to store your age in a new variable, you can do so like this:
public class Main {
public static void main(String[] args) {
// <type> <name>
int age;
}
}
You start by writing out the type of data or variable. Since age
is a whole number, its type will be integer or int
for short, followed by the name of the variable age
and a semicolon.
At the moment, you've declared the variable but you haven't initialized it. In other words, the variable doesn't have any value. You can initialize the variable as follows:
public class Main {
public static void main(String[] args) {
// <type> <name>
int age;
// <name> = <value>
age = 27;
// prints the age on the terminal
System.out.println("I am " + age + " years old.");
}
}
When assigning a value, you start by writing the name of the variable you want to initialize, followed by an equal sign (it's called the assignment operator) then the value you want to assign to the variable. And don't forget the semicolon at the end.
The System.out.println();
function call will print the line I am 27 years old.
to the console. In case you're wondering, using a plus sign is one of the many ways to dynamically print out variables in the middle of a sentence.
One thing that you have to keep in mind is you can not use an uninitialized variable in Java. So if you comment out the line age = 27
by putting two forward slashes in front of it and try to compile the code, the compiler will throw the following error message at you:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable age may not have been initialized
at variables.Main.main(Main.java:13)
The line The local variable age may not have been initialized
indicates that the variable has not been initialized.
Instead of declaring and initializing the variable in different lines, you can do that in one go as follows:
public class Main {
public static void main(String[] args) {
// <type> <name> = <value>
int age = 27;
// prints the age on the terminal
System.out.println("I am " + age + " years old.");
}
}
The code should be back to normal again. Also, you can change the value of a variable as many times as you want in your code.
public class Main {
public static void main(String[] args) {
int age = 27;
// updates the value to be 28 instead of 27
age = 28;
System.out.println("I am " + age + " years old.");
}
}
In this code, the value of age
will change from 27 to 28 because you're overwriting it just before printing.
Keep in mind, while you can assign values to a variables as many times as you want, you can not declare the same variable twice.
public class Main {
public static void main(String[] args) {
// <type> <name> = <value>
int age = 27;
int age = 28;
// prints the age on the terminal
System.out.println("I am " + age + " years old.");
}
}
If you try to compile this code, the compiler will throw the following error message at you:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Duplicate local variable age
at variables.Main.main(Main.java:9)
The line Duplicate local variable age
indicates that the variable has already been declared.
Apart from variables, you may find the term "literal" on the internet. Literals are variables with hardcoded values.
For example, here, age = 27
and it's not dynamically calculated. You've written the value directly in the source code. So age
is an integer literal.
To work with different kinds of data in Java, you can create variables of different types. For example, if you want to store your age in a new variable, you can do so like this:
public class Main {
public static void main(String[] args) {
// <type> <name>
int age;
}
}
You start by writing out the type of data or variable. Since age
is a whole number, its type will be integer or int
for short, followed by the name of the variable age
and a semicolon.
At the moment, you've declared the variable but you haven't initialized it. In other words, the variable doesn't have any value. You can initialize the variable as follows:
public class Main {
public static void main(String[] args) {
// <type> <name>
int age;
// <name> = <value>
age = 27;
// prints the age on the terminal
System.out.println("I am " + age + " years old.");
}
}
When assigning a value, you start by writing the name of the variable you want to initialize, followed by an equal sign (it's called the assignment operator) then the value you want to assign to the variable. And don't forget the semicolon at the end.
The System.out.println();
function call will print the line I am 27 years old.
to the console. In case you're wondering, using a plus sign is one of the many ways to dynamically print out variables in the middle of a sentence.
One thing that you have to keep in mind is you can not use an uninitialized variable in Java. So if you comment out the line age = 27
by putting two forward slashes in front of it and try to compile the code, the compiler will throw the following error message at you:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable age may not have been initialized
at variables.Main.main(Main.java:13)
The line The local variable age may not have been initialized
indicates that the variable has not been initialized.
Instead of declaring and initializing the variable in different lines, you can do that in one go as follows:
public class Main {
public static void main(String[] args) {
// <type> <name> = <value>
int age = 27;
// prints the age on the terminal
System.out.println("I am " + age + " years old.");
}
}
The code should be back to normal again. Also, you can change the value of a variable as many times as you want in your code.
public class Main {
public static void main(String[] args) {
int age = 27;
// updates the value to be 28 instead of 27
age = 28;
System.out.println("I am " + age + " years old.");
}
}
In this code, the value of age
will change from 27 to 28 because you're overwriting it just before printing.
Keep in mind, while you can assign values to a variables as many times as you want, you can not declare the same variable twice.
public class Main {
public static void main(String[] args) {
// <type> <name> = <value>
int age = 27;
int age = 28;
// prints the age on the terminal
System.out.println("I am " + age + " years old.");
}
}
If you try to compile this code, the compiler will throw the following error message at you:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Duplicate local variable age
at variables.Main.main(Main.java:9)
The line Duplicate local variable age
indicates that the variable has already been declared.
Apart from variables, you may find the term "literal" on the internet. Literals are variables with hardcoded values.
For example, here, age = 27
and it's not dynamically calculated. You've written the value directly in the source code. So age
is an integer literal.
What Are the Rules for Declaring Variables?
There are some rules when it comes to naming your variables in Java. You can name it anything as long as it doesn't start with a number and it can't contain any spaces in the name.
Although, you can start a variable name with an underscore (_) or a dollar sign ($), not being mindful of their usage can make your code hard to read. Variable names are also case sensitive. So age
and AGE
are two different variables.
Another important thing to remember is you can not use any of the keywords reserved by Java. There are around 50 of them at present. You can learn about these keywords from the official documentation but don't worry about memorizing them.
As you keep practicing, the important ones will slip into your neurons automatically. And if you still manage to mess up a variable declaration, the compiler will be there to remind you that something's wrong.
Apart from the rules, there are some conventions that you should follow:
- Start your variable name with small letter and not any special character (like an underscore or dollar sign).
- If the variable name has multiple words, use camel case:
firstName
, lastName
- Don't use single letter names:
f
, l
As long as you follow these rules and conventions, you're good to go. If you'd like to learn more about naming conventions in general, checkout my article on the topic.
There are some rules when it comes to naming your variables in Java. You can name it anything as long as it doesn't start with a number and it can't contain any spaces in the name.
Although, you can start a variable name with an underscore (_) or a dollar sign ($), not being mindful of their usage can make your code hard to read. Variable names are also case sensitive. So age
and AGE
are two different variables.
Another important thing to remember is you can not use any of the keywords reserved by Java. There are around 50 of them at present. You can learn about these keywords from the official documentation but don't worry about memorizing them.
As you keep practicing, the important ones will slip into your neurons automatically. And if you still manage to mess up a variable declaration, the compiler will be there to remind you that something's wrong.
Apart from the rules, there are some conventions that you should follow:
- Start your variable name with small letter and not any special character (like an underscore or dollar sign).
- If the variable name has multiple words, use camel case:
firstName
, lastName
- Don't use single letter names:
f
, l
As long as you follow these rules and conventions, you're good to go. If you'd like to learn more about naming conventions in general, checkout my article on the topic.
What Are final
Variables?
A final
variable in Java can be initialized only once. So if you declare a variable as final
, you can not reassign it.
public class Main {
public static void main(String[] args) {
// final <type> <name> = <value>
final int age = 27;
age = 28;
System.out.println("I am " + age + " years old.");
}
}
Since the age
variable has been declared as final
, the code will throw the following error message at you:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final local variable age cannot be assigned. It must be blank and not using a compound assignment
at variables.Main.main(Main.java:9)
However, if you leave the variable uninitialized while declaring, the code will work:
public class Main {
public static void main(String[] args) {
// final <type> <name>
final int age;
age = 28;
// prints the age on the terminal
System.out.println("I am " + age + " years old.");
}
}
So, declaring a variable as final
will limit your ability to reassign its value. If you leave it uninitialized, you'll be able to initialize it as usual.
A final
variable in Java can be initialized only once. So if you declare a variable as final
, you can not reassign it.
public class Main {
public static void main(String[] args) {
// final <type> <name> = <value>
final int age = 27;
age = 28;
System.out.println("I am " + age + " years old.");
}
}
Since the age
variable has been declared as final
, the code will throw the following error message at you:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final local variable age cannot be assigned. It must be blank and not using a compound assignment
at variables.Main.main(Main.java:9)
However, if you leave the variable uninitialized while declaring, the code will work:
public class Main {
public static void main(String[] args) {
// final <type> <name>
final int age;
age = 28;
// prints the age on the terminal
System.out.println("I am " + age + " years old.");
}
}
So, declaring a variable as final
will limit your ability to reassign its value. If you leave it uninitialized, you'll be able to initialize it as usual.
To perform the assignment operation, we use the equal sign (
=
)."I'll say it again: This isn't making a comparison. We are copying the value on the right of the equal sign to the variable on the left. To perform a comparison, Java uses a double equal sign (
==
)."Variable types:
- non-static variables are accessible within any non-static method
- non static variables are not accessible within any static method
Static Variables | Non-Static Variables |
They can access them using class names. | They can be accessed only using objects. |
They can access them with static methods as well as non-static methods. | They can be accessed only using non-static methods. |
They are allocated memory only once while loading the class. | A memory per object is allocated. |
These variables are shared by all the objects or instances of the class. | Each object has its own copy of the non-static variables. |
Static variables have global scope. | They have local scope. |
The static
keyword in Java is used to indicate that a member (field or method) belongs to a class, rather than an instance of the class. This means that the member can be accessed without creating an instance of the class.
Here are some examples of how the static
keyword is used in real-time applications:
- Class constants: The
static
keyword is often used to define constants that are associated with a class, rather than with a specific instance of the class. For example:
- Factory methods: The
static
keyword can be used to define factory methods that create and return instances of a class. For example:
- Utility methods: The
static
keyword is often used to define utility methods that perform a specific task, such as generating a random number or calculating the distance between two points. For example:
- Singleton classes: The
static
keyword can be used to create singleton classes, which are classes that have only one instance. For example:
- Can Static variables be used with Static methods - YES
- Can Static variables be used with non-static methods - YES
- Can non-static variables be used with static methods - NO
- Can non-static variables be used with non-static methods - YES
Variable Concept Interview Questions?
1)what is
a variable?
2)what are
the naming conventions of a variable?
3)what is a local variable and explain in detail?
4)What is the Instance variable and explain in detail?
5)what is a static variable and explain in detail?
6)can we
access nonstatic data in static methods?
7)can we
access static data in nonstatic methods?
Questions
- The term "instance variable" is another name for ___.
- The term "class variable" is another name for ___.
- A local variable stores a temporary state; it is declared inside a ___.
- A variable declared within the opening and closing parenthesis of a method signature is called a ____.
Exercises
- Create a small program that defines some fields. Try creating some illegal field names and see what kind of error the compiler produces. Use the naming rules and conventions as a guide.
- In the program you created in Exercise 1, try leaving the fields uninitialized and print out their values. Try the same with a local variable and see what kind of compiler errors you can produce. Becoming familiar with common compiler errors will make it easier to recognize bugs in your code.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.