--Originally published at Alan TC201
This is not a masterie neither a WSQ, I’m just writing this as an excersise for me to practice and know better the variables in Java.
“Field” and “variable” in In the Java programming language are very confusing because they are basicly the same most of the times, but it depends of the code to know wich term you are going to use.
Instance Variables (Non-Static Fields): Non-static fields are also known as instance variables because their values are unique to each instance of a class (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html). For example, let’s use an example that my teacher used told me. You have 10 cats, each one has it own color, one is brown other one is black, a little one is red and so on, each cat has its particular value of color.
Class Variables (Static Fields):: A class variable is any field declared with the static
modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html). With the same example of cats, but with Class Variables, you will have one behavior, like eat(), and does not matter what color the cat is, it will always eat, so this variable affect all the objects inside the class cat.
To name a variable there is no specific rule, but it is best to program in a orginice way so that not only you can read it, but other human beings can. So it is better to name a variable correctly.
NOT CORRECT int c = 10;
CORRECT int cat = 10;
Other rule is that you can not use the list of words that command somthing in Java to name your variable, because the program will get confuse. This is the list of words.(https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html)
“The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable’s type and name.” (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)
Doing so tells your program that a field named “gear” exists, holds numerical data, and has an initial value of “1”. A variable’s data type determines the values it may contain, plus the operations that may be performed on it.
But int is not the only command, there is more that holds different cuantitie of bits.
Data Type |
Default Value (for fields) |
byte |
0 |
short |
0 |
int |
0 |
long |
0L |
float |
0.0f |
double |
0.0d |
char |
‘u0000’ |
String (or any object) |
null |
boolean |
false |
(https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)