November 24, 2020

Essentials of Java Programming Language

Index:

  1. Detecting if Java is installed on your computer
  2. Installing Java on your device
  3. Ways to run your Java code
  4. A little bit about Java
  5. How Java works
  6. The Main Method
  7. Data Types in Java
  8. Round and Around with Loops
  9. Decisions using Conditionals
  10. Optimizing decisions with Operators
  11. Escape Characters
  12. Reserved Keywords in Java
  13. A challenge to end the basics

Detecting if Java is installed on your computer

Before diving into coding let’s see if Java is installed on your device or not. We will be covering two operating systems only, Mac OSX & Windows. Here is how to detect whether Java is installed on your device or not.

Open Terminal on Mac OSX or Command Prompt/PowerShell on windows and enter the following command:

java -version

If you receive an error of unknown command/symbol then it’s time to install Java on your device.

Installing Java on your device

The installation process is a bit different for Mac OSX and Windows but the procedure to download Java is the same. Visit the following URL and download Java for your device. The website will detect your operating system automatically.

https://java.com/en/download

An easy video tutorial on how to install Java on Windows

Tutorial for installing Java on Mac OSX

Ways to run your Java code

There are two ways to run your Java Code

  1. Use an IDE (Integrated Development Environment) like IntelliJ IDEA Community/Ultimate, NetBeans, BlueJ, Eclipse, etc.
  2. Run manually with an editor like Visual Studio Code, Atom, Notepad++, Sublime Text, etc.

Whenever learning a programming language, it’s recommended to use code editors rather than an IDE to understand the basic way of running your program manually. Automated environments are useful and help a lot but as a programmer, it is efficient and good to start from the bottom. So, we will be using Visual Studio Code for running Java. Let us show you how to run your Java code using Visual Studio Code with the following steps:

  • Download and Install Visual Studio Code from https://code.visualstudio.com/download.
  • Open Visual Studio Code.
  • Create a new file by pressing Ctrl + N (Windows) or Command + N (Mac).
  • Create a folder with a name of HelloWorld anywhere on your computer. We prefer placing it on our Desktop.
  • Within the HelloWorld folder create a file called HelloWorld.java
  • Copy the following code into the HelloWorld.java file
class HelloWorld {

    public static void main(String[] args) {

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

    }

}
  • Open Command Prompt/Powershell or Terminal depending on your operating system.
  • Navigate to the HelloWorld directory within your Command Prompt/Powershell or Terminal.
  • Enter the following command:
javac HelloWorld.java
  • If you’re following the procedure, there won’t be an error. If you take a look in the directory, you will see a file called HelloWorld.class automatically created. The HelloWorld.class is the bytecode class understood by the Java Virtual Machine (JVM). Now let’s run the program with the following command:
java HelloWorld

After pressing enter you will see the following output printed to the console. It might occur to you why we need to write two commands to display results? Because the javac command compiles the java file into bytecode class which can be executed by the Java Virtual Machine (JVM) and then the java command which outputs the result of the bytecode.

Hello, World!

A little bit about Java

Java is an Object-Oriented Programming Language which was developed by James Gosling and his colleagues at Sun Microsystems in the early 1990s. One thing to clear about Java is that there is no connection between Java and JavaScript, they both have their own purpose and syntax, so don’t assume Java and JavaScript. Using Java Programming Language, it is possible to develop Desktop Graphical User Interface (GUI) Applications, Mobile Applications, Embedded Applications, Web Applications, Web & Application Servers, Enterprise Applications or Scientific Applications. Let us know in the comments below, what type of application development are you interested in.

How Java Works

To learn how Java works behind the scenes, the diagram above should be understood. It is a very simple procedure as little of it is explained above in the diagram too. A Java file with an extension of .java is sent to the Java compiler which converts the file into a bytecode class. The reason for this conversion is the Java Virtual Machine (JVM) which does not understand the high-level language (Java Syntax) directly so it should be converted into a language understood by the JVM. Then for execution, the Bytecode Class is sent to JVM which displays the output on the respective device.

The Main Method

The Main Method is like the base of operations. Where everything is discussed and finalized for execution. The Main Method in Java is used with a similar concept. There can be hundreds of classes but to run and execute the code within them, the Main Method is required. For the Main Method in Java, a class is required. In other words, the Main Method should be within a class. A class in Java is like a container. The compiler understands the main function when written within a class and makes it possible to run and execute the code within it. Let’s look at a simple example:

public class MainMethod {

    public static void main(String[] args) {

        System.out.println("The main method always lives within a class!");

    }

}
Output
The main method always lives within a class!

Let’s break down the syntax:

public – There are four types of access modifiers in Java which are public, private, default, and protected. These define the usage of a function/variable within a package/class.

class – Class is the reserved keyword which defines a java file into a class. A class is made up of functions & variables. A class always requires a name next to it and an optional access modifier before it. If no access modifier is provided then the default is the selected access modifier.

MainMethodMainMethod is the name of the class. The name of the class should match the name of the file or it will result in an error

static – static is a reserved keyword which makes the function/variable restricted to the class in which it is being used.

void – The void is a reserved keyword which acts as a return type of the function which means nothing to return from the function. More on functions will be covered later.

main – main is the reserved keyword which informs the compiler that this function will run the code written within the main function. Whatever inside the function will execute in order from top to bottom, line per line will be compiled. So, any code inside a function should be written within an order the way you want it to execute.

(String[] args) – The parentheses after the function name are called function parameters which can either be empty or populated with Data Types which can be passed later as arguments when the function is called. More on functions will be covered later.

{} – These curly braces include the code for execution. The code inside them is also known as a code block or code statement.

System.out.println("I live within a class.") – This is Java’s general way of outputting values to the console. We access the System class and then functions within it and pass a string value to it which needs to be displayed in the console.

; – The semicolon is the most important part. Semicolons are written at every end of a code statement where logic fulfils its purpose.

Data Types in Java

Primitive Data Types are the building blocks of a Programming Language. A Data Type is an attribute of data which tells the compiler how a developer wants to use the Data. Data Types in Java are categorized into two types, Primitive and Non-Primitive Data Types. Primitive Data Types are basics types which support integer numbers, floating-point numbers, characters, and booleans. Non-Primitive Data Types are basically those types which aren’t Primitive Data Types like, Classes, Arrays, and Interfaces. We aren’t covering Interfaces in the essentials as its a bit out of the scope of basics. Following are the Data Types categorized into the two types as discussed:

  • Primitive Data Types
    1. String
    2. Character (char)
    3. Boolean (boolean)
    4. Byte (byte)
    5. Short (short)
    6. Integer (int)
    7. Long (long)
    8. Float (float)
    9. Double (double)
  • Non-Primitive Data Types
    1. Classes
    2. Arrays

Primitive Data Types

String

In Java, String Data Type is declared as String. It is one of the most used Data Type in Java. The value of a string is covered in double quotes "". String values contain text, numbers (which don’t act as numbers), special characters like escape characters which have certain functions, placeholders and much more. Strings cannot be modified, if you try changing a string, an entirely new string will be created.

Some points to keep in mind before moving forward
Comments

Comments are very useful in the world of Programming, not only in Java. Comments are ignored by the compiler as they are good for readability only. They can be written anywhere in a Java file. They help in understanding what a line of code does. In Java, there are two types of Comments:

  • Single-Line Comments
  • Multiple Line Comments

Single-Line Comments
Single-Line Comments in Java are written using two forward slashes //. After the slashes, we describe what the line of code does. Here is a quick example:

class SingleLine {

    public static void main(String[] args) {
        
        // This is a single line comment

    }
    
}

Multi-Line Comments
Multi-Line Comments in Java start with a single slash and an asterisk /* and end the opposite way by writing the asterisk first and then slash */. Every new line in the Multi-Line Comment starts with an Asterisk. Here is a quick example:

class MultiLine {

    public static void main(String[] args) {
        
        /**
        * This is a Multi-Line Comment
        */

    }

    
}
A small look at Variables

3 things to know about variables before moving on is that they can have any name and should come after the Data Type as Java is a statically typed Programming Language. Variables can either have no initial value or a value can be assigned according to the Data Type. Let’s see how we can assign a String Data Type with a value.

class VariableWithValue {

    public static void main(String[] args) {
        
        // Declaring a String with a value
        String name = "This is an inline initialization statement.";

        // Printing the variable 'name' to the console
        System.out.println(name);

    }
    
}
Output
This is an inline initialization statement.

Now an example of how we can declare a String without a value.

class VariableWithoutValue {

    public static void main(String[] args) {

        // This is a declaration statement
        String name; // Variable 'name' has no value 

    }
    
}

