In this lesson we will look at our second Java program. This program will introduce us to variables and a few new ways to write output to the console window.
public class HelloVariable
{
public void multiplyBy2() {
/*
* Syntax for declaring a variable
* type variable-name;
*/
int number; // Here, we declare a variable called number
number = 50; // 50 gets assigned to number
System.out.println("The value of number is " + number);
number = number * 2; // Multiply the value of number by 2
System.out.print("After multiplication by 2, the value of number is ");
System.out.println(number);
}
}
We have a class named HelloVariable
. It contains a public method multiplyBy2
which takes no arguments and returns no value. Notice that multiplyBy2
is not marked static and there is no main
method in HelloVariable
class. So, in order to execute multiplyBy2
method we will need an object of HelloVariable
class. We will see how to create that object a little later, before that we will go through the program and try to understand it.
int number; // Here, we declare a variable called number
The first line of multiplyBy2
method declares an integer variable called number
. Variables are at the core of any meaningful program. You can think of variables as containers that hold information. Your program can change the information in these containers as needed. These containers are basically memory locations that hold some value. This value represents the information stored in that memory location. The memory location is given a name and this name is used to access that memory location in your program. In Java, you first need to declare a variable before using it. The syntax for variable declaration is
type variable-name;
Java defines several data types like integer, character and floating-point. The variable number
is of integer type as specified by the keyword int
at the beginning of its declaration. We will discuss data types and variables in detail in a later lesson. This is just a brief introduction to get us started.
In the next line, we assign a value of 50
to our variable number
.
number = 50; // 50 gets assigned to number
Moving on to the next line,
System.out.println("The value of number is " + number);
it prints The value of number is 50
to the console. Notice the use of ‘+’ to join this string with the value of number
. You can use the plus operator to join as many items you want within a single println statement and output the resultant string to the console.
Next line multiplies the value of number
by 2 and assigns it back to number
.
number = number * 2; // Multiply the value of number by 2
The current value of number
is 50. 50 multiplied by 2 gives 100. This result 100 is assigned back to the variable number
so when this line is executed, the value of number
changes from 50 to 100.
The next line uses print
method of System.out
to print After multiplication by 2, the value of number is
to the console.
System.out.print("After multiplication by 2, the value of number is ");
print
method is like println
method with one difference. It does not output the newline character after every call. What this means is that the next output that is printed on the console will start on the same line rather than starting on the next line.
The next line uses println method to print the value of number on the screen.
System.out.println(number);
So, 100 which is current value of number
gets printed to the console. Notice that number
is used by itself while calling the println
method. Both print
and println
methods can print the values of any of Java’s built-in types.
This is a simple program which uses a variable to multiply it’s value by 2 and assign it back to the variable. Let’s execute the program and see if the output comes as per our expectations or not.
As I said before, to execute multiplyBy2
method, we will first need to create an object of HelloVariable
class. After compiling the class, go to the main window, right click on HelloVariable
class and select this option new HelloVariable()
. This dialog is asking for a name of this object. You can give any name of your choice, but it should be a valid identifier. I will go with the name suggested by BlueJ helloVar1
and hit ok. The newly created object appears in the lower part of the window. The name you specified is written on the object. It is followed by a colon and then the class name to which this object belongs. This helps to identify your object when multiple objects are present. Right click on the object, select the method multiplyBy2
and it gets executed. As multiplyBy2
doesn’t take any arguments so BlueJ didn’t show any dialog for entering the arguments and directly executed the method. As you can see, the output is exactly as we discussed when we were going over the program.
Control statements overview
Next, we will briefly look at two control statements – the if statement and the for loop. A basic knowledge of these is needed to understand some of the concepts which I will be discussing next. This is just a quick overview, later in the course there is a dedicated section for control statements where we will spend a good amount of time to understand control statements in depth.
In the two programs you have seen so far, you would have noticed that when the program is run, its statements are executed from top to bottom in order in which they are written. The order in which the statements of a program are executed is known as control flow or flow of control. Most of the times you will want to alter the control flow to suit the needs of your program. You might want to skip some set of statements based on some condition while repeating some other set of statements. Programming languages provide statements to alter the control flow of the program and these statements are known as control statements.
if statement
When you need to make a decision in your program, you will use the if statement. It executes a certain section of code only if a test evaluates to true.
Its syntax is this:
if(condition) statement;
The if statement will evaluate the condition. If condition is true, then statement is executed. If condition is false, then the statement is bypassed.
Let’s see a program that demonstrates if statement in its most simple form.
public class HelloIf
{
public void demoIfStmt() {
int a, b;
a = 1;
b = 2;
if (a < b) System.out.println("a is less than b");
a = a * 2; //The value of a is now 2
if (a == b) System.out.println("a is now equal to b");
a = a * 2; //The value of a is now 4
if (a > b) System.out.println("a is now greater than b");
//This println will not be executed
if (a == b) System.out.println("This won't be printed");
}
}
Let’s execute it and then corelate the output with the code.
int a, b;
a = 1;
b = 2;
These statements above declare 2 integer variables a & b and assign the values 1 & 2 to them, respectively. You can declare multiple variables of the same type in a single line by separating them with commas.
if (a < b) System.out.println("a is less than b");
The next line shown above is an if statement which checks if a
is less than b
. The condition is true as the value of a
which is 1 is less than the value of b
which is 2 so the println
statement following it gets executed and we see the output a is less than b
on the console.
a = a * 2; //The value of a is now 2
if (a == b) System.out.println("a is now equal to b");
After this the value of a
is multiplied by 2 which gives the result as 2. This 2 is assigned back to a
changing its value from 1 to 2. The next if statement checks if a
is equal to b
. The condition is true as both a
and b
are now 2 so the println
following it gets executed and we see the second line of output a is now equal to b
on the console.
a = a * 2; //The value of a is now 4
if (a > b) System.out.println("a is now greater than b");
We again multiply a
by 2 and assign it back to a
. Now a
contains 4. The next if statement checks if a
is greater than b
. Value of a
is 4 and b
is 2. So, the condition of if statement evaluates to true as 4 is greater 2 and the println
following it gets executed and we see the third line of output a is now greater than b
on the console.
//This println will not be executed
if (a == b) System.out.println("This won't be printed");
Next if statement checks if a
is equal to b
. a
is 4 and b
is 2 so clearly, they are not equal. The condition is false, the println
following it is not executed and we don’t see the text This won't be printed
on the console.
This should give you a basic idea of how if statement works which is good enough for us to get started. We will revisit if later in the control statements section.
for loop
The other control statement that we will be looking at now is the for loop. In a programming language, loops are used to execute a set of statements repeatedly until the specified condition is satisfied. Java provides a very rich collection of looping constructs. The most commonly used one is the for loop.
This is the syntax of for loop:
for(initialization; condition; increment/decrement) statement;
The initialization portion of the loop sets the loop control variable to an initial value. Initialization happens only for the first time when the for statement is executed, which means that the initialization part of for loop only executes once. One execution of the for loop is called an iteration. Condition in for loop is evaluated on each iteration, if the condition is true then the statement gets executed. Once the condition returns false, the statement does not execute and the control gets transferred to the next statement in the program after for loop. After each iteration of the for loop the increment/decrement part of the loop gets executed and it updates the loop control variable.
For loop may sound complicated in theory but it is quite easy and straight forward to use in practice. So, let’s look at a program to understand for loop.
public class HelloFor
{
public void demoForLoop() {
int i;
/*
* For statement has the following syntax
* for(initialization; condition; increment/decrement) statement;
*/
for (i = 0; i < 3; i = i + 1)
System.out.println("The value of i is " + i);
System.out.println("Now you know for loop");
}
}
HelloFor
class will help us to understand for loop. We have a variable i
here which is of integer type. Then we have a for loop which contains a println
statement inside it. Lets execute the demoForLoop
method and see what is the output.
There are 4 output lines on the console even though our program has only two println
statements. The reason for this is the for loop which is repeatedly executing the first println
statement 3 times. Let’s take a closer look at the program and understand how this output got generated.
for (i = 0; i < 3; i = i + 1)
System.out.println("The value of i is " + i);
i
is the loop control variable of this for loop. It is assigned a value of 0 in the initialization portion of for loop. This initialization happens only the first time when for loop is executed. Next, the conditional test is performed. The current value of i
is 0 which is less than 3 so the condition is true. As the condition is true, the println
statement gets executed and we get our first output line on the console. After executing the statement, the increment/decrement part of the for loop is executed which increments i to 1. With this the first iteration of our for loop completes.
On the second iteration again, the conditional test is performed. i
is now 1 but it is still less than 3 so the condition is true and println
statement gets executed again. This gives us our second output line with value of i
as 1. Note that the initialization part of for loop is not executed again as it is only executed once at the beginning of the first iteration. After executing the println
statement, the increment/decrement part of for loop changes the value of i
to 2.
Like second iteration, at the beginning of third iteration, conditional test is true as value of i
is 2 so it is still less than 3. println
is executed, we get the third output line on the console. Then increment/decrement part of for loop changes the value of i
to 3.
At the beginning of fourth iteration, the conditional test is performed. Value of i
is now 3. That means, i is no longer less than 3 so the condition becomes false. As the condition is false, println
statement is not executed and program control moves to the statement after the for loop. In our case, it is this System.out.println("Now you know for loop");
statement and we see the output Now you know for loop
on the console.
Wouldn’t you agree with me now that for loop is quite simple and straight forward in practice.