Most values in a computer program have a type. The type tells Java what the value represents and what operations make sense for it.
Java divides types into primitive and reference types. Common examples include:
- Integer types:
int,long, andshort(plus byte) - Floating-point types:
double(plus float) - Character and Boolean types:
booleanand char - Reference types:
String,arrays,classes, andinterfaces
Variables
A variable is a named storage location. Java is statically typed, so every variable declaration states what kind of data the variable can store.
For example, int num = 10; gives a type, name, and initial value, followed by a semicolon.
int num = 10;
System.out.println(num); // 10
double salary = 8232.56;
System.out.println(salary); // 8232.56Here, num is declared as int, while salary is declared as double. Java checks later assignments against those types.
KNOWLEDGE QUIZ
Naming variables
Good variable names are clear and valid:
- Use letters, digits, and underscores, but do not start with a digit.
- Do not use Java reserved keywords.
- Prefer meaningful English words.
Names like age, studentName, and totalScore are easier to read than a or x1.
KNOWLEDGE QUIZ
Java keywords
Keywords are reserved by Java and cannot be used as ordinary variable names.
Common keywords include:
true,false,nullboolean,byte,char, doubleif,else,switch, casefor,while,break,continuevoid,return,class, interfacetry,catch,finally, throwimport,package,public, private
Using a keyword as a variable name would make Java unable to tell whether you mean a language feature or an ordinary value.
KNOWLEDGE QUIZ