WEB Programmer - Unit 3

ADVANCED LEVEL

Youth Included ZS.

UNIT 3: 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 «exiting loops», «working with data», «generating random numbers», «search for strings», «arrays of variables», «Java Classes».

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

3.1 Exiting loops

    The break keyword can be used to prematurely terminate a loop under a specified condition. The break statement is located inside the loop statement block and is preceded by a test expression. When the test returns true, the loop ends immediately and the program moves on to the next task. For example, in the case of a nested loop, it moves to the next iteration of the outer loop.

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

class Break

{

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

}

  1. Inside the main method, create two nested for loops. These loops will display the value of their counters at each of the three iterations.

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

{

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

{

System.out.println (“Iteration i =” + i + “j =” + j);

}

}

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

3.2 Return control

The standard behavior of the break and continue statements can be changed by explicitly specifying that control should be passed to the labeled loop statement by specifying the name of its label.

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

class Label

{

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

}

  1. Inside the main method, create two nested for loops that

output the values ​​of their counters at each of the three iterations.

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

{

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

{

System.out.println (“Iteration i =” + i + “j =” + j);

}

}

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

To mark a loop, precede it with the name of the label and a colon character.

3.3 Working with data

Type conversion

      In Java programming, when working with values, you should carefully consider data types to avoid compilation errors. For example, if a float variable is passed to a method that requires an int value, then this will lead to a compiler error. This means that often in order to process data, it must be converted from one type to another. Numeric values can be easily converted (cast) from one numeric data type to another using the syntax:

(data-type) value

     Values of a character data type (char) can be automatically used as values of an integer type (int) because they each have a unique integer representation, namely the numeric ASCII code supported by the Java compiler. For example, the Latin letter A has a numeric code of 65. Numeric values can be converted to a string type (String) using the toString () method. It takes a numeric value as an argument in its parentheses. For example, converting an integer variable num to a string type is Integer. toString (num). Similarly, the conversion of a floating-type variable num to a string will have the form Float.toString (num). In fact, such conversions are not always required, because, for example, concatenation of two variables into a string, if one of them is of a string type, occurs automatically.

3.3 Working with data

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

class Convert

{

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

}

  1. Inside the main method, declare and initialize one a string variable and one floating point variable.

float daysFloat = 365.25f;

String weeksString = “52”;

  1. Convert the floating point variable to integer.

int daysInt = (int) daysFloat;

  1. Convert the string variable to integer.

int weeksInt = Integer.parseInt (weeksString);

  1. Perform arithmetic operations on the converted values ​​and print the result.

int week = (daysInt / weeksInt);

 

System.out.println (“Days in a week:” + week);

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

3.4 Creating arrays of variables

        An array is a simple variable that can hold multiple values, as opposed to a regular variable that can hold a single value. An array declaration includes a datatype using keywords to denote datatypes, followed by square brackets to denote that it will be an array. The declaration then contains the name of the array in accordance with the naming conventions. An array can be initialized upon declaration by assigning a value of the appropriate data type, enclosed in curly braces and separated by commas. For example, declaring an integer array initialized with three values might look like this:

int [] numbersArray = {1, 2, 3};

      This creates an array of length equal to the number of elements specified in the list. In this case, the array consists of three elements. The values of the elements are stored in the array under the ordinal numbers (indices) by which you can refer to these elements.

To refer to elements, write the array name and the corresponding element index in square brackets. Items are indexed starting at zero. For example, to refer to the first element in the array above, we would write numbersArray [0].

The total number of elements in the array can be found by referring to the length property of the array. To do this, write “array name.length” through the dot notation.

3.5 Passing multiple arguments

You can pass multiple arguments to a program using the command line, which follow the program name and a space. Arguments must be separated by at least one space, and their values are placed in the elements of the args [] array. After that, each of the values can be accessed by index, just like any other element in the array, – args [0] for the first argument, args [1] for the second argument, and so on. To make sure that the user has entered the required number of arguments, the program needs to check the length property of the args [] array. If the check fails, you can use the return keyword to exit the main method, thereby exiting the program.

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

class Args

 {

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

}

  1. Inside the main method, enter a conditional if statement to check the number of arguments entered and output the appropriate messages, as well as exit the program if the number of arguments does not match the required – in this case three.

 if (args.length! = 3)

 {

 System.out.println (“Invalid number of arguments”);

return;

 }

  1. After the if statement, create two integer variables and initialize them with the values of the first and third arguments respectively.

 int num1 = Integer.parseInt (args [0]);

 int num2 = Integer.parseInt (args [2]);

