Variables and Data Types
A variable stores a value. In Java you must say its type when you create it.
A variable is a named box that holds a value. Java asks you to label the box with its type up front - "this box only holds whole numbers". If you later try to put text in it, the compiler refuses. This catches a whole family of bugs before your program runs.
Java has two kinds of types. Primitive types are simple values stored directly (numbers, true/false, single characters). Reference types like String, arrays and your own classes are objects; the variable holds a reference (an address) pointing to the object.
Primitive types (simple values)
intwhole numbers:int qty = 3;longbig whole numbers:long views = 5000000000L;doubledecimal numbers:double price = 499.99;booleantrue or false:boolean inStock = true;charone character:char grade = 'A';
Why so many number types? Memory and range. int holds up to about 2.1 billion - fine for quantities and prices in paise. For bigger values (like views or bank transaction ids) use long. For money in real apps, professionals often use long paise or BigDecimal, because double can give tiny rounding errors (0.1 + 0.2 is not exactly 0.3).
Text with String
String holds text. Join strings with +.
Strings are objects with many useful methods: length(), toUpperCase(), contains(), substring(). Compare their text with .equals(), never with == (which compares whether they're the same object). This is one of the most common Java beginner bugs.
final for a value that must not change: final double GST = 0.18;- Every variable has a type:
int,long,double,boolean,char,String... - Primitives hold values; objects like String are reached through references.
- Compare Strings with
.equals(), not==. - Use
finalfor constants.