On line 06 we have declared a variable called name with String Data Type without assigning a value, which is totally fine by Java but it is not recommended to leave variables unused or unassigned. If we try to print the variable name to the console, it will give an error stating that the variable name is not initialized. Let’s understand more deeply how to declare variables in Java with the rule of initialization.

The rule of initialization

The right way to declare a variable in Java is to write the Data Type first then the variable, an assignment operator, and then comes the value based on the Data Type being used. So, breaking down the above code where String is the Data Type, name is the variable and using the assignment operator which is an equal sign = to set the value as "This is Java". Last but not least semicolons are important at the end of every logical statement.

We can also declare String variables using the String class. It is not recommended but still possible. Here’s how:

class VariableClass {

    public static void main(String[] args) {
        
        String name = new String("We are learning Java.");
        System.out.println(name);

    }
    
}
Output
We are learning Java.

The only difference is we are creating an object of the String class and adding the value as an argument. The new keyword is used to create an object in Java.

String Concatenation

String concatenation is a process of connecting strings or characters. Let’s see how we can connect two String variables in a single line.

class StringsInJava {

    public static void main(String[] args) {
        
        String name = "Java";
        String sentence = "Programming Language";

        // A concatenated String
        System.out.println(name + " is  a " + sentence);

    }
    
}
Output
Java is a Programming Language

We have declared two String values (name & sentence). Within the print statement on line 09, we have gathered all the declared variables in such a sense which makes a sentence. Variables use the value within them to be displayed not the Data Type or the variable name as above in the program we can see how the variable name has a value of "Java" and sentence has a value of "Programming Language.". When we print these variables to the console, we get the value and to join them or concatenate them we use the plus sign (+). When printing anything to the console we can use either variable(s) or we can directly write a String/Character. After the name variable, we have written a String directly which is " is a " for the sentence to make sense. When printing to the console or using a String variable, whitespaces count so remember to put a number of required whitespaces within the double-quotes.

– String Methods

trim()

In Java, there are predefined methods which are written by expert developers for accessibility. Rather than going through the hassle of writing a function for trimming out all the spaces from the beginning and end of a string, Java has a predefined function called trim() which trims all the space at the beginning and at the end of a String. To access a pre-defined method, we add a dot (.) next to the string variable and then the name of the function with parentheses "()" at the end , as done in the following example below. We will be covering functions later in the course.

TIP: For beginners, it is recommended to drill down these pre-defined functions to understand how they work under the hood and write code either to imporve or compare your solutions to them.

class Trimming {

    public static void main(String[] args) {
    
        String email = "    [email protected]     ";
        System.out.println(email);
        System.out.println(email.trim());
    
    }
    
}
Output
    [email protected]     
[email protected]

We have declared a String variable email which has a value of " [email protected] ". The first print statement prints the whitespaces as Strings do count whitespaces but the second print statement with the predefined function email.trim() trims all spaces in the beginning and end of the email String. This is how useful predefined functions can be. Let’s look at another predefined function in the String class.

length()

The length function finds the length of a string. Using the length function we can determine the character count (Number of characters) within a String. In Java whitespace is also a character having a value which means it counts too. The length function returns an integer which is a numeric (number) Data Type. Let’s find the length of a String in Java.

class LengthFinder {

    public static void main(String[] args) {
        
        String name = "Java";
        System.out.println(name.length());

    }
    
}
4

isEmpty() or isBlank()

isEmpty() or isBlank() return a boolean which is either true or false. Both of them work almost the same but they do have a minor difference. isEmpty() counts whitespaces whereas isBlank() doesn’t. Let’s go through isEmpty() first

public class EmptyCount {

    public static void main(String[] args) {
        
        String name = " ";
        System.out.println("name is empty: " + name.isEmpty());
        System.out.println("name iEs blank: " + name.isBlank());

    }
    
}
Output
name is empty: false
name is blank: true

isEmpty() returned false because it knows there is a character within the variable name which is whitespace and isBlank() ignored the whitespace because a Blank String can contain whitespaces but if we write a single alphabet isBlank() will also return false.

There are enormous functions with every pre-defined Class. Have a look at the String class here and try using every pre-defined function to understand how they work.

char (Character)

The Character Data Type is written as char in Java. The Character Data Type is a single letter covered in single quotes. Every character in Java has an ASCII Code. Check out the codes for every character in the ASCII Character Code Table here. Let’s see a simple example of how to use characters in Java:

class AssignCharacter {

    public static void main(String[] args) {
        
        char smallA = 'a'; // ASCII CODE = 97
        char bigA = 'A'; // ASCII CODE = 65
        System.out.println(smallA + " or " + bigA);

    }
    
}
Output
a or A

To assign a character we follow the Rule of Initialization. First, we write the Data Type char, then the variable name smallA, then the assignment operator = and lastly, the value 'a' covered in single quotes with a semicolon ; at the end. To print the character to the console, we have used the concatenation technique to join both the characters.

So, now you might be thinking about displaying the Decimal value of any character from the ASCII Character Code Table in a Java Program? Let’s do that but it can be done in three ways which are:

class ASCIICode {

    public static void main(String[] args) {
        
        // Old fashioned way
        char bigA = 'A';
        int bigAvalue = (int) bigA;
        System.out.println("Value of A: " + bigAvalue);

        // The new way
        int whitespace = ' ';
        System.out.println("Value of a whitespace: " + whitespace);

    }
    
}
Output
Value of A: 65
Value of a whitespace: 32

We have 2 ways of finding out how the ASCII Character Code for every character. Let’s go through the first one:

// Old fashioned way
We declare a character with any value, then we declare an int and we parse the character into int which means we convert the Character Data Type into Integer Type. The reason we convert the Character into an Integer is that using the Integer Data Type we can find the ASCII Character Code automatically. Then we output the ASCII Character Code using the Integer variable in which the parsed/converted value of the character is stored.

// The new way
Rather than declaring a character, we directly declare an Integer and assign a character value. The character value will print the ASCII Character Code of the character rather than printing the original character.

PRACTICE: Try different values from the ASCII Character Code Table.

boolean (Boolean)

The Boolean Data Type has only two values TRUE or FALSE. In Java, Boolean is declared as bool and a value of true or false is used for assignment. Mostly, programmers use the boolean Data Type for decision making.

class AssignBoolean {

    public static void main(String[] args) {
        
        boolean isValid = false;
        String name = "Java";

        System.out.println("Value of isValid: " + isValid);

        if (name.contains("J")) {
            isValid = true;
        }

        System.out.println("Value of isValid: " + isValid);

    }
    
}
Output
Value of isValid: false
Value of isValid: true

Using the same rule of initialization we have declared two variables of different Data Type. One of them is a boolean and another one is the String. Don’t worry about the if part now, later we will be talking about decision statements. Next, we print the output of isValid and then a decision statement which is known as an if statement is used to look into the String for a value of “J” which is found and within the decision statement body, the value of isValid changes to true. Next, the value isValid is printed to the console again which tells the decision statement was executed. The decision statement uses boolean values as an end result. For example, in the above code name.contains("J") will result in either true or false depending on the variable name value. If the value is true, the statement within the curly brackets {} will execute and if false then it will not. Here is another way without using if statement but with the same result.

class WithoutIfBool {

    public static void main(String[] args) {
        
        boolean isValid = false;
        String name = "Java";

        System.out.println("Value of isValid: " + isValid);

        isValid = name.contains("J");

        System.out.println("Value of isValid: " + isValid);

    }

}
Output
Value of isValid: false
Value of isValid: true

The if statement is removed in the above code and the value of name.contains("J") is assigned to isValid. More on conditional statements later.

byte (Byte)

In Java Byte is written as byte which is an 8 bit signed 2’s complement integer which means positive and negative numbers are allowed within its range. It has a value range of -128 to 128, exceeding it will result in an error. Using Byte for saving memory in large arrays is very useful and a recommended technique. Let’s start with a simple initialization

class AssignByte {

    public static void main(String[] args) {
        
        byte number = 100;
        System.out.println(number + " bytes");

    }
    
}
Output
100 bytes

Using the Rule of Initialization, we declared the Data Type first byte, then the variable number, and after the assignment operator = the value 100. We can find the maximum and minimum value of the Byte Data Type using the Byte class constants. Constants are values which cannot change. We will learn about constants later in the course.

class ByteSize {

    public static void main(String[] args) {
        
        byte max = Byte.MAX_VALUE;
        System.out.println("Max value of Byte: " + max);

        byte min = Byte.MIN_VALUE;
        System.out.println("Min value of Byte: " + min);

        byte size = Byte.SIZE;
        System.out.println("Size of Byte: " + size);

    }
}
Output
Max value of Byte: 127
Min value of Byte: -128
Size of Byte: 8

