Java Tutorial

Java Tutorial – A Guide for Beginners

Welcome to Java Tutorial for Selenium Testers / Software Testers. This Java Tutorial is mainly written for the Beginners who wants to learn Java and also for the Selenium testers who are learning Java. It helps everyone who wants to learn core java from the beginning. Any beginner can follow this tutorial very easily and learn core java programming.

Java Introduction:

Let’s see a brief introduction to Java. Java is a high-level programming language originally developed by Sun Microsystems in 1995. Java is a platform independent language. Yes, it runs on a multiple platforms such as UNIX, Windows, Mac OS. The Java language’s programming is based on the concept of OOP. We will see this in detail in later part of this Java Tutorial.


We need to understand three terminologies for sure in Java such as JDK, JRE and JVM. Here I give basic idea about these terms in the next post we will see detailed explanation.

What is JDK?

JDK stands for Java Development Kit.
Using JDK, we can develop, compile and execute (run) new applications and also we can modify existing applications. We need to install JDK in developers machine where we want to develop new applications or modify existing applications.
JDK includes JRE and development tools (environment to develop, debug and monitor Java programs).

What is JRE?

JRE stands for Java Runtime Environment.
Using JRE, we can only execute already developed applications. We cannot develop new applications or modify existing applications.
As the name suggests, JRE only provides Runtime Environment.

What is JVM?

JVM stands for Java Virtual Machine. JVM drives the java code. Using JVM, we can run java byte code by converting them into current OS machine language.

Java Environment Setup:

Download and Install JAVA

Go to the below mentioned link and download the latest version of JAVA

Accept the license agreement and choose the right ‘JDK’ file to download based on your system requirement.

Once downloaded. Go ahead and verify the Java version. To do this, open command prompt and type “java -version” and hit enter

Java Syntax:

1. Java is a case sensitive language
Ex: NAME and name are not same as per Java Language
2. Java file name should be same as its Class name
3. Class name should start with upper case letter
4. Method name should start with lower case letter
5. Every statement should end with semi colon
6. Java program execution starts from main method which is mandatory in every program

In Java, we use print to output required text directly to the console of IDE


Simple print statement:

Simple print statement with new line:

Check this link to read more on Print in Java

User Input In Java:

Sometimes, we may face a situation where we need to get the input from the user in runtime. We use “Scanner” class to accept input from the user.


User Input in Java with sample programs

Comments in Java:

In Java, we have two types of comments. We use comments to write some text within our code. Compiler will ignore these comments.


Note: Comments in between the code gives more readability

Do you want to show auto generated code whenever you create a new class as shown below.

Follow the below steps:

I assume, you are using Eclipse IDE.

1. In eclipse, Go to Window – Preferences
2. From the left panel, Select Java – Code style – Code template
3. Under ‘Configure generated code and comments’, Expand Comments – Select Files and Click Edit and Enter your text and Click OK.

Whenever you create a new class, you can see comments.

Read From File:

To read a text file, we use FileReader and wrap it in a BufferedReader.

In the below example, we read a file named “FileToRead.txt” which is located in my local system and output the file line by line in my eclipse console.

Sample program on Read From File in Java

Write To File:

To create a new file and write text on it. We can write to a file using Java in different ways but I show you how to write text to a file using BufferedWriter.

Sample program on Write To File in Java

Variables In Java:

In Java, variable is a name given to a memory location and this variable is associated with a value.

int x = 99;

int – data type
x – variable
99 – value

variable x holds integer values and its current value is 99.

Let’s see how to declare variables in Java

Syntax to declare a variable in Java:

data_type variable = value;


int x = 99;

Variable Naming Convention in Java:

Earlier we have learnt that Java is a Case Sensitive Language. Even variables have their own naming convention to follow.

1. Variable name can starts with special characters such as _ or $


int $myAge;

2. Variable name should begin with lower case leter


Wrong way: int Age;
Correct way: int age;

3. If the variable name consists of more than one word, it’s a best practice to capitalize the first letter of each subsequent word.


Wrong way: int myage;
Correct way: int myAge;

4. Variable name should not contain white spaces


Wrong way: int my Age;
Correct way: int myAge;

Types of Variables in Java:

