Skip to content

Declaring and naming variables

โ˜• Java 17 ยท Declaring Variables ยท 1/2

Declaration and initialization

A variable is a named slot in memory. Declaring it means giving its type and its name; initializing it means giving it a first value:

String title;                        // declaration
title = "Stranger Things";           // initialization

int releaseYear = 2016;              // both on one line
double rating = 9.5;

The pattern is always: type, name, optionally = and a value, then ;.

Declaring several variables at once

Variables of the same type can share one declaration, separated by commas. Each one may or may not get a value:

int season, episode, duration;
int season = 1, episode, duration = 45;   // only season and duration initialized

You can't mix types in one declaration:

int season, String title;    // โŒ doesn't compile
int season; String title;    // โœ… two separate declarations on one line (legal, but hard to read)

Java checks every name, or identifier, against four rules:

Rule โœ… โŒ
Starts with a letter, $ or _ movieTitle, _year2024, $price 3dMovie
Then letters, digits, $, _ only season2 my-rating (that's a minus)
Not a reserved word isActive class, int, for
Not a single underscore _count _

Names are case-sensitive: rating, Rating and RATING are three different variables.

Naming conventions

The compiler only enforces the rules above. Professional Java code also follows these conventions:

String streamingPlatformName = "Netflix";     // camelCase: variables and methods
class StreamingPlatform { }                   // PascalCase: classes
final int MAX_EPISODE_DURATION = 3600;        // SCREAMING_SNAKE_CASE: constants
Convention Used for Shape
camelCase variables, methods first word lowercase, next words capitalized
PascalCase classes every word capitalized
SCREAMING_SNAKE_CASE constants (final) all uppercase, words joined by _

Stick to them: anyone reading your code knows at a glance what each name is.

Next, the variables you declare inside methods follow stricter rules, and two keywords change how a declaration works: final and var.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

Next: local variables, final and var โ†’