We have used three constants from the Byte class Byte.MAX_VALUE, Byte.MIN_VALUE and Byte.SIZE. Every constant is placed in the Byte class which have a fixed value which cannot be changed/modified. Byte.MAX_VALUE is the max value a Byte Data Type can have, Byte.MIN_VALUE is the minimum value and Byte.SIZE is the size of Byte Data Type in bits which is 8 bit as discussed above.

short (Short)

In Java, the Short Data Type is written as short and is a 16-bit signed 2’s complement integer. It has a value range of -32,768 to 32,767, exceeding it will result in an error. The usage of Short can be similar to the usage of byte depending on saving memory is how much your priority. Let’s see the maximum, minimum, and size of the Short Data Type

class ShortSize {

    public static void main(String[] args) {
        
        short max = Short.MAX_VALUE;
        System.out.println("Max Value of Short: " + max);

        short min = Short.MIN_VALUE;
        System.out.println("Min Value of Short: " + min);
        
    }
}
Output
Max Value of Short: 32767
Min Value of Short: -32768
Size of Short: 16

int (Integer)

Integer in Java is the most used Data Type. Integers are a 32-bit signed 2’s complement integer. They have a total value of 4,294,967,296. The value is distributed among negative and positive numbers which makes a range of -2147483648 to 2147483647. In Java 8 and later, integers can be used as a 32-bit unsigned integer which has a range of value starting from 0 to 4294967296 which means only positive numbers. Let’s see how we can use signed integers:

class IntegerSize {

    public static void main(String[] args) {
        
        int max = Integer.MAX_VALUE;
        System.out.println("Max value of Integer: " + max);

        int min = Integer.MIN_VALUE;
        System.out.println("Min value of Integer: " + min);

        int size = Integer.SIZE;
        System.out.println("Size of Integer: " + size);

    }
    
}
Output
Max value of Integer: 2147483647
Min value of Integer: -2147483648
Size of Integer: 32

long (Long)

The Long Data Type is much bigger than the Integer Data Type. It is represented using the word long. It is a 64-bit 2’s complement integer with a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Let’s look at an example of a long program.

class LongSize {

    public static void main(String[] args) {
        
        long max = Long.MAX_VALUE;
        System.out.println("Max value of Long: " + max);

        long min = Long.MIN_VALUE;
        System.out.println("Min value of Long: " + min);

        long size = Long.SIZE;
        System.out.println("Size of long: " + size);

    }
    
}
Output
Max value of Long: 9223372036854775807
Min value of Long: -9223372036854775808
Size of long: 64

float (Float)

Float is a single-precision 32-bit IEEE 754 floating-point Data Type. It is really helpful when things are being measured in terms of accuracy. Float is written as float in Java which has a very long range of 1.4e-45 to 3.4028235e38. The difference between int/long & float is the point-based result. Let’s go through a simple initialization, max, min and size values of the Float Data Type:

class FloatSize {

    public static void main(String[] args) {

        float number = 9.0f;
        System.out.println("Number: " + number);

        float max = Float.MAX_VALUE;
        System.out.println("Max value of Float: " + max);

        float min = Float.MIN_VALUE;
        System.out.println("Min value of Float: " + min);

        float size = Float.SIZE;
        System.out.println("Size of Float: " + size);
    }

}
Output
Number: 9.0
Max value of Float: 3.4028235E38
Min value of Float: 1.4E-45
Size of Float: 32.0

Using the Rule of Initialization, we declared a Float variable but the difference is that the value has to be in a decimal format and with an f at an end. Why do we need the Float Data Type when we have Integer and Long? If you divide 1 by 2 using the Integer Data Type you will get a result of 0 but if you use the Float Data Type then the result will be 0.5. Let’s understand with an example:

class Difference {

    public static void main(String[] args) {
        
        int intValueOne = 1;
        int intValueTwo = 2;
        System.out.println("Integer Result: " + (intValueOne / intValueTwo));

        float floatValueOne = 1.0f;
        float floatValueTwo = 2.0f;
        System.out.println("Float Result: " + (floatValueOne / floatValueTwo));

    }
    
}
Output
Integer Result: 0
Float Result: 0.5

In the above code, using the rule of initialization, we have declared 2 Integer variables and 2 Float variables. When both the Integer variables are added as done on Line 07 the result gives us a 0 but if both the Float variables are added, we get a different result.

double (Double)

The Double data type is a double-precision 64-bit IEEE 754 floating-point whereas Float was a single-precision floating-point Data Type. Such a difference proves double to be more accurate and better in terms of memory and precision. Let’s start with a simple code as usual of declaring a double, finding the max, min, and size of the Double Data Type

class DoubleSize {

    public static void main(String[] args) {
        
        double number = 100.50; // 100.50D
        System.out.println("Number: " + number);

        double max = Double.MAX_VALUE;
        System.out.println("Max value of Double: " + max);

        double min = Double.MIN_VALUE;
        System.out.println("Min value of Double: " + min);

        double size = Double.SIZE;
        System.out.println("Size of Double: " + size);

    }
    
}
Output
Number: 100.5
Max value of Double: 1.7976931348623157E308
Min value of Double: 4.9E-324
Size of Double: 64.0

Using the Rule of Declaration, we have declared 4 variables with different values. number variable initializes a Double value, max is the maximum value of the Double Data Type, min is the minimum value and size variable stores the size of the Double Data Type. Double can be declared in two days, with or without the letter D/d at the end.

Non-Primitive Types

Classes

A class in Java is like a body in which the following things can be placed:

  • Variables
  • Constants
  • Functions

Variables

We have been using variables from the start of this lesson but let’s now dive deep into understanding what a variable is. A variable is a piece of memory which holds a Data Type. As discussed above, variables can hold different data types but with a memory limitation. Choosing the right Data Type according to the program’s requirement is said to be best practice in terms of saving memory. Variables have the following types

  • Local
  • Instance
  • Static
Local Variables

Local variables are defined inside a function and are not accessible to other methods. Here is an example.

class LocalVariables {

    public static void main(String[] args) {
        hello // Not accessible by the main method!
    }
    
    private static String printHello() {
        String hello = "Hello, Java";
        return hello;
    }

}

In the above example, we have created the main function along with a user-defined function which we will cover later. Just understand that the function called printHello() below the main function has a variable called hello which we are trying to access in the main method but it cannot be accessed due to its scope which is local. The hello variable can be accessed within the printHello() function only. A variable in Java can only be accessed after it’s declared. A local variable cannot have an access modifier (public, private or protected) because it’s limited to a function.

Instance Variables

Instance variables are variables which are declared outside a method/function. Methods within the class can access the instance variable but not directly, we need to create an object of the current class to access the variable. Here is a small example of how useful instance variables can be.

class InstanceVariable {

    String hello;

    public static void main(String[] args) {

        InstanceVariable iVariables = new InstanceVariable();
        iVariables.hello = "Hello, Java from main method.";
        System.out.println(iVariables.hello);
        System.out.println(printHello());

    }
    
    private static String printHello() {
        InstanceVariable iVariables = new InstanceVariable();
        iVariables.hello = "Hello, Java from the printHello function.";
        return iVariables.hello;
    }
    
}
Output
Hello, Java from main method.
Hello, Java from the printHello function.

We have declared an instance variable hello of String Data Type. We have created two objects, one in the main function and one in the printHello() function. Both the Objects have the same variable name iVariables but aren’t aware of each other, so there is no chance of conflict between them. Objects declared in different functions do not have access outside the function. The Object in the main function accesses the instance variables and then assigns a value and prints it. The Object in the printHello() function also accesses the same instance variable and assigns a value but returns the value from the function and prints it in the main function. As both Objects don’t have a connection between them, it makes it okay to assign different values to each of the Object and expect different results.

Static variables

Static variables are declared static by writing an instance variable and adding the word static at the beginning. Static variables can be accessed anywhere in the class without creating an object or instance of the class. Static variables can also be accessed by other classes if the access modifier is set to public but it is a bad practice to use public static variables. Here is the same example used in instance variables with static variables

class StaticVariable {

    static String hello;

    public static void main(String[] args) {

        hello = "Hello, Java from the main method";
        System.out.println(hello);
        System.out.println(printHello());

    }
    
    private static String printHello() {
        hello = "Hello, Java from printHello function";
        return hello;
    }
    
}
Output
Hello, Java from the main method
Hello, Java from printHello function

