WEB Programmer - Unit 2

ADVANCED LEVEL

Youth Included ZS.

UNIT 2: The Java programming language

AIMS & OBJECTIVES

1) The purpose of this Unit is to enhance migrants’ basic soft skills and competencies, which are needed in today’s labor market and help them in their fist steps while in search for a job.

2) The main part of this presentation is the compilation of programmers with Java.

3) The Unit aims at helping the reader to understand «arithmetic operations», «assigning values», «evaluation logic», «control literals», «creation of operators», «while loop».

LEARNING OUTCOMES

LOut1: Understand the concept of Java language

LOut2: Describe the installation steps, regarding the Java language

LOut3: Create your first program in Java

LOut4: Demonstrate knowledge in running programs

LOut5: Contrast data types

LOut6: Formulate constants

KEYWORDS

  • Variables
  • Java
  • Javac
  • JavaDevelopmentKit
  • James Gosling
  • JavaRuntimeEnvironment (JRE)
  • StandardEditionDevelopment Kit (JDK)
  • 1995
  • Constants

TABLE OF CONTENTS

2.1 Performing arithmetic operations

    The arithmetic operations listed in the table below are used to create expressions in Java programs that return a single result value. For example, the expression 4 * 2 returns the value 8:

 

2.1 Performing arithmetic operations

  1. Create a new program named Arithmetic containing the standard main method.

class Arithmetic {public static void main (String [] args) {}}

  1.  Within the curly braces of the main method, declare and initialize three integer variables. int num = 100; int factor = 20; int sum = 0;
  2.  Add the following lines to perform addition and subtraction operations and display the corresponding results. sum = num + factor; // 100 + 20 out.println (“Result of addition:” + sum); sum = num – factor; // 100 – 20 System.out.println (“Subtraction result:” + sum);
  3. Now add lines that perform multiplication and division and output

the results. sum = num * factor; // 100 x 20 System.out.println

(“The result of the multiplication:” + sum); sum = num / factor; //

100 ÷ 20 System.out.println (“Division result:” + sum);

  1. Save the program as Arithmetic.java, then compile and run.

2.2 Assigning values

    The assignment operators listed in the table below are used to assign the result of an expression to a variable. All of them, with the exception of the = operator, are shorthand for the longer equivalent expression.

2.2 Assigning values

  1. Create a new program named Assignment containing the standard main method.

class Assignment

{

public static void main (String [] args) {}

}

  1. Inside the curly braces of the main method, add the following lines of code to add and assign a string value.

String txt = “Fantastic”;

String lang = “Java”;

txt + = lang; // Assignment with concatenated strings

System.out.println (“Adding and assigning lines:” + txt);

  1. 3. Add these lines for addition and assignment of integers.

int sum = 10;

int num = 20;

sum + = num; // Assign the result (10 + 20 = 30)

System.out.println (“Add and assign integers:” + sum);

  1. 4. Now add the lines that multiply and assign integers.

int factor = 5;

sum * = factor; // Assign the result (30 x 5 = 150)

System.out.println (“Result of multiplication” + sum);

  1. 5. Add lines that perform division and assignment of integers.

sum / = factor; // Assign the result (150 ÷ ​​5 = 30)

System.out.println (“Result of division:” + sum);

  1. 6. Save the program as Assignment.java, then compile and run.

2.3 Evaluation logic

The logical operators listed in the table below are used to combine multiple expressions, each of which returns a Boolean value, into one complex expression that will return a single Boolean value

Logical operators operate on operands that have a boolean value, that is, true or false, or with values ​​that convert to true or false.

The logical AND (&&) operator evaluates two

operands and returns true only if both

operands are themselves true, otherwise

the operator returns false. This operator

is usually used in conditional branching,

when the direction of the program is determined by checking two conditions: if both are true, the program is going in a certain direction, otherwise – in the other. Unlike the and operator, which requires both operands to be true, the logical OR (||) operator evaluates two operands and returns true if at least one of them itself returns true. Otherwise, the operator || will return false. This is useful when programming certain actions when one of the two checked conditions is met. The logical NOT operator (!) Is unary and is used with one operand. It returns the opposite of what the operand had. So, if the variable a was true, then! A will return false.

2.3 Evaluation logic

  1. Create a new program named Logic containing the standard main method.

class Logic

{

public static void main (String [] args) {}

}

  1. Inside the curly braces of the main method add the following lines with the declaration and initialization of two variables of the boolean type.

boolean yes = true;

boolean no = false;

  1. Add lines containing tests for two conditions to be true.

System.out.println (“Result of expression yes AND yes:” + (yes && yes));

System.out.println (“Result of expression yes AND no:” + (yes && no));

  1. Add lines to test that one of the two conditions is true.

