Every programming language has variables. Variables are the most commonly used concept when programming. Any data/information that can be changed is a variable. A variable consists of 2 things, a name and a value, the name can carry some value/data, you give the name some data by using the = sign.Ex. favouriteNumber = 13; favouriteColor = blue;
There are different types of variables, there are variables that hold numbers, there are variables that hold letters, there are variables that hold sentences, etc.
- Int variables holds Integers
- ex. int age=5; int pinNumber =4021; int temperature = 28;
- Char variables hold single characters
- ex. char multipleChoiceAnswer= ‘c’; char grade=’a’;
- Double variables holds more precise numbers
- ex. double piMeasurement = 3.147; double heightInMeters = 1.8; double dollars=285.99;
- String variables hold words or a combination of characters
- ex. String color = “yellow”; String phrase = “I like to learn new things”; String password = “3fbU#cOol”;
- Boolean variable can either be set to true or false
- ex boolean lightOn = true; boolean dead=false; boolean readyToStart = false;
When we add a variable to our program, we must let the program know what type of variable it is by putting the type at the beginning of the variable name. Ex int age or String color.
Your program will not recognize your variable as a variable unless you declare its type.
45.8 is a
Kite is a
false is a
345 is a
Y is a
To display the contents of a variable on the screen, we use this code: System.out.print( variableName );
Replace ‘variableName’ with the name of your variable.
* Variable names cannot contain spaces or start with special characters, once you declare the variable type you don’t have to declare it again
You can change a variable’s data using operators
Here are some of the math operators: + (add) – (subtract) * (multiply) / (divide)
Ex. int age = 23; I have set the age as 23… but next year I would want to increase the age by 1. I can do that by using the + sign. Like this: age = age+1; this will make the new age 23+1 so age will now be 24.
Ex. int length = 2; int width = 3; If I want to calculate the area -> int area = length * width; This will compute 2X3 and assign the result 6 to the variable named area;
You can add two strings together using the + sign.
Program -> Create 2 variables, assign some data to the variables, then print the variables
Add two variables and see the result
int num1 = 5;
int num2 = 7;
String word1 = “hello”;
String word2 = ” Let’s Begin “;