Variables
INFO
When we write code in Java, it needs to be written inside something called a class
. This won't mean anything to you right now, but it will soon!
For now, it's enough to know that to make Java code run, it has to go inside some boilerplate like this:
public class Main {
public static void main(String[] args) {
// Your code goes here
}
}
Using var
In Java, we can use var
to create new variables.
public class Main {
public static void main(String[] args) {
var bookTitle = "Persepolis";
System.out.println(bookTitle);
}
}
Persepolis
The order of the lines matters.
public class Main {
public static void main(String[] args) {
System.out.println(bookTitle);
var bookTitle = "Persepolis";
}
}
./Main.java:3: error: cannot find symbol
System.out.println(bookTitle);
^
symbol: variable bookTitle
location: class Main
1 error
error: compilation failed
Specifying type
Rather than using var
, it is possible to explicitly give the type of the variable.
public class Main {
public static void main(String[] args) {
String bookTitle = "Persepolis";
System.out.println(bookTitle);
}
}
Persepolis
Whether to use var
or the explicit type is a matter of opinion.
INFO
A string in programming is a sequence of text characters. There are other types, too, such as integers and booleans. We will learn all about them soon!
Redefining variables
Variables can be reassigned new values.
public class Main {
public static void main(String[] args) {
String bookTitle = "Persepolis";
System.out.println(bookTitle);
bookTitle = "The Kite Runner";
System.out.println(bookTitle);
}
}
Persepolis
The Kite Runner
Using final
To define a constant in Java, we use the final
keyword.
public class Main {
public static void main(String[] args) {
final var libraryName = "Central Library";
System.out.println(libraryName);
}
}
Central Library
However, because we used final
, we cannot change its value.
public class Main {
public static void main(String[] args) {
final var libraryName = "Central Library";
System.out.println(libraryName);
libraryName = "Quantum Codex"; // This will cause an error
}
}
./Main.java:6: error: cannot assign a value to final variable libraryName
libraryName = "Quantum Codex";
^
1 error
error: compilation failed
Referencing between variables
A variable which points to another variable's value does not update its value when the original variable changes.
public class Main {
public static void main(String[] args) {
String user1 = "BookishBen99";
String user2 = user1;
System.out.println("User 1: " + user1);
System.out.println("User 2: " + user2);
user1 = "pageturner_mia";
// Notice that user2 does not change
System.out.println("User 1: " + user1);
System.out.println("User 2: " + user2);
}
}
User 1: BookishBen99
User 2: BookishBen99
User 1: pageturner_mia
User 2: BookishBen99