OOP (java)
MSc. Mohammed AL-Sayani
Java Comments
Java Comments
Comments can be used to explain Java code, and to make it more
readable. It can also be used to prevent execution when testing alternative
code.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not
be executed).
This example uses a single-line comment before a line of code:
Example
// This is a comment
System.out.println("Hello World");
This example uses a single-line comment at the end of a line of code:
Example
System.out.println("Hello World"); // This is a comment
Java Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Java.
This example uses a multi-line comment (a comment block) to explain
the code:
Example
/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");
It is up to you which you want to use. Normally, we use // for short
comments, and /* */ for longer.
Test Yourself With Exercises
Exercise:
Insert the missing part to create two types of comments.
This is a single-line comment
This is a multi-line comment
Java Variables
Java Variables
Variables are containers for storing data values.
In Java, there are different types of variables, for example:
• String - stores text, such as "Hello". String values are surrounded
by double quotes
• int - stores integers (whole numbers), without decimals, such as
123 or -123
• float - stores floating point numbers, with decimals, such as 19.99
or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
• boolean - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
type variableName = value;
Where type is one of Java's types (such as int or String), and
variableName is the name of the variable (such as x or name). The equal
sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type String and assign it the value
"John":
String name = "John";
System.out.println(name);
To create a variable that should store a number, look at the following
example:
Example
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
System.out.println(myNum);
You can also declare a variable without assigning the value, and assign
the value later:
Example
int myNum;
myNum = 15;
System.out.println(myNum);
Note that if you assign a new value to an existing variable, it will
overwrite the previous value:
Example
Change the value of myNum from 15 to 20:
int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(myNum);
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the
final keyword (this will declare the variable as "final" or "constant",
which means unchangeable and read-only):
Example
final int myNum = 15;
myNum = 20; // will generate an error: cannot assign a value
to a final variable
Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
You will learn more about data types in the next section.
Test Yourself With Exercises
Exercise:
Create a variable named carName and assign the value Volvo to it.
= ;
Java Declare Multiple Variables
Declare Many Variables
To declare more than one variable of the same type, you can use a
comma-separated list:
Example
Instead of writing:
int x = 5;
int y = 6;
int z = 50;
System.out.println(x + y + z);
You can simply write:
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
Test Yourself With Exercises
Exercise:
Fill in the missing parts to create three variables of the same type, using a
comma-separated list:
x = 5 y = 6 z = 50;
Java Identifiers
Identifiers
All Java variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names
(age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create
understandable and maintainable code:
Example
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
The general rules for naming variables are:
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter
• Names should start with a lowercase letter and it cannot contain
whitespace
• Names can also begin with $ and _ (but we will not use it in this
tutorial)
• Names are case sensitive ("myVar" and "myvar" are different
variables)
• Reserved words (like Java keywords, such as int or boolean)
cannot be used as names
Java Data Types
Java Data Types
As explained in the previous chapter, a variable in Java must be a
specified data type:
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Data types are divided into two groups:
• Primitive data types - includes byte, short, int, long, float,
double, boolean and char
• Non-primitive data types - such as String, Arrays and Classes (you
will learn more about these in a later chapter)
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it
has no additional methods.
There are eight primitive data types in Java:
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int
Stores whole numbers from -2,147,483,648 to
4 bytes
2,147,483,647
Stores whole numbers from -
long 8 bytes 9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float
Stores fractional numbers. Sufficient for
4 bytes
storing 6 to 7 decimal digits
double
Stores fractional numbers. Sufficient for
8 bytes
storing 15 decimal digits
boolean 1 bit Stores true or false values
char
Stores a single character/letter or ASCII
2 bytes
values
Test Yourself With Exercises
Exercise:
Add the correct data type for the following variables:
myNum = 9;
myFloatNum = 8.99f;
myLetter = 'A';
myBool = false;
myText = "Hello World";
Java Numbers
Numbers
Primitive number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or
-456), without decimals. Valid types are byte, short, int and long.
Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part,
containing one or more decimals. There are two types: float and double.
Even though there are many numeric types in Java, the most used for
numbers are int (for whole numbers) and double (for floating point
numbers). However, we will describe them all as you continue to read.
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can
be used instead of int or other integer types to save memory when you
are certain that the value will be within -128 and 127:
Example
byte myNum = 100;
System.out.println(myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
short myNum = 5000;
System.out.println(myNum);
Int
The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is the
preferred data type when we create variables with a numeric value.
Example
int myNum = 100000;
System.out.println(myNum);
Long
The long data type can store whole numbers from -
9223372036854775808 to 9223372036854775807. This is used when int
is not large enough to store the value. Note that you should end the value
with an "L":
Example
long myNum = 15000000000L;
System.out.println(myNum);
Floating Point Types
You should use a floating point type whenever you need a number with a
decimal, such as 9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that
you should end the value with an "f" for floats and "d" for doubles:
Float Example
float myNum = 5.75f;
System.out.println(myNum);
Double Example
double myNum = 19.99d;
System.out.println(myNum);
Use float or double?
The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of float is only six
or seven decimal digits, while double variables have a precision of about
15 digits. Therefore it is safer to use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to
indicate the power of 10:
Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
Java Boolean Data Types
Boolean Types
Very often in programming, you will need a data type that can only have
one of two values, like:
• YES / NO
• ON / OFF
• TRUE / FALSE
For this, Java has a boolean data type, which can only take the values
true or false:
Example
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Boolean values are mostly used for conditional testing.
You will learn much more about booleans and conditions later in this
tutorial.
Java Characters
Characters
The char data type is used to store a single character. The character must
be surrounded by single quotes, like 'A' or 'c':
Example
char myGrade = 'B';
System.out.println(myGrade);
Alternatively, if you are familiar with ASCII values, you can use those to
display certain characters:
Example
char myVar1 = 65, myVar2 = 66, myVar3 = 67;
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
Strings
The String data type is used to store a sequence of characters (text).
String values must be surrounded by double quotes:
Example
String greeting = "Hello World";
System.out.println(greeting);
The String type is so much used and integrated in Java, that some call it
"the special ninth type".
A String in Java is actually a non-primitive data type, because it refers to
an object. The String object has methods that are used to perform certain
operations on strings. Don't worry if you don't understand the term
"object" just yet. We will learn more about strings and objects in a later
chapter.
Java Type Casting
Java Type Casting
Type casting is when you assign a value of one primitive data type to
another type.
In Java, there are two types of casting:
• Widening Casting (automatically) - converting a
smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
• Narrowing Casting (manually) - converting a
larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a smaller size type
to a larger size type:
ExampleGet your own Java Server
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to
double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting
Narrowing casting must be done manually by placing the type in
parentheses in front of the value:
Example
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to
int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
ava If ... Else
Java Conditions and If Statements
You already know that Java supports the usual logical conditions from
mathematics:
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b
You can use these conditions to perform different actions for different
decisions.
Java has the following conditional statements:
• Use if to specify a block of code to be executed, if a
specified condition is true
• Use else to specify a block of code to be executed, if
the same condition is false
• Use else if to specify a new condition to test, if the
first condition is false
• Use switch to specify many alternative blocks of
code to be executed
The if Statement
Use the if statement to specify a block of Java code to be executed if a
condition is true.
SyntaxGet your own Java Server
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will
generate an error.
In the example below, we test two values to find out if 20 is greater than
18. If the condition is true, print some text:
Example
if (20 > 18) {
System.out.println("20 is greater than 18");
}
We can also test variables:
Example
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
In the example above we use two variables, x and y, to test whether x is
greater than y (using the > operator). As x is 20, and y is 18, and we know
that 20 is greater than 18, we print to the screen that "x is greater than y".
Java Switch
Java Switch Statements
Instead of writing many if..else statements, you can use the switch
statement.
The switch statement selects one of many code blocks to be executed:
SyntaxGet your own Java Server
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each
case.
• If there is a match, the associated block of code is executed.
• The break and default keywords are optional, and will be
described later in this chapter
The example below uses the weekday number to calculate the weekday
name:
Example
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
The break Keyword
When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the
block.
When a match is found, and the job is done, it's time for a break. There is
no need for more testing.
A break can save a lot of execution time because it "ignores" the
execution of all the rest of the code in the switch block.
Java While Loop
Loops
Loops can execute a block of code as long as a specified condition is
reached.
Loops are handy because they save time, reduce errors, and they make
code more readable.
Java While Loop
The while loop loops through a block of code as long as a specified
condition is true:
SyntaxGet your own Java Server
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again,
as long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Note: Do not forget to increase the variable used in the condition,
otherwise the loop will never end!
ADVERTISEMENT
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:
Example
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
Test Yourself With Exercises
Exercise:
Print i as long as i is less than 6.
int i = 1;
(i < 6) {
System.out.println(i);
;
}
Java For Loop
Java For Loop
When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop:
SyntaxGet your own Java Server
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code
block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been
executed.
The example below will print the numbers 0 to 4:
Example
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
1. Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than
5). If the condition is true, the loop will start over again, if it is false, the
loop will end.
Statement 3 increases a value (i++) each time the code block in the loop
has been executed.
Another Example
This example will only print even values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2) {
System.out.println(i);
}
Nested Loops
It is also possible to place a loop inside another loop. This is called a
nested loop.
The "inner loop" will be executed one time for each iteration of the "outer
loop":
Example
// Outer loop
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2
* 3)
}
}
Test Yourself With Exercises
Exercise:
Use a for loop to print "Yes" 5 times.
(int i = 0; i < 5; ) {
System.out.println( );
}
Java For Each Loop
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:
Syntax
for (type variableName : arrayName) {
// code block to be executed
}
The following example outputs all elements in the cars array, using a
"for-each" loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Note: Don't worry if you don't understand the example above. You will
learn more about Arrays .