0% found this document useful (0 votes)
2 views22 pages

Java Programming Basics Explained

This document presents the basics of programming in Java, including the installation of the JDK, the creation and execution of Java applications, as well as the fundamental syntax of the language. It also explains variable types, output methods, and provides practical examples to illustrate these concepts. Finally, it addresses the portability of Java applications and the importance of comments in the code.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Java Programming Basics Explained

This document presents the basics of programming in Java, including the installation of the JDK, the creation and execution of Java applications, as well as the fundamental syntax of the language. It also explains variable types, output methods, and provides practical examples to illustrate these concepts. Finally, it addresses the portability of Java applications and the importance of comments in the code.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1/22

Java Course: The Basics Chapter 1


This chapter presents the essential knowledge for acquiring the techniques of the
Java programming: the fundamental elements of the language syntax.

Java is a programming language and a runtime environment. Applications


can run on all platforms (Windows, Linux, Unix, Mac) that have
a suitable runtime environment JRE (Java Runtime Environment). The Oracle site
propose the JREs for the different current operating systems.

LeJRE includes a JVM, Java Virtual Machine, as well as the


libraries and the components necessary for running Java applications.

A Java application can be developed on a Windows machine, and for example


to run on a Linux machine: it is said that a Java application is portable.

The Java language was developed by the company Sun. The company Sun no longer exists because it was
acquired by Oracle.
The following examples will be developed and executed on a Windows machine.
There are high-performance development products like Eclipse or JBuilder or
NetBeans which we will not use in this chapter. These products are not essential.
And for learning the Java language, it's better not to use them right away.

Basic tools needed for Java application development.

Install a JDK, Java Development Kit, for example JDK 1.8, which is installed by
error in the folder C:\Program Files\Java\jdk1.8.0_05.
Here for the PATH
In the Windows control panel, select
System and Security/System/Advanced System Settings/System Variables
will add the following path to the system PATH variable:
2/22

C:\Program Files\Java\jdk1.8.0_05\bin.
It is in this directory that one finds the commands necessary for compilation.
in the execution of Java applications, and in particular:
javacqui is the compilation command.
java is the execution command.
Use an ASCII text editor like Notepad++ to write the programs
sources.

To develop a Java application, we go through the following steps:

Writing the source file, named [Link], with a text editor,


file recording.
Compilation with the javac compiler in a console window (command prompt
commands). We use the javac command for this.
Execution with the Java interpreter in a console window. This is used for that purpose.
[Link]

Q0 Test the installation

Open a console window (command prompt or Start/Run/cmd then OK). Type


javac, a list of Java-specific messages should be displayed.
If a message like 'javac is not recognized as an internal or external command...' appears.
is displayed, it means that either the jdk is not installed, or the PATH is not set correctly
configured, see above.

1. First example.
The Java language is 100% object-oriented, and every application is contained in one or more
classes.

Q1 Create a folder for the exercises of TP1, for example courstp1.


•Write the source file below, with Notepad++.

public class Hello1


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

Save the file with the exact name: [Link]


You have no other choice, as Java requires the .java extension and wants the name
the file should have the same name as the class, with regard to uppercase and lowercase letters.
[Link] Hello There are 3 errors in [Link].

We need to open a console window (command prompt or terminal or


execution of commands in Windows) and navigate with the command cd in the folder
3/22

containing the file [Link]. The command dir (ls under Linux) in this folder must
display the name of the file [Link].

Compile the file [Link] with the javac compiler by typing the command
next :
javac [Link]

If there are syntax errors, they are indicated by the compiler, and you need to go back.
in the editor to correct them.
If the compilation is successful, it creates a file [Link].

The file [Link] is a bytecode file, or sequence of bytes, which is not


not directly understandable by the real machine: it is the virtual machine
Java (JVM) that controls the execution of bytecodes, like it does a
microprocessor that executes a sequence of instructions.

Run the application with the java interpreter by typing the following command:
java Hello1

The execution displays Hello !! on the screen in text mode.

Adding comments:
A Java program, before it can be executed, must be compiled into bytecodes. The
the possibility of forcing the compiler to ignore certain instructions exists! This is what we
call the comments, and two syntaxes are available to comment a program:
1. Single-line comments: introduced by the symbols "//", they encompass everything that follows.
suit in comment, as long as the text is on the same line;
2. Multiline comments: they are introduced by the symbols "/*" and end
by the symbols " */ "