We have declared a static variable hello of String Data Type. In the main function, the hello variable has a value of "Hello, Java from the main function" and in the printHello() function the hello variable has a value of "Hello, Java from printHello function". Now, the value returning from the printHello() function is different and the value in the main function is different because of the scope they are in and the printHello() function is returning the String from the function. We will be looking into function more deeply later in the course.

It can be a hassle of putting too many variables on each line but there is an efficient way of writing technique for variables known as inline variables. We declare all the variables in the same line along with their values but it is not recommended if your values aren’t small. Let’s go through a small example:

class InlineVar {

    public static void main(String[] args) {
        
        int a = 1, b = 2, c = 3;
        
        System.out.println("a is " + a);
        System.out.println("b is " + b);
        System.out.println("c is " + c);

    }
    
}
Output
a is 1
b is 2
c is 3

We have declared three variables on the same line a, b, and c along with values. It is not important to assign values to every inline declared variable. Inline Variables can be declared with or without a value.

Constants

Constants are fixed values that cannot be changed. They can be accessed anywhere in your project. They are very helpful when it comes to values which do not need to be altered with. Constants cannot be changed or reassigned like variables. They always require a value. A constant is always written at the top of the class. Here is a small example of what constants are

class Constants {

    static final String PROGRAMMING_LANGUAGE = "Java";

    public static void main(String[] args) {

        System.out.println("Hello, " + PROGRAMMING_LANGUAGE);
        
    }
    
}
Output
Hello, Java

Creating a constant is easy, take a static variable and add the word final after static and value at the end. As in the above example, static final String declares a constant and the value "Java" is set for it which is accessible all over the project. A constant can be recognized in Java by its uppercase letters. It’s an old and good fashion of writing constants in the uppercase and using an underscore for spaces as done for our constant. PROGRAMMING_LANGUAGE.

Functions/Methods

Functions are the most important and useful topics in Java. To understand a function let’s take an example of a routine that happens again and again in your daily life. If we were to write down the routine of our daily life using the print statement in java then it might look like this:

class BadExample {

    public static void main(String[] args) {
        
        System.out.println("-- Monday Routine --");
        System.out.println("Wake up");
        System.out.println("Take a shower");
        System.out.println("Exercise");
        System.out.println("Make Breakfast");
        System.out.println("Get Ready");
        System.out.println("Go to Work");
        System.out.println("Have Lunch");
        System.out.println("Have Dinner");
        System.out.println("Enjoy Netflix");
        System.out.println("Sleep");

    }
    
}
Output
-- Monday Routine --
Wake up
Take a shower
Exercise
Make Breakfast
Get Ready
Go to Work
Have Lunch
Have Dinner
Enjoy Netflix
Sleep

Now we have an awful lot of print statements with our routine only for Monday, what about the other days? So, there are 7 days in a week and we have to write out these statements 7 more times which can be too much of a hassle of doing the same thing again and again. What if we could access the whole routine within a single line? We can by using functions. Here is an example.

class Functions {

    public static void main(String[] args) {

        System.out.println("-- Monday --");
        routine();

    }
    
    private static void routine() {
        System.out.println("Wake up");
        System.out.println("Take a shower");
        System.out.println("Exercise");
        System.out.println("Make Breakfast");
        System.out.println("Get Ready");
        System.out.println("Go to Work");
        System.out.println("Have Lunch");
        System.out.println("Have Dinner");
        System.out.println("Enjoy Netflix");
        System.out.println("Sleep");
    }
}

Now we need to access the routine function only once by calling it in the main method. Let’s break the function down and see what a function is made up of:

private/public
An Access Modifier is optional depending upon the usage of the function. If the function is required to be accessed within another class then we use the public modifer or leave it blank, if we want the function not to be accessed by any of the classes we use the private modifer. Access Modifiers are written at the start of a Function, Variable or a Class.

static
Making the function static makes it available to be used within the current class without creating an Object of the class just like we did for the Instance Variables.

void
A function can return values. If void is written that means no values should be returned. A function can return values depending on the return type. If we want to return a value we change the void to the certain Data Type we want to return.

routine
routine is just a name of the function through which it can be called. A function should be named according to its usage.

()
Parentheses are important after the name of the function. They can either be empty or carry Parameters for a function. Parameters contain Data Types and Variables which help passing values when called.

Functions with a return type

Functions can return a value which can either be a Number, String, Interface, Class, etc. Depending on the need of what we require from a function we can return the value. For example, we need a String value Hello from a function called sayHello(). We will write such a function by first writing static then the return type which is String as we require a String value Hello from the function and then the name of the function sayHello(). Then within two curly brackets, the whole logic of our code will reside. As we are returning the String value, we need to use the return reserved keyword and then the value we are returning which can either directly be a String or a variable with a String Data Type. Reserved words in Java are those which cannot be used as a variable like new, static, void, public, private etc. Let’s see how we can return a String from a function:

class ReturnFunction {

    public static void main(String[] args) {

        System.out.println(sayHello() + "Java");
        

    }
    
    private static String sayHello() {

        String hello = "Hello, ";
        return hello; // or return "Hello";

    }
}
Output
Hello, Java
Functions with Parameters, Arguments & Return Type

Now, let’s look at a more complex version of a function. Giving values to a function means the function has parameters. Parameters are how functions take in values, Arguments are values which are given to a function. Here is a graphical representation:

Let’s go through a Function with Parameters & Arguments in Java Code:

class ParamsArgsFunc {

    public static void main(String[] args) {

        // Calling function directly
        System.out.println("1 + 2 = " + add(1, 2));

        // Storing the value of the function returned
        int value = add(5, 5);
        System.out.println("5 + 5 = " + value);

    }
    
    static int add(int valueOne, int valueTwo) {

        return valueOne + valueTwo;
        
    }
    
}
Output
1 + 2 = 3
5 + 5 = 10

Below the main method, We’ve created a function called add which takes in 2 Parameters. Parameters within a function are written like assigning a variable. A good programming practice is to use necessary parameters rather can overwhelming the parameters within a function. The add function returns an Integer by applying an arithmetic operation on both the parameters by adding them together and returning the value. To write a parameter we first write the Data Type as we’ve chosen an Integer for valueOne and the same for valueTwo, after the Data Type, comes the variable which can be named according to your desire. In the main method, we’ve called the add function in two ways, one by either calling it directly and putting in the values the parameters expect which are an integer. For valueOne it is 1 and for valueTwo it is 2 which add up in the add function and return as 3 and prints the output. Below it, we have stored the value of the add function and added two different integers (5, 5) which output a result of 10 and then finally printed the variable in which the function returned value is stored. The only difference between parameters and arguments is that parameters define what values a function should require and arguments are values which are passed to a function.

User-Defined & Predefined functions

Functions are of two types, User-Defined and Predefined. User-Defined functions are those which we created above sayHello(), routine(), and add(). Predefined functions are derived from a class and are already defined and ready to use. Here is a short example:

class PredefinedFunc {

    public static void main(String[] args) {
        System.out.println("Using Pre-Defined Function: " + Math.addExact(2, 3));
        System.out.println("Using User-Defined Function: " + add(2, 2));

    }
    
    static int add(int valueOne, int valueTwo) {

        return valueOne + valueTwo;

    }
    
}
Using Pre-Defined Function: 5
Using User-Defined Function: 4

In the first print statement, we’ve used the Math Class Predefined function addExact() which takes in two parameters and output the result of it and below we have a user-defined function which also does the same but there is a big difference. If we add 2 to the maximum value an Integer can hold then the addExact() method will throw an Exception (error) of integer overflow but the user-defined function will not, it will output an unexpected result. Let’s see an example of the Predefined function

class ErrorPreDef {

    public static void main(String[] args) {
        
        System.out.println(Math.addExact(Integer.MAX_VALUE, 2));

    }
    
}
Output
Exception in thread "main" java.lang.ArithmeticException: integer overflow

User-Defined function example

class ErrorUserDef {

    public static void main(String[] args) {

        System.out.println(add(Integer.MAX_VALUE, 2));

    }
    
    static int add(int valueOne, int valueTwo) {
        return valueOne + valueTwo;
    }
    
}
Output
-2147483647

Rather than getting a result of 2147483649 we get -2147483647, Why?
When we add 2 into the maximum value of Integer it rolls back to the minimum value of the Integer and removes 1 from it whereas 1 was lost during rolling back to the minimum value. So, that is why Predefined methods/functions are said to be more useful and error-free then User-Defined ones.

Object Creation

To call any Class in your main method we create an Object of the Class. Here is a graphical representation of how we can call a Class by making its object:

Arrays

