Loops: Syntax
Loops: Syntax
Loops are handy because they save time, reduce errors, and they make code
more readable.
Syntax
while (condition) {
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++;
Try it Yourself »
Note: Do not forget to increase the variable used in the condition, otherwise
the loop will never end!
Syntax
do {
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++;
Java Strings
Strings are used for storing text.
Example
Create a variable of type String and assign it a value:
Try it Yourself »
String Length
A String in Java is actually an object, which contain methods that can
perform certain operations on strings. For example, the length of a string can
be found with the length() method:
Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Try it Yourself »
More String Methods
There are many string methods available, for
example toUpperCase() and toLowerCase():
Example
String txt = "Hello World";
Try it Yourself »
Example
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
Try it Yourself »
String Concatenation
The + operator can be used between strings to combine them. This is
called concatenation:
Example
String firstName = "John";
Try it Yourself »
Note that we have added an empty text (" ") to create a space between
firstName and lastName on print.
Example
String firstName = "John ";
System.out.println(firstName.concat(lastName));
Try it Yourself »
Special Characters
Because strings must be written within quotes, Java will misunderstand this
string, and generate an error:
String txt = "We are the so-called "Vikings" from the north.";
The backslash (\) escape character turns special characters into string
characters:
\' '
\" "
\\ \
Example
String txt = "We are the so-called \"Vikings\" from the north.";
Try it Yourself »
Example
String txt = "It\'s alright.";
Try it Yourself »
Example
String txt = "The character \\ is called backslash.";
Try it Yourself »
Code Result
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
Example
int x = 10;
int y = 20;
Try it Yourself »
Example
String x = "10";
String y = "20";
Try it Yourself »
If you add a number and a string, the result will be a string concatenation:
Example
String x = "10";
int y = 20;
Try it Yourself »