Java Programming Language: Introduction To
Java Programming Language: Introduction To
Java Programming Language: Introduction To
Java Programming
Language
Prepared by: Sarwan
Outline (I)
• Introducing Java
• Installing Java
• Create Your First Application
• Java Syntax
• Java Comments
• Java Variables
• Java Data Types
• Java Type Casting
• Java Operators
Outline (II)
• Java Strings
• Java Math
• Java Booleans
• Java If…Else
• Java Switch
• Java While Loop
• Java For Loop
• Java Break & Continue
• Java Arrays
• Java Exceptions
• Java Methods
Introducing Java (I)
What is Java?
• Java is one of the most popular programming languages in the world
• Owned by Oracle, created in 1995 by Sun Microsystems
• More than 3 billion devices run Java
• A general-purpose programming language that is class-based and object-oriented
• Java is cross-platform and is called write once, run anywhere
Introducing Java (II)
Your computer might have Java Installed already, to check if you have Java installed on
windows, type the following in Command Prompt (cmd.exe):
C:\Users\Your Name>java -version
If Java is installed, you will see something like this (based 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)
Installing Java (II)
If you don’t have java installed on your computer, you must download and install Java
Development Kit (JDK) from Oracle website:
https://www.oracle.com/technetwork/java/javase/downloads/index.html
Installing Java (III)
After you have JDK installed on your computer, perform the next step-by-step
Java development environment setup in order to be able to create Java
applications.
Installing java (IV)
Step 5: at last, open Command Prompt (cmd.exe) and type “java –version”
to see if Java is running on your machine.
C:\Users\Your Name>java -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)
Create Your First Application (I)
Let’s create our first java application using windows Command Prompt (CMD), copy and
paste below code into Notepad and save the file as MyClass.java.
public class MyClass {
public static void main(String[] args) {
System.out.println("Hello World");
}
Don’t worry if you don’t understand the above code, for now just focus on how to run the code.
Note: the name of the saved file (MyClass.java) and the class name (MyClass) must be the same!
Create Your First Application (II)
Open CMD and navigate to the directory where you saved your file, and type
"javac MyClass.java“ to compile the code:
C:\Users\Your Name>javac MyClass.java
Congratulations, you have written and executed your first Java program.
Java Syntax (I)
The main Method is inside every Java program where any code inside it will be executed.
Java Syntax (III)
System.out.println() Method
Inside the main method, we can use println() method to print a line of text to the screen:
public static void main(String[] args) {
System.out.println("Hello World");
}
• 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 start with two forward slashes //
• Any text followed by slashes to the end of the line will be ignored (will not be executed)
// This is a comment
System.out.println("Hello World");
Java Comments (II)
This example uses a multi-line comment (a comment block) to explain the code:
Example
To create a variable that should store text, look at the following example:
String name = "John";
System.out.println(name);
To create a variable that should store a number, look at the following example:
int myNum = 15;
System.out.println(myNum);
Java Variables (IV)
Example
You can also declare a variable without assigning the value, and assign the value later:
int myNum;
myNum = 15;
System.out.println(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";
System.out.println("Hello " + name);
Display Variables
For numeric values, the + character works as a mathematical operator (notice that we use int
(integer) variables here):
int x = 5;
int y = 6;
System.out.println(x + y); // Print the value of x + y
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).
The general rules for constructing names for variables (unique identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs
• Names should begin with a letter
• 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)
• Names should start with a lowercase letter and it cannot contain whitespace
• Reserved words (like Java keywords, such as int or String) cannot be used as names
Java Data Types (I)
As explained in the previous chapter, a variable in Java must be a specified data type:
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
Note: 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).
Java Data Types (V)
You should use a floating-point type whenever you need a number with a decimal, such as 9.99 or
3.14515.
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
• 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
• The size of a primitive type depends on the data type, while non-primitive types have all the same size.
Java Data Types (VII)
Note: 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 is 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 (I)
Type casting is when you assign a value of one primitive data type to another type.
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
public class MyClass {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
public class MyClass {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
In the example below, the numbers 100 and 50 are operands, and the + sign is an operator:
int x = 100 + 50;
Java Operators (II)
Although the + operator is often used to add together two values, like in the example above, it can
also be used to add together a variable and a value, or a variable and another variable:
Arithmetic Operators
Arithmetic operators
are used to perform
common mathematical
operations.
Java Operators (V)
Assignment Operators
Assignment operators
are used to assign
values to variables.
Java Operators (VI)
Comparison Operators
Comparison operators
are used to compare
two values.
Java Operators (VII)
Logical Operators
Logical operators are
used to determine the
logic between variables
or values.
Java Strings (I)
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:
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
Java Strings (III)
String Concatenation
The + operator can be used between strings to add them together to make a new string. This is
called concatenation:
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
You can also use the concat() method to concatenate those two strings.
Note: Note that we have added an empty text (" ") to create a space between firstName and
lastName on print.
Java Strings (VI)
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 solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
Java Strings (VII)
Special Characters
The sequence \" inserts a double quote in a string:
String txt = "We are the so-called \"Vikings\" from the north.";
The sequence \’ inserts a single quote in a string::
String txt = "It\'s alright.";
The sequence \\ inserts a backslash in a string:
String txt = "The character \\ is called backslash.";
Java Strings (VIII)
Special Characters
Six other escape sequences are valid in Java:
Java Strings (IX)
Math Class
The Java Math class has many methods that allows you to perform mathematical operations
on numbers.
• Math.max(x,y): this method can be used to find the highest value of x and y
• Math.min(x,y): method can be used to find the lowest value of x and y
• Math.sqrt(x): method returns the square root of x
• Math.abs(x): method returns the absolute (positive) value of x
• Math.random(): returns a random number between 0 (inclusive), and 1 (exclusive)
Java Booleans (I)
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
For this, Java has a boolean data type, which can take the values true or false.
Java Booleans (II)
Boolean Values
A boolean type is declared with the boolean keyword and can only take the values true or false:
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Java Booleans (III)
Boolean Expression
A Boolean expression is a Java expression that returns a Boolean value: true or false.
You can use a comparison operator, such as the greater than (>) operator to find out if an
expression (or a variable) is true:
int x = 10;
int y = 9;
System.out.println(x > y); // returns true, because 10 is higher than 9
Java Booleans (IV)
Boolean Expression
In the examples below, we use the equal to (==) operator to evaluate an expression:
int x = 10;
System.out.println(x == 10); // returns true, because the value of x is
equal to 10
Note:
The Boolean value of an expression is the basis for all Java comparisons and conditions.
You will learn more about conditions in the next chapter.
Java If…Else (I)
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
Note: Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Java If…Else (IV)
The if Statement
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:
if (20 > 18) {
System.out.println("20 is greater than 18");
}
Note: Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Java If…Else (V)
Use the else statement to specify a block of code to be executed if the condition is false.
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
}
Java If…Else (VI)
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Java If…Else (VII)
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
}
Java If…Else (VIII)
The example below uses the weekday number to calculate the weekday name:
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 Switch (IV)
Note: 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 Switch (V)
Note: 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 (I)
Loops
Loops can execute a block of code as long as a specified condition is reached.
While Loop
The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
// code block to be executed
}
Java While Loop (II)
While Loop
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:
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!
Java While Loop (III)
do {
// code block to be executed
}
while (condition);
Java While Loop (IV)
Note: do not forget to increase the variable used in the condition, otherwise the loop will never end!
Java For Loop (I)
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.
Java For Loop (II)
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:
for (type variable : arrayname) {
// code block to be executed
}
Java For Loop (V)
For-Each Loop
The following example outputs all elements in the cars array, using a "for-each" loop:
Note: Don't worry if you don't understand the example above. You will learn more about Arrays later.
Java Break & Continue (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 jumps out of the loop when i is equal to 4:
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Java Break & Continue (II)
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.
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value.
Java Arrays
We have now declared a variable that holds an array of strings. To insert values to it, we can use
an array literal - place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Java Arrays (IV)
Array Length
To find out how many elements an array has, use the length property:
You can loop through the array elements with the for loop, and use the length property to specify
how many times the loop should run.
The following example outputs all elements in the cars array:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Java Arrays (VII)
There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:
Multidimensional Arrays
Multidimensional Arrays
To access the elements of the myNumbers array, specify two indexes: one for the array, and one
for the element inside that array. This example accesses the third element (2) in the second array
(1) of myNumbers:
Multidimensional Arrays
We can also use a for loop inside another for loop to get the elements of a two-dimensional array
(we still have to point to the two indexes):
public class MyClass {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}
Java Exceptions (I)
Java Exceptions
When executing Java code, different errors can occur: coding errors made by the programmer,
errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical term
for this is: Java will throw an exception (throw an error).
Java Exceptions (II)
Java Exceptions
In the below example, an error will be generated because myNumbers[10] does not exist.
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Java Exceptions (IV)
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
public class MyClass {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
The output will be:
System.out.println(myNumbers[10]);
} Something went wrong.
catch (Exception e) { The 'try catch' is finished.
System.out.println("Something went wrong.");
}
finally {
System.out.println("The 'try catch' is finished.");
}
}
}
Java Exceptions (VI)
Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Java Methods (II)
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also
create your own methods to perform certain actions:
Example Explained
• myMethod() is the name of the method
• static means that the method belongs to the MyClass class and not an object of the MyClass class.
You will learn more about objects and how to access methods through objects later in this tutorial.
• void means that this method does not have a return value. You will learn more about return values
later in this chapter
Java Methods (IV)
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Inside main, call the myMethod() method:
Call a Method
A method can also be called multiple times:
Method Parameters
Information can be passed to functions as parameter. Parameters act as variables inside the
method.
Parameters are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
Java Methods (VII)
Method Parameters
The example below has a method that takes a String called fname as parameter. When the method
is called, we pass along a first name, which is used inside the method to print the full name:
Return Values
The void keyword, used in the examples above, indicates that the method should not return a
value. If you want the method to return a value, you can use a primitive data type (such as int,
char, etc.) instead of void, and use the return keyword inside the method:
Return Values
This example returns the sum of a method's two parameters:
Return Values
You can also store the result in a variable (recommended):