JAVA

Java Online Tutorial

Java – Core

Java is a popular programming language.

Java is used to develop mobile apps, web apps, desktop apps, games and much more.

public class Main {

public static void main(String[] args) {

System.out.println(“Bareilly”);

  }

}

What is Java?

Java is a popular programming language, created in 1995.

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

It is used for:

  • Mobile applications (specially Android apps)
  • Desktop applications
  • Web applications
  • Web servers and application servers
  • Games
  • Database connection
  • And much, much more!

Why Use Java?

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

Java Install

Some PCs might have Java already installed.

To check if you have Java installed on a Windows PC, search in the start bar for Java or type the following in Command Prompt (cmd.exe):

C:\Users\>java –version

Java Syntax

In the previous chapter, we created a Java file called Main.java, and we used the following code to print “Hello World” to the screen:

Main.java

publicclassMain{publicstaticvoidmain(String[]args){System.out.println(“Hello World”);}}

System.out.println()

Inside the main() method, we can use the println() method to print a line of text to the screen:

publicstaticvoidmain(String[]args){System.out.println(“Hello World”);}

Java Comments

Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:

// This is a commentSystem.out.println(“Hello World”);

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:

/* The code below will print the words Hello Worldto the screen, and it is amazing */System.out.println(“Hello World”);

Java Variables

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

  • String – stores text, such as “Hello”. String values are surrounded by double quotes
  • int – stores integers (whole numbers), without decimals, such as 123 or -123
  • float – stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
  • boolean – stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax

typevariableName= value;

Declare Many Variables

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

int x =5;

int y =6;

int z =50;

System.out.println(x + y + z);

You can simply write:

int x =5, y =6, z =50;

System.out.println(x + y + z);

Java Data Types

As explained in the previous chapter, a variable in Java must be a specified data type:

intmyNum=5;// Integer (whole number)

floatmyFloatNum=5.99f;// Floating point number

charmyLetter=’D’;// Character

booleanmyBool=true;// Boolean

StringmyText=”Hello”;// String

Data types are divided into two groups:

  • Primitive data types – includes byte, short, int, long, float, double, boolean and char
  • Non-primitive data types – such as StringArrays and Classes 

Primitive Data Types

A primitive data type specifies the size and type of variable values, and it has no additional methods.

There are eight primitive data types in Java:

Data TypeSizeDescription
byte1 byte

Stores whole numbers from

-128 to 127

short2 bytes

Stores whole numbers from

-32,768 to 32,767

int4 bytes

Stores whole numbers from

-2,147,483,648 to 2,147,483,647

long8 bytes

Stores whole numbers from

-9,223,372,036,854,775,808

to 9,223,372,036,854,775,807

float4 bytes

Stores fractional numbers. Sufficient

for storing 6 to 7 decimal digits

double8 bytes

Stores fractional numbers.

Sufficient for storing 15 decimal digits

boolean1 bitStores true or false values
char2 bytes

Stores a single character/letter or

ASCII values

 

Java Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

public class Main {

public static void main(String[] args) {

int x = 100 + 50;

System.out.println(x);

  }

}

Arithmatic Operator:

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

public class Main {

public static void main(String[] args) {

int sum1 = 100 + 50;

int sum2 = sum1 + 250;

int sum3 = sum2 + sum2;

System.out.println(sum1);

System.out.println(sum2);

System.out.println(sum3); 

  }

}

Java divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators

Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

public class Main {

public static void main(String[] args) {

int x = 10;

    x += 5;

System.out.println(x);

  }

}

Java Comparison Operators

Comparison operators are used to compare two values:

public class Main {

public static void main(String[] args) {

int x = 5;

int y = 3;

System.out.println(x < y); // returns false because 5 is not less than 3

  }

}

Java Logical Operators

Logical operators are used to determine the logic between variables or values:

public class Main {

public static void main(String[] args) {

int x = 5;

System.out.println(x > 3 && x < 10); // returns true because 5 is greater than 3 AND 5 is less than 10

  }

}

