Creating Primitives
Estimated time to read: 2 minutes
Declaring a variable with primitive types¶
To create a primitive, simply state its type and name separated by a space and followed by a semi-colon to declare it.
If you have several primitives of the same time, you can declare them in a comma separated list.
Using variables with primitive types¶
Primitives can be declared anywhere in the code. Their placement affects their visibility Primitives that are declared inside a code bock, delimitated by braces, are only visible within their block. Primitives are also only visible below the point at which they are declared
Variable primitive type naming conventions¶
Primitives and methods share the same naming convention: the first word in the name is lower-case, the first letter in each additional word in the name is upper-case (Lower Camel Case).
public class Car {
// Some "Primitive" Data
private int numberOfDoors;
private int numberOfWheels;
}
For finals (constants), words are separated by underscores and are all capitals.
Initialising a variable with a primitive type¶
If you do not assign a value to a primitive to the variable, Java automatically users a default value depending on the type.
public class Car {
// Some "Primitive" Data
private int numberOfDoors = 2;
private int numberOfWheels = 4;
}
You can assign an initial value at the time you declare a variable, however, best practise dictates that these types of variable are given values in constructor methods.