In the previous code:
You can now save your code and run the application; you should see two additional messages displayed in the console window (i.e., the ones that you have just added).
For now, using blocks of instructions may look like it will not make much of a difference to your coding. This being said, blocks of instructions are very helpful, as we will see later, especially when we need to tell the browser to execute a list of instructions based on a condition, for example. This is because, in this case, instead of telling the system to execute each instruction individually, we can instead, ask for a block of instructions to be executed.
Comments
In Java, you can use comments to explain your code and to make it more readable by others. This becomes important as the size of your code increases; and it is also important if you work in a team, so that other team members can understand your code and make amendments in the right places, if and when it is needed.
Code that is commented is usually not executed. There are two ways to comment your code in Java using either single– or multi-line comments.
In single-line comments, a double forward slash is added at the start of a line or after a statement, so that this line (or part thereof) is commented, as illustrated in the next code snippet.
//the next line prints Hello in the console window System.out.println("Hello"); //the next line declares the variable name String name; name = "Hello";//sets the value of the variable name
In multi-line comments, any code between the characters forward slash and star ” /*“ and the characters star and forward slash “*/“ will be commented, and this code will not be executed. This is also referred as comment blocks.
name = “My Name”;
/* the next lines after the comments will print the message "hello" in the console window we then declare the variable name and assign a value */ System.out.println("Hello"); String name; name = "Hello";//sets the value of the variable name //System.out.println("Hello World") /* String name; name = "My Name"; */
In addition to providing explanations about your code, you can also use comments to prevent part of your code from being executed. This is very useful when you would like to debug your code and find where the error or bug might be, using a very simple method. By commenting sections of your code, and by using a process of elimination, you can usually find the issue quickly. For example, you can comment all the code and run the application; then comment half the code, and run the application. If it works without no errors, it means that the error is within the code that has been commented, and if it does not work, it means that the error is in the code that has not been commented. In the first case (when the code works), we could then just comment half of the portion of the code that has already been commented. So, by successively commenting more specific areas of our code, we can get to discover what part of the code includes the bug. This process is often called dichotomy, as we successively divide a code section into two.
Let’s use comments in our application:
public static void Main(String[] args) { //System.out.println("Hello, this is my fist line of code"); System.out.println("Hello, this is my second line of code"); { System.out.println("this is my first application");
In the previous code, we comment the message “Hello this is my first line of code” and replace it with the message “Hello this is my second line of code”.
Now that you have made these changes, please save your code and run the application; you should see that, this time, the message Hello this is my first line of code has been replaced with “Hello this is my second line of code”.
We could also use multi-line comments as follows (new code in bold).
System.out.println("Hello, this is my second line of code"); { /*System.out.println("this is my first application"); System.out.println("This statement and the previous one belong to the same block of instructions");*/ }
In the previous code, we used a multi-line comment. This means that the two lines comprised between /* and */, while they belong to the file, will not be executed.
If you save your code and run the application, you should see that the only message displayed onscreen is “Hello this is my second line of code”.
Variables
Now that you know a bit more about statements and comments, we will start to learn more about variables, which are quite important in Java, as you will probably use them in most of your programs to perform calculations or to work with text.
So what is a variable?
A variable can be compared to a container that includes a value that may change over time. When using variables, we usually need to: (1) declare the variable by specifying its type, (2) assign a value to this variable, and (3) possibly combine this variable with other variables using operators, as illustrated in the next code snippet.
int myAge;//we declare the variable myAge myAge = 20;// we set the value of the variable myAge to 20 myAge = myAge + 1; //we add 1 to the variable myAge
In the previous example, we have declared a variable called myAge and its type is int (as in integer). We save the value 20 in this variable, and we then add 1 to it.
Note that in Java the variable is declared using its type followed by its name. As we will see later, we will also need to use what is called an access modifier in order to specify how and from where this variable can be accessed.
Also note that in the previous code, we have assigned the value myAge + 1 to the variable myAge; the = operator is an assignment operator; in other words, it is there to assign a value to a variable and is not to be understood in a strict algebraic sense (i.e., that the values or variables on both sides of the = sign are equal).
To make Java coding easier and leaner, you can declare several variables of the same type in one statement. For example, in the next code snippet, we declare three variables v1, v2, and v3 in one statement. This is because they are of the same type (i.e., they are integers).
int v1,v2,v3; int v4=4, v5=5, v6=6;
In the previous code, the first line declares the variables v1, v2, and v3. All three variables are integers. In the second line of code, not only do we declare three variables simultaneously, but we also initialize them by setting a value for each of these variables.
When using variables, there are a few things that we need to determine including their name, their type and their scope:
String myName = "Patrick";//the text is declared using double quotes int currentYear = 2017;//the year needs no decimals and is declared as an integer float width = 100.45f;//the width is declared as a float (i.e., with decimals)
String myName;
myName = “My Name”
Common variable types include:
Using variables
In this section, we will start to use variables and combine them using statements and operators. So let’s get started:
//System.out.println(“Hello, this is my second line of code”);
{
/*System.out.println(“this is my first application”);
System.out.println(“This statement and the previous one belong to the same block of instructions”);*/
}
int dateOfBirth = 1990; int currentYear = 2017; int age = currentYear - dateOfBirth; System.out.println("My age is " + age);
In the previous code:
Note that adding a number and a String is equivalent to concatenating these two, so the result of this addition will be a String.
You can now save your code, compile it, and run your application; you should see the message “My age is 27” in the Console window.
Operators
Once we have declared and assigned a value to a variable, we can use operators to modify or combine variables. There are different types of operators available in Java, including arithmetic operators, assignment operators, comparison operators and logical operators.
So let’s look at each of these.
int number1 = 1;// the variable number1 is declared int number2 = 1;// the variable number2 is declared int sum = number1 + number2;// we add two numbers and store them in sum int sub = number1 - number2;// we subtract two numbers and store them in sub
int number1 = 1; int number2 = 1; number1+=1; //same as number1 = number1 + 1; number1-=1; //same as number1 = number1 - 1; number1*=1; //same as number1 = number1 * 1; number1/=1; //same as number1 = number1 / 1; number1%=1; //same as number1 = number1 % 1;
Note that the + operator, when used with Strings, will concatenate them (i.e., add them one after the other to create a new String). When used with a number and a String, the same will apply and the result is a String (for example “Hello“+1 will result in “Hello1“).
if (number1 == number2); //if number1 equals number2 if (number1 != number2); //if number1 and number2 have different values if (number1 > number2); //if number1 is greater than number2 if (number1 >= number2); //if number1 is greater than or equal to number2 if (number1 < number2); //if number1 is less than number2 if (number1 <= number2); //if number1 is less than or equal to number2
Conditional statements
While we have looked at simple variables such as numbers or text, and how to modify them with operators, we will now look at conditional statements.
Conditional statements are statements that are performed based on a condition, hence their name. Their syntax is usually as follows:
if (condition) statement;
This means if the condition is verified (or true) then (and only then) the statement is executed. When we assess a condition, we test whether a declaration (or statement) is true.
For example, by typing if (a == b), we mean “if it is true that a equals b“. Similarly, if we type if (a>=b) we mean “if it is true that a equals or is greater than b“
As we will see later, we can also combine conditions. For example, we can decide to perform a statement if two (or more) conditions are true. For example, by typing if (a == b && c == 2) we mean “if a equals b and c equals 2“. In this case using the operator && means AND, and that both conditions will need to be true. We could compare this to making a decision on whether we will go sailing tomorrow.
For example, we could translate the sentence “if the weather is sunny and the wind speed is less than 5km/h then I will go sailing” as follows.
if (weatherIsSunny == true && windSpeed < 5) IGoSailing = true;
When creating conditions, as for most natural languages, we can use the operator OR noted ||. Taking the previous example, we could translate the following sentence “if the weather is too hot or the wind is faster than 5km/h then I will not go sailing ” as follows.
if (weatherIsTooHot == true || windSpeed > 5) IGoSailing = false;
Another example could be as follows.
if (myName == "Patrick") System.out.println("Hello Patrick"); else System.out.println ("Hello Stranger");
In the previous code, we display the text “Hello Patrick” if the variable myName equals to “Patrick“; otherwise, we display the message “Hello Stranger“.
When we assess true and false conditions, we are effectively applying what is called Boolean logic. Boolean logic deals with Boolean numbers that have two values 1 and 0 (or true and false). By evaluating conditions, we are effectively processing Boolean numbers and applying Boolean logic. While you don’t need to know about Boolean logic in depth, some operators for Boolean logic are important, including the ! operator. It means NOT or “the opposite of“. This means that if a variable is true, its opposite will be false, and vice versa. For example, if we consider the variable weatherIsGood = true, the value of !weatherIsGood will be false (its opposite). So the condition if (weatherIdGood == false) could also be written if (!weatherIsGood) which would literally translate as “if the weather is NOT good”.
Let’s experiment with conditional statements:
import Java.util.Scanner;
In the previous code we import the class called Scanner so that we can use it in our own programme; this class, provided by Java, makes it possible to read the users’ input.
System.out.println("My age is " + age); System.out.println("Please enter your name: "); Scanner sc= new Scanner (System.in); String nameOfUser = sc.nextLine(); System.out.println("Hello "+nameOfUser);
In the previous code:
As we will see later, when we build a new Scanner variable, we need to tell the system where the information it has to process is coming from; in our case, this information is coming from the standard input (i.e., the keyboard) which we refer as System.in, hence the following syntax sc = new Scanner (System.in).
You can now save your code and run the application:
Now that we have managed to capture the entry from the user, we will experiment with using conditional statements. So, please amend the code in the file MyClass as follows (new code in bold).
/*System.out.println("Please enter your name: "); Scanner sc= new Scanner (System.in); String nameOfUser = sc.nextLine(); System.out.println("Hello "+nameOfUser);*/ System.out.println("What is 1 + 1"); Scanner sc= new Scanner (System.in); int answer= sc.nextInt(); if (answer == 2) System.out.println("Well Done!"); else System.out.println("Sorry Incorrect Answer!");
In the previous code:
You can now save your code, compile it, and run your application, and you should see, as for the previous example, a text asking you to enter your answer to the question “What is 2 + 2”.
Methods
Now that you can declare and combine numbers and Strings, it is a good time to start looking into methods.
Methods can be compared to a friend or a colleague to whom you gently ask to perform a task, based on specific instructions, and to return information afterwards, if need be.
For example, you could ask your friend the following: “Can you please tell me when I will be celebrating my 20th birthday given that I was born in 2000“. So you give your friend (who is good at Math :-)) the information (i.e., the date of birth) and s/he will calculate the year of your 20th birthday and give this information back to you. So in other words, your friend will be given an input (i.e., the date of birth) and s/he will return an output (i.e., the year of your 20th birthday). Methods work exactly this way: they are given information (and sometimes not), perform an action, and then sometimes, if needed, return information.
In programming terms, a method is a block of instructions that performs a set of actions. It is executed when invoked (or put more simply called) from the application, or when an event occurs (e.g., when the player has clicked on a button). As with variables, methods are declared and can also be called.
Methods are very useful because once the code for a method has been created, it can be called several times without the need to rewrite the same code all over again. Also, because methods can take parameters, a method can process these parameters and produce or return information accordingly; in other words, they can perform different actions and produce different outputs based on the input. As a result, methods can do one or all of the following:
A method is usually declared using two keywords followed by its name as follows:
accessType typeOfDataReturned nameOfTheFunction (listOfParameters) { Perform actions here }
In the previous snippet:
Using this template, we could, for example, define the following method:
public void myMethod () { System.out.println("hello"); }
In the previous code:
A method can be called using the () operator, as illustrated in the next code snippet:
nameOfTheFunction1(); nameOfTheFunction2(value); int test = nameOfFunction3(value);
In the previous code, a method is called with no parameter (first line), or with a parameter (second line). On the third line, a variable called test will be set with the value returned by the method nameOfFunction3 which takes one parameter.
Let’s create our very own method:
//System.out.println("What is 1 + 1"); //String resultAsString = Console.ReadLine(); //int result = Int32.Parse(resultAsString); //if (result == 2) System.out.println("Well done"); //else System.out.println("Sorry, wrong answer");
int myAge = calculateAge(1990); System.out.println("My Age is " + myAge); }
In the previous code:
We can now create the method called calculateAge by adding the following code after the method main.
public static int calculateAge(int yearOfBirth) { return (2018 - yearOfBirth); }
In the previous code:
Note that the new method called calculateAge is declared as static; this is because, the method main is static by default, and that as a result, it can only call a method that is also static. If you forget to declare this method as static and try to call it from the main method, the system will generate an error message.
The main method is static because it is the entry point of the programme, and it is the first method to be called (or invoked) when the application is started. It is public because it needs to be accessible from outside the application. Its return type is void because it usually doesn’t return any data. It includes parameters but these are not compulsory.
Please save your code, and run the application, and you should see the message “Hello, My Age is 28” in the console window.
Scope of variables
Whenever you create variables in Java, you will need to be aware of their scope so that you use it where its scope makes it possible for you to do so. This is particularly important if you use methods, as some variables will be used just locally, whereas others will be used throughout the class or the application.
The scope of a variable refers to where you can use this variable in an application. In Java, in addition to access modifiers that will be covered later in this book, variables can be member variables or local variables.
Put simply, your application will be made of several parts called classes. In our case, the entry point for our application is a class called MyClass.
class MyClass { public int myVar; public void method1() { myVar = 0; } public void method2() { myVar = myVar + 1; }
In the previous code, the member variable myVar is declared at the start of the class MyClass; it is then initialized in method1, and updated in method2. Note that the variable was declared as public, which means that not only is it accessible throughout the class called MyClass, but it is also accessible from outside this class.
public void method1() { int myVar; myVar = 0; } public void method2() { int myVar2; myVar2 = 2; }
In the previous code, myVar is a local variable to the method method1, and can only be used within this method; myVar2 is a local variable to the method method2, and can only be used within this method.
Note that it is always good to avoid what is called variable masking/shadowing, which occurs when you give a local variable the same name as a member variable in the same file, as this could lead to confusion.
Classes and member variables can be compared to a city with different clubs and societies. The city is made of these different clubs. Each club has members. Some of these members can only be accessed if you are already part of this specific club where they belong to; other members will be available more publically for people who are not part of the same club. Because some of these members (for example a treasurer) are very powerful and could change significantly the future and safety of the club, you may prefer that not everyone outside the club has access to them, as it would mean that anyone can ask them to make drastic changes to the club. However, all the club members, because they are trusted, could be granted access to this treasurer. On the other hand, each club could have a PR person in charge of promoting the club. In this case, this member could be made public so that anyone outside this club can access them to get information about the club (e.g., opening hours, features, etc.).
So let’s experiment with variables and their scope:
public class MyClass { public static int myMemberVariable; public static void myMethod() { myMemberVariable = 3; System.out.println("The value of myMemberVariable is " + myMemberVariable); } public static void Main(String[] args) { myMemberVariable = 1; System.out.println("The value of myMemberVariable before calling the method is " + myMemberVariable); myMethod(); } }