System.out.println (“Result of expression yes OR yes:” + (yes || yes));

System.out.println (“Result of expression yes OR no:” + (yes || no));

System.out.println (“Result of expression no OR no:” + (no || no));

  1. Add lines showing the original and opposite values ​​of the boolean variable.

System.out.println (“Initial value of the variable yes:” + yes);

System.out.println (“Inverted variable yes:” +! Yes);

  1. Save the program as Logic.java, then compile and run

2.4 Checking conditions

Probably one of the most beloved operators of Java programmers is the conditional operator, which makes the large construction very concise. While its unusual syntax may seem overwhelming at first glance, it is still worth getting to know this useful operator. The conditional operator first evaluates the expression for true or false and then returns one of its two operands based on the results of the evaluation. Its syntax is as follows: (boolean-expression)? if-true-return-this: if-false-return-this;

           Each of the specified operands is an alternative program execution branch, depending on the boolean value returned by the test expression. For example, string values can be returned as options:

status = (quit == true)? “Done!” : “In the process…” ;

In this case, when quit is true, the conditional statement assigns the value of its first operand (Done!)

variable status, and otherwise the operator assigns it the value of the second operand (In progress …).

           When a simple boolean is tested, a short notation for the test expression is available, in which case the == true symbols can be omitted. So the above example can be written as:

status = (quit)? “Done!” : ” In the process…” ;

 

           The conditional operator can return any data type and use any valid test expression. 

2.4 Checking conditions

  1. Create a new program named Condition containing the standard main method.

class Condition

{

public static void main (String [] args) {}

}

  1. Inside the curly braces of the main method add the following strings declaring and initializing two integers variables.

int num1 = 1357;

int num2 = 2468;

  1. Next, declare a string variable to store the result checks.

String result;

  1. Add lines to determine if the value is the first variable even or odd number, also add the output result.

result = (num1% 2! = 0)? “Odd”: “Even”;

System.out.println (num1 + “-” + result);

  1. Add the following lines for similar validation of the value second integer variable.

result = (num2% 2! = 0)? “Odd”: “Even”;

System.out.println (num2 + “-” + result);

  1. Save the program as Condition.java, then compile and run.

2.5 Control literals

      Numeric and text values ​​are known as “literals” in Java programs – they don’t really represent anything, they are just the characters you see. Literals are usually separated from Java language keywords, but where double or single quotes within a string variable are required, you must specify that the quotation marks must somehow be separated to avoid abnormal termination of the string.        

      This is accomplished by prefixing each character with escape quotes (or control operator) \. For example, to include quotes in a string variable, write the following: String quote = “\” Fortune favors the brave. \ “Said Virgil”; Various escape sequences can be used to format the simplest output:

2.5 Control literals

  1. Create a new program named Escape containing the standard main method.

class Escape

{

public static void main (String [] args) {}

}

  1. Inside the curly braces of the main method add the following lines of code to create a string variable containing formatted table titles and column headers.

String header = “\ n \ t NEW YORK 3 DAY FORECAST: \ n”;

header + = “\ n \ tDay \ t \ tMax \ tMin \ tPrecipitation \ n”;

header + = “\ t — \ t \ t —- \ t — \ t ———- \ n”;

  1. Add the following lines to create a string variable,containing formatted data and table cells.

String forecast = “\ tSunday \ t68F \ t48F \ tClear \ n”;

forecast + = “\ tMonday \ t69F \ t57F \ tClear \ n”;

forecast + = “\ tTuesday \ t \ t71F \ t50F \ tClouds \ n”;

  1. Add a line to output both formatted values lines.

System.out.print (header + forecast);

  1. Save the program as Escape.java, then compile and run.

2.6 Creation of operators

Branching with the if statement The if keyword performs a conditional check against the boolean value of an expression. The statement following this expression will be executed only if the given value is true. Otherwise, the program moves on to subsequent lines of code, performing alternative branching. The syntax of the if statement is as follows: if (test-expression) code-to-execute-if-result-true; The executable code can contain several operators, and they form a block of operators and are enclosed in curly braces.

  1. Create a new program named If containing the standard main method.

class If

{

public static void main (String [] args) {}

}

  1. Inside the curly braces of the main method add the following a simple check in which, provided that one number is greater another, one statement is executed (in this case, printing is performed).

if (5> 1) System.out.println (“Five is more than one.”);

  1. Add a second check, which, assuming one number less than the other, will execute the statement block.

if (2 <4)

{

System.out.println (“Two is less than four.”);

System.out.println (“The check was successful.”);

}

2.6 Creation of operators

  1. Save the program as If.java, then compile and run. Since both checks will return true, then in both cases all statements will be executed. The expression being tested can contain a complex compound expression. This checks several conditions for a logical value. Individual expressions can be separated by parentheses to establish the order of evaluation – expressions in parentheses will be evaluated first.