public class Main {

public static void main(String[] args) {

int x = 5;

System.out.println(x > 3 || x < 4); // returns true because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)

  }

}

public class Main {

public static void main(String[] args) {

int x = 5;

System.out.println(!(x > 3 && x < 10)); // returns false because ! (not) is used to reverse the result

  }

}

Math.max(x,y)

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

public class Main {

public static void main(String[] args) {

System.out.println(Math.max(5, 10)); 

  }

}

Math.min(x,y)

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

public class Main {

public static void main(String[] args) {

System.out.println(Math.min(5, 10)); 

  }

}

Math.sqrt(x)

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

public class Main {

public static void main(String[] args) {

System.out.println(Math.sqrt(64)); 

  }

}

Math.abs(x)

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

public class Main {

public static void main(String[] args) {

System.out.println(Math.abs(-4.7)); 

  }

}

Random Numbers

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

public class Main {

public static void main(String[] args) {

System.out.println(Math.random()); 

  }

}

Java Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

For this, Java has a boolean data type, which can take the values true or false.

Boolean Values

A boolean type is declared with the boolean keyword and can only take the values true or false:

public class Main {

public static void main(String[] args) {

booleanisJavaFun = true;

booleanisFishTasty = false;   

System.out.println(isJavaFun);

System.out.println(isFishTasty);

  }

}

However, it is more common to return boolean values from boolean expressions, for conditional testing (see below).

Boolean Expression

Boolean expression is a Java expression that returns a Boolean value: true or false.

You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:

public class Main {

public static void main(String[] args) {

int x = 10;

int y = 9;

System.out.println(x > y); // returns true, because 10 is higher than 9 

  }

}

Or even easier:

public class Main {

public static void main(String[] args) {

System.out.println(10 > 9); // returns true, because 10 is higher than 9 

  }

}

 

The if Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.

Syntax

if(condition){// block of code to be executed if the condition is true}

 

public class Main {

public static void main(String[] args) {

if (20 > 18) {

System.out.println(“20 is greater than 18”); // obviously

    } 

  }

}

 

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if(condition){// block of code to be executed if the condition is true}else{// block of code to be executed if the condition is false}

public class Main {

public static void main(String[] args) {

int time = 20;

if (time < 18) {

System.out.println(“Good day.”);

    } else {

System.out.println(“Good evening.”);

    } 

  }

}

 

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

if(condition1){

// block of code to be executed if condition1 is true

}elseif(condition2){

// block of code to be executed if the condition1 is false and condition2 is true

}else{

// block of code to be executed if the condition1 is false and condition2 is false

}

 

public class Main {

public static void main(String[] args) {

int time = 22;

if (time < 10) {

System.out.println(“Good morning.”);

    } else if (time < 20) {

System.out.println(“Good day.”);

}  else {

System.out.println(“Good evening.”);

    }

  }

}

 

Short Hand If…Else

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

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

Syntax

variable=(condition)?expressionTrue:expressionFalse;

 

public class Main {

public static void main(String[] args) {

int time = 20;

if (time < 18) {

System.out.println(“Good day.”);

    } else {

System.out.println(“Good evening.”);

    } 

  }

}

Java Switch Statements

Instead of writing many if..else statements, you can use the switch statement.

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

Syntax

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

 

public class Main {

public static void main(String[] args) {

int day = 4;

switch (day) {

case 1:

System.out.println(“Monday”);

break;

case 2:

System.out.println(“Tuesday”);

break;

case 3:

System.out.println(“Wednesday”);

break;

case 4:

System.out.println(“Thursday”);

break;

case 5:

System.out.println(“Friday”);

break;

case 6:

System.out.println(“Saturday”);

break;

case 7:

System.out.println(“Sunday”);

break;

    }

  }

}

Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

Java While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax

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

 

public class Main {

public static void main(String[] args) {

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.

Syntax

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

 

public class Main {

public static void main(String[] args) {

int i = 0;

do {

System.out.println(i);

i++;

    }

while (i < 5); 

  }

}

Java For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Syntax

for(statement 1; statement 2; statement 3){// code block to be executed}

 

public class Main {

public static void main(String[] args) {

for (int i = 0; i < 5; i++) {

System.out.println(i);

    } 

  }

}

For-Each Loop

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

Syntax

for(typevariableName:arrayName){// code block to be executed

public class Main {

public static void main(String[] args) {

String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};

for (String i : cars) {

System.out.println(i);

    }   

  }

}

Java Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to “jump out” of a switch statement.

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

public class Main {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

      }

System.out.println(i);

    } 

  }

}

Java Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

public class Main {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {

if (i == 4) {

continue;

      }

System.out.println(i);

    } 

  }

}

Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

 

String[] cars ={“Volvo”,”BMW”,”Ford”,”Mazda”};

 

int[]myNum={10,20,30,40};

 

Access the Elements of an Array

You can access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

public class Main {

public static void main(String[] args) {

String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};

System.out.println(cars[0]);

  }

}

