Variables, Data Types, and Operators in Java: The Building Blocks of Programming
When starting with Java programming, one of the first things to learn is how to store and manipulate data. This involves understanding variables, the types of data they hold, and operators that perform operations on these variables.
Let’s break these concepts down!
Variables in Java
A variable is a named storage location in memory that holds data your program can use and manipulate.
Declaring Variables
In Java, you must declare a variable’s data type before using it:
Initializing Variables
Assign a value to a variable when you declare it or later:
Common Data Types in Java
Primitive Data Types
| Data Type | Description | Example Value | Size |
|---|---|---|---|
int |
Integer numbers | 42 | 4 bytes |
double |
Decimal numbers | 3.14 | 8 bytes |
char |
Single character | ‘A’ | 2 bytes |
boolean |
True or false | true or false | 1 bit |
byte |
Small integer (-128 to 127) | 100 | 1 byte |
short |
Small integer (-32,768 to 32,767) | 20000 | 2 bytes |
long |
Large integer | 123456789L | 8 bytes |
float |
Single precision decimal | 3.14f | 4 bytes |
Reference Data Types
-
String: Represents text (a sequence of characters)
-
Arrays, Classes, Objects: More complex data structures
⚙️ Operators in Java
Operators allow you to perform operations on variables and values.
Arithmetic Operators
| Operator | Description | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 10 / 2 |
5 |
% |
Modulus (remainder) | 10 % 3 |
1 |
Assignment Operators
| Operator | Description | Example |
|---|---|---|
= |
Assign value | x = 5 |
+= |
Add and assign | x += 3 (x = x + 3) |
-= |
Subtract and assign | x -= 2 |
*= |
Multiply and assign | x *= 4 |
/= |
Divide and assign | x /= 2 |
Comparison Operators
| Operator | Description | Example | Result |
|---|---|---|---|
== |
Equal to | x == y |
true/false |
!= |
Not equal to | x != y |
true/false |
> |
Greater than | x > y |
true/false |
< |
Less than | x < y |
true/false |
>= |
Greater than or equal to | x >= y |
true/false |
<= |
Less than or equal to | x <= y |
true/false |
Logical Operators
| Operator | Description | Example | Result |
|---|---|---|---|
&& |
Logical AND | (x > 5 && y < 10) |
true if both true |
| ` | ` | Logical OR | |
! |
Logical NOT | !(x > 5) |
true if condition false |
Example: Using Variables and Operators
Summary
-
Variables hold data and must be declared with a type
-
Java has primitive and reference data types
-
Operators help manipulate and compare data
-
Understanding these basics is key to programming in Java
