Java Variables – What They Are and How to Use Them
- Krishnamohan Yagneswaran
- Apr 30
- 2 min read
In Java, variables are like containers that store data values. You can think of them as placeholders for different types of data that your program can use.
🧑💻 Types of Java Variables
Java offers a variety of variable types, each designed to store specific kinds of data. Let’s go over them:
String: Stores text (e.g., "Hello"). Strings are wrapped in double quotes.
int: Stores whole numbers without decimals (e.g., 123 or -123).
float: Stores numbers with decimals (e.g., 19.99 or -19.99).
char: Stores a single character (e.g., 'a' or 'B'). Characters are wrapped in single quotes.
boolean: Stores one of two possible values: true or false.
📄 Declaring (Creating) Variables
To create a variable, you need to define its type and assign it a value. Here’s the syntax:
type variableName = value;
For example:
java
String name = "John"; System.out.println(name);
This creates a variable name of type String and assigns it the value "John". The println() method then prints it to the screen.
➡️ Working with Numbers
To store numbers, you can create an int variable like this:
java
int myNum = 15; System.out.println(myNum);
This creates a variable myNum of type int and assigns it the value 15.
You can also declare the variable without assigning a value immediately, like this:
java
int myNum; myNum = 15; System.out.println(myNum);
If you change the value of an existing variable, it overwrites the previous value:
java
int myNum = 15; myNum = 20; // myNum is now 20 System.out.println(myNum);
🔒 Final Variables – Making Them Constant
If you don’t want to allow changes to a variable after it’s been assigned a value, you can declare it as final. This means the value becomes immutable (unchangeable).
java
final int myNum = 15; myNum = 20; // will generate an error: cannot assign a value to a final variable
The final keyword ensures the variable’s value cannot be altered.
🧳 Other Variable Types
Here’s how you can declare variables of other types:
int: int myNum = 5;
float: float myFloatNum = 5.99f;
char: char myLetter = 'D';
boolean: boolean myBool = true;
String: String myText = "Hello";
📍 Summary Box
Variable Type | Description | Example |
String | Stores text | String name = "John"; |
int | Stores whole numbers | int myNum = 15; |
float | Stores numbers with decimals | float myFloatNum = 5.99f; |
char | Stores a single character | char myLetter = 'D'; |
boolean | Stores true or false values | boolean myBool = true; |
🚀 Next Steps
Now that you've learned about Java variables, you're ready to explore more! Next up:
Java Data Types
Java Operators
Java Strings
Java Conditional Statements
Support the content: Donate here if you found this helpful! 💖
Next Print Variable
Comments