Explanation of the first example.


For this, comments have been added:

public class Hello1 //definition of the class Hello1


// start of the class definition Bonjour1

In the class definition, we place the members of the class:


Here, the class contains only one member, which is the method (or member function)
named main()*/

public static void main(String[] args) // header of the main() method


// start of the main() method body
[Link]("Hello !! ");
} // end of the main() method

}// end of the definition of the class Bonjour1

We must write a class. We have chosen the name Bonjour1 as the name of the class.
The definition of the class must be enclosed in a block defined by curly braces.
opening brace and a closing brace: "{ .... }" »
4/22

A method (or member function) is a sequence of instructions to be executed. It is


a piece of logic from our program. A method contains:
a header: this will be somewhat the identity card of the method;
- a body: the content of the method. It is placed in a block delimited by
{ .... } »

In this class, there is only one method (or member function): the
method main(). This method main() is the execution entry point of the
program. Every executable Java program must contain a class with a
methodtomorrow()

public static void main(String[] args) // header of the main() method


The main() method can receive a list of arguments (or parameters) of type
String (string). It is public like the class because this way it can
to be called/used by an external object to the class Bonjour1. It is static
because it must be called by the JVM while the instance object of the class
Hello1 is not created. It never returns a value and therefore the type of it
the return value is void.
The JVM executes [Link]() to run the application.

In the main() method, that is to say in the body of this method, there is only one
single instruction. This is ended by a semicolon (like all the
Java language instructions) and performs the simple display of a text:
Hello !!

The class System is a class of the [Link] package.


allows access to the screen which is the standard output display. is an object
(stream instance of the PrintStream class) that identifies the standard output, this object is
content in the System class, it is systematically and automatically created for
each execution of a Java program.
println() is a method (member function) of the PrintStream class that writes to
an output stream, the text passed as a parameter (in parentheses) with a return to the
line at the end.
. access to a member of a class or an object.
Note: the operator "" allows

A Java application usually starts with the import of classes


contained in packages, by writing lines of code like
import [Link].*;

The previous line of code allows you to import all classes (thanks to the use of
of the symbol*) contained in the [Link] package
[Link] is the only package whose classes are imported automatically.
So, the previous line of code is useless.
A package is a Java entity that groups together several classes that have already been written by the
language developers. One can see a package as a library of classes.
Many packages exist: for networking, for creating GUIs (windows), for
access the databases...

Q2 Import all the classes from the [Link] package in the first example, compile,
5/22

execute, what does that change?

To write Java applications, one must gain experience with packages and
classes, and use the Java Doc documentation available (or downloadable) on the site
from Oracle at the address:The provided text is a URL and cannot be translated.

Example No. 2
The print() method is a method of the PrintStream class that writes to a stream of
output, the text passed in parameter (within the parentheses) without line breaks.

Q3 Compile and execute the following program:

public class Bonjour2 //definition of the class Bonjour2


// beginning of the class definition Bonjour2

/* We place in the class definition the members of the class:


Here, the class contains only one member, which is the method (or member function)
named main()*/

public static void main(String[] args) // header of the main() method


// start of the body of the main() method
Hello !!
Welcome
Today is Monday, April 13.
} // end of the main() method body

} // end of the Bonjour2 class definition

Q4Modify the program so that the 3 messages are displayed on different lines.

To insert a line break, you can also use the escape character \n. Likewise,
The escape character \t allows you to insert a tab.

Q5 Compile and run the following program:

public class Hello3


{
public static void main(String[] args)
{
Hello
Welcome
We are on Monday, April 13.
}
}
The string that we display is surrounded by " ". In Java, the quotes
(double quotes) are string delimiters! If you want to display a quotation mark
double on the standard output, you must "escape" it with a "\", which gives:
Test "ok" !
June 22

4. The variables
They allow storing numbers, characters, booleans... whose value can
to be modified during the execution of the program.

The declaration of a variable consists of a type followed by a name and is terminated by a


semicolon
<type of the variable> <name of the variable> ;

Note: The type of a variable is chosen based on what we wish to store (or
put) in the variable.

In Java, there are two types of variables:


1. simple or 'primitive' type variables;
2. complex type variables or "objects".