The logical AND operator (&&) will return true only if both tested expressions are true:

if ((condition-1) && (condition-2)) execute-this-code;

The logical OR operator (||) will return true if at least one of the test expressions is true:

if ((condition-1) || (condition-2)) execute-this-code;

Combinations of the above expressions can form more complex and lengthy test expressions.

  1. Add the following line inside the main method to declare and initialize an integer variable named num.

int num = 8;

  1. Add a third test expression that will execute the output statement if the value of num is within the specified range or is exactly equal to the specified value.

if (((num> 5) && (num <10)) || (num == 12))

System.out.println (“A number in the range from 6 to 9 inclusive or equal to 12”);

  1. Re-compile the program and run it again to see that the statement is executed after

passing the complex test.

  1. Change the value assigned to num so that it is not in the range 6-9 or equal to 12.

Re-compile the program and run it again to see that the statement is no longer executed

after a complex check.

2.7 Alternative branching

In addition to the if keyword, you can use the else keyword, which, together with if, forms an if else statement that provides alternative branches to continue the program according to the result of evaluating the test expression. In the simplest case, it simply offers an alternative operator for execution, and when the test fails, it returns false: if (test-expression) code-to-execute-if-the-result is true; else code-to-execute-if-result-false; Each alternate branch can be either a single statement or a statement block enclosed in curly braces.

Using the if else operator, you can build more complex structures to perform additional checks inside each of the if and else branches. This results in nested if statements. When the program encounters an expression evaluating to true, it executes the statements associated with that branch and then exits the if else statement

2.7 Alternative branching

  1. Create a new program named Else containing the standard main method.

class Else

{

public static void main (String [] args) {}

}

  1. Inside the main method add the following line with the declaration and initialization of the integer variable hrs.

int hrs = 11;

  1. Add a simple test expression that will execute one statement if the hrs variable is less than 13.

if (hrs <13)

{

System.out.println (“Good morning” + hrs);

}

  1. Save the program as Else.java, then compile and run to see the executable statement
  2. Set the hrs variable to 15, and then add the alternate branch just after the if statement.

else if (hrs <18)

{

System.out.println (“Good afternoon” + hrs);

}

  1. Save your changes, compile and rerun the program to see the alternate statement being executed.

It is sometimes useful to include the final else clause without a nested if statement to define a default statement to execute if no test expression evaluates to true.

  1. Set the hrs variable to 21, then add the following default branch to the end of the if else statement. else System.out.println (“Good evening:” + hrs);
  2. Save your changes, recompile, and run the program again to see the default statement being executed.

2.8 Branching with switches

Constructs with if else statements offering a large number of conditional program branches can get quite cumbersome. In cases where you need to repeat the check for the same value of a variable, a switch statement offers a more elegant solution. The typical syntax of a switch statement block looks like this: switch (checked-variable)

{

case value-1: code-to-run-if-true; break;

case value-2: code-to-be-run-if-true; break;

case value-3: code-to-be-run-if-true; break;

default: code-to-execute-if-false;

}

The switch statement works in a rather unusual way. It checks the values ​​specified by a variable against the values ​​of its case options, and then executes the statement associated with the value of the specified option. The last option, default, is optional and can be added to a switch statement to specify statements to be executed if none of the specified values ​​match the variable being checked. Each operator option begins with the keyword case and the value to be tested, followed by a colon and the statements to be executed if the value matches. It is important to remember that the statement and statement block associated with a particular case option must end with the break keyword. Otherwise, the program will continue to execute statements with another case option after the one that passed the test. It is sometimes useful to specify multiple case options for which the same statement block needs to be executed.

2.8 Branching with switches

  1. Create a new program named Switch containing the standard main method.

class Switch

{

public static void main (String [] args) {}

}

  1. Inside the main method add a declaration and initialization three integer variables.

int month = 2, year = 2016, num = 31;

  1. Add a switch statement block to test the values assigned to the month variable.

switch (month)

{

}

  1. Inside the switch block, add case options, assigning new values to the num variable for months 4, 6, 9, and 11.

case 4: case 6: case 9: case 11: num = 30; break;

  1. Add a case option, assigning a new value to the num variable for month 2 according to the value of the variable

year.

case 2: num = (year% 4 == 0)? 29: 28; break;

  1. After the switch block at the end of the main method, add the following a string to display all three variable values.

System.out.println (month + “/” + year + “:” + num + “days”);

  1. Save the program as Switch.java, then compile and run.

2.9 For loop

A loop is a block of code in which the statements contained in it are executed with a certain frequency until a certain condition is fulfilled; then the loop ends and the program moves on to its next task.

