0% found this document useful (0 votes)
1 views66 pages

Java Manual 1

This document provides a comprehensive guide on getting started with Java, including installation instructions for Windows and a basic introduction to Java syntax and structure. It covers creating a simple Java program, understanding the main method, variables, data types, and comments. Additionally, it explains how to display output and the rules for naming variables in Java.

Uploaded by

makenaweddy594
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)
1 views66 pages

Java Manual 1

This document provides a comprehensive guide on getting started with Java, including installation instructions for Windows and a basic introduction to Java syntax and structure. It covers creating a simple Java program, understanding the main method, variables, data types, and comments. Additionally, it explains how to display output and the rules for naming variables in Java.

Uploaded by

makenaweddy594
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

Java Getting Started

Install Java
Some PCs might have Java already installed.
To check if you have Java installed on a Windows PC,
search in the start bar for Java or type the following in
Command Prompt ([Link]):
C:\Users\Your Name>java -version
If Java is installed, you will see something like this
(depending on version):
java version "11.0.1" 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-
LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-
LTS, mixed mode)
If you do not have Java installed on your computer, you
can download it for free at [Link].
Note: In this tutorial, we will write Java code in a text
editor. However, it is possible to write Java in an Integrated
Development Environment, such as IntelliJ IDEA, Netbeans
or Eclipse, which are particularly useful when managing
larger collections of Java files.

1
Setup for Windows
To install Java on Windows:
1. Go to "System Properties" (Can be found on Control
Panel > System and Security > System > Advanced
System Settings)
2. Click on the "Environment variables" button under the
"Advanced" tab
3. Then, select the "Path" variable in System variables
and click on the "Edit" button
4. Click on the "New" button and add the path where
Java is installed, followed by \bin. By default, Java is
installed in C:\Program Files\Java\jdk-11.0.1 (If
nothing else was specified when you installed it). In
that case, You will have to add a new path
with: C:\Program Files\Java\jdk-11.0.1\bin
Then, click "OK", and save the settings
5. At last, open Command Prompt ([Link]) and
type java -version to see if Java is running on
your machine
Show how to install Java step-by-step with images
Step 2

2
Step 3

3
Step 4

Step 5
Write the following in the command line ([Link]):
C:\Users\Your Name>java -version
If Java was successfully installed, you will see something
like this (depending on version):
java version "11.0.1" 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-
4
LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-
LTS, mixed mode)

Java Quickstart
In Java, every application begins with a class name, and
that class must match the filename.
Let's create our first Java file, called [Link], which can
be done in any text editor (like Notepad).
The file should contain a "Hello World" message, which is
written with the following code:
public class Main {
public static void main(String[] args) {
[Link]("Hello World");
}
}
Save the code in Notepad as "[Link]".
Open Command Prompt ([Link]),
Navigate to the directory where you saved your file, and
type "javac [Link]":
C:\Users\Your Name>javac [Link]

5
This will compile your code. If there are no errors in the
code, the command prompt will take you to the next line.
Now, type "java Main" to run the file:
C:\Users\Your Name>java Main
The output should read:
Hello World

Java Syntax
In the previous chapter, we created a Java file
called [Link], and we used the following code to print
"Hello World" to the screen:
public class Main {
public static void main(String[] args) {
[Link]("Hello World");
}
}
Example explained
Every line of code that runs in Java must be inside a class.
In our example, we named the class Main. A class should
always start with an uppercase first letter.
Note: Java is case-sensitive: "MyClass" and "myclass" has
different meaning.

6
The name of the java file must match the class name.
When saving the file, save it using the class name and add
".java" to the end of the filename.
To run the example above on your computer, make sure
that Java is properly installed:
The output should be:
Hello World

The main Method


The main() method is required and you will see it in every
Java program:
public static void main(String[] args)
Any code inside the main() method will be executed.

The line:

public static void main(String[] args)

looks complicated at first, but it is made up of several small parts. Think of it as an


instruction that tells Java where to start running your program.

Let's break it down.

1. public

Meaning: Anyone can use this method.

Think of a classroom.

7
• Public = The classroom door is open. Anyone is allowed to enter.
• Private = Only certain people are allowed inside.

In Java, public means the main method is accessible to everyone, including the
Java program that starts your application.

2. static

Meaning: Java can use this method without creating an object.

Imagine you want to switch on a television.