An Array in Java is a collection of elements. An Array can contain several elements like Classes, Data Types and more. Let’s go through an example of initializing an array in Java.

class AssignArray {

    public static void main(String[] args) {
        
        int[] numbers = { 1, 2, 3, 4, 5 };

        System.out.println("Index 0: " + numbers[0]);
        System.out.println("Index 1: " + numbers[1]);
        System.out.println("Index 2: " + numbers[2]);
        System.out.println("Index 3: " + numbers[3]);
        System.out.println("Index 4: " + numbers[4]);

    }
    
}
Output
Index 0: 1
Index 1: 2
Index 2: 3
Index 3: 4
Index 4: 5

To create an array we need to choose a Data Type first, as we have chosen to make an array of the Integer Data Type. The syntax for creating an array only consists of adding square brackets [] next to the Data Type int[]. The value of an array is always covered in curly braces {} similarly as {1, 2, 3, 4, 5}. When selected to create an Integer array, we can have values what an Integer can support. Then we printed out every element according to its index. A protip to keep in mind is that an array always has an index which starts from 0, not from 1. Same as our 1 has an index of 0 and 5 has an index of 4. So if we count the total numbers according to the index, we have 4 elements and if normally then we have 5. Rather than writing 5 lines of print statements, we can optimize the code and print every element using a loop. Here is a small example, don’t worry. We will be covering loops further in the lesson.

class IterateArray {

    public static void main(String[] args) {

        int[] numbers = { 1, 2, 3, 4, 5 };
        for (int number : numbers) {
            System.out.print(number + " ");
        }

    }

}
1 2 3 4 5

Let’s go through an example where can add multiple values in an array and iterate over them.

class MultipleValues {

    public static void main(String[] args) {
        
        Object[] mixed = { 1, 2.0, true, "string", 'c' };
        
        for (Object value : mixed) {
            System.out.print(value + " ");
        }

    }
    
}
Output
1 2.0 true string c

Here we have an Object Array which can carry mixed values. The value of mixed is an Object Array which contains an Integer (1), Float (2.0), Boolean (true), String ("string") and a Character ('c'). Then we iterate on the mixed Array using For Loop.

Here’s how we can limit an array to a specific range:

class LimitArray {

    public static void main(String[] args) {
        
        String[] chocolates = new String[2];

        chocolates[0] = "Dark Chocolate";
        chocolates[1] = "White Chocolate";
        // chocolates[2] = "Milk Chocolate"; // Array index out of bounds

        System.out.println(chocolates[0] + " & " + chocolates[1] + " are my favorite.");
        // System.out.println(chocolates[2]);

    }
    
}
Output
Dark Chocolate & White Chocolate are my favorite.

We start by adding square brackets to the Data Type String[] and then the variable chocolates, the assignment operator = and then the new reserved keyword and again the Data Type with square brackets but with the range of an array you want to limit it to String[2]. We have limited the chocoaltes String array to have a size of 2. For adding values within an array, we need to access the index and if you remember the index of an array always starts from 0, so to access the first element within an array and assign a value to it we use the variable chocolates and then add square brackets [] and the value 0 to access the first element [0]. Proceeding with an assignment operator = and at last value of your choice according to the Data Type. Then for the second element chocolates[1] the value is set to "White Chocolate". Don’t forget the semi-colons.

If we try to add values out of the range we provided to an array we might get a very popular exception (Error) known an Array Index Out Of Bounds Exception which simply means we are trying to assign/access a value which is not in the bound of the current Array. Try to uncomment the last print statement and run the code to get a similar output:

Dark Chocolate & White Chocolate are my favorite.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
         at LimitArray.main(LimitArray.java:12)

Let’s go through an example which can help us count the number of elements within an Array

class ArrayLength {

    public static void main(String[] args) {

        float[] numbers = { 1.0f, 2.0f, 55.0f, 22.0f, 9.0f };
        
        System.out.println("Number of elements in numbers array is " + numbers.length);
        
    }
}
Output
Number of elements in numbers array is 5

In the code above, there is a Float Array which is populated with float values. Now to find the length/count of elements within the values float array we use one of the Array methods called length which counts the number of elements within an Array and outputs the length as an integer. Then, we have printed the value which has accurately told us about the number of elements in the numbers array is 5. There is a difference between normal and index-based counting. When finding the length of an array, the counting starts normally from one not from zero.

Round and Around with Loops

Loops are an essential part of a Programming Language. Loops make development a much more easy task. Loops are the repetition of instructions until the following condition is met. Loops have the followings kinds in Java

  • For Loop
  • While Loop
  • Do While Loop
  • For Each Loop

For Loop

For loop in Java has 3 parts. The first one is the Initialization, Condition, and Increment/Decrement. Let’s go through an example first to understand the for loop

class ForLoop {

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            System.out.print(i + " ");
        }
        
    }
}
0 1 2 3 4 5 6 7 8 9

Above in the code, we have written a basic For Loop which prints numbers starting from 0 to 9, a total of 10 numbers. To write a for loop we use the following syntax

Let’s break down the syntax of For Loop

for – To create a For Loop we start with the keyword for which is a reserved word in Java.

() – After the keyword, we use the parentheses which contain the creation method of For Loop.

int i = 0; – The first part of the for loop is always the Initialization which defines where the loop will start or end and what value it will carry but the value should be numbers which are preferable for the loop to understand the beginning. We start with a numeric Data Type, we have chosen Integer Data Type int and then the variable i and after the equal sign, the starting value or it can be the ending value also depending on how you want the Loop to begin.

i < 10; – The second part is the Condition part where you want the loop to work based on a condition or it can work infinitely which is undesirable. Here, we have taken the variable i and used a mathematical operator which is less than < and then the number it should be less than which is 10. Now, the loop will start from 0 and end at 9 because we are neglecting 10 when we say i should be less than 10 and if we want it to end on ten, then we need to use an equal sign next to the less than operator <=.

i++; – Here we are incrementing the value of the variable i. The reason we increment is that if the value stays on a single point, it won’t be able to access the next value and it won’t be called a loop. We use two plus signs (++) which denote increment and for decrementing values we use two minus signs --. The loop will execute and increment the value of i until it reaches the specified condition which is i < 10;.

{} – The curly braces contain the logic of For Loop. These curly braces are also called code block/statements. All the logic inside these curly braces executes until the defined condition is true.

In the above example, when the variable i is initialized with 0, the loop starts with it, then the loop moves forward by checking the condition according to the value placed in the variable i which is currently 0. If the condition, that 0 is less than 10 is true then the loop increments the value and executes the code placed in the code block/statement. The same process happens until the variable i holds the value 10, the loop checks the condition of 10 being less than 10 which is false, due to which the loop breaks. This is how for loops function.

Here is an example where we can start the loop at 0 and end at 10.

class ExactEndLoop {

    public static void main(String[] args) {
        
        for (int i = 0; i <= 10; i++) {
            System.out.print(i + " ");
        }

    }
    
}

The only difference here is in the condition part i <= 10;. After the mathematical operator less than, we have used an assignment operator which tells the loop to end at 10 and when the loop has the value 10 stored in the variable i at the end of the loop, it checks the condition if 10 is either less than or equal to 10 which means it is not less than but it is equal which makes the condition true so it executes and increments also due to which the variable stores the value 11 and checks the condition and it returns false so the loop breaks.

Here is an another example which starts at 10 and ends at 0

class UpSideLoop {

    public static void main(String[] args) {
        
        for (int i = 10; i >= 0; i--) {
            System.out.print(i + " ");
        }

    }
    
}
Output
0 1 2 3 4 5 6 7 8 9 10

We have created a loop which counts from 10 to 0. The difference lies within the Initialization where the starting value is 10, the condition is set to be greater and equal to 0 because we are moving backwards from 10 to 0 and at last we have used the decrement operator which helps in decreasing the value stored in the variable i.

While Loop

While loops are another type of loops in Java. They have a similar process of Initialization, Condition and Increment/Decrement but not on a single line and within parentheses. Let’s go through an example of a while loop

class WhileLoop {

    public static void main(String[] args) {
        
        float count = 0.0f;

        while (count <= 10.0f) {
            System.out.print(count + " ");
            count++;
        }

    }
    
}
0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0

The difference between while and for loop’s syntax is how the process is laid out. In the above program, we have initialized count as a Float with a value of 0.0f and then, using the while keyword and the condition count <= 10.0f within the parentheses. The increment goes inside the code body/statement. Depending on when you want to increment the value is also possible within a while statement.

Do While Loop

The Do While Loop is another loop in Java which is almost similar to While Loop but there is a small difference between them. Let’s go through a simple example of a Do While Loop example.