There are three types of variables in Java.

1. Local variable
2. Instance variable
3. Class/Static variable

Read more on Variables in Java with Sample programs

Data Types in Java:

Data types in java specify the size and type of values that can be stored in an identifier. There are two types of Data Types in Java.

1. Primitive Data Type
2. Non-primitive Data Type

Primitive Data Type:

There are 8 primitive data types such as byte, short, int, long, float, double, char, and boolean. Size of these 8 primitive data types wont change from one OS to other.

byte, short, int & long – stores whole numbers
float, double – stores fractional numbers
char – stores characters
boolean – stores true or false

Non-primitive Data Type:

Non-primitive data types include Classes, Interfaces and Arrays which we will learn in coming tutorials.

Sample program on Data Types in Java

Operators In Java:

Operators in Java are the special symbols that perform specific operations and then return a result.

Types of Operators in Java are

1. Arithmetic Operators (+*/%)
2. Assignment Operators (=+=-=*=/=%=)
3. Auto-increment Operator and Auto-decrement Operators (++)
4. Logical Operators (&&||!)
5. Comparison (relational) Operators (==!=><>=<=)
6. Bitwise Operators (&|^~<<>>)
7. Ternary Operator

Sample programs on Operators in Java

Control Flow Statements:

Following image shows you the subdivisions of Control Flow Statements in Java.


Conditional Statements:

Let’s see the following conditional statements

1. if statement
2. nested if statement
3. if-else statement
4. if-else-if statement
5. Switch Case Statement

if statement:

The if statement is the most basic of all the control flow statements. The if statement tells our program to execute a certain section of code only if a particular test evaluates to true.

Nested if statement:

An if statement inside another the statement. If the outer if condition is true then the section of code under outer if condition would execute and it goes to the inner if

The for statement in Java allows us to repeatedly loops until a particular condition is satisfied.


Detailed explanation on For Loop with sample program

Enhanced For Loop:

The Enhanced For Loop is designed for iteration through Collections and Arrays. This enhanced for loop makes our loops more compact and easy to read.


Enhanced For Loop with a sample program

While Loop:

The while statement continually executes a block of statements while a particular condition is true.


If the expression of while statement evaluates to true, then it executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

While Loop with Sample Program

Do While Loop:

The do-while is similar to the while loop. In do-while loop, the condition is evaluated after the execution of statements with in the do block at least once.

Do While Loop with Sample Program

Continue Statement:

The Continue Statement in Java is used to continue loop. It is widely used inside loops. Whenever the continue statement is encountered inside a loop, control immediately jumps to the beginning of the loop for next iteration by skipping the execution of statements inside the body of loop for the current iteration.



Continue Statement in Java with Sample Program

Break Statement:

The Break statement in Java is used to break a loop statement or switch statement. The Break statement breaks the current flow at a specified condition.

Note: In case of inner loop, it breaks just the inner loop.



Break Statement with Sample Program

OOPS Concept:

OOPS Stands for Object Oriented Programming System. In this tutorial, I will introduce you to Class, Object, Constructor, Abstraction, Encapsulation, Inheritance, Polymorphism, Interface etc.,


A class is a blueprint or prototype from which objects are created. A class contains variables (data types) and methods (functions) to describe the behavior of an object.


Object is a software bundle of related state and behavior. Objects have two characteristics namely state and behavior.

We can also say, Object is an entity that has state and behavior.

State: It represents value (data types/variables) of an object
Behavior: It represents the functionality (methods) of an object

Object is an instance of a class.



State: Maker, Model, Color etc.,
Behavior: Turn on, Turn off etc.,

To understand what is a class and object in detail, let me give you a basic example related to a computer. Computer with Model and Price.

Assume, you have two computers of Apple and Lenovo. Now say the model of Apple is MacBook Pro and the model of Lenovo is Yoga. The price of Apple is $299 and the price of Lenovo is $99.

Computer is a class which has two attributes namely Model and Price. Apple and Lenovo are the objects of the class Computer.

Let’s see how to create an object:

Compter laptop = new Computer();

Class: Computer
Reference: laptop
Keyword: new
Constructor: Computer()
Object: new Computer()