• If the remote works immediately, that's like static.


• If you first have to buy the TV before using the remote, that's like a non-
static method.

Since Java has not created any objects when the program starts, the main method
must be static so it can run immediately.

3. void

Meaning: This method does not return any value.

Think of a school bell.

You ring the bell.

Students hear it.

The bell does not give you anything back.

Similarly,

void

means the method performs its task but does not return an answer.

8
4. main

Meaning: This is the starting point of the program.

Think of a movie.

Before the movie begins, it starts from the first scene.

In Java,

main

is the first method that Java runs.

Without a main method, Java does not know where to begin.

5. (String[] args)

This part allows information to be passed into the program when it starts.

String

A String means text.

Examples:

"Samuel"
"Hello"
"Kenya"

These are all Strings.

[]

The square brackets mean many.

For example:

9
One student:

Samuel

Many students:

Samuel
Mary
John
Peter

Likewise,

String[]

means many pieces of text.

args

args is simply the name given to those pieces of text.

You could even write:

String[] names

or

String[] students

but by convention, programmers usually use args, which stands for arguments.

Putting it all together

public static void main(String[] args)

means:

10
"This is the method that everyone can access. Java can run it immediately
without creating an object. It does not return a value, it is the starting point of
the program, and it can receive text information when the program starts."

Every Java program has a class name which must match


the filename, and that every program must contain
the main() method.
[Link]()
Inside the main() method, we can use the println() method
to print a line of text to the screen:
public static void main(String[] args) {
[Link]("Hello World");
}

Note: The curly braces {} marks the beginning and the end
of a block of code.
System is a built-in Java class that contains useful
members, such as out, which is short for "output".
The println() method, short for "print line", is used to print
a value to the screen (or a file).
Don't worry too much about System, out and println(). Just
know that you need them together to print stuff to the
screen.
You should also note that each code statement must end
with a semicolon (;).
11
You can use the println() method to output values or print
text in Java:
public class Main {
public static void main(String[] args) {
[Link]("Hello World!");
[Link]("I am learning Java.");
[Link]("It is awesome!");
}
}
Double Quotes
When you are working with text, it must be wrapped inside
double quotations marks "".If you forget the double quotes,
an error occurs:
Exercise
Identify an error in the following code:
public class Main {
public static void main(String[] args) {
[Link](This sentence will produce an error);
}
}

12
The Print() Method
There is also a print() method, which is similar to println().
The only difference is that it does not insert a new line at
the end of the output:

Java Output Numbers


Print Numbers
You can also use the println() method to print numbers.
However, unlike text, we don't put numbers inside double
quotes:

You can also use the println() method to print numbers.

However, unlike text, we don't put numbers inside double


quotes:
[Link](3);
[Link](358);
[Link](50000);

Example

13
public class Main {
public static void main(String[] args) {
[Link](3);
[Link](358);
[Link](50000);
}
}

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:
This example uses a single-line comment at the end of a
line of code:
Example