4.1 Simple or 'primitive' type variables


For simple or 'primitive' types, declaring a variable allocates memory space.
used by this variable.

4.1.1 The different types of integer numbers

Type Memory space occupied Possible values


byte 1 byte -128 (= -27) to +127 (=27-1)
short 2 octets -32768 (= -215to +32767 (= 215-1)
int 4 octets -2,147,483,648 (= -231) to 2,147,483,647 (= 231-1)
long 8 octets 9.1018(= -263) at +9.1018(= 263-1)

Examples of declaration and initialization of variables using the types above:

public class Test1


{
public static void main(String[] args)
{
byte temp; // declaration of a variable named temp of type byte
temp = 64; We assign 64 to the variable temp
As this is the first time we are assigning a value to the temp variable,
this is an initialization */

short maxSpeed; // declaration of a variable named vitesseMax of type short


vitesseMax = 32000; // initialisation de la variable vitesseMax

We can initialize a variable at the same time we declare it.


int tempSoleil = 15600000;
[Link](tempSoleil); //displaying the content of the variable tempSoleil

long light year;


anneeLumiere = 9460700000000000L;//ne compile pas sans le L
}
}
July 22

The operator "=" is the assignment operator. To assign means to store, place or
store a value in a variable.

By default (without a suffix), integer constants are placed in ints. So, without the L at the
end of the integer constant 9460700000000000, the compiler tries to place this value
in an int (4 bytes), which is impossible. This causes a compilation error.

Note: prefixes used in Java to write integer constants:


without prefix, the number is written in decimal;
the prefix 0x indicates that the number is written in hexadecimal (base 16);
the prefix 0b allows writing a number in binary (base 2).
Example : 92 = 0x5C = 0b1011100

4.1.2 The different types of real digital numbers

Type Occupied memory space Possible values


float 4 octets -3.4 × 1038at +3.4×1038
(around 7 significant figures)
double 8 octets -1.79×10308at +1.79×10308
(approximately 17 significant digits)

Examples of declaration and initialization of variables using the above types:

public class Test2


{
public static void main(String[] args)
{
float pi;
pi = 3.141592653f; // do not compile without the f

float number = 2; //ok


name = 2.0f; //does not compile without the suffix f

double division;
0.3333333333333333333333333334; // the suffix d is optional
[Link](name); //displaying the content of the variable name
}
}

Q6Test the program above.

By default (without the suffix f), real constants are placed in doubles. When a
this constant is assigned to a variable of type float, it must therefore be converted to float.
This conversion to float is degrading because it results in a loss of precision and thus it
causes a compilation error.
Conclusion: to assign a real constant to a variable of type float, it is necessary to use
the suffix f (so that the constant is placed in a float!).

4.1.2 The char type


August 22

A char type variable allows you to store a character. Characters are encoded in
Unicode on 16 bits: from 0x0000 to 0xFFFF.
Simplifying for ASCII characters: High-order byte to 0
low weight octet: ASCII code

ASCII code
ASCII (American Standard Code for Information Interchange) uses 7 bits to represent a
character: they are therefore numbered in decimal from 0 to 127, coded in binary from 0b0000000 to
0b1111111 and in hexadecimal from 0x00 to 0x7F.
So, only 128 characters are represented.

DEL
Characters number 0 to 31 and 127 are non-printable: they correspond to commands.
computer terminal control. Character number 32 is the space. The other characters are
Arabic numerals, uppercase and lowercase Latin letters without accents, and some symbols of
punctuation.

Examples:
September 22

char a; //declaration of a variable named a of type char


a = 'B'; We assign the ASCII code of the letter B to the variable a.
[Link](a); //displaying the content of variable a
a = 67; We assign the ASCII code of the letter C to the variable a.
[Link](a); //displaying the content of the variable a
a = 0x65; We assign the ASCII code of the letter e to the variable a
[Link](a); //display the content of the variable a

Remarks: - The expressions in quotes (or apostrophes) are of type char.

Q7 Test the program above.

4.1.3 The boolean type


A variable of boolean type can only take (or contain) two values: true or false.
(fake), without quotes (these values are native to the language, it understands them directly and knows them
interpret)

boolean a; //declaration of a variable named a of type boolean


a = true; we assign true to the variable a
[Link](a); //displaying the content of the variable a
a = false; we assign false to the variable a
[Link](a); //displaying the content of the variable a

Test the program above.

4.1.3 To declare multiple variables of the same type:


int a = 5, b = 3, c = 85;
The previous instruction declares 3 variables of type int. These variables are named a, b, and c and are
respectively initialized to 5, 3, and 85.

4.2 String Type Objects


Letype String is a class that is part of the package [Link].
A variable of type String, like any variable of class type, is an object.
String objects are constant (immutable) objects.

Examples:
String phrase; //declaration of an object named phrase of type String
toto at the swimming pool
[Link](phrase); //displaying the content of the phrase object
titi We can initialize the ph2 object at the same time we declare it.
[Link](ph2); //displaying the content of the object ph2

Note: constant strings are denoted in quotes (double): " " .

5. Naming convention
To facilitate the reading of programs, the following conventions are commonly used.
adopted:
All class names must start with an uppercase letter;
all variable names must start with a lowercase letter;
October 22

if the name of a variable is made up of several words, the first starts with a lowercase letter, the
or the others with a capital letter, and this, without separation (example: int nombrePlusGrand; )

Remarks:
All these names must be without accents.
the names of primitive types start with a lowercase letter, which allows them to
differentiate types of classes.

6. The operators
6.1 Arithmetic Operators
Notation in Java language Significance
+ Addition
- Subtraction
* Multiplication
(with real numerical type variables) Real Division
/ (with integer type numeric variables) Integer division
% (with integer data type variables) Remainder of the integer division
These operators are binary operators: they must be applied to 2 operands.
variables, 2 constants or one variable and one constant.

Examples:
int n1, n2, n3, n4; //declaration of variables
n1 = 3 + 1; //n1 is worth 4
n2 = 2*6; //n2 is worth 12
n3 = n2 / n1; //n3 is worth 3
n1 = n1 + 1; the JVM calculates the value of n1 + 1 and assigns the result (5) to n1
n2 = n2 + 2; //n2 is worth 14
n4 = n2 / n1; //n4 is worth 2 because 14 = 2*5 + 4
n1 = n2 % n1; //n1 is worth 4

6.2 The increment and decrement operators


Incrementing a variable means 'Adding 1 to the variable'.
Decrementing a variable means "Subtracting 1 from the variable."

Notation in Java language Significance


++ Increment
-- Decrementation
These operators are unary operators: they must be applied to a single operand: a
variable.

Examples:
int n1 = 0; //declaration of a variable
n1++; //n1 is equal to 1
n1++; //n1 is worth 2
n1 = n1 + 1; //n1 is worth 3 (same as n1++;)
n1--; //n1 is worth 2
n1 = n1 - 1; //n1 is equal to 1 (same as n1--);
November 22

6.3 Extended assignment operators (+= ; -= ; *= ; /= ; %=)

Examples:
int n1 = 9, n2 = 5; //variable declaration
n1 += 5; //equivalent to n1 = n1 + 5 => n1 is 14
n1 /= n2; // equivalent to n1 = n1 / n2 => n1 is 2
n1 += 7; n1 is equal to 9
n1 %= 2; //equivalent to n1 = n1 % 2 => n1 is 1

7. Key entries
To enter variables, we can use the Scanner class which is part of the [Link] package.
Since this Scanner class is not part of the [Link] package which all classes
are imported by default, it is necessary to explicitly import this class at the beginning of the program:
import [Link];

Then in the definition of the main() function, it creates an object of the Scanner class from the
in the following way:
Scanner sc = new Scanner([Link]);

We can divide the previous instruction into 2:


Scanner sc; declaration of the object named sc (1)
sc = new Scanner([Link]); // creation of the Scanner class object (2)

(*1) : the declaration of the object corresponds more precisely to the declaration of a variable
named reference sc designed to contain the memory address (or reference) of an object of
type class Scanner.
You have the right to choose another name for this reference variable.

(*2): the new operator allows you to create an object, which implies reserving space.
Memory occupied by this object. You must indicate the type of object to create (here, the class type)
Scanner). Moreover, creating this object (of type Scanner) requires the passing of a
parameter: the object named in of type InputStream, which is part of the System class (the object
is associated with the standard input, by default the keyboard). After creating the object of the class
Scanner, the new operator returns the memory address of the created object and this is
affected in sc.