class DoWhileLoop {

    public static void main(String[] args) {
        
        int count = 0;
        do {
            System.out.print(count + " ");
            count++;
        } while (count < 10);

    }
    
}
Output
0 1 2 3 4 5 6 7 8 9

We have initialized the count variable on the top with a value of 0. To create a Do While Loop, we start with the keyword do and then the curly braces mark the start of the logic to be executed by the loop. Here, we put the while keyword in the end with the condition count < 10;. The difference between While and Do While Loop is that while loop doesn’t execute if the condition is false but do while guarantees an execution for at least once even if the condition is false at the first encounter.

For Each Loop

For Each Loop is the most used loop in Java. The reason is very simple. Let’s take an example of a list of users. On Day 1, you have 2 users and their values can be accessed using the square notation [] as we did above in the Arrays section. What if we wanted to access a list of users more than 50 users? Would you use the square notation for more than 50 times? We hope you don’t because first of all, it might be not error-free and you might miss a user. Ok, you’ve done it awesomely using the square notation but what if there are a million users? That is why it is always efficient to use loops to iterate over Arrays. Let’s go through a simple For Each Loop:

class ForEachLoop {

    public static void main(String[] args) {

        String[] values = { "This", "is", "Java", "for", "Beginners" };

        for (String value : values) {
            System.out.print(value + " ");
        }
        
    }
}
This is Java for beginners 

Above in the program, we have a String Array values which has 5 values making up a sentence. To access the elements inside and make it a sentence we use the For Each Loop. To create a For Each Loop we start with the keyword for and then parentheses (), within the parentheses, we start by writing the Data Type String of the Array we are trying to access and a variable value next to it. The variable value is the single value of what the Array contains. Next, we use a colon : and then the value we want to loop on which is the String Array values. Next, comes the curly braces {} which contain the logic you want the loop to execute every time it detects a value within the array. The loop itself detects the length of the array and neutralizes when the values are finished. So it is a very simple loop which helps in iterating over an array.

Decisions using Condition Statement

Conditional Statements are an essential part of Java. Making decision-based output is very important in the world of programming, for example, allowing certain actions if the user is logged or allowing a certain amount of price for an order to be placed. There are the following conditional statements in Java:

  • If Statement
  • If Else Statement
  • If Else If Statement
  • Switch Statement
  • Quick decisions using the Ternary Operator

If Statement

The If Statement is the basic condition statement in Java. If statements help execute certain instructions based on a specific condition. Let’s go through the syntax of If Statement

if ([condition]) {
    // Code Block/Statement
}

We start writing the If Statement with the reserved keyword if and then parentheses () within which the condition is placed, after that comes curly braces {} which contain the logic for the If Statement. The logic only executes if the given condition is true else it won’t. Let’s go through a small example of an If Statement in Java

class IfStatement {

    public static void main(String[] args) {
        
        int number = 100;
        
        if (number > 55) {
            System.out.println("Number is greater than 55");
        }

    }
    
}
Output
Number is greater than 55

We have initialized an Integer with a value of 100 stored in the variable number. Then we check for a condition which states if the number is greater than 55 if (number > 55), execute a print statement saying "Number is greater than 55". The if statement looks for the variable number and checks for the value it contains which is 100 and compares it according to the mathematical operator which is the greater than sign > with 50 so the condition becomes 100 > 55 which is true, so the code body/statement executes. Let’s change the mathematical operator to an equal sign which is 2 equal signs whereas a single equal sign means an assignment operator and two for an Equality Check.

class EqualityCheck {

    public static void main(String[] args) {
        
        int number = 100;

        if (number == 55) {
            System.out.println("Number is equal to 55.");
        }

    }
    
}
Output

There will be no output because of the condition which checks if the number with value 100 is equal to 55 which in the case is false will not execute the print statement. Some of the basic operators which are used for making decisions are Equality Check ==, Not Equal !=, Greater Than >, Less Than <, Greater Than or Equal to >=, Less Than or Equal to <=. More on operators later. If statements aren’t restricted to numeric types only, let’s see an example with a String.

class StringCheck {

    public static void main(String[] args) {
        
        String dinner = "We are going to have salad for dinner.";
        
        if (dinner.contains("salad")) {
            System.out.println("Looks like, I'm going for a Diet!");
        }

    }
    
}
Looks like, I'm going for a Diet!

Here, we are using a String class function which helps us find a word within the String dinner and if it is present which execute a print statement according to it. Within the condition dinner.contains("salad") dinner is the variable which contains the sentence. The dot and the word contains are String class functions as we discussed above that every Data Type Class has its own pre-defined functions. The contains function takes a parameter of a CharSequence which is a sequence of letters, similar to a String but not String and due to which we provided the word we were looking for. This example justifies that conditional statements can be based on what decision(s) we are making on what kind of Data.

If Else Statement

In Java, the If Else Statement is used widely. The If-Else Statment is like making a decision and keeping a backup if the decision isn’t made. Let’s go through the syntax of If-Else Statment

if ([condition]) {
// if true
} else {
// if not true
}

The If Statement stays the same, but we add another part at the end of the if statement which starts with else and curly braces. Let’s see an example to make the syntax more clear.

class IfElseIf {

    public static void main(String[] args) {

        int number = 100;

        if (number < 55) {
            System.out.println("Number is less than 55.");
        } else {
            System.out.println("Number is greater than 55.");
        }
        
    }
}
Output
Number is greater than 55.

We have the old example, in which we have an Integer with a value of 100 but the condition is a bit changed. In the If Statement, we are looking for a condition where the number 100 is less than 55 which isn’t true. So, when it’s not true, then the If Statement isn’t going to execute, the else part will, which outputs the print statement saying "Number is greater than 55". The else part is like having a backup executing when the if statement is not true.

If Else If Statement

The If Else If Statement gives more control on making decisions in Java. More often, when developers are twisted between taking multiple decision, we have the If Else If Statement to the rescue. Let’s go through the syntax of If Else If Statement.

if ([condition]) {
// if true
} else if ([condition]) {
// if true
} else {
// if false
}

The If Else If Statement is always written before an else statement and after an if statement. We write the first if condition, then if we have another condition to meet we can add another if statement after the else keyword. It is optional to add an else statement in the end if we are using If Else If Statement but it’s a good practice to give a failsafe when both the if conditions aren’t true. Let’s go through a simple example.

class IfElseIf {

    public static void main(String[] args) {
        

        int number = 100;

        if (number < 55) {
            System.out.println("Number is less than 55.");
        } else if (number > 23) {
            System.out.println("Number is greater than 23.");
        } else {
            System.out.println("Number is 100");
        }

    }
    
}

We declared a number variable with a value of 100 and then use an If Else If Statement which checks for two conditions and has a failsafe if both aren’t true. The first condition is false as 100 is not less than 55, the second condition is true because 100 is greater than 23 which means the failsafe, the else condition isn’t going to execute.

Switch Statement

The Switch Statement is a lifesaver if you have too many decisions to make. The switch statement takes in a parameter and works accordingly based on cases and has a default case which is the failsafe when no case is executed. Let’s go through the syntax of the switch statement.

switch ([value]) {
    case [value]:
        break;
    case [value]:
        break;
    default:
        break;
}

To create a switch statement we start with the switch keyword and then parentheses, which takes a parameter on which decision has to be made accordingly. Then we use curly braces within which the cases are put up. A case takes in a value based on the parameter Data Type and executes the code based within the specific case until it breaks. A case is always written within a switch statement and to write one we use the keyword case and then the value. Notice here, there are no parentheses in which the value is covered. We write a colon at the end of the value and then on the next line comes the logic we need to execute. The keyword break is important because we want a certain case to only execute until we wish two or more cases to execute concurrently. And at the end comes the default case which doesn’t require a break statement. The default case is the failsafe which executes when none of the cases are true. Let’s go through a simple switch example.

class Switch {

    public static void main(String[] args) {

        char character = 'a';

        switch (character) {
        case 'a':
            System.out.println("You selected 'a'");
            break;
        case 'A':
            System.out.println("You selected 'A'");
            break;
        default:
            System.out.println("Nothing selected!");
            break;
        }
        
    }
}
Output
You selected 'a'

Here, we have initialized a character variable character with a value of 'a'. Using the switch statement on the character variable we have different cases. The first case looks for the value 'a' in the character variable and matches the value given in the case. If both are true, then the code within the case executes. As the first case is true, it executes. When the case is being executed, it goes through the break keyword which breaks the execution out of the switch statement. So, case 'a' will be executed and case 'A' and default won’t be.

Let’s see through an example of what happens if we remove the break statement from the first case.

