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
. - If there is a match, the associated block of code is executed.
- The
break
anddefault
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)
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) {
System.out.println(i);
i++;
}
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!
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);
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
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);
}
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);
}
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;
}
System.out.println(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++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
Break and Continue in While Loop
You can also use break
and continue
in while loops:
Break Example
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
if (i == 4) {
break;
}
}
Continue Example
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
System.out.println(i);
i++;
}
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type with square brackets:
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Access the Elements of an Array
You can access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
cars[0] = "Opel";
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use the length
property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
44 Responses
purchase levaquin pills levofloxacin buy online
order avodart sale tamsulosin 0.2mg uk zofran 8mg us
aldactone 25mg tablet finasteride 1mg generic fluconazole 200mg cost
cheap ampicillin brand cephalexin 500mg erythromycin 250mg ca
sildenafil buy online nolvadex 10mg oral buy robaxin without prescription
generic sildenafil 50mg estrace online buy order estrace 2mg
lamictal 50mg uk tretinoin tablet retin cream usa
tadalis 10mg canada avana cost voltaren without prescription
buy isotretinoin pills amoxicillin over the counter buy zithromax pill
indomethacin pills order lamisil 250mg pill order trimox generic
order cialis 20mg generic taking two cialis pills sildenafil 50mg drug
order anastrozole 1mg generic buy arimidex generic order sildenafil generic
cialis 40mg en ligne acheter 20mg cialis vrai viagra 50mg prix
buy generic prednisone 5mg viagra professional cheap viagra tablets
cialis 10mg bestellen cialis 20mg für frauen viagra 200mg kaufen für männer
order isotretinoin for sale amoxicillin brand ivermectin 5ml
oral modafinil order acetazolamide 250 mg pills diamox 250mg price
doxycycline 200mg us purchase lasix generic lasix brand
altace 10mg without prescription buy generic avapro buy astelin 10ml online cheap
generic catapres clonidine over the counter spiriva 9 mcg us
cost buspirone 5mg oral oxybutynin 2.5mg oxybutynin 2.5mg without prescription
terazosin 1mg over the counter order terazosin sale cheap sulfasalazine 500 mg
alendronate online order fosamax 70mg sale pepcid 40mg us
purchase benicar generic verapamil without prescription buy generic acetazolamide 250 mg
purchase prograf without prescription ropinirole price urso without prescription
imdur 20mg pill buy azathioprine generic micardis 80mg price
buy zyban 150mg pill buy generic atomoxetine purchase seroquel pill
brand molnunat naprosyn ca order lansoprazole 15mg online cheap
imuran 100mcg canada imuran pill viagra for sale
order tadalafil 5mg online cheap tadalafil for sale viagra pill
order cialis 10mg generic tadalafil online buy amantadine 100 mg price
cheap naltrexone purchase femara online order generic aripiprazole
buy dapsone 100mg without prescription perindopril cost oral aceon 4mg
buy medroxyprogesterone 10mg without prescription periactin 4 mg generic periactin 4 mg over the counter
provigil 100mg sale provigil 200mg without prescription ivermectin cream 1%
luvox 100mg without prescription order luvox 100mg for sale order glucotrol without prescription
oral accutane accutane 40mg cheap cheap deltasone
piracetam 800 mg tablet nootropil 800mg without prescription sildenafil 100mg price
zithromax 250mg canada generic prednisolone 20mg order gabapentin 100mg generic
order tadalafil 20mg pills tadalafil 20mg usa viagra for men over 50
purchase lasix hydroxychloroquine drug plaquenil 200mg ca
cialis 40mg tablet cost betnovate 20gm clomipramine for sale online
chloroquine order online olumiant 2mg without prescription olumiant 4mg drug
completely free dating free single chat date online site free web date site