Introduction

Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. Unlike conventional languages which are generally designed either to be compiled to native (machine) code, or to be interpreted from source code at runtime, Java is intended to be compiled to a bytecode, which is then run (generally using JIT compilation) by a Java Virtual Machine.

Installing JDK and a Java IDE

In order to develop Java applications or Java APIs you need the Java Software Developer Kit (Java SDK) installed. You can find the differents Java SDKs here:

Java Software Developer Kit (Java SDK)

If you plan to be working more seriously with Java, I would recommend that you install a Java IDE (Integrated Development Environment). An IDE contains both a code editor with syntax highlighting, code completion, code generation, often with version control system integration and more. An IDE also makes it easy to compile and run your Java code, all from within the IDE.

Here are the three most popular Java IDEs:

Syntax

Every line of code that runs in Java must be inside a class. In our example, we named the class MyClass. A class should always start with an uppercase first letter.

Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.

The name of the java file must match the class name. When saving the file, save it using the class name and add ".java" to the end of the filename.

MyClass.java

                    
                public class MyClass {
                    public static void main(String[] args) {
                        System.out.println("Hello World");
                    }
                }
            
        

The output should be:

                    
                Hello World
            
        

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, just remember that 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");
                }
            
        

Note: Remember the curly braces {} marks the beginning and the end of a block of code and each code statement must end with a semicolon.

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 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 before a line of code:

                    
                // This is a comment

                System.out.println("Hello World");
            
        

This example uses a single-line comment at the end of a line of code:

                    
                System.out.println("Hello World");

                // This is a comment
            
        

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

Variables

A Java variable is a piece of memory that can contain a data value. A variable thus has a data type.

Variables are typically used to store information which your Java program needs to do its job. This can be any kind of information ranging from texts, codes (e.g. country codes, currency codes etc.) to numbers, temporary results of multi step calculations etc.

In the code example below, the main() method contains the declaration of a single integer variable named number. The value of the integer variable is first set to 10, and then 20 is added to the variable afterwards.

                    
                public class MyClass {
                    public static void main(String[] args) {            
                        int number = 10;         
                        number = number + 20;
                    }               
                }
            
        

Variable Declaration

Exactly how a variable is declared depends on what type of variable it is (non-static, static, local, parameter). In Java you declare a variable like this:

                    
                type name;
            
        

Instead of the word type, you write the data type of the variable. Similarly, instead of the word name you write the name you want the variable to have.

Here are examples of how to declare variables of all the primitive data types in Java:

                    
                byte    myByte;
                short   myShort;
                char    myChar;
                int     myInt;
                long    myLong;
                float   myFloat;
                double  myDouble;
            
        

Here are examples of how to declare variables of the object types in Java:

                    
                Byte       myByte;
                Short      myShort;
                Character  myChar;
                Integer    myInt;
                Long       myLong;
                Float      myFloat;
                Double     myDouble;
                String     myString;
            
        

The equal sign is used to assign values to the variable. To create a variable that should store text, look at the following example:

                    
                String myName = "Mario";

                System.out.println(myName);
            
        

Operators

Java contains a set of built-in math operators for performing simple math operations on Java variables. The Java math operators are reasonably simple. Therefore Java also contains the Java Math class which contains methods for performing more advanced math calculations in Java.

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Name Operator Description Example
Addition + Adds together two values x + y
Subtraction - Subtracts one value from another x - y
Multiplication * Multiplies two values x * y
Division / Divides one value from another x / y
Modulus % Returns the division remainder x % y
Increment ++ Increases the value of a variable by 1 ++x
Decrement -- Decreases the value of a variable by 1 --x

The Java Math Class

The Java Math class provides more advanced mathematical calculations than what the basic Java math operators provide. The Math class contains methods for finding the maximum or minimum of two values, rounding values, logarithmic functions, square root, and trigonometric functions (sin, cos, tan etc.).

Math.abs()

The Math.abs() function returns the absolute value of the parameter passed to it. The absolute value is the positive value of the parameter. If the parameter value is negative, the negative sign is removed and the positive value corresponding to the negative value without sign is returned. Here are two Math.abs() method examples:

                    
                int abs1 = Math.abs(10);  // abs1 = 10

                int abs2 = Math.abs(-20); // abs2 = 20
            

Math.ceil()

The Math.floor() function rounds a floating point value down to the nearest integer value. The rounded value is returned as a double. Here is a Math.floor() Java example:

                    
                double floor = Math.floor(7.343);

                // floor = 7.0
            
        

Math.min()

The Math.min() method returns the smallest of two values passed to it as parameter. Here is a Math.min() Java example:

                    
                int min = Math.min(10, 20); 
                
                // min = 10
            
        

Math.max()

The Math.max() method returns the largest of two values passed to it as parameter. Here is a Math.max() Java example:

                    
                int max = Math.max(10, 20);

                //max = 20;
            
        

Math.round()

The Math.round() method rounds a float or double to the nearest integer using normal math round rules (either up or down). Here is a Java Math.round() example:

                    
                double roundedDown = Math.round(23.445); 
                
                // roundedDown = 23.0

                double roundedUp   = Math.round(23.545); 
                
                // roundedUp = 24.0
            
        

