A Lecture Number 2 (Java
A Lecture Number 2 (Java
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).
Example
// This is a comment
System.out.println("Hello World");
Example
System.out.println("Hello World"); // This is a comment
Example
/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");
Java Variables
Java Variables
Variables are containers for storing data values.
Syntax
type variableName = value;
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);
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
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.
Example
Instead of writing:
int x = 5;
int y = 6;
int z = 50;
System.out.println(x + y + z);
Example
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
Java Identifiers
Identifiers
All Java variables must be identified with unique names.
Example
// Good
int minutesPerHour = 60;
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
myNum = 9;
myFloatNum = 8.99f;
myLetter = 'A';
myBool = false;
myText = "Hello World";
Java Numbers
Numbers
Primitive number types are divided into two groups:
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
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);
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
Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
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
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".
Widening Casting
Widening casting is done automatically when passing a smaller size type
to a larger size type:
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
The if Statement
Use the if statement to specify a block of Java code to be executed if a
condition is true.
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");
}
Example
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
Java Switch
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)
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.
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.
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++;
}
ADVERTISEMENT
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!
Statement 3 is executed (every time) after the code block has been
executed.
Example
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
1. Example explained
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)
}
}
(int i = 0; i < 5; ) {
System.out.println( );
}
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 .