Numbers
Part of the Fundamentals section of Coddy's Java journey — lesson 5 of 73.
Variables are containers that hold data values. They are used to store, manipulate, and display information within a program.
In short a variable is like a memory unit that we can access by typing the name of the variable.
Each variable has a unique name and a value that can be of different types. Java has various built-in data types that define the type of value a variable can hold.
To initialize a variable, we use the following format:
variable_type variable_name = value;In Java, numbers are typically represented using two main data types: int and double.
int is used to store whole numbers without any decimal point. For example:
int age = 30;
int temperature = -5;
int count = 100;double is used to store numbers with a decimal point. For example:
double price = 99.99;
double pi = 3.14159;
double fraction = 0.5;When declaring variables in Java, you need to specify the type of the variable before the variable name. This is known as type declaration. Once a variable is declared with a certain type, it can only hold values of that type.
Challenge
BeginnerWrite a Java program that declares and initializes the following variables:
- Declare an
intvariable namedquantityand initialize it with the value5. - Declare a
doublevariable nameditemPriceand initialize it with the value24.99.
After declaring and initializing these variables, use System.out.println() to output the values of the variables to the console in the following format:
Quantity: [value of quantity]
Price: [value of itemPrice]Cheat sheet
Variables are containers that hold data values. To initialize a variable, use the format:
variable_type variable_name = value;int is used for whole numbers:
int age = 30;
int temperature = -5;double is used for numbers with decimal points:
double price = 99.99;
double pi = 3.14159;Java requires type declaration - you must specify the variable type before the variable name, and the variable can only hold values of that declared type.
Try it yourself
public class Main {
public static void main(String[] args) {
// Declare and initialize variables here
// Output the values
System.out.println("Quantity: " + quantity);
System.out.println("Price: " + itemPrice);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else