7.1 Input of a string


You must use the method (or member function) nextLine() of the Scanner class. This
method returns a String (*3), which simply needs to be assigned to an object of type String (in order to
to be able to use the input string in the rest of the program).

String str; //declaration of the object named str (*4)


[Link]("Enter a string: ");
str = [Link](); input a String and assign the entered string to str (*5)
[Link]("Thank you for : ");
[Link](str); // display the string contained (6)
in str

(4) : more precisely, declaration of a reference variable intended to hold the address
12/22

memory (or the reference) of an object of type String.


(*5) : The operator " " .indicates that the nextLine() method is called for the object sc. Following this
the call of this function, the program waits for the user to enter a string of
characters and press the "Enter" key. After pressing "Enter", the function creates or
create a String type object and store the entered string in it. When the function is executed
nextLine() ends, it returns the memory address of the String it has created and this latter
is affected in str.
(*3): the nextLine() function returns the reference or memory address of the String.
(*6): display of the string contained in the String referenced by str.

Test the above program.

7.2 Entry of a primitive type variable


The Scanner class has a method for each primitive type: the methods nextByte(),
nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble() and nextBoolean() allow the
input of variables of the corresponding types.

Examples:
long nb4; //declaration of an int type variable named nb
boolean bo;
Enter an integer:
nb4 = [Link](); input a long and assign the entered integer to nb4
Thank you for :
[Link](nb4); // displaying the value contained in nb4
[Link]("Enter a boolean: ");
bo = [Link](); Input a boolean and assign the input boolean to bo
Thank you for:
[Link](bo); // display the value contained in bo

