
Knowing variables are highly important in Java programming. The purpose of variables is to store data values. Each variable needs to have a unique name to make sure for the allocating of memory. We will learn how to create a variable and key tips to name it in this post, so further when we start to create bigger projects with multiple functions, variables will be important to make sure the code isn’t over ruined.
The most used variables are like following:
String – text, such as “Hi”. String values need double quotes and String keyword should start with a capital letter
int – stores integers, without decimals
double – stores numbers, with decimals
float – stores point numbers, with decimals
char – stores single characters. Char values need single quotes
boolean – stores value: true or false
You need a simple format to use those variables. The following shows common format and examples to demonstrate it.
type variable name= value;
Examples;
int price = 43;
char subject = ‘A’;
String name = “Kaan”;
We can use this syntax format for any of six variable types.
Final keyword
If you do not want anybody to overwrite values that you want for variables, you can write it with the final keyword. For example;
You can overwrite your initial integer like following;
int number = 10;
number =15;
// your new number is 15 now
If you do not want to overwrite your number, type like following;
final int number =10;
Multiple variables together
You can put together multiple variables of the same type and print them with operators. I give an example with the “+” sign.
Example 1
Example 2
Naming Variables
Java programming has its own rules for naming like following;
- Variable names are case sensitive, for example; eye and EYE are different variable names
- Variable names cannot start with number
- Variable names can have letter,digits, two special characters, underscore and $ sign
- Variable names may not contain punctuation character or spaces
- Variable names can be followed by underscore or $ sign
- White space and special characters like , ; * : are not allowed
- Variable names must not be a keyword, such as; if, else, for, while, int, double, etc.