14
[Link]("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 */
[Link]("Hello World");
public class Main {
public static void main(String[] args) {
/* The code below will print the words Hello World
to the screen, and it is amazing */
[Link]("Hello World");
}
}
Java Variables
Java Variables
Variables are containers for storing data values.
15
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:
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":
16
String name = "John";
[Link](name);
public class Main {
public static void main(String[] args) {
String name = "John";
[Link](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;
[Link](myNum);
public class Main {
public static void main(String[] args) {
int myNum = 15;
[Link](myNum);
}
}

17
You can also declare a variable without assigning the
value, and assign the value later:
Example
int myNum;
myNum = 15;
[Link](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:

public class Main {


public static void main(String[] args) {
int myNum = 15;
myNum = 20; // myNum is now 20
[Link](myNum);
}
}

18
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";
Example
public class Main {
public static void main(String[] args) {
String name = "John";
[Link](name);
}
}

Example
Create a variable called myNum of type int and assign it
the value 15:
int myNum = 15;
[Link](myNum);
19
You can also declare a variable without assigning the
value, and assign the value later:
Example
int myNum;
myNum = 15;
[Link](myNum);

Display Variables
The println() method is often used to display variables.
To combine both text and a variable, use the + character:
String name = "John";
[Link]("Hello " + name);
You can also use the + character to add a variable to
another variable:
Example
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
[Link](fullName);

20
For numeric values, the + character works as a
mathematical operator (notice that we use int (integer)
variables here):
Example
int x = 5;
int y = 6;
[Link](x + y); // Print the value of x + y
From the example above, you can expect:
• x stores the value 5
• y stores the value 6
• Then we use the println() method to display the value
of x + y, which is 11

Java Declare Multiple Variables


Declare Many Variables
Example
Instead of writing:
int x = 5;
int y = 6;
int z = 50;
[Link](x + y + z);

21
Example
public class Main {
public static void main(String[] args) {
int x = 5, y = 6, z = 50;
[Link](x + y + z);
}
}

Java 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
public class Main {
public static void main(String[] args) {
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is

22
int m = 60;
[Link](minutesPerHour);
[Link](m);
}
}

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)

23
• 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


As explained in the previous chapter, a variable in Java
must be a specified data type:
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

EXAMPLE
public class Main {
public static void main(String[] args) {
int myNum = 5; // integer (whole number)
float myFloatNum = 5.99f; // floating point number
char myLetter = 'D'; // character
boolean myBool = true; // boolean

24
String myText = "Hello"; // String
[Link](myNum);
[Link](myFloatNum);
[Link](myLetter);
[Link](myBool);
[Link](myText);
}
}

Data types are divided into two groups:

• Primitive data types -


includes byte, short, int, long, float, double, boolean a
nd char

25
• 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 Size Description


Type
byte 1 byte Stores whole numbers from -128 to 127
short 2 Stores whole numbers from -32,768 to 32,767
bytes
int 4 Stores whole numbers from -2,147,483,648 to
bytes 2,147,483,647
long 8 Stores whole numbers from -
bytes 9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 Stores fractional numbers. Sufficient for
bytes storing 6 to 7 decimal digits
double 8 Stores fractional numbers. Sufficient for
bytes storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 Stores a single character/letter or ASCII
bytes values

26
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;
[Link](isJavaFun); // Outputs true
[Link](isFishTasty); // Outputs false

Boolean values are mostly used for conditional testing.

27
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':

char myGrade = 'B';


[Link](myGrade);

public class Main {


public static void main(String[] args) {
char myGrade = 'B';
[Link](myGrade);
}
}

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";
28
[Link](greeting);

EXAMPLE
public class Main {
public static void main(String[] args) {
String greeting = "Hello World";
[Link](greeting);
}
}

Java Non-Primitive Data Types


Non-Primitive Data Types
Non-primitive data types are called reference
types because they refer to objects.
The main difference between primitive and non-
primitive data types are:
• Primitive types are predefined (already defined) in
Java. Non-primitive types are created by the
programmer and is not defined by Java (except
for String).
• Non-primitive types can be used to call methods to
perform certain operations, while primitive types
cannot.
29
• A primitive type has always a value, while non-
primitive types can be null.
• A primitive type starts with a lowercase letter, while
non-primitive types starts with an uppercase letter.
Examples of non-primitive types
are Strings, Arrays, Classes, Interface, etc. You will learn
more about these in a later chapter.

Java Operators
Operators are used to perform operations on variables and
values.
In the example below, we use the + operator to add
together two values:
Example
int x = 100 + 50;
public class Main {
public static void main(String[] args) {
int x = 100 + 50;
[Link](x);
}
}
Although the + operator is often used to add together two
values, like in the example above, it can also be used to
30
add together a variable and a value, or a variable and
another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
public class Main {
public static void main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
[Link](sum1);
[Link](sum2);
[Link](sum3);
}
}

31
Java divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common
mathematical operations.

Operator Name Description Example Try


it
+ Addition Adds together two x+y Try
values it »

32
- Subtraction Subtracts one value x-y Try
from another it »
* Multiplication Multiplies two values x*y Try
it »
/ Division Divides one value by x/y Try
another it »
% Modulus Returns the division x%y Try
remainder it »
++ Increment Increases the value of ++x Try
a variable by 1 it »
-- Decrement Decreases the value --x
of a variable by 1

Java Assignment Operators


Assignment operators are used to assign values to
variables.
In the example below, we use the assignment operator (=)
to assign the value 10 to a variable called x:
Example
int x = 10;
public class Main {
public static void main(String[] args) {
int x = 10;
[Link](x);
}
}

33
A list of all assignment operators:

Operator Example Same As Try it


= x=5 x=5 Try it »
+= x += 3 x=x+3 Try it »
-= x -= 3 x=x-3 Try it »
*= x *= 3 x=x*3 Try it »
/= x /= 3 x=x/3 Try it »
%= x %= 3 x=x%3 Try it »
&= x &= 3 x=x&3 Try it »
|= x |= 3 x=x|3 Try it »
^= x ^= 3 x=x^3 Try it »
>>= x >>= 3 x = x >> 3 Try it »
<<= x <<= 3 x = x << 3 Try it »

Java Comparison Operators


Comparison operators are used to compare two values (or
variables). This is important in programming, because it
helps us to find answers and make decisions.
The return value of a comparison is either true or false.
These values are known as Boolean values, and you will
learn more about them in
the Booleans and If..Else chapter.
In the following example, we use the greater than operator
(>) to find out if 5 is greater than 3:
Example

34
int x = 5;
int y = 3;
[Link](x > y); // returns true, because 5 is
higher than 3
EXAMPLE
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
[Link](x > y); // returns true, because 5 is
higher than 3
}
}

Operator Name Example Try it


== Equal to x == y Try it »
!= Not equal x != y Try it »
> Greater than x>y Try it »
< Less than x<y Try it »
>= Greater than or x >= y Try it »
equal to
<= Less than or equal x <= y Try it »
to

35
Java Logical Operators
You can also test for true or false values with logical
operators.
Logical operators are used to determine the logic between
variables or values:

Operator Name Description Example Try


it
&& Logical Returns true if both x < 5 && x Try
and statements are true < 10 it »
|| Logical Returns true if one of x < 5 || x < Try
or the statements is true 4 it »
! Logical Reverse the result, !(x < 5 && Try
not returns false if the x < 10) it »
result is true

Java Booleans
Java Booleans
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

36
For this, Java has a boolean data type, which can
store true or false values.

Boolean Values
A boolean type is declared with the boolean keyword and
can only take the values true or false:
Example
boolean isJavaFun = true;
boolean isFishTasty = false;
[Link](isJavaFun); // Outputs true
[Link](isFishTasty); // Outputs false

EXAMPLE
public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
[Link](isJavaFun);
[Link](isFishTasty);
}
}