Test the program above.

Remarks:
if the user inputs anything (a string of characters instead of a number for
For example), the program crashes. We will see how to manage this problem later as one
In general, one cannot trust the data entered by the user.
- In the Scanner class, there is no function (named nextChar()) for input.
a single character. You can only enter a string (object of type String)
with the nextLine() function then access the various characters entered using the function
charAt() member of the String class (see following example)

String str; // declaration of the object named str

Enter a string:
str = [Link](); //input a String and assignment of the entered string to str
Thank you for :
[Link](str); //display the string contained in str

char car1, car2, car3; //declaration of 3 variables of type char


car1 = [Link](0); // (*7)
car2 = [Link](1);
car3 = [Link](2);
The first 3 characters:
13/22

[Link](car1);
[Link](car2);
[Link](car3);

(*7): calling the charAt() function for the str object. This function takes a parameter that
represents the index or the position of the character it returns. The 1st character is located at
the index 0 (cf. course on arrays), the second at index 1, the 3rd at index 2, etc...

Q11Test the above program.

7.3 Exercise

Q12 Create a program that:


- request the input of an integer, then display the entered integer;
request the input of a string, then display the entered string.

If you respect what was seen earlier, it doesn't work: the user does not have the
main to enter the string.

Explanation:
All inputs are done through an input buffer:
Entry tampon Program
Keyboard
running

The content of the buffer is "analyzed" when the user "presses" the Enter key: the
Line Feed character (LF, '\n' in Java language) is then inserted into the buffer.

Here is the following code:


String str; //declaration of the object named str
int nb;

[Link]("1. Enter an integer: ");


nb = [Link](); Input an int and assign the entered integer to nb
1. Thank you for :
[Link](nb); displaying the value contained in nb

[Link]("2. Enter a string: ");


str = [Link](); Input a String and assign the entered string to str
2. Thank you for :
[Link](str); Display the string contained in str

When executing, if the user enters "123456\n" following the prompt "1. Enter a
, these 7 characters are transmitted in the input buffer and analyzed at the time of
pressing the Enter key. The 6 digits are then extracted from the buffer and used for
form a number that is assigned to nb. The character '\n' is left in the buffer.
So when entering the following string, since the buffer already contains a
The call to the nextLine() function is non-blocking. This function returns a string of
empty characters and extract the character '\n' (remaining) from the buffer. So after execution of
In the instruction 'str = [Link]();', the buffer is empty!
14/22

Note: the behavior of the nextLine() method is different from that of the others.
methods of the Scanner class (such as nextInt(), nextDouble(), nextBoolean(), ...) :

Behavior of the nextLine() method:


