Java Programming Basics Explained
Java Programming Basics Explained
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.
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.
1. First example.
The Java language is 100% object-oriented, and every application is contained in one or more
classes.
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].
Run the application with the java interpreter by typing the following command:
java Hello1
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 " */ "
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
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()
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 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
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.
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.
4. The variables
They allow storing numbers, characters, booleans... whose value can
to be modified during the execution of the program.
Note: The type of a variable is chosen based on what we wish to store (or
put) in the variable.
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.
double division;
0.3333333333333333333333333334; // the suffix d is optional
[Link](name); //displaying the content of the variable name
}
}
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!).
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
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
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
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
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]);
(*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.
(4) : more precisely, declaration of a reference variable intended to hold the address
12/22
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
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)
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
[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...
7.3 Exercise
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.
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(), ...) :
8. The conditions
They allow for executing different instructions depending on different scenarios.
int nb;
Enter an integer:
nb = [Link](); //input an int and assign the entered integer to nb
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.
Enter an integer:
nb = [Link](); Input an int and assign the entered integer to nb
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: 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.
Enter an integer:
17/22
bo = nb < 0;
if (bo) // same as if (bo == true)
{
[Link]("nb is negative."); // executed only if nb < 0
}
End of the program.
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.
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;
int nb;
switch(nb) //
{
18/22
The words 'switch', 'case', 'break', and 'default' are keywords in the Java language.
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.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.
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.
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.
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.
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;
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.
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.