37
However, it is more common to return boolean values from
boolean expressions, for conditional testing (see below).

Boolean Expression
A Boolean expression returns a boolean value: true or false.
This is useful to build logic, and find answers.
For example, you can use a comparison operator, such as
the greater than (>) operator, to find out if an expression
(or a variable) is true or false:
Example
int x = 10;
int y = 9;
[Link](x > y); // returns true, because 10 is
higher than 9

EXAMPLE
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 9;

38
[Link](x > y); // returns true, because 10 is
higher than 9
}
}
public class Main {
public static void main(String[] args) {
int x = 10;
[Link](x == 10); // returns true, because
the value of x is equal to 10
}
}
EXAMPLE
public class Main {
public static void main(String[] args) {
[Link](15 == 10); // returns false, because
10 is not equal to 15
}
}

Let's think of a "real life example" where we need to find out


if a person is old enough to vote.

39
In the example below, we use the >= comparison operator
to find out if the age (25) is greater than OR equal to the
voting age limit, which is set to 18:
Example
int myAge = 25;
int votingAge = 18;
[Link](myAge >= votingAge);

EXAMPLE
public class Main {
public static void main(String[] args) {
int myAge = 25;
int votingAge = 18;
[Link](myAge >= votingAge); // returns true
(25 year olds are allowed to vote!)
}
}
Cool, right? An even better approach (since we are on a roll
now), would be to wrap the code above in
an if...else statement, so we can perform different actions
depending on the result:
Example

40
Output "Old enough to vote!" if myAge is greater than or
equal to 18. Otherwise output "Not old enough to vote.":
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
[Link]("Old enough to vote!");
} else {
[Link]("Not old enough to vote.");
}
EXAMPLE
public class Main {
public static void main(String[] args) {
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
[Link]("Old enough to vote!");
} else {
[Link]("Not old enough to vote.");
}
}
}
41
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

42
The if Statement
Use the if statement to specify a block of Java code to be
executed if a condition is true.
Syntax
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) {
[Link]("20 is greater than 18");
}
public class Main {
public static void main(String[] args) {
if (20 > 18) {
[Link]("20 is greater than 18"); //
obviously
}
}
43
}
Example
int x = 20;
int y = 18;
if (x > y) {
[Link]("x is greater than y");
}

