Java Introduction

What is Java?

Java is a popular programming language, created in 1995.

It is owned by Oracle, and more than 3 billion devices run Java.

It is used for:

  • Mobile applications (specially Android apps)
  • Desktop applications/li>
  • Web applications
  • Web servers and application servers
  • Games
  • Database connection, etc.

Why Use Java?

  • Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
  • It is one of the most popular programming language in the world
  • It has a large demand in the current job market
  • It is easy to learn and simple to use
  • It is open-source and free
  • It is secure, fast and powerful
  • It has a huge community support (tens of millions of developers)
  • Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs
  • As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa
Java Instalation

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 (cmd.exe):

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)

How 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 (cmd.exe) and type java -versionversion to see if Java is running on your machine
Java Syntax

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.

Every Java program has a class name which must match the filename, and that every program must contain the main() method.

System.out.println()

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) {
System.out.println("Hello World");
}
Java OutPut

Print Text

You can add as many println() methods as you want. Note that it will add a new line for each method:

System.out.println("Hello World!"); System.out.println("I am learning Java.");

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:

System.out.println(This sentence will produce an error);

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:

System.out.print("Hello World! "); System.out.print("I will print on the same line.");

Print Numbers

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

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

System.out.println(333);

You can also perform mathematical calculations inside the println() method:

System.out.println(2 * 5);
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:

System.out.println("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:

/* The code below will print the words Hello World to the screen, and it is amazing */
System.out.println("Hello World");
Java Variables

Variables are containers for storing data values.

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.

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);

Declare Many Variables

To declare more than one variable of the same type, you can use a comma-separated list:

int x = 5, y = 6, z = 50;
System.out.println(x + y + z);

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

int minutesPerHour = 60;

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

Data types are divided into two groups:

  1. Primitive data types - includes byte, short, int, long, float, double, boolean and char
  2. Non-primitive data types - such as String, Arrays and Classes (you will learn more about these in a later chapter)
Java Type Casting

Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

  • Widening Casting (automatically) - converting a smaller type to a larger type size
    byteshortcharintlongfloatdouble
  • Narrowing Casting (manually) - converting a larger type to a smaller size type
    doublefloatlongintcharshortbyte
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:

int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)

Java divides the operators into the following groups:

  • Arithmetic operators : used to perform common mathematical operations.
  • Assignment operators : used to assign values to variables.
  • Comparison operators : used to compare two values (or variables).
  • Logical operators : used to determine the logic between variables or values.
  • Bitwise operators
Java Strings

Strings are used for storing text.

A String variable contains a collection of characters surrounded by double quotes:

String greeting = "Hello";

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());

There are many string methods available, for example toUpperCase() and toLowerCase():

String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"

Finding a Character in a String

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace):

String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7

String Concatenation

The + operator can be used between strings to combine them. This is called concatenation:

String firstName = "John"; String lastName = "Doe"; System.out.println(firstName + " " + lastName);

Adding Numbers and Strings

If you add two numbers, the result will be a number:

int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer/number)

If you add two strings, the result will be a string concatenation:

String x = 10;
String y = 20;
String z = x + y; // z will be 1020 (a String)

If you add a number and a string, the result will be a string concatenation:

int x = 10;
String y = 20;
String z = x + y; // z will be 1020 (a String)

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

String txt = "We are the so-called \"Vikings\" from the north.";
String txt = "It\'s alright.";
String txt = "The character \\ is called backslash.";
Java Math

The Java Math class has many methods that allows you to perform mathematical tasks on numbers.

Math.max(x,y)

The Math.max(x,y) method can be used to find the highest value of x and y:

Math.max(5, 10);

Math.min(x,y)

The Math.min(x,y) method can be used to find the lowest value of x and y:

Math.min(5, 10);

Math.sqrt(x)

The Math.sqrt(x) method returns the square root of x:

Math.sqrt(64);

Math.abs(x)

The Math.abs(x) method returns the absolute (positive) value of x:

Math.abs(-4.7);

Random Numbers

Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive)

To get more control over the random number, for example, if you only want a random number between 0 and 100, you can use the following formula:

int randomNum = (int)(Math.random() * 101); // 0 to 100
Java Booleans

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

Booleans Value

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

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:

System.out.println(10 > 9); // returns true, because 10 is higher than 9
System.out.println(10 == 15); // returns false, because 10 is not equal to 15
Java If ... Else

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:

    1. Use if to specify a block of code to be executed, if a specified condition is true
    2. Use else to specify a block of code to be executed, if the same condition is false
    3. Use else if to specify a new condition to test, if the first condition is false
    4. Use switch to specify many alternative blocks of code to be executed

Short Hand If...Else

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.

It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else statements:

variable = (condition) ? expressionTrue : expressionFalse;
Java Switch

Java Switch Statements

The switch statement selects one of many code blocks to be executed:

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

  1. The switch expression is evaluated once.
  2. The value of the expression is compared with the values of each case.
  3. If there is a match, the associated block of code is executed.
  4. The break and default keywords are optional, and will be described later in this chapter

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.

The default Keyword

The default keyword specifies some code to run if there is no case match

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:

while (condition) {
// code block to be executed
}

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.

do {
// code block to be executed
}
while (condition);
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

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.

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

// 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)
}
}

For-Each Loop

There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

for (type variableName : arrayName) {
// code block to be executed
}
Java Break / Continue

Java Break

The break are used to "jump out" of switch statement.

The break statement can also be used to jump out of a loop.

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.

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.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo

Change an Array Element

To change the value of a specific element, refer to the index number:

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:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4

Loop Through an Array

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.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}

Loop Through an Array with For-Each

There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:

for (type variable : arrayname) {
...
}

Multidimensional Arrays

A multidimensional array is an array of arrays.

Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows and columns.

Reference

All of the documentation in this page is taken from w3school.com