3.5 Passing multiple arguments

  1. Add a string variable, initializing it with the value of the union of all three arguments.

String msg = args [0] + args [1] + args [2] + “=”;

  1. Add an ifelse statement that performs arithmetic on the arguments and concatenates the result into a variable

string type.

 if (args [1] .equals (“+”)) msg + = (num1 + num2);

 else if (args [1] .equals (“-“)) msg + = (num1 – num2);

 else if (args [1] .equals (“x”)) msg + = (num1 * num2);

 else if (args [1] .equals (“/”)) msg + = (num1 / num2);

 elsemsg = “Invalid operator”;

  1. Add the following line to the end of the main method for output the resulting line.

System.out.println (msg);

  1. Save the program as Args.java, then compile and run with three arguments – an integer,

any arithmetic operation symbol (+, -, x and /) and one more integer

  1. Restart the program with the wrong second argument and the wrong number of

arguments.

3.6 Learning Java Classes

       The Java language contains an extensive library of tested code that is housed in so-called “packages”. The core Java language package is the java.lang package, which by default has access to the Java Application Programming Interface (Java API). This means that when creating programs, the properties and methods provided by the java.lang package are always available. For example, the standard output functionality provided by the System. out.println () actually calls a method on the System class, which is part of the java.lang package. The contents of the package are organized in a hierarchical order that allows you to refer to any of its elements using dot notation. For example, the System class contains an out (field) property, which in turn includes a println () method — which can be accessed as System.out.println ().

      Math calculations

      The java.lang package contains a Math class that provides two constants used for mathematical calculations. The first one, Math.PI, stores the value of Pi, and the second, Math.E, stores the base of the natural logarithm. Both constants are of type double (double precision, with 15 decimal places).

 

3.6 Learning Java Classes

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

 class Pi

 {

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

}

  1. Inside the main method, declare and initialize a float variable from the command line argument, as well as a second float variable that you want to get by casting from the Math.PI constant.

float radius = Float.parseFloat (args [0]);

 float shortPi = (float) Math.PI;

  1. Do the math using the above values ​​and assign the results to two more floats.

float circ = shortPi * (radius + radius);

 float area = shortPi * (radius * radius);

  1. Print the value of the constant Math.PI, as well as its equivalent cast to the float type, then print the results of the calculations.

 System.out.print (“If the number of Pi is calculated in the range from” + Math.PI);

System.out.println (“before” + shortPi + “…”);

 System.out.println (“Circle with radius” + radius + “cm”);

 System.out.print (“has a length” + circ + “cm”);

 System.out.println (“andarea” + area + “sq.cm”);

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

3.7 Rounding numbers

The Math class inside the java.lang package provides three methods for rounding floating point numbers to the nearest integer. The simplest of the Math.round () methods rounds the number that is its argument up or down to the nearest integer. The Math.floor () method rounds down to the nearest integer, and the Math.ceil () method rounds up to the nearest up. While the Math.round () method returns an integer value (int), the Math.floor () and Math.ceil () methods return a double value.

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

class Round

 {

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

}

  1. Inside the main method, declare and initialize a float variable.

 float num = 7.25f;

  1. Output the rounded value that has acquired the int type as a result of rounding.

 System.out.println (num + “rounded equals” + Math.round (num));

  1. Output the rounded value as double values.

 System.out.println (num + “rounded down equals” + Math.floor (num));

 System.out.println (num + “rounded up equals” + Math.ceil (num));

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

3.8 Generating random numbers

The java.lang Math class provides a facility for generating random numbers using the Math.random () method, which returns a double-precision random number (of type double) in the range 0.0 to 0.999. The desired range can be expanded by multiplying by a random number. For example, by multiplying by 10, you can create a random number between 0.0 and 9.999. After that, if you round the resulting number using the Math.ceil () method, then the resulting integer falls in the range from 1 to 10.

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

class Random

 {

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

}

  1. Inside the main method, assign a random number to a float variable and output this value.

float random = (float) Math.random ();

 System.out.println (“Random number:” + random);

  1. To the second variable of the float type, assign the value of the random number multiplied

by 10 and also print its value.

