Starting to Code in Java (Part 2)

In the previous code:

 We have created a block of instructions that starts with an opening curly bracket and that ends with a closing curly bracket.
 Within this block, we have created two statements that display a message in the console window; both statements are ending with a semi-colon.

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:

 Please open the file MyClass.
 Modify the code as follows (new code in bold).
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:

 Name of a variable: a variable is usually given a unique name so that it can be identified easily and uniquely. The name of a variable is usually referred to as an identifier. When defining an identifier, it can contain letters, digits, a minus, an underscore or a dollar sign, and it usually begins with a letter. Identifiers cannot be keywords (for example the keyword if cannot be used as an identifier).
 Type of variable: variables can hold several types of data, including numbers (e.g., integers, doubles or floats), text (e.g., Strings or characters), Boolean values (e.g., true or false), arrays, or objects (we will see the concept of arrays later in this chapter).

.

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)
 Variable declaration: variables need to be declared so that the system knows what you are referring to if you use this variable in your code. The first step in using a variable is to declare or define this variable. At the declaration stage, the variable does not have to be assigned a value, as this can be done later. In the next example, we declare a variable called myName and then assign the value My Nameto it.

String myName;

myName = “My Name”

 Scope of a variable: a variable can be accessed in specific contexts that depend on where in the application the variable was initially declared. We will look at this concept later.
 Accessibility level: as we will see later, a Java program consists of classes; for each of these classes, the methods and variables within can be accessed depending on their accessibility levels, and we will look at this principle later.

Common variable types include:

 String: same as text.
 Int: integer (1, 2, 3, etc.).
 Boolean: true or false.
 Float: with a fractional value (e.g., 1.2f, 3.4f, etc.).
 Arrays: a group of variables of the same type. If this is unclear, not to worry, this concept will be explained further in this chapter.

Using variables

In this section, we will start to use variables and combine them using statements and operators. So let’s get started:

 Please add the following code just after the code that you have previously created, 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”);*/

}

int dateOfBirth = 1990;
int currentYear = 2017;
int age = currentYear - dateOfBirth;
System.out.println("My age is " + age);

In the previous code:

 We have commented the previous code that displayed “Hello, this is my second line of code” using the two forward slashes; so this code will not be executed.
 We declare two variables dateOfBirth and currentYear.
 We then declare a variable called age.
 We perform a subtraction between the variable currentYear and the variable dateOfBirth, and we then save the result in the variable called age.
 Finally, we print the text “My age is “, followed by the value of the variable called age.

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.

 Arithmetic operators are used to perform arithmetic operations including additions, subtractions, multiplications, or divisions. Common arithmetic operators include +, , *, /, or % (modulo) and their use is illustrated in the next code snippet.
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
 Assignment operators can be used to assign a value to a variable and include =, +=, -=, *=, /= or %= and their use is illustrated in the next code snippet.
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“).

 Comparison operators are often used for conditions to compare two values. Comparison operators include ==, !=, >, <, >= and >=, and their use is illustrated in the next code snippet.
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:

 Please open the file MyClass.
 Add the following line at the start of the class
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.

 Please add the following code (new code in bold) at the end of the main method:
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:

 We write a message that asks the user to enter his/her name.
 We declare the variable sc; this variable will be used to capture the information entered by the user. The variable sc is of type Scanner.

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).

 We then declare the variable nameOfUser. This variable will then contain the answer (a String) entered by the user.
 We store the name using the method nextLine, which is a method provided by Java to read text entered by the user (after the user has pressed the key Enter).
 Once the name has been entered by the user, it is stored in the variable nameOfUser.
 We then display a message that includes the word “Hello” followed by the name that the user has entered.

You can now save your code and run the application:

 Enter a name of your choice using the text field located at the bottom of the window.
 Press Enter.
 A new message should be displayed in the console window with the word Hello followed by the name that you have entered.
A screenshot of a computer

Description automatically generated

Figure 116: Testing your code
 You can then close the console window.

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:

 We comment the previous code.
 We display text that invites the user to write the solution to the question “What is 1 + 1”.
 We declare a variable called result.
 We then ask the user to enter his/her guess. This time we use the method sc.nextInt() because the answer will be stored as an integer.
  Once the answer has been entered, it is stored in the variable result.
 We then perform a conditional statement based on the value of the variable result. If the text entered is “2“, then the message “Well done” is displayed, otherwise, the message “Sorry Wrong Answer” is displayed instead.

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”.

 After entering the number 2 and pressing Enter, a message saying “Well done” should appear.

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:

Perform an action.
Return a result.
Take parameters and process them.

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:

 The access type defines the scope of the method or, put simply, from where this method will be available (or can be called).
 The type of the data returned can be: void (no data is returned) or any type of data that this method could return such as int, Boolean, or String.
 The previous information is then followed by the name of the method.
 The list of parameters can be empty if this method does not take any parameter. Otherwise, it includes a list of parameters preceded by their type and separated by a comma; we will cover this aspect later.

.

Using this template, we could, for example, define the following method:

public void myMethod ()
{
  System.out.println("hello");
}

In the previous code:

 The method is declared as public.
 Its return type is void, which means that it does not return any data.
 It takes no parameters.
 When called this method will write the message “hello” to the console.

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:

 Please open the file MyClass, and comment your previous code as in the next code snippet; to speed up things, and if you are working with Visual Studio, you can select these lines and then press simultaneously CTRL + / (or APPLE + /).
//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");
 Then add the following code to the main method:
int myAge = calculateAge(1990);
System.out.println("My Age is " + myAge);
}

In the previous code:

 We declare a variable called myAge.
 We call the method calculateAge, passing the number 1990 as a parameter.
 The information (or value) returned by the method is stored in the variable myAge and then displayed in the console window.

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:

 The method calculateAge is declared; it takes one parameter called yearOfBirth. So any parameter passed to this method will be referred as yearOfBirth within this method.
 This method returns the result of the subtraction 2018 – yearOfBirth.
 When the method is called, yearOfBirth is equal to 1990; so it will return 28 (i.e., 2018-1990).

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.

 Member variables can be used in a specific class or throughout your application, depending on their access type.

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.

 Member variables can be declared at the start of the class, using the usual declaration syntax, preceded by what is called an access type (we will come back to this concept later on). They can then be used anywhere in the class (and sometimes outside the class also), as illustrated in the next code snippet.
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.

 Local variables are declared (and should only be used) within a specific method; hence the term local, because they can only be used locally, as illustrated in the next code snippet.
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:

 Please open the file MyClass.
 Comment the code already present in the main method.
 Add the following code to the file MyClass (new code in bold).
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();
    }
}