Variables:
int myInteger = 4; // Declare a int type variable and assign value
myInteger = 6; // Assign a different value to the variable
System.out.println(myInteger); // Access the variable (this will display 6)
System.out.println(myInteger + 4); // Use the variable in math (this will display 10)
- Variables are useful, because you can change the value in one place, then it will be changed everywhere it is used
Variable Data Types:
int myInt = 2; // An integer is a whole number between -/+ 2147483647 (32 bits)
float myFloat = 2.42f; // A float is a number that can have a decimal
char myChar = 'w'; // A char is a single character (letter, number, symbol)
boolean myBoolean = false; // A boolean stores a value of true or false
long myLong = 14234456234453756l; // A long is capable of storing very large whole numbers (64 bits)
double myDouble = 0.012341234; // A float capable of storing higher precision numbers
String myString = "Some text"; // A string of characters is used to store text
- Data types specify to the computer how much memory space your variable needs
- Data types also allow the computer to ensure that a value is of the expected type when you change/access it later, which helps you find mistakes in your code
- Put "f" at the end of float values with decimals, and "L" at the end of long values too big to be integers
Converting variable values to similar data types (a.k.a. casting):
long myLong = 223423l;
int myInt = (int)myLong; // Cast it to an integer with the "(int)" command
- If casting to a type with less storing capacity, be careful only to do so when you know that the value isn't too big to be contained by the new data type
Adding to Variable Values:
int myInteger = 4; // A calculation can be assigned to a variable
myInteger = myInteger + 3; // The variable can access its current value when assigning
myInteger += 3; // += means "= itself plus"; you can also use *=, /=, etc.
myInteger++; // ++ means add 1, -- means subtract 1
String myString = "words";
myString += " more words"; // += works on strings too
Adding numbers to Strings:
String myString = "testing" + 3; // Results in a string "testing3"
Convert between a String number and an integer:
String myStringNum = "3";
int myInt = Integer.parseInt(myStringNum);
- This is useful for receiving a number as input from the console
Challenge
Create a variable called name, and a variable called age. Display the following,
replacing the values in angle brackets with the variable values:
"Joe is <age + 5> years old, which is about five years older than <name>",