Understanding Java Basics: Data Types, Variables, and Operators
Now, lets look at the basics of Java: data types, variables, and operators. These are the core of any Java program. We’ll explore each of these concepts with real-world examples to make it easier for you.
Primitive Data Types
Java has several basic data types:
int
: For whole numbers (like 10, -5, 0). Range from -2,147,483,648 to 2,147,483,647.float
: For decimal numbers (like 3.14, -2.5). It’s a single-precision 32-bit IEEE 754 floating point.double
: For bigger decimal numbers (like 3.14159, -123.456). A double-precision 64-bit IEEE 754 floating point.boolean
: For true/false values.char
: For single letters (like ‘A’, ‘b’). A single 16-bit Unicode character.byte
: Very small whole numbers. Range from -128 to 127.short
: Small whole numbers. Range from -32,768 to 32,767.long
: Large whole numbers. Range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
int age = 30;
double price = 19.99;
boolean isTrue = true;
char grade = 'A';
Variables and Constants
Variables store data. Constants are variables whose values don’t change.
int score; // Declaring a variable
score = 100; // Initializing it
final double PI = 3.14159; // Declaring a constant
Variable names must start with a letter, underscore, or dollar sign. They can’t start with a number. Also, Java is case-sensitive (myVar
and myvar
are different).
Operators in Java
Operators do things with variables and values.
- Arithmetic:
+
(add),-
(subtract),*
(multiply),/
(divide),%
(modulus). - Relational:
==
(equal),!=
(not equal),>
(greater than),<
(less than),>=
(greater than or equal),<=
(less than or equal). - Logical:
&&
(and),||
(or),!
(not). - Assignment:
=
,+=
,-=
,*=
,/=
,%=
. - Bitwise: Operate on bits.
int x = 10 + 5; // Addition
boolean isEqual = (x == 15); // Equality
boolean isGreater = (x > 12) && (x < 20); // Logical AND
Operators have an order of precedence (like in math). Use parentheses to control the order.