# 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!

👀 E2 Practice 3

### 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: 2005Current Year: 2020Age : 15``
✍ Solve the problem using Replit
✍ You can solve the problem here using Trinket
💡 Hint Program: This program calculates when you will be 20.

👀 E2 Practice 4

##### 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 milesIf Shannon covers twice as much distance as Pete, distance travelled by Shannon is 20 miles``
✍ Solve the problem using Replit
✍ You can solve the problem here using Trinket