Chapter 1a - Variables
Variablesβ
Example Variables
int age=15;
π§ͺ Try the code out!
- Do you think you are able to change the printing message from
Hello World
to a different thing?
Basic Math Operations using Variablesβ
int num = 100;
// Addition
int sum = 20 + 10;
System.out.println(sum);
// Subtraction
int sub = 20 - 10;
System.out.println(sub);
// Multiplication
int mul = 20 * 10;
System.out.println(mul);
// Division
int div = 20 - 10;
System.out.println(div);
π§ͺ Try the code out!
Example Program that adds two variablesβ
class Main{ //βclassβ is a keyword which is used to define a class.
public static void main(String[] args) {
System.out.println("PROGRAM TO ADD TWO NUMBERS");
int num1 = 10; // num1 is a variable of int data type
int num2 = 20; // num2 is a variable of int data type
int sum = num1 + num2; //sum is a variable of int data type
System.out.println(num1);
System.out.println(num2);
System.out.println(sum);
}
}
Rules for Defining Variablesβ
It is important to follow the below guidelines to name a variable in java.
- A variable must start with a letter of the alphabet or an underscore (_).
- A variable name can have alphabets, numbers & underscore (_).
- No white space (spaces) is allowed within the variable name.
- Variable names are case sensitive.
- A variable name must not be any reserved word or keyword e.g. char, float etc.
π§ͺ Try the code out!
Concatenationβ
Concatenating Wordsβ
System.out.println("Pineapple " + " Pen");
π§ͺ Try the code out!
You can also concatenate int and wordsβ
int books = 51;
System.out.println("I have " + books + " books in my study");
π§ͺ Try the code out!
Exercisesβ
Activity: Age Calculator
Write a Java program that uses year of birth and current year to calculate the age of a person. Make sure to output the year of birth, current year and age in a neatly formatted sentence.
Before you start, think about how many variables you will need for this activity. Expected Output:
Age Calculator
---------------
Year Of Birth: 2005
Current Year: 2020
Age : 15
β Solve the problem using Replit
β You can solve the problem here using Trinket
π‘ Hint Program: This program calculates when you will be 20.
Activity Hiking β°
Pete and Shannon are hiking. Shannon is always 2 miles ahead of Pete. What is the distance Shannon has covered if Pete has covered 10 miles? How would the program change if Shannon has covered twice as much distance as Pete? The output should look something like this:
If Shannon is two miles ahead of Pete, distance hiked by Shannon is 12 miles
If Shannon covers twice as much distance as Pete, distance travelled by Shannon is 20 miles