When this method is called, it waits for a ' ' character in the buffer.
from the moment a '\n' is present in the input buffer, the characters that precede it
are used to form the String returned by the method, and the character ' ' is removed
the buffer. So, after the call to nextLine(), the buffer is necessarily empty. Similarly, if
there was a ' ' in the buffer before the call to nextLine(), the user does not have control to
enter something.

Behavior of other methods (like nextInt(), nextDouble(), nextBoolean(), ...):


When calling one of these methods, if there is a ' ' remaining in the buffer, it is extracted from the
the input and the corresponding method wait for the entry of an integer, a real number, or a boolean
ended with a press of the Enter key, which causes the insertion of a ' ' in the
tampon. So, the user must have control and if they enter "158.6\n" in the case of a call.
for example, the first 5 characters are extracted to form a real number that
is returned as the return value of the method. The character ' ' (which follows '6') is left as is.
in the buffer.

Conclusion: we can chain the inputs by calling methods like nextInt(),


nextDouble(), nextBoolean(), ... without asking any questions. But when, after the call of one of
these methods, we want to capture a String, we need to clear the buffer (by calling it "blank")
nextLine() method to be able to input this String.

Solution to the exercise:


String str; //declaration of the object named str
int nb;

[Link]("1. Enter an integer: ");


nb = [Link](); input an int and assign the entered integer to nb
1. Thank you for :
[Link](nb); //displaying the value contained in nb

[Link]("2. Enter a string: ");


[Link](); // to remove the ' ' that remains in the buffer (*1)
str = [Link](); Input a String and assign the entered string to str
2. Thank you for :
[Link](str); //displaying the string contained in str

(*1) : the String returned by nextLine() containing an empty string is lost!

Q13Test the program above.

8. The conditions
They allow for executing different instructions depending on different scenarios.

8.1 Conditional algorithmic structure


15/22

int nb;

Enter an integer:
nb = [Link](); //input an int and assign the entered integer to nb

if(nb < 0) // if (logical condition)


{
[Link]("nb is negative."); //executed only if nb < 0
}
[Link]("End of the program."); // executed in all cases.

The word 'if' is a keyword in the Java language. It must be followed by a logical condition.
in parentheses. This logical condition is a boolean that can therefore only take 2
TRUE or FALSE. It is evaluated (or calculated) at the time of execution.
program. The code placed in the block (enclosed by the braces) that follows is executed only
if the logical condition is evaluated to TRUE.

Test the above program in both scenarios.

8.2 Alternative algorithmic structure


int nb;

Enter an integer:
nb = [Link](); Input an int and assign the entered integer to nb

if(nb < 0) // if (logical condition)


{
//executed if the evaluated logical condition is true
[Link]("nb");
is negative.
}
else
{
[Link]("nb is positive or zero."); //executed if the logical condition is false
}
End of the program.

Q15 Test the above program in both scenarios.

The word 'else' is a keyword in the Java language. It can only be used following a block.
preceded by an 'if'. Indeed, the instructions contained in the block following the 'else' do not
are executed only if the logical condition evaluated in the 'if' is false.

Note: the use of an 'else' clause following an 'if' is optional.

8.3 Nested alternative algorithmic structures


int nb;
[Link]("Enter an integer: ");
nb = [Link](); Input an int and assign the entered integer to nb

if(nb < 0) // if (logical condition)


{
16/22

// executed if the evaluated logical condition is true


[Link]("nb");
is negative.
}
else
{
if(nb > 0)
{
[Link]("nb");
is positive.
}
else
{
nb is null.
}
}
[Link]("End of the program."); // executed in all cases.
Q16 Test the above program in the 3 scenarios.

Note: with each entry into a new block, I have indented one tab to the left
the instructions contained in this block. These various shifts constitute the indentation of
programs and aim to facilitate its reading. Advice: to indent a program, do not
never use spaces, always use tabs.