Computer is a class name followed by the name of the reference laptop. Then there is a “new” keyword which is used to allocate memory. Finally, there is a call to constructor “Computer()”. This call initializes the new object “new Computer()”.

We create an Object by invoking the constructor of a class with the new keyword.

I hope, now you got to know how to create an object


Earlier we have seen Object is an entity which has both state and behavior. Here we are going to discuss about behavior of an Object. Method describes the behavior of an Object. A method consists of collection of statements which performs an action.

Methods are also known as procedures or functions

Let’s see an example of a method declaration.

Every method declaration must have return type of the method, a pair of parenthesis, and a body between braces

In general, method consists of 6 components.

Modifiers: private, public, and others
Return Type: The data type of the value returned by the method, or void if the method doesn’t return a value.
Method Name: Name of the method.
Built in methods are standard such as System.out.println();
User defined methods accept any names which a developer assigns.
Parameters inside parenthesis: list of parameters preceded by their data types and separated with a comma. If no parameters then you must specify an empty parenthesis.
Exception: Exceptions depends on the operation of the method
Method Body: Method body should be enclosed between braces

The signature of the above declared method is

Int sum(int a, int b, int c)

A method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.

Let’s see how to call methods using an object.

Hope you have heard a phrase “Instantiating a class”. The phrase “Instantiating a class” means the same thing as “Creating an Object” which we did in the above program. Whenever you create an Object, it means you are creating an instance of a class, therefore “instantiating a class”.

Methods are of two types

1. Built-in methods or Pre-defined methods: Methods such as String methods, Date & Time methods, etc.,
2. User Defined methods: It contains ‘method with returning value’ and ‘method without returning any value’


In Java, there are two types of modifiers in Java

1. Access Modifiers: Access modifiers are subdivided into four types such as Default, Public, Private, Protected
2. Non-access Modifiers: Non-access modifiers are subdivided into four types such as Static, Final, Abstract, Synchronized

Access Modifiers:

default: The scope of default access modifier is limited to the package only. If we do not mention any access modifier, then it acts like a default access modifier.

private: The scope of private access modifier is only within the classes.

Note: Class or Interface cannot be declared as private

protected: The scope of protected access modifier is within a package and also outside the package through inheritance only.

Note: Class cannot be declared as protected

public: The scope of public access modifier is everywhere. It has no restrictions. Data members, methods and classes that declared public can be accessed from anywhere.

See this simple table to understand access modifiers easily

Access Modifiers in Java with Sample Programs


Constructor in Java is used in the creation of an Object that is an instance of a Class. Constructor name should be same as class name. It looks like a method but its not a method. It wont return any value. We have seen that methods may return a value. If there is no constructor in a class, then compiler automatically creates a default constructor.


Inheritance is a process where one class inherits the properties of another class.

Let’s say we have two classes namely Parent Class and Child Class. Child class is also known as Derived Class. As per the above definition, the Child class inherits the properties of the Parent Class. The main purpose of Inheritance is Code Reusability.

Assume we have a Class named Laptop, Apple MacBook Pro, Lenovo Yoga. Apple MacBook Pro and Lenovo Yoga classes extend the Laptop Class to inherit the properties of the Laptop Class.

We will see detailed explanation with some example programs about Inheritance in the post related to Inheritance.


Polymorphism allows us to perform a task in multiple ways. Let’s break the word Polymorphism and see it, ‘Poly’ means ‘Many’ and ‘Morphos’ means ‘Shapes’.

Let’s see an example. Assume we have four students and we asked them to draw a shape. All the four may draw different shapes like Circle, Triangle, and Rectangle, .

We will see detailed explanation with some example programs about Polymorphism in the post related to Polymorphism.

There are two types of Polymorphism in Java

1. Compile time polymorphism (Static binding) – Method overloading
2. Runtime polymorphism (Dynamic binding) – Method overriding

We can perform polymorphism by ‘Method Overloading’ and ‘Method Overriding’

Method Overloading:

A class having multiple methods with same name but different parameters is called Method Overloading

There are three ways to overload a method.

1. Parameters with different data types
2. Parameters with different sequence of a data types
3. Different number of parameters

Earlier we have seen method signature. At compile time, Java knows which method to invoke by checking the method signatures. So this is called compile time polymorphism or static binding.