Change an Array Element

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

cars[0]=”Opel”;

 

public class Main {

public static void main(String[] args) {

String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};

cars[0] = “Opel”;

System.out.println(cars[0]);

  }

}

Array Length

To find out how many elements an array has, use the length property:

public class Main {

public static void main(String[] args) {

String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};

System.out.println(cars.length);

  }

}

Java Methods

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:

Example

Create a method inside Main:

publicclassMain{staticvoidmyMethod(){// code to be executed}

}

Call a Method

To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when it is called:

Example

Inside main, call the myMethod() method:

public class Main {

static void myMethod() {

System.out.println(“I just got executed!”);

  }

 

public static void main(String[] args) {

myMethod();

  }

}

A method can also be called multiple times:

public class Main {

static void myMethod() {

System.out.println(“I just got executed!”);

  }

 

public static void main(String[] args) {

myMethod();

myMethod();

myMethod();

  }

}

Java Scope

In Java, variables are only accessible inside the region they are created. This is called scope.

Method Scope

Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:

public class Main {

public static void main(String[] args) {

 

    // Code here cannot use x

 

int x = 100;

 

    // Code here can use x

System.out.println(x);

  }

}

Java Recursion

Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.

public class Main {

public static void main(String[] args) {

int result = sum(10);

System.out.println(result);

  }

public static int sum(int k) {

if (k > 0) {

return k + sum(k – 1);

    } else {

return 0;

    }

  }

}

Java – What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the Java code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time

Tip: The “Don’t Repeat Yourself” (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.

Java Classes/Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a “blueprint” for creating objects.

Create a Class

To create a class, use the keyword class:

publicclassMain{

int x =5;

}

Create an Object

In Java, an object is created from a class. We have already created the class named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object name, and use the keyword new:

public class Main {

int x = 5;

 

public static void main(String[] args) {

    Main myObj = new Main();

System.out.println(myObj.x);

  }

}

Multiple Objects

You can create multiple objects of one class:

public class Main {

int x = 5;

 

public static void main(String[] args) {

    Main myObj1 = new Main();

    Main myObj2 = new Main();

System.out.println(myObj1.x);

System.out.println(myObj2.x);

  }

}

Java Class Attributes

In the previous chapter, we used the term “variable” for x in the example (as shown below). It is actually an attribute of the class. Or you could say that class attributes are variables within a class:

Example

Create a class called “Main” with two attributes: x and y:

publicclassMain{

int x =5;

int y =3;

}

Accessing Attributes

You can access attributes by creating an object of the class, and by using the dot syntax (.):

The following example will create an object of the Main class, with the name myObj. We use the x attribute on the object to print its value:

public class Main {

int x = 5;

 

public static void main(String[] args) {

    Main myObj = new Main();

System.out.println(myObj.x);

  }

}

Modify Attributes

You can also modify attribute values:

public class Main {

int x;

 

public static void main(String[] args) {

    Main myObj = new Main();

myObj.x = 40;

System.out.println(myObj.x);

  }

}

Modifiers

By now, you are quite familiar with the public keyword that appears in almost all of our examples:

publicclassMain

The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors.

We divide modifiers into two groups:

  • Access Modifiers – controls the access level
  • Non-Access Modifiers – do not control access level, but provides other functionality
ModifierDescriptionTry it
publicThe code is accessible for all classesTry it »
privateThe code is only accessible within the declared classTry it »
default

The code is only accessible in the same package.

This is used when you don’t specify a modifier.

You will learn more about packages in the Packages chapter

Try it »
protected

The code is accessible in the same package and subclasses.

You will learn more about subclasses and superclasses.

 

Non-Access Modifiers

For classes, you can use either final or abstract:

ModifierDescriptionTry it
final

The class cannot be inherited by other classes

(You will learn more about inheritance in the Inheritance chapter)

Try it »
abstract

The class cannot be used to create objects

(To access an abstract class, it must be inherited from another class.

You will learn more about inheritance and abstraction in the 

Inheritance and Abstraction chapters)

 

Encapsulation

The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users. To achieve this, you must:

  • declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable

Get and Set

You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:

Example

publicclassPerson{privateString name;// private = restricted access // GetterpublicStringgetName(){return name;} // SetterpublicvoidsetName(StringnewName){this.name =newName;}}  

Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable. The this keyword is used to refer to the current object.

publicclassMain{

publicstaticvoidmain(String[]args){

PersonmyObj=newPerson();

myObj.setName(“John”);

System.out.println(myObj.getName());

}

}

Java Packages & API

A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:

  • Built-in Packages (packages from the Java API)
  • User-defined Packages (create your own packages)

Built-in Packages

The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.

The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:

Syntax

importpackage.name.Class;// Import a single classimportpackage.name.*;// Import the whole package

Import a Class

If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:

Example

importjava.util.Scanner;

importjava.util.Scanner;// import the Scanner class

 

classMain{

publicstaticvoidmain(String[]args){

ScannermyObj=newScanner(System.in);

StringuserName;

 

// Enter username and press Enter

System.out.println(“Enter username”);

userName=myObj.nextLine();

 

System.out.println(“Username is: “+userName);

}

}

Java Polymorphism

Polymorphism means “many forms”, and it occurs when we have many classes that are related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds – And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):

class Animal {

public void animalSound() {

System.out.println(“The animal makes a sound”);

  }

}

 

class Pig extends Animal {

public void animalSound() {

System.out.println(“The pig says: wee wee”);

  }

}

 

class Dog extends Animal {

public void animalSound() {

System.out.println(“The dog says: bow wow”);

  }

}

 

class Main {

public static void main(String[] args) {

    Animal myAnimal = new Animal();

    Animal myPig = new Pig();

    Animal myDog = new Dog();

 

myAnimal.animalSound();

myPig.animalSound();

myDog.animalSound();

  }

}

Abstract Classes and Methods

Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter).

The abstract keyword is a non-access modifier, used for classes and methods:

  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

 

  • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).

An abstract class can have both abstract and regular methods:

abstractclassAnimal{publicabstractvoidanimalSound();publicvoidsleep(){System.out.println(“Zzz”);}}

// Abstract class

abstract class Animal {

  // Abstract method (does not have a body)

public abstract void animalSound();

  // Regular method

public void sleep() {

System.out.println(“Zzz”);

  }

}

 

// Subclass (inherit from Animal)

class Pig extends Animal {

public void animalSound() {

    // The body of animalSound() is provided here

System.out.println(“The pig says: wee wee”);

  }

}

 

class Main {

public static void main(String[] args) {

    Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

  }

}

Java User Input

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:

importjava.util.Scanner;// import the Scanner class

 

classMain{

publicstaticvoidmain(String[]args){

ScannermyObj=newScanner(System.in);

StringuserName;

 

// Enter username and press Enter

System.out.println(“Enter username”);

userName=myObj.nextLine();

 

System.out.println(“Username is: “+userName);

}

}

Java Exceptions

When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).

Java try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

public class Main {

public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

    } catch (Exception e) {

System.out.println(“Something went wrong.”);

    } finally {

System.out.println(“The ‘try catch’ is finished.”);

    }

  }

}