8.4 Remark
In reality, using a block (delimited by braces) following an 'if' clause is not
mandatory only if we wish to execute more than one instruction when the logical condition
tested is true. Indeed, without the braces following an if, only the instruction (ended by
A semicolon that follows the if is executed when the tested logical condition is true.
Same for the else clause.

Q17 Take the examples from paragraphs 8.1, 8.2, and 8.3 and remove the braces.

8.5 Relational Operators


To create a logical condition or a boolean, you have relational operators at your disposal.
next:
Notation in Java Significance
== Equal to
!= Different from
< Less than
> Greater than
<= Less Than or Equal To
>= Greater than or equal to
These operators are binary operators: they must be applied to 2 operands.
provide a logical expression or a boolean as a result.

Example: resumption of example 8.1


int nb;
boolean bo;

Enter an integer:
17/22

nb = [Link](); //input an int and assign the entered integer to nb

bo = nb < 0;
if (bo) // same as if (bo == true)
{
[Link]("nb is negative."); // executed only if nb < 0
}
End of the program.

Q17 Test the program above

8.6 Logical operators


Notation in Java Meaning
&& Logical AND function
|| Logical OR function
! Logical function NOT

These operators are binary operators: they must be applied to 2 operands that
are interpreted as booleans. These operators provide a result of a
logical expression or a boolean.

Truth tables of the different logical operators:


Let A and B be logical expressions:

A B A || B A B A && B A !A
false false false false false false false
false true false true false true
true false true false false
true true true true true true

Example:
With:
int largeur = 4, longueur = 10;

(length == 10) is !(true) which is false


// (width > 5) || (length <= 10) is false || true which is true
// (!(width > 6)) && (length < 11) is equal to (! false) && true which equals true

8.7 Algorithmic structure with multiple choices: SWITCH CASE


This algorithmic structure allows for different actions to be performed depending on the values.
discrete values that a single variable can take.

int nb;

[Link]("Enter an integer: ");


nb = [Link](); Input an int and assign the entered integer to nb

switch(nb) //
{
18/22

case1 : //executed if nb equals 1


nb is equal to 1.
break; //means: exit the block
case2 : //executed if nb is equal to 2
nb is equal to 2.
break;
case3 : //executed if nb equals 3
[Link]("nb");
[Link](" is worth 3.");
break;

//executed if nb is different from 1, 2, and 3


nb is different from the values tested in the case.
}
End of the program.

The words 'switch', 'case', 'break', and 'default' are keywords in the Java language.

Q18Test the program above in all scenarios.

Q19 Create a program that gives the same results using the keywords "if" and
"else" instead of the keywords "switch", "case", "break" and "default".

Q20 Return to the program of question 18. Remove all 'break;' statements.
and test the program in all scenarios. Conclusion?

9. Exercises
9.0 The 5 rules of writing a program:
Add a header
Add comments
Respect the indentation
Choose explicit variable names
Choose explicit file names (and thus classes in Java)

9.1 Exercise 1: create a program that calculates the area of a rectangle whose length and width
will be entered by the user, then displays the result.

9.2 Exercise 2: create a program that:


request the entry of the hour (without the minutes);
display "Hello" if the hour is less than or equal to 16 and "Good evening" otherwise
opposite;

9.3 Exercise 3:
A store offers a discount under the following conditions:
If the purchase amount is strictly less than €350, there is no discount.
If the purchase amount is between €350 and €600, a 3% discount is granted.
If the purchase amount is equal to or greater than €600, a 5% discount is granted.

Create a program that:


request the entry of the purchase amount;
Calculate the net price to be paid and display it.
19/22

9.4 Exercise 4: Calculation of BMI (Body Mass Index)

Reminder: BMI is calculated by dividing weight by height squared.


The interpretation of BMI is done according to the criteria defined by the World Health Organization.

BMI (Kg.m)-2) Interpretation (according to the WHO)


Less than 16.5 Undernutrition
16.5 to 18.5 Thinness
18.5 to 25 Normal body weight
25 to 30 Overweight
More than 30 Obesity
Note: this classification is statistical, it does not necessarily apply to all adults.
notably athletes or seniors.

Create a program that:


Calculate and display a person's BMI (weight and height will be entered by the user);
interpret the calculated BMI using the table above.

10. Iterative algorithmic structures (or loops)


They allow for repeating the same process several times.

10.1 The while loop


It allows repeating a set of instructions as long as a logical condition is true.

Example 1:
int nb = 0;

while( nb != 1) {
The instructions contained in this block are repeated as long as the condition
// logic (nb != 1) is true
Enter an integer, 1 to exit:
nb = [Link]();
}
[Link]("End of the program."); // executed when exiting the loop