EXAMPLE
public class Main {
public static void main(String[] args) {
int x = 20;
int y = 18;
if (x > y) {
[Link]("x is greater than y");
}
}
}

44
Example explained
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".

The else Statement


Use the else statement to specify a block of code to be
executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
[Link]("Good day.");
} else {
[Link]("Good evening.");
}
45
// Outputs "Good evening."

EXAMPLE
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
[Link]("Good day.");
} else {
[Link]("Good evening.");
}
}
}

Example explained
In the example above, time (20) is greater than 18, so the
condition is false. Because of this, we move on to
the else condition and print to the screen "Good evening". If
the time was less than 18, the program would print "Good
day".
The else if Statement

46
Use the else if statement to specify a new condition if the
first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false
and condition2 is true
} else {
// block of code to be executed if the condition1 is false
and condition2 is false
}
Example
int time = 22;
if (time < 10) {
[Link]("Good morning.");
} else if (time < 18) {
[Link]("Good day.");
} else {
[Link]("Good evening.");
}

47
// Outputs "Good evening."
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
[Link]("Good morning.");
} else if (time < 18) {
[Link]("Good day.");
} else {
[Link]("Good evening.");
}
}
}
Example explained
In the example above, time (22) is greater than 10, so
the first condition is false. The next condition, in the else
if statement, is also false, so we move on to
the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".
However, if the time was 14, our program would print
"Good day."

48
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:
Syntax
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.

49
• 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:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");

50
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
}
// Outputs "Thursday" (day 4)
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:

51
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
}
}
}

52
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.

The default Keyword


The default keyword specifies some code to run if there is
no case match:
Example
int day = 4;
switch (day) {
case 6:
[Link]("Today is Saturday");
break;
case 7:
[Link]("Today is Sunday");

53
break;
default:
[Link]("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 6:
[Link]("Today is Saturday");
break;
case 7:
[Link]("Today is Sunday");
break;
default:
[Link]("Looking forward to the Weekend");
}
}
}

54
Note that if the default statement is used as the last
statement in a switch block, it does not need a break.

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:
Syntax
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) {

55
[Link](i);
i++;
}
Note: Do not forget to increase the variable used in the
condition, otherwise the loop will never end!
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
[Link](i);
i++;
}
}
}
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
56
}
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 {
[Link](i);
i++;
}
while (i < 5);
EXAMPLE
public class Main {
public static void main(String[] args) {
int i = 0;
do {
[Link](i);
i++;
}
while (i < 5);
57
}
}
Do not forget to increase the variable used in the condition,
otherwise the loop will never end!
EXAMPLE
public class Main {
public static void main(String[] args) {
int i = 0;
do {
[Link](i);
i++;
}
while (i < 5);
}
}

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:
Syntax

58
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++) {
[Link](i);
}
EXAMPLE
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
[Link](i);
}

59
}
}
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:
for (int i = 0; i <= 10; i = i + 2) {
[Link](i);
}
EXAMPLE
public class Main {
public static void main(String[] args) {
for (int i = 0; i <= 10; i = i + 2) {
[Link](i);
}
}

60
}

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++) {
[Link]("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
[Link](" Inner: " + j); // Executes 6 times (2 *
3)
}

61
}

EXAMPLE
public class Main {
public static void main(String[] args) {
// Outer loop.
for (int i = 1; i <= 2; i++) {
[Link]("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
[Link](" Inner: " + j); // Executes 6 times
(2 * 3)
}
}
}
}

62
Java Break and Continue
Java Break
You have already seen the break statement used in an
earlier chapter of this tutorial. It was used to "jump out" of
a switch statement.
The break statement can also be used to jump out of
a loop.
This example stops the loop when i is equal to 4:

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
63
[Link](i);
}

EXAMPLE
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
[Link](i);
}
}
}
Java Continue
The continue statement breaks one iteration (in the loop), if
a specified condition occurs, and continues with the next
iteration in the loop.
This example skips the value of 4:
Example
for (int i = 0; i < 10; i++) {

64
if (i == 4) {
continue;
}
[Link](i);
}
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
[Link](i);
}
}
}

65
Java Arrays

66

You might also like