Java Fundamentals Prework Variable Initialization

Initializing variables

10 min

To start writing more complex apps, you’ll have to initialize variables at some point so that you’re able to hold and reference data in your programs.

Creating a variable in Java requires us to define the data type of that variable by providing the type before the name of the variable. Here’s the syntax:

int theAnswerToEverything = 42; int is labeled with 1, theAnswerToEverything is labeled with 2, and 42 is labeled with 3

  1. The data type that will be stored in the declared variable.
  2. The identifier (name) of the variable.
  3. The value to be assigned to the variable. The data type of this value must match the data type you provided earlier.

Here are some more examples:

src/main/java/Main.java

double priceOfWater = 3.99;
String bestLanguage = "Java";

In Java, the standard practice is to initialize a value to a variable when it is declared if possible, but you are able to declare a variable without assigning anything to it and then initialize it later.

src/main/java/Main.java

int iWillBeSomethingOneDay
iWillBeSomethingOneDay = 100;

When you do this, it may be initialized with a default value depending on its data type. You’ll learn more about all of Java’s different data types soon, but these are the ones above:

Naming variables

Variable names are written in lower camel case, like how you wrote the main() method - each word is joined so there are no spaces or characters between them, and every word after the first word starts with a capital letter.

Variable names follow a few rules: