Saturday, March 12, 2016

Intro To Java: Section 2.1 - Variables

Now that we've setup Eclipse, the JDK, and have created our first program, it's time to start learning how to use variables to store and manipulate information in Java.


Variables are elements of programs that store data such as numbers or text in the computer's memory. They can be thought of as containers that hold values. The types of variables you use for each program will vary depending on what you are trying to accomplish. Variables are declared by typing the keyword for the variable type followed by the variable identifier, or name. Variables are initialized by setting the variable equal to some value with the assignment operator, which is an equal sign.

Rules For Naming Variable Identifiers

  1. You may start the identifier with an underscore, a letter, or a money sign $.
  2. The following characters in the identifier may be letters, underscores, money signs, or numbers.
  3. Do not use keywords (reserved words for use by Java) in variable names.
  4. Identifiers for variables typically do not start with a capital letter. Each additional word in the identifier typically does. This format is known as lowerCamelCase. This is not required but is good practice.
    1. Name your variable myVariable - not myvariable or MyVariable.


One of the simplest examples of a variable is an integer. Integers are variables which can store whole numbers such as 1, 2, 3, and so on. They cannot store numbers containing decimal places. They may be negative or positive. In Java, integers are declared using the keyword int followed by the identifier name for the variable. You can initialize variables with values using equal signs. The example line below declares a variable and initializes its value to five.
int x = 5;
You don't have to initialize the variable with a value immediately if you do not want to. You may also declare a variable and initialize it later:
int x;
x = 5;
Note that you do not use the int keyword again on the second line. You only use the int keyword when you are first declaring the variable.
You can also print the value of variables to the console using the print methods. Instead of printing a string, you could print a variable. Note that Java is converting the integer to a string for output behind the scenes.
int x;
x = 5;
You should create a new project wtih a class file and a main method. Place the above code in the main method to see how it works. The console should look as follows when you run the program:

Basic Arithmetic Operations

It is possible to perform simple mathematical operations on integers without using special methods from the Java API. The example below shows you the five basic arithmetic operators you can use in Java.
public class SomeProgram{

     public static void main(String []args){
        //Addition Example
        int x = 5; //Create the variable x and set it to 5
        x = x + 5; //add 5 to x, then store in x for a value of 10
        //Display the results
        System.out.println("Addition: x + 5 =");
        //Subtraction Example
        int y = 10; //Create the variable y and set it to 10
        y = y - 5; //Subtract 5 from y and store result in y
        //Display the results
        System.out.println("Subtraction: y - 5 ="); 

        //Multiplication Example
        int z = 10; //Create the variable z and set it to 10
        z = z * 10; //Multiply z by 10 and store the result in z
        //Display the results
        System.out.println("Multiplication: z * 10 = ");
        //Division Example
        int a = 100; //Create the variable a and set it to 100
        a = a / 10; //Divide a by 10, store result in a
        //Display the results
        System.out.println("Division: a / 10 =");
        //Remainder Example (Modulus)
        int b = 100; //Create the variable b and set it to 100
        b = b % 10; //Find the remainder of b divided by 10
        //Display the results
        System.out.println("Remainder: b % 10 =");
In addition to being able to perform operations with numbers, it's also possible to do operations using variables themselves. The example below creates two integers, adds them together, and stores the result in variable named result.
//Initialize variables
int firstNumber = 10;
int secondNumber = 100;
int result = 0;

result = firstNumber + secondNumber;

//Display result

Shorthand Arithmetic

Java provides us with many useful ways to do arithmetic. These are "shorthand" methods that allow you to type less and produce the same code. The table below explains the functions, characters, and equivalencies of the various arithmetic functions. These should work for all of the primitive data types.

Add the following number or variable to the previous variable.
x += 5;
x = x + 5;
x += y; 
x = x + y; 
Subtract the following number from the previous
x -= 5; 
x = x - 5; 
x -= y;
x = x - y;
Multiply the numbers and store the result in the original variable
x *= 5; 
x = x *5; 
x *= y;
x = x * y;
Divide the original number by the second number
x /= 5;
x = x / 5;
x /= y;
x = x / y;
Add one to the variable
x = x + 1;
Subtract one from the variable
x = x - 1;

The example below demonstrates how you can add 1 to a variable using both the traditional method and using shorthand. Note that the output is the same. You will see these shorthand codes a lot when programming.
//Increment X value by 1
  int x = 1;
  x = x + 1;
  System.out.println("x + 1 = " + x);
  //Increment Y value by 1 using shorthand code
  int y = 1;
  System.out.println("y + 1 = " + y);
x + 1 = 2
y + 1 = 2

Order of Operations

It is possible to perform multiple arithmetic operations with a single statement, as is shown below.
int x = 5;
int y = 22;
int z;
z = 2*x+y;
When performing multiple operations it's important to know how Java's order of operations works. The equations are solved from left to right beginning with the parts of the statement in parenthesis. It then does multiplication and division, followed by addition and subtraction. The following example adds before multiplying with the use of parenthesis.
int x = 5;
int y = 22;
int z;
z = 2*(x+y);


Post a Comment