Java Programming Fundamentals
Java Syntax and Data Types
Variables and Data
In programming, we need a way to store information. We do this using variables. Think of a variable as a labeled box where you can keep a piece of data. To create one in Java, you need to tell the computer two things: what type of data you're storing and what you want to name the box.
Every variable in Java must have a specific type, and that type can't be changed later.
The basic structure for creating, or declaring, a variable looks like this:
type variableName = value;
Let's break that down:
typeis the data type (like a whole number or text).variableNameis the custom name you give the variable (e.g.,userAgeorproductName).=is the assignment operator. It assigns the value on the right to the variable on the left.valueis the actual data you want to store.;is a semicolon. Java requires a semicolon at the end of most statements. It’s like the period at the end of a sentence.
Primitive Types
Java has a set of fundamental data types called primitive types. They are the simplest building blocks for handling data. Let's look at the most common ones.
Primitives store simple, raw values.
For whole numbers, we use int (short for integer).
int score = 100;
int year = 2024;
For numbers with a decimal point, double is the standard choice. It's used for things like prices or scientific measurements.
double price = 19.99;
double pi = 3.14159;
For simple true or false values, we use boolean.
boolean isLoggedIn = true;
boolean hasError = false;
Finally, for a single character, we use char. The value is always enclosed in single quotes.
char grade = 'A';
char currencySymbol = '$';
Reference Types
Not all data fits neatly into a simple primitive type. For more complex data, Java uses reference types. Unlike primitives that hold their value directly, a reference variable holds a reference—think of it as an address—to where the actual object is stored in memory.
Two essential reference types you'll use constantly are String and arrays.
A
Stringis a sequence of characters. Note the capitalS—unlike the primitive types,Stringis a class. String values are enclosed in double quotes.
String greeting = "Hello, world!";
String userName = "Alex";
An array is a fixed-size collection of elements of the same type. Think of it as a row of numbered boxes, each holding a value. You declare an array by adding square brackets [] after the type.
// An array of integers
int[] scores = {88, 92, 75, 100, 95};
// An array of Strings
String[] days = {"Monday", "Tuesday", "Wednesday"};
Understanding the difference between storing a value directly (primitive) and storing a reference to it (reference type) is a core concept in Java. We'll build on these fundamentals as we explore more complex topics.