class BuggySwitch {

    public static void main(String[] args) {

        char character = 'a';

        switch (character) {
        case 'a':
            System.out.println("You selected 'a'");
        case 'A':
            System.out.println("You selected 'A'");
            break;
        default:
            System.out.println("Nothing selected!");
            break;
        }
        
    }
}
Output
You selected 'a'
You selected 'A'

Now the output is a bit different and incorrect. When the value in the switch parameter is compared to the first case and set to true, the execution starts and looks for the break keyword to break out of the switch statement. As we have not provided the break keyword in the first case, it moves the execution to the second case and executes it also and finds the break keyword. So, be careful when using the switch statement. Don’t forget to break out of the switch statement.

Ternary Operator

The Ternary Operator is a very basic way of making decisions. It is used to make an instant decision which can help in setting values based on a condition. The syntax goes like this

[Data Type] [variable] = [condition] ? [if true] : [if false]

We start with using a Data Type, then a variable for it, an assignment operator then the condition rather than putting a value directly. After the condition, comes the question mark which denotes it as a ternary operator. Then comes the part, where if the value is true, what it should be and then a colon and if not true then what it should be. Let’s go through a simple example

class Ternary {

    public static void main(String[] args) {
        
        String dinner = "Chicken Burger";

        String decision = dinner.contains("Burger") ? "We are having burgers" : "Oh! No burgers today?";

        System.out.println(decision);


    }
    
}
Output
We are having Burgers.

We have declared a String variable with a value of "Chicken Burger" and another String which decides the value based on the condition using the ternary operator. If the variable dinner value contains the word "Burger" then the value of decision will be "We are having Burgers" and if not, then the value will be "Oh! No burgers today?". This is how the Ternary Operator works. Here is a graphical representation of Ternary Operator

Optimizing Decisions with Operators

Operators are a special type of symbols which are used to perform different operations on Operands. An Operand is a value on which an Operator is being applied. Following are the basic operators in Java

  • Arithmetic Operators
    • Addition (+)
    • Subtraction (-)
    • Multiplication (*)
    • Division (/)
    • Modulus (%)
  • Unary Operators
    • Postfix (expr++/expr--)
    • Prefix (++expr/--expr)
  • Relational Operators
    • Greater Than (>)
    • Less Than (<)
    • Greater/Less than or Equal To (>= / <=)
    • Not Equal to (!=)
  • Logical Operators
    • AND (&&)
    • OR (||)
    • NOT (!)
  • Assignment Operator (=)

Arithmetic Operators

Arithmetic Operators are Mathematical Operators which are used to perform mathematical operations on operands. Simple Math operations include Addition, Subtraction, Multiplication, Division, and Modulus. Let’s go through each of them one by one.

Addition (+)

The plus sign is used to add two operands. Let’s go through a simple example of adding two variables or directly adding two numeric numbers.

class Addition {

    public static void main(String[] args) {
        
        int a = 10, b = 10;
        int addition = a + b;

        System.out.println("addition result: " + addition);
        System.out.println("a + b: " + (10 + 10));

    }
    
}
Output
addition result: 20
a + b: 20
Subtraction (-)

The minus sign is used to subtract two operands. Here is a simple example.

class Subtraction {

    public static void main(String[] args) {
        
        int a = 10, b = 10;
        int subtraction = a - b;

        System.out.println("subtraction result: " + subtraction);
        System.out.println("a - b: " + (10 - 5));

    }
    
}
Output
subtraction result: 0
a - b: 5
Multiplication (*)

The star sign is used to multiply two or more operands. Here is a simple example.

class Multiplication {

    public static void main(String[] args) {
        
        int a = 10, b = 10;
        int multiplication = a * b;

        System.out.println("multiplication result: " + multiplication);
        System.out.println("a * b: " + (10 * 10));

    }
    
}
Output
multiplication result: 100
a * b: 100
Division (/)

The slash sign is used to divide two more operands. Here is a simple example.

class Division {

    public static void main(String[] args) {
        
        int a = 10, b = 10;
        int division = a / b;

        System.out.println("division result: " + division);
        System.out.println("a / b: " + (10 / 2));

    }
}
Output
division result: 1
a / b: 5
Modulus (%)

The percentage sign is used to find the remainder from two operands by dividing them first. Here is a simple example.

class Modulus {

    public static void main(String[] args) {
        
        int a = 10, b = 3;
        int modulus = a % b;

        System.out.println("modulus result: " + modulus);
        System.out.println("a % b: " + (10 % 2));


    }
    
}
Output
modulus result: 1
a % b: 0

Here is an example which prints and tells which number is an odd number and which is an even number.

class OddEven {

    public static void main(String[] args) {
        
        int limit = 10;

        for (int i = 1; i <= limit; i++) {

            if (i % 2 == 0) {
                System.out.println(i + " is Even");
            } else {
                System.out.println(i + " is Odd");
            }
            
        }

    }
    
}
Output
1 is Odd
2 is Even
3 is Odd
4 is Even
5 is Odd
6 is Even
7 is Odd
8 is Even
9 is Odd
10 is Even

We have initialized a variable limit with a value of 10, then used a for loop from 1 to 10. Within the loop, we are checking if the number is divisible by two using the modulus operator checking for the remainder to be 0 then it is even and if not then it’s odd.

Unary Operator

A unary operator requires a single operand on which it can perform various operations. Let’s go through some basic Unary Operators.

Postfix & Prefix Operator

Postfix is an operator in which the increment or decrement sign with the expression is written after the operand. The postfix operator returns the original value first and then increments it whereas, the prefix operator returns the incremented/decremented value first rather than the original value. Let’s go through an example

class PostPreFixOp {

    public static void main(String[] args) {
        
        int a = 10, b = 10;

        System.out.println("\n------ Before ------");
        System.out.println("Value of a before: " + a);
        System.out.println("Value of b before: " + b);

        int prefix = ++a; // prefix increment operator
        int postfix = b++; // postfix increment operator

        System.out.println("\n------ After ------");

        System.out.println("prefix value: " + prefix);
        System.out.println("Value of a now: " + a);

        System.out.println("postfix value: " + postfix);
        System.out.println("Value of b now: " + b);


        

    }
    
}
Output
------ Before ------
Value of a before: 10
Value of b before: 10

------ After ------
prefix value: 11
Value of a now: 11
postfix value: 10
Value of b now: 11

We have declared two inline variables a & b with a value of 10 for both. We printed the value of both the variables beforehand and then we created two variables again which are prefix & postfix. The prefix variable contains the prefix operator ++expr on the a variable as an operand ++a. The postfix variable contains the postfix operator expr++ on the b variable as an operand. Both are incrementing the value but the difference is between when the increment happens. For the prefix variable, the original value is incremented and stored in the prefix variable, we can see the value of postfix and the variable a value match but for the postfix variable, the original value is stored within the postfix variable whereas the value of b variable is incremented. They are a bit tricky to understand but they do have a good role in Java.

Relational Operators

Greater than (>)

The Greater than operator > is used in many ways, in loops, in conditions and even in creating boolean variables. This operator returns a boolean of true or false by comparing the value on the left side with the right side. Let’s go through an example using conditions.

class GreaterThan {

    public static void main(String[] args) {

        String[] flavors = { "Chocolate", "Oranage", "Vanilla", "Strawberry" };
        
        if (flavors.length > 2) {
            System.out.println("We have enough flavors for desserts.");
        } else {
            System.out.println("We need more flavors!");
        }
        
    }
}
Output
We have enough flavors for desserts.

We have created a string array with 4 values in it. The condition statement uses the Greater than > operator to confirm if the condition is true or false. As we know the condition flavors.length > 2 is true, so the if statement executes.

Less than (<)

The less-than operator is used to check if the value on the left side is less than the value on the right side to output a boolean. Let’s go through an example:

class LessThan {

    public static void main(String[] args) {
        
        String[] flavors = { "Chocolate", "Oranage", "Vanilla", "Strawberry" };

        if (flavors.length < 5) {
            System.out.println("We need more flavors!");
        } else {
            System.out.println("We have enough flavors.");
        }

    }
    
}
We need more flavors!
Greater/Less than or Equal to (>= / <=)

To understand the difference between Greater than or Equal to and Less than or Equal to can be understood easily through the following example.

class GreaterLessEqual {

    public static void main(String[] args) {
        
        String[] flavors = { "Chocolate", "Oranage", "Vanilla", "Strawberry" };
        if (flavors.length >= 4) {
            System.out.println("We have enough flavors");
        } else {
            System.out.println("We need more flavors!");
        }

        String toppings[] = { "Sprinkles", "M&M", "Choclate Chip", "Dry Fruits" };
        if (toppings.length > 4) {
            System.out.println("We have enough toppings");
        } else {
            System.out.println("We need more toppings!");
        }
    }
    
}
Output
We have enough flavors
We need more toppings!

Now, we have two string arrays flavors and toppings. The first condition is using the Greater than or Equal to >= operator which checks for the length and compares it with 4 and returns true because it is equal to 4, so it executes the if statement only. Coming to the second condition which is applied to the toppings variable. It also checks for the length of toppings String Array which is also 4 but the operator is Greater than > only which means, it will compare the length of the String array which is 4 with 4 but will be false because the operator is only looking for values which are greater than 4 so the condition becomes false. This is the major difference between Greater than and Greater than and Equal to Operator. Less than or Equal to operator also works the same way but it compares and expects the left side value to be less than or equal to the right-side value to be true.

Not Equal to (!=)

The Not Equal to operator is a very simple operator which outputs to true if the value on the left side is not equal to the value on the right side. Let’s look at an example.

class NotEqual {

    public static void main(String[] args) {
        
        String[] flavors = { "Chocolate", "Oranage", "Vanilla", "Strawberry" };

        if (flavors.length != 5) {
            System.out.println("We need atleast 5 flavors.");
        } else {
            System.out.println("We have enough flavors.");
        }

    }
    
}
Output
We need atleast 5 flavors.

We have a flavors String Array again with 4 values. The condition checks for the length of the flavors Array which should not be equal to 5 to confirm we either have the number of flavors we require or not. The if condition returns true because the length of the flavors array is 4 which is not equal to 5 so the if statement executes.

Logical Operators

Logical operators are very useful for optimizing conditional statements. For example, if we want a decision to be taken on multiple conditions, we can use the logical operators to combine conditions within a single conditional statement. Let’s go through basic Logical Operators one by one:

AND (&&)

The AND && operator combines conditions and expects every AND condition to be true. Let’s go through an example to clearly understand AND operator.

class AND {

    public static void main(String[] args) {
        
        int number = 100;

        if (number != 0 && number > 50) {
            System.out.println("Both the conditions are true.");
        } else {
            System.out.println("None of the conditions are true.");
        }

    }
    
}
Output
Both the conditions are true!

Here we have an Integer with a value of 100 stored in the variable number. The if statement checks for two conditions, the first one checks if the number variable is not equal to 0 and using the AND operator && which are two ampersand signs the second condition which checks if the number is greater than 50. Both the conditions need to be true for the if statement to be executed so here both the conditions are true.

OR (||)

The OR operator also combines conditions but doesn’t expect all the conditions to be true. The OR operator is denoted using two pipes. Here is a small example:

class OR {

    public static void main(String[] args) {
        
        float number = 25.1f;

        if (number != 0 || number > 25.5f) {
            System.out.println("One of the condition is true.");
        } else {
            System.out.println("None of the conditions are true!");
        }

    }
    
}
Output
One of the condition is true!

The if statement consists of two conditions which are separated by the OR || operator. The OR operator requires one of the condition to be true to execute the if statement. The first condition states that the number should not be equal to 0 which is true and the second condition states the number should be greater than 25.5 which is false. As we have one true condition which means the if statement can be executed.

NOT (!)

The Not operator is just an exclamation mark which is used to invert the value from any condition statement for example, if we want to search a string for a word it does not contain we will use the not operator. Let’s look at such an example…

class NOT {

    public static void main(String[] args) {

        String sentence = "Hi, I am Java!";

        if (!sentence.contains("Python")) {
            System.out.println("We are learning Java!");
        } else {
            System.out.println("What are we learning?");
        }
        
    }
}
Output
We are learning Java!

The if condition looks for the word ‘Python’ in the String variable sentence but couldn’t find it which returns false but due to the NOT operator at the start of the condition, the NOT operator turns the false into true which makes the if statement execute.

Here is the truth table which defines how logical operators execute based on given conditions

XYX AND Y (&&)X OR Y (||)X NOT (!)
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

Assignment Operator (=)

The Assignment Operator is used for assigning a value to a variable. As we have been doing it already again and again and in every code sample. Let’s go through a revisional example of assigning every Data Type we have in Java.

class Equal {

    public static void main(String[] args) {
        
        // Integer
        int integer = 10;
        System.out.println("Integer: " + integer);

        // Character
        char character = 'a';
        System.out.println("Character: " + character);

        // Boolean
        boolean bool = true;
        System.out.println("Boolean: " + bool);

        // Byte
        byte mByte = 20;
        System.out.println("Byte: " + mByte);

        // Short
        short mShort = 30;
        System.out.println("Short: " + mShort);

        // Long
        long mLong = 40;
        System.out.println("Long: " + mLong);

        // Float
        float mFloat = 50;
        System.out.println("Float: " + mFloat);

        // Double
        double mDouble = 60;
        System.out.println("Double: " + mDouble);

    }
    
}
Output
Integer: 10
Character: a
Boolean: true
Byte: 20
Short: 30
Long: 40
Float: 50.0
Double: 60.0

Escape Characters

Escape Characters in Java are very useful for manipulating Strings. Escape Characters start with a backslash and then the character which has a special meaning for the compiler. There are 8 Escape characters in Java and we will cover all of them one by one. Let’s go through the first one.

\t

\t is an Escape Sequence which enters a tab within the string when placed. Here’s how:

class Tab {

    public static void main(String[] args) {
        
        System.out.println("Start \t End");

    }
    
}
Output
Start    End

\b

\b enters a backspace within the String when placed. It removes the character it is placed next to. Here’s how:

class BackSpace {

    public static void main(String[] args) {

        System.out.println("Hih\b!");
        
    }
    
}
Output
Hi!

\n

\n enters a new line within the String when placed. Here’s how:

class NewLine {

    public static void main(String[] args) {
        
        System.out.print("J\nA\nV\nA");

    }
    
}
Output
J
A
V
A

\r

\r inserts a carriage return within the String when placed. Here’s how:

class Carriage {

    public static void main(String[] args) {
        
        System.out.println("JA\rVA");

    }
    
}
Output
VA

\f

\f inserts a formfeed within the String when placed. Here’s how:

class FormFeed {

    public static void main(String[] args) {
        
        System.out.println("Ja\fva");

    }
    
}
Output
Ja
  va

\’

\’ inserts a single quote within the String when placed. Here’s how:

class SingleQuote {

    public static void main(String[] args) {
        
        System.out.println("I am \'Java\'");

    }
    
}
Output
I am 'Java'

\”

\” inserts a double quote within the String when placed. Here’s how:

class DoubleQuote {

    public static void main(String[] args) {
        
        System.out.println("I am \"Java\"");

    }
    
}
Output
I am "Java"

\\

\\ inserts a backslash character within the String when placed. Here’s how:

class Backslash {

    public static void main(String[] args) {

        System.out.println("This is a backslash -> \\");
        
    }
}
Output
This is a backslash -> \

Reserved Keywords in Java

Reserved keywords in Java are words which have a special meaning and a function to perform. They cannot be used as a variable name. Here is a list of reserved keywords in Java:

abstractassertbooleanbreakbytecase
catchcharclassconst*continuedefault
doubledoelseenumextendsfalse
finalfinallyfloatforgoto*if
implementsimportinstanceofintinterfacelong
nativenewnullpackageprivateprotected
publicreturnshortstaticstrictfpsuper
switchsynchronizedthisthrowthrowstransient
truetryvoidvolatilewhile

A challenge to end the basics

Before we wrap everything up. Try working on these challenges to practice Java. Before jumping into the challenges, the best way is to keep track of your journey. Following steps are optional but recommended.

  • Make an account on Github.
  • Create a repository with a name java-basics-app-club.
  • Create a directory for every challenge in the repo.
  • Work on your challenges locally.
  • Using any Git Client, upload your progress to the repo.
  • Mention your repo in the comments.

Link to GitHub repo for this course is available at http://bit.ly/ejpgrac

Challenges
  • Challenge #1 – Build a console-based calculator which performs mathematical operations on two operands.
  • Challenge #2 – Create a decision-based console game which takes input from a user and depending on the input the game proceeds.
  • Challenge #3 – Create a Menu taking Robot which asks the user for what they would like to eat and show prices for the dishes available.

TIP: Break down every step when going through the challenges and if you’re stuck somewhere then Google is your best friend.

Thank you for reading this so long post on Java’s basics. We hope you’ve learned a lot from it and are able to create something wonderful. Let us know in the comments how you liked it and what wasn’t clear to understand. We will be releasing the PDF version soon.