Math.random()

The Math.random() method returns a random floating point number between 0 and 1. Of course the number is not fully random, but the result of some calculation which is supposed to make it as unpredictable as possible.

To get a random value between 0 and e.g. 100, multiply the value returned by Math.random() with the maximum number. If you need an integer value, use the round(), floor() or ceil() method.

Here is a Java Math.random() example:

                    
                double random = Math.random() * 100;
            
        

Math.exp()

The Math.exp() function returns e (Euler's number) raised to the power of the value provided as parameter. Here is a Java Math.exp() example:

                    
                double exp1 = Math.exp(1);

                System.out.println("exp1 = " + exp1);
                
                //  exp1 = 2.718281828459045

                double exp2 = Math.exp(2);

                System.out.println("exp2 = " + exp2);
                
                // exp2 = 7.38905609893065
            
        

Math.log()

The Math.log() method provides the logarithm of the given parameter. The base for the logarithm is i (Euler's number). Thus, Math.log() provides the reverse function of Math.exp(). Here is a Java Math.log() example:

                    
                double log1  = Math.log(1);

                System.out.println("log1 = " + log1); 
                
                // log1 = 0.0

                double log10 = Math.log(10);

                System.out.println("log10 = " + log10); 
                
                // log10 = 2.302585092994046
            
        

Math.pow()

The Math.pow() function takes two parameters. The method returns the value of the first parameter raised to the power of the second parameter. Here is a Math.pow() Java example:

                    
                double pow2 = Math.pow(2,2);

                System.out.println("pow2 = " + pow2);
                
                // pow2 = 4.0

                double pow8 = Math.pow(2,8);

                System.out.println("pow8 = " + pow8); 
                
                // pow8 = 256.0
            
        

Math.sqrt()

The Math.sqrt() method calculates the square root of the parameter given to it. Here are a few Java Math.sqrt() example:

                    
                double sqrt4 = Math.sqrt(4);
                
                System.out.println("sqrt4 = " + sqrt4); 
                
                // sqrt4 = 2.0

                double sqrt9 = Math.sqrt(9);

                System.out.println("sqrt9 = " + sqrt9); 
                
                // sqrt9 = 3.0
            
        

Arrays

Arrays in Java are also objects. They need to be declared and then created. In order to declare a variable that will hold an array of integers, we use the following syntax:

                    
                int[] arr;
            
        

Notice there is no size, since we didn't create the array yet.

                    
                arr = new int[10];
            
        

This will create a new array with the size of 10. We can check the size by printing the array's length:

                    
                System.out.println(arr.length);
            
        

We can access the array and set values:

                    
                arr[0] = 4;

                arr[1] = arr[0] + 5;
            
        

Java arrays are 0 based, which means the first element in an array is accessed at index 0 (e.g: arr[0], which accesses the first element). Also, as an example, an array of size 5 will only go up to index 4 due to it being 0 based.

                    
                int[] arr = new int[5];
                
                //accesses and sets the first elements

                arr[0] = 4;
            
        

We can also create an array with values in the same line:

                    
                int[] arr = {1, 2, 3, 4, 5};
            
        

Don't try to print the array without a loop, it will print something nasty like [I@f7e6a96. To print out an array, use the following code:

                    
                for (int i=0; i < arr.length; i++) {
                    System.out.println(arr[i]);
                }
            
        

Multidimensional Java Arrays

The examples shown above all created arrays with a single dimension, meaning elements with indexes going from 0 and up. It is, however, possible to create arrays where each element has two or more indexes which identify (locate) it in the array.

You create a multidimensional array in Java by appending one set of square brackets ([]) per dimension you want to add. Here is an example that creates a two-dimensional array:

                    
                int[][] intArray = new int[10][20];
            
        

This example creates a two-dimensional array of int elements. The array contains 10 elements in the first dimension, and 20 elements in the second dimension. In other words, this examples creates an array of arrays of int elements. The array of arrays has space for 10 int arrays, and each int array has space for 20 int elements.

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.

While Loop

The while loop loops through a block of code as long as a specified condition is true. 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++;
                }
            
        

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

                    
                int i = 0;

                do {
                    System.out.println(i);
                    i++;
                }
                while (i < 5);
            
        

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. Is executed (one time) before the execution of the code block. Defines the condition for executing the code block. Is executed (every time) after the code block has been executed. The example below will print the numbers 0 to 4:

                    
                for (int i = 0; i < 5; i++) {
                    System.out.println(i);
                }
            
        

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

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:

                    
                public class MyClass {
                    static void myMethod() {
                        // code to be executed
                    }
                }
            
        

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.
  • void means that this method does not have a return value.

Call a Method

To call a method in Java, write the method's name followed by two parentheses () and a semicolon ";". A method can also be called multiple times. In the following example, myMethod() is used to print a text (the action), when it is called:

                    
                public class MyClass {
                        static void myMethod() {
                            System.out.println
                            ("I just got executed!");
                        }

                    public static void main(String[] args) {
                        myMethod();
                        myMethod();
                        myMethod();
                    }
                  }
                  
                // I just got executed!
                // I just got executed!
                // I just got executed!
            
        

Reference

All the documentation in this page is taken from: