Unlike Python, variables in Java sometimes referred to as identifiers are declared by their type. Common types used are String and int. Also take note that Java is very case sensitive, so a variable "data", "Data" and "DATA" would be treated as separate variables. When naming your variables in Java or any other programming language, it is important that you abide to the following rules. In other words, you should adopt the PascalCase for class names and camelCase for other identifiers.
- An identifier MUST not start with a digit and all characters must be letters, digits or underscore symbol.
- The FIRST character should be lower case if the identifier is a variable
- ALL characters must be upper case if the identifier is a constant variable
- The FIRST character should be upper case if the identifier is a class name
These naming conventions are there to make it easy to read code and it also comes in handy when debugging. When you are reading a code written by another programmer, you should be able to spot the name of the class right away and identify any variables used at any stage of the code. The following are perfectly legal ways of naming a variable.
- mydata
- my_data
- myData
- myData1
- thisJavaVariable
Just like any other programming language, Java too does have special words that can NEVER be used to name identifiers. These special words are referred to as keywords and reserved words. You have already seen public, class, static, void, main, String, int, print, System, print, println, etc.
A variable has to be declared before it can be used in Java. The prefix to the variable name indicate what type of data is to be stored in the variable. More than one variable of the same type can be declared in the same line. Here is an example of variable declaration.
- String myData;
- String varOne, varTwo, varThree;
- int thisData = 1;
Variables can also be initialized in the same line it is declared. If it isn't initialized, it is automatically assigned a default value. Java has 8 basic data types also known as primitive data type. See the table below that shows their different properties.
Primitive Data Types | ||||
---|---|---|---|---|
Type | Value Type | Memory Used | Default Value | Size Range |
byte | integer | 1 byte | 0 | -128 to 127 |
short | integer | 2 bytes | 0 | -32768 to 32767 |
int | integer | 4 bytes | 0 | -2147483648 to 2147483647 |
long | integer | 8 bytes | 0 | -9223372036854775808 to -9223372036854775807 |
float | decimal | 4 bytes | 0.0 | -3.40282347 × 1038 to -1.40239846 × 10-45 |
double | decimal | 8 bytes | 0.0 | ±1.76769313486231570 × 10308 to ±4.94065645841246544 × 10-324 |
char | single character (unicode) |
2 bytes | \u0000 | all unicode characters |
boolean | true or false | 1 byte | false | n/a |
Take note that String is not a primitive data type but an object data type. Its default value is null which is the same for all object data types.
Share your thoughts