The most commonly used looping structure in Java programming uses the for keyword, and the syntax for this loop is as follows:

for (initialization; test-expression; iteration)

{

statements-to-execute-on-each-iteration;

}

The parentheses after the for keyword must contain three control expressions that determine the action of the loop.

  • Initialization – assigns an initial value to a variable to a counter that will count the number of loop iterations. A variable for this purpose can be declared right here, and it is usually the simplest integer variable named i.
  • Check expression – this expression is evaluated at the beginning of each loop iteration for the logical value true. When the evaluation returns true, iteration continues, and when false is returned, the loop immediately terminates without ending the current iteration.
  • Iteration – changes the current value of the counter variable, storing the total number of iterations made by the loop. Usually, the expression i ++ is used to increase or i — to decrease the counter value.

2.9 For loop

  1. Create a new program named For containing the standard main method.

class For

{

public static void main (String [] args) {}

}

  1. Inside the main method, declare and initialize an integer variable to count the total number of iterations.

int num = 0;

  1. Add a for loop that iterates three times and displays the current value of its counter-variable i at each iteration.

for (int i = 1; i <4; i ++)

{

System.out.println (“Outer loop i =” + i);

}

  1. Inside the for loop block, add a nested for loop that also performs three iterations, displaying the current value variable counter j and the total number of iterations.

for (int j = 1; j <4; j ++)

{

System.out.print (“\ tInner loop j =” + j);

System.out.println (“\ t \ tTotal num =” + (++ num));

}

  1. Save the program as For.java, then compile and run to see the output.

2.10 While loop

          An alternative structure for a for loop is a loop structure that uses the while keyword and has the following syntax: while (test-expression) {statements-to-be-executed-on-each-iteration; } Like a for loop, a while loop also periodically executes the statements it contains until the test condition evaluates to true. In this case, the cycle ends its work, and the program proceeds to the next task. Unlike the for loop, the parentheses after the while keyword contain neither an initializer nor a modifier that modifies the counter variable.

          This means that the test expression must contain some value that will change as the loop iterates, otherwise an infinite loop will be created that executes its statements. The test expression is evaluated at the beginning of each iteration of the loop for the logical value true. If the test returns true, iteration continues, otherwise the loop ends immediately without iterating. Note that if the test expression returns false on the very first evaluation, then the loop statements will never be executed.

          Using the while loop, you can simulate the structure of the for loop, in which case the counter variable will be evaluated in the test expression, which will be created outside the loop, and change its value inside the loop at each iteration.

2.9 For loop

  1. Create a new program called While, containing the standard main method.

class while

{

public static void main (String [] args) {}

}

  1. Inside the main method, declare and initialize an integer variable named num.

int num = 100;

  1. Add a while loop to display the current value of num as long as it remains greater than zero.

while (num> 0)

{

System.out.println (“Countdown using While:” + num);

}

  1. At the end of the while block, add a modifier to decrease the value of the num variable

by 10 at each iteration, thereby avoiding an infinite loop. num – = 10;

  1. Save the program as While.java, then compile and run

SYNOPSIS

The Java programming language was developed in 1990 by James Gosling, an engineer at SunMicrosystems. Subsequently, the language was given the name Java (simply because it sounds better),  and in 1995 it became freely available. In the center of Java language are libraries of files called classes, each of which contains small chunks of tested, ready-to-run code.

Like bricks in a wall, any of these classes can be embedded in a new program, and so there is usually a small amount of code left to write to complete the program. This technique saves programmers a lot of time and is one of the main reasons for the widespread popularity of Java programming. All Java programs usually start out as text files, which are then used to create “class” files, which in turn are actually executable programs. This means that Java programs can be written in any basic text editor, such as Notepad. Follow these steps to create a simple Java program that displays a traditional greeting.

In Java programming, a “variable” is a container in which a value can be stored for later use in a program. The stored value can change as the program is executed – hence the name “variable”. A variable is created using a “declaration” that specifies the type of data contained in the variable and gives it a name.

List of references

Cay S. Horstmann. «Core Java Volume I». Prentice Hall. 2020 Informit.com
Joshua Bloch. «Effective Java/ 3rd Edition». Addison Wesley. 2017 Informit.com
Herbert Schildt. «Java: A Beginner’s Guide, Eighth Edition Paperback». 2018
Scott Oaks. «Java Performance: The Definitive Guide Paperback». 2014 oreully.com
Mike Mc Grath «The Complete Reference. Java/10 edition», 2018, McGraw Hill Education.

Further reading

1.Robert C. Martin, «Clean code. A Handbook of Agile Software Craftsmanship». 2018

2.Brian Goetz, «Java Concurrency in Practice». 2006 awprofessional.com