The word "while" is a keyword in the Java language. It must be followed by a logical condition.
placed in parentheses. This logical condition is a boolean that therefore cannot take
which has 2 values: TRUE or FALSE. It is evaluated (or calculated) before each possible
execution of the instructions placed in the block that follows. The code placed in the block
(delimited by the braces) is executed as long as the logical condition is evaluated as TRUE.

Test the above program.

Q22 Modify the program by initializing the variable nb to the value 1. Test the program.
Conclusion?
Example 2:
int nb = 0;

while( nb < 5)
{
20/22

The instructions contained in this block are repeated as long as the condition
// logic (nb < 5) is true
nb++;
[Link]("nb = ");
[Link](nb);
}
End of the program.

Q23 Test the above program. Justify the obtained result.


Comment on the instruction that increments nb. Test the program. To interrupt its
execution, press the key combination: CTRL C. Conclusion?

10.2 The do while loop


In this structure, the processing is executed once and its repetition continues as long as the
the logical condition is met.

Example:
int nb = 1;
do
{
We are certain that the instructions contained in this block will be executed.
at least once
Enter an integer, 1 to exit:
nb = [Link]();
}
while( nb != 1);// do not forget the semicolon
End of the program.

The words 'do' and 'while' are keywords in the Java language. After each execution of
Instructions contained in the block, the logical condition that follows the 'while' is evaluated. If
it is evaluated as TRUE, we restart a new execution of the instructions contained
in the block, otherwise we exit the loop.

Q25 Test the program above.

10.3 The for loop


A 'for' loop has the following structure:
for(expression1;expression2;expression3) {
treatment //to repeat
}
and is equivalent to:
expression1
while(expression2) {
treatment to repeat
expression3;
}

The word 'for' is a keyword in the Java language. It must be followed by 3 expressions placed between
parentheses and separated by semicolons. The expression1 is generally used to initialize
a variable used by the loop. Expression2 is interpreted as a condition
logic. As for expression 3, it is generally used to modify the variable used by the
loop.
21/22

Example:
int i;

for(i = 0;i < 3;i++) {


//treatment to be repeated
Value of i :
[Link](i);
}
[Link]("When exiting the loop, i is equal to ");
[Link](i);

In the previous example, the processing is executed for i = 0, then for i = 1 and finally for i = 2.
When we exit the loop, i is equal to 3.

Q26 Test the program.

Q27 Write a program that produces the same result using a while loop.

Conclusion: the 'for' loop is used when the number of repetitions is known in advance.
It allows writing this type of loop more concisely than a 'while' loop.

11. Exercises
11.1 Exercise 1: create a program that displays 'Hello' 5 times using a loop.

11.2 Exercise 2: create a program that displays 'Hello' multiple times: the number of displays
must be entered by the user.

11.3 Exercise 3:
Create a program that asks the user for a number between 0 and 3 (inclusive) until
that the response is suitable. If the response is not suitable, it should be reported to the user.

11.4 Exercise 4:
Create a program that asks for a number between 10 and 20 (inclusive), until the
satisfactory response. In case of a response greater than 20, a message should appear: 'More
small!" and conversely, "Bigger!" if the number is less than 10.

11.5 Exercise 5:
Create a program that asks for a starting number, and then displays the ten numbers.
following. For example, if the user enters the number 17, the program must display the numbers from 18
to 27.

11.6 Exercise 6:
Create a program that asks for a starting number, and then writes the table of
multiplication of this number, presented as follows (case where the user enters the number 7):
Table of 7:
7x1=7
7 x 2 = 14
7 x 3 = 21

7 x 10 = 70
22/22

11.7 Exercise 7:
Create a program that asks for a starting number and calculates the sum of the integers up to it.
this number. For example, if 5 is entered, the program should calculate:
1 + 2 + 3 + 4 + 5 = 15

Note: we want to display only the result, not the breakdown of the calculation.

11.8 Exercise 8:
Create a program that:
ask the user to enter 10 numbers,
Determine and display the largest number among the 10 entered numbers:
Enter number 1: 12
Enter number 2: 14
etc.
Enter the number 10: 6
The largest of these numbers is: 14

Then modify the algorithm so that the program also displays the position at which the most
a large number is entered:
The largest number was entered at position 2

11.9 Exercise 9:
Same problem as in exercise 8, but this time the number of user inputs is not
fixed in advance: the entry of numbers stops when the user enters a zero.

You might also like