Learning Java Fundamentals: Variables
Variables
In programming, variables are usually used for data storage. In Java, there are different types of variables:
String ~ stores text surrounded by double quotes, such as “Friend”
int ~ stores whole number integers — excluding decimals, such as 300 or -300
float ~ stores decimal, or floating point numbers such as 23.55 or -23.55
char ~ stores single characters, such as ‘d’ or ‘C’
boolean ~ stores truthy or falsey values
Declaring Variables
When declaring a variable in Java, we must first specify the type of variable it is and then assign the value with a unique name:
type variableName = value;String myName = "Ifeoluwa";int myAge = 100;float decimal = 0.03;char letter = 'g';boolean imHappy = true;
A variable can also be declared before assigning it a value!
int wholeNumber; //declared firstwholeNumber = 6; //then assigned
Values stored in variables can be overwritten with new values.
int wholeNumber; //declared firstwholeNumber = 6; //then assignedwholeNumber = 7; //new valuesidenote: to keep a variable from being overwritten use the keyword final. This declares the variable as constant, or unchangeable
Declaring Multpile Variables
To declare variables of the same type, commas are utilized like so:
int x = 8, y = 9, z = 10;
System.out.println(x + y + z);
Can also assign the same value to multiple variables — of the same type:
String name, noun, text;name = noun = text = "Ifeoluwa ";
System.out.println(name + noun + text); // Ifeoluwa Ifeoluwa Ifeoluwa what will print on to the screen
Print Variables
The statement System.out.println()
is used to print code on to the screen. It is also utilized to print varaibles:
String myName = "Ifeoluwa";System.out.println(myName); // Ifeoluwa what will print on to the screen
To add text, use +
character
System.out.println("Hello " + myName); // Hello Ifeoluwa what will print on to the screen
Can also combine variables together and store them in to another variable:
String myFirstName = "Ifeoluwa ";
String myLastName = "Akinremi Wade";
String myFullName = myFirstName + myLastNameSystem.out.println(myFullName); // Ifeoluwa Akinremi Wade what will execute on to the screen
The +
characters works for mathematical values as well
int x = 5;
int y = 6;
System.out.println(x + y); // // 11 what will print on to the screen