float multiplied = random * 10;

 System.out.println (“Multiplied by 10:” + multiplied);

  1. Now store the rounded integer value obtained in the previous step of the random number into an int variable, then output its value.

int randomInt = (int) Math.ceil (multiplied);

 System.out.println (“Random integer:” + randomInt);

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

3.8 Generating random numbers

Using the Math.random () method, you can generate a sequence of six non-repeating integers ranging from 1 to 49, inclusive, to simulate the drawing of numbers in the lottery.

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

class Lottery

 {

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

}

  1. Inside the main method, create an integer array from 50 items, and then fill items 1 through 49 with integers 1 through 49.

int [] nums = new int [50];

for (int i = 1; i <50; i ++) {nums [i] = i; }

  1. Shuffle the values ​​in array elements 1 through 49.

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

 {

 int r = (int) Math.ceil (Math.random () * 49);

 int temp = nums [i];

 nums [i] = nums [r];

nums [r] = temp;

 }

  1. Print only those values ​​that are contained in elements from 1 to 6.

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

 {

 System.out.print (Integer.toString (nums [i]) + “”);

}

  1. Save the program as Lottery.java, then compile and run three times to produce three different sequences of numbers.

3.9 String management

In Java, a string (an element of type String) is 0 or more characters, enclosed in quotation marks. Valid strings are, for example: String txt1 = “My first line”; String txt2 = “”; String txt3 = “2”; String txt4 = “null”; The empty quotes in the txt2 variable example initialize the variable to contain an empty string. The numeric value assigned to the txt3 variable is the string representation of the number. The Java language keyword null usually represents the absence of any value, but it is a simple string literal when enclosed in quotes. A string in Java is essentially a set of characters, each of which contains its own data, like the elements of an array. Therefore, it is logical to represent a string as an array of characters and, working with it, apply the characteristics of the array.

3.9 String management

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

class StringLength

 {

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

}

  1. Inside the main method, create and initialize two variables of string type.

String lang = “Java”;

 String series = “in easy steps”;

  1. Add another string variable and assign it the value of the two strings created above.

String title = lang.concat (series);

  1. Print the concatenated string using quotation marks and its size.

System.out.print (“\” “+ title +” \ “contains”);

 System.out.println (title.length () + “characters”);

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

3.10 Search for strings

    The String class in java.lang provides the startsWith () and endsWith () methods for comparing portions of strings. These methods are very useful, for example, when finding strings that have the same beginning or the same ending. When a portion of the string matches the specified argument, the method returns true, otherwise it returns false. It is possible to copy part of a string by specifying the position of the first character from which to start copying as an argument to the substring () method.

    This method will return a so-called substring to the original string, starting at the specified starting position and ending with the last character of the original string. The substring () method can take an optional second argument that will indicate the position of the last character to copy. In this case, the method will return a substring of the original string, starting at the specified start position and ending at the specified end position.

    The indexOf () method is used to find a character or substring in a string. This method returns the numeric position of the first occurrence of the specified character or substring within the string being processed. If no match is found, the method returns -1.

  1. Create a new program named StringSearch containing

the standard main method.

 class StringSearch

 {

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

}

3.10 Search for strings

  1. Inside the main method, create and initialize a string array containing the titles of the books.

String [] books =

{“Java in easy steps”, “XML in easy steps”,

 “HTML in easy steps”, “CSS in easy steps”,

 “Gone With the Wind”, “Drop the Defense”};

  1. 3. Create and initialize three integer counter variables.

intcounter1 = 0, counter2 = 0, counter3 = 0;

  1. Add a for loop to loop through the string array, printing out the first four characters of each name.

for (inti = 0; i <books.length; i ++)

{

 System.out.print (books [i] .substring (0,4) + “|”);

}

  1. Add a statement to the for loop block to count the titles that contain the specified ending.

if (books [i] .endsWith (“in easy steps”)) counter1 ++;

  1. Add another statement to the for loop to count the titles that contain the specified beginning.

if (books [i] .startsWith (“Java”)) counter2 ++;

  1. Add another operator to count the names that do not contain the specified substring.

if (books [i] .indexOf (“easy”) == -1) counter3 ++;

  1. At the end of the main method, add the following statements to display the results

 of each search.

System.out.println (“\ nFound” + counter1 + “titles from this series”);

System.out.println (“Found” + counter2 + “names from Java”);

System.out.println (“Found” + counter3 + “other names”);

  1. Save the program as StringSearch.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