Method Overriding:

Declaring a method in child class which is already present in the parent class is called Method Overriding.

In simple words, overriding means to override the functionality of an existing method.

In this case, if we call the method with child class object, then the child class method is called. To call the parent class method we have to use super keyword.


Abstraction is the methodology of hiding the implementation of internal details and showing the functionality to the users.

Example: Mobile Phone.

A layman who is using mobile phone doesn’t know how it works internally but he can make phone calls.

Abstraction in Java is achieved using abstract classes and interfaces. Let’s see what is Abstract Class and Interface in detail.

Abstract Class:

We can easily identify whether a class is an abstract class or not. A class which contains abstract keyword in its declaration then it is an Abstract Class.


Points to remember:

1. Abstract classes may or may not include abstract methods
2. If a class is declared abstract then it cannot be instantiated.
3. If a class has abstract method then we have to declare the class as abstract class
4. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

Abstract Method:

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

In order to use an abstract method, you need to override that method in sub class.

Check this link to learn more on Abstraction

Interface in Java:

An interface in Java looks similar to a class but both the interface and class are two different concepts. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract. We can achieve 100% abstraction and multiple inheritance in Java with Interface.

Points to remember:

1. Java interface represents IS-A relationship similar to Inheritance
2. Interface cannot be instantiated same like abstract class
3. Java compiler adds public and abstract keywords before the interface methods
4. Java compiler adds public, static and final keywords before data members
5. Interface extends another interface just like a Class extends another Class but a class implements an interface.
6. The class that implements interface must implement all the methods of that interface.
7. Java allows you to implement more than one interface in a Class

Check this link to learn more on Interface in Java


Encapsulation is a mechanism of binding code and data together in a single unit. Let’s take an example of Capsule. Different powdered or liquid medicines are encapsulated inside a capsule. Likewise in encapsulation, all the methods and variables are wrapped together in a single class.

We will see detailed explanation with some example programs about Encapsulation in the post related to Encapsulation.

Arrays in Java:

Collection of similar type of elements is known as Array. Array in Java is an Object that holds fixed number of values of a similar data types which means an array of int will contain only integers, an array of string will contain only strings etc.. The length of an array is established when the array is created. After creation, its length is fixed. Array is a index based and its index starts from 0 which means the first element of an array is stored at 0 index. Array holds primitive types as well as object references.



ArrayList in Java:

Using ArrayList we can overcome the size issue. ArrayList is a resizable array.

ArrayList Class implements List interface. ArrayList allows duplicate elements (remember that Set in Java wont allow duplicate values. We will see Set in later sections)

How To Convert Array to ArrayList:

Collections Framework in Java:

Collections Framework was introduced in Java 1.2 . The Java collections framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures. Collection framework has many different interfaces and classes. Each and every interface and class has different purpose. We can perform add, edit, delete etc., operations on group of objects as per methods and implementation of a class.

Map in Java:

Java Map is a part of collections framework. The Map interface is based on key value pair. It maps unique keys to values. The Map interface is not a subtype of the Collection interface. The Map interface acts similar to Collections but a bit different from the rest of the collection types. It can’t contain duplicate keys however duplicate values are allowed.

LinkedList in Java:

LinkedList is a class in the Collection Framework. LinkedList class implements List and Deque interfaces. LinkedList class extends AbstractList class. Lets see some key points on LinkedList.

  • LinkedList class can hold duplicate elements in list.
  • LinkedList is used to create an empty linked list.
  • LinkedList class maintains insertion order.
  • LinkedList class is non synchronized.
  • In LinkedList class, manipulation is fast because shifting is not required when new element is inserted or deleted from the list.

Exception Handling:

The Java programming language uses exceptions to handle errors and other exceptional events.

What is an Exception:

An exception is an event that interrupts the normal flow of the program’s instructions. Exceptions occur during the execution of a program and terminates the program. As mentioned earlier, the Java language uses exceptions to handle errors and other exceptional events.

The main purpose of exception handling is to continue the flow of the program.

Types of Exceptions:

There are two types of exceptions:

1. Checked Exceptions
2. Unchecked Exceptions

WhatsApp us