Java Tutorial
I assume that you know the history of Java and its characteristics. But still, I would quickly run you through its features so that you don’t get stuck in the middle. Before that be updated that Java is not an acronym and is just a name and If you want to learn java directly visit our Java Training.


Java Tutorial : Features of Java


  • Platform independent: Write once run anywhere is the core concept of Java. It is an excellent choice for applications that need to be run on various platforms. The Java Runtime Environment is what it takes to run anywhere.
  • High scalability : Java provides excellent scalability by letting developers develop applications ranging from mobile apps to large-scale industrial apps.
  • Versatility : Java is ideal for developing apps for every device, mobile phones, etc. Several OSes may apply different JVMs, but the code across all of them is still mainly Java.
  • Simplicity : Java has less confusing syntax terminology. You can quickly grasp Java with the fundamental principles of programming. And that’s precisely my role here in making you understand the terminologies of Java.
  • Security : Java is considered to be highly secure. This can be attributed to its compiler, which is believed to catch more run time errors.
  • Object-oriented : Everything is an object in Java, and thus, it can be easily extended.
  • Architecture Neutral : Java does not build its object code; instead, it builds byte code and then converts it into object code as per various architecture of the machine.
  • Multithreaded : You can write programs that can carry out several tasks simultaneously. Besides, the multithreaded feature lets the developers build interactive applications that can run smoothly.

Robust: Java is robust because it is portable across several operating systems. It also consists of garbage collection and automatic memory management.


Now that you would be having a fair idea about the features of Java, aren’t you interested in knowing how to write your first code in Java? Well, it is nothing but the simple Hello World program. Now let’s see how to write it. I will write and later explain the inherent concepts.


//the evergreen Hello World Program!

Class HelloWorld


public static void main ( String[]  args)


System.out.println(Hello World”);




Tip: We follow the habit of copying the program and then pasting it in our text editor. However, avoid doing so. It’s always suggested to write the code by yourself so that you get a grasp of it quickly. Even if you make mistakes don’t worry! Each mistake will give you more confidence as a programmer. You won’t commit that mistake again since you would have made it a point not to do so.


Now that we have written our first code in Java, we have to understand one important concept. This is nothing but object-oriented programming. Java is 99.99% object-oriented programming language. Well, this is the argument of some experts.


The biggest misconception is that Java is a 100% object-oriented language, but wait. I have to give you a clear explanation. When you compare Java with earlier languages like C++, it offers a more object-oriented environment. So considering this, one will have a misunderstanding that Java is a pure object-oriented language.


Well, now you would be curious to know what is that makes Java a 99% object-oriented language? Follow the points below:

  • Java does not consist of some object-oriented features:
  • Java doesn’t support multiple inheritances.
  • Java supports primitive data types including int, byte, long, etc. which don’t belong to the object type. Well, let’s look at these points at the end of this module:


There are seven aspects to be fulfilled for a programming language to be pure Object Oriented. They are:

  • Encapsulation
  • Polymorphism
  • Abstraction
  • Inheritance


All predefined types are objects. Al operations carried out by communicating with objects.If you go through these qualities thoroughly, Java fulfills most of them. Yes, Java supports encapsulation at package and class level. It also supports inheritance (although not directly), polymorphism, and abstraction. Now let’s come to the real difference. All primitive types are not objects in Java.  You can define primitive types (which are pre-defined in the language) in Java. So, the last point is also not valid here. Now go through the two points mentioned in the beginning of this module.


Java Tutorial: Java Basic Language Constructs



Now before going into the technical definition, let’s understand the definition of a variable. Now the words “liable to change” would inevitably cross your mind. Yes, variables in Java are liable to change. These variables are the specific identifiers of the memory location, which is applied to save data temporarily for later application in the program. When the program is executed, values can be stored in this container, and the stored can be later changed. As far as Java programming is concerned, you should declare the variable before being used.


Java Tutorial: Declaration of variables in Java


When you are declaring a variable in Java, you are dealing with the type of data it will store. Variables show named storage location, whose value can be changed at the time of program execution.


The syntax of the variable is:


type variable_name

type variable_name, variable_name;

Type is basically the data type here, and the name is the unique name given to the variable.

Example: int p, q, r;

double f;

char b;

Java Tutorial: Variable initialization

For initializing a variable, you must first assign it a specific valid value:




Now that we have  both declared and initialized the variable, we can combine these two:

int p=2, q=4, r=6;

char b-‘v’;

Java Tutorial: Types of variables

Firstly it is the Local variables

Instance variables

Static or class variables (should include some more before class and objects)


Java Tutorial: Scope of variables


When you tell scope of a variable, it refers to the location in the program where the scope is accessible. In other words, it defines the part of the code in which the variable is seen. When you define a variable within a block, it is not accessible outside the scope of the block. In Java, the scope rules come under the following categories:


Class Scope


If the variable is declared inside of a class’s bracket with the private access modifier, however outside of any method, then it has class scope. You can use these variables anywhere in the class. But you cannot use outside of it.


Method Scope


A variable declared inside a method has method scope. Remember that it will be valid within the scope of the same method.


Loop Scope


As explicit from the name, if you declare a variable inside a loop, it will consist of a loop scope and will be present only inside the loop.


Bracket Scope


Extra scopes can be defined anywhere using brackets


Java Tutorial: Java Class Structure


Well, it’s not possible to form a Java application without creating a class. These classes consists of a specific structure. Just take into the consideration the blueprint of a building. They have certain characteristics right? In the same way, the classes you create also have some predefined formats. Then how come the Java Runtime Compiler interprets your design and applies the classes to form objects within an application?


Java tutorial: main method


Now let’s talk about the main method. This is essential to begin your code execution. Keep in mind that the Java compiler doesn’t comprehend anything other than Main method. Once the compiler gets the main method, it begins execution. If you don’t write this important main method then your code will never be compiled and thus throws Exception:

  1. You can call other functions from the main method to execute them.
  2. Once you understand the importance of main method, you should also understand the significance of the main method syntax:
  3. One valid syntax of main method in Java is: public static void main (String[] args)

Java Tutorial: Java packages


As explicit from the name, a Java package is group of classes, interfaces and other packages. The usage of packages in Java is to organize the classes and interfaces. While there are built-in packages in Java there are also packages that we create. The second type of packages is also known as user-defined package.

Give examples of user-defined package and built-in package.


Java Tutorials: Java Data Types


  • Data types point the different sizes and values that can be stored in the variable, The two types of variables in Java are:
  • Primitive data types: char, byte, int, long, float, boolean, short, and double.
  • The Boolean data type is for storing only two values: true or false. Eg. Boolean one = true
  • Byte- the value range is between -128 to 127.  The default size is 1 byte.
  • short- Its value is between -32,768 to 32,767. The default size is 2 byte.
  • int- Applied when short is not huge enough to hold the number. Its range is 2,147,483,648 to 2,147,483,647. Its default size is 4 byte.
  • long: Applied when int is not huge enough to hold the value. Is range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
  • float: Adequate for holding 6 to 7 decimal digits
  • Its default size is 4 bytes.
  • Double: Adequate for holding 14 decimal digits
  • It default size is 8 bytes.


Give Examples for these


This is custom heading element

  • Non-primitive data types are built by the programmer at the time of coding process. They are called the reference variables or object variables.
  • The non-primitive data type can be classified as array, class, object, string, interface etc.
  • A string is a sequence of characters. For eg. “Welcome” is a string of 7 characters. A string cannot be changed once it has formed.
  • Objects and arrays are also non-primitive data types since they refer to the memory location.

Java Tutorial: Java Class and objects


Now, let us take the example of the beautiful house that you are planning to build. A class can be defined as the sketch of this beautiful house. It comprises all the details regarding the floors, panels, windows, etc. These descriptions pave the way to the building of the house. So what is the house? You, you got it right! It is the object.

Create a class named “FirstClass” with a variable x:

public class FirstClass {

int x = 7;


An object is formed from a class in Java. Revisit your creation of class just now. Now we can easily create objects.

Now specify the class name, followed by the object name. Now there is a new object formed, right? So give the keyword new.

Public class FirstClass {

int x=7;

public static void main string[] args) {

FirstClass firstObj=new FirstClass();





Java Tutorial: Interfaces


Interface has similarity with class such that it can have methods and variables. But, the methods declared in interface are abstract by default.

For declaring an interface, make use of interface keyword. It is applied to offer total abstraction. This implies that all the methods in interface are declared with empty body and are public. Besides, all fields are public, static and final by default. For implementing interface apply inter



interface <interface name>


– variable declaration with initilization.

– method declaration.(un defined method)



interface Demo


String file=”balaji”;

void check();


Face Keyword:

The highlight of interface is that you can accomplish multiple inheritance by using interface. The key is that Java doesn’t support multiple inheritance with regard to class.


abstract class <class name>


defined method( if required);

un-defined method (if required);



abstract class Demo


abstract void initial();

int detail(int s)



return s;




An abstract class cannot be instantiated since it does not contain the appropriate defined methods similar to a regular class. The necessity of abstract class is when you force the subclass to extend the supeclass. These incomplete classes cannot be applies as they are, but they can be subclassed. Abstract classes cannot be applied directly. Sometimes, you may consider an abstract class as useless. But the main advantage of abstract class is that you can make the best use of polymorphism and inheritance. As far as flexibility is concerned, abstraction takes up a significant role.

The key point to remember in abstract class is that  it is not a complete class in Java. You have to extend abstract class to make use of that class.

Java Tutorial: Insight into the Final Keyword in Java

Sometimes we take the English word for granted when analyzing meaning for Java names. For example, variable, operators, packages, etc. However, concerning final, it is not final in Java.

  • Final classes: These classes cannot be extended.
  • Final methods: These methods cannot be overridden.
  • Final variables: These variables cannot be reassigned
  • Final field: this field is a constant
Java Tutorial: Operators

We know variables in Java. Now let’s see about operators. Operators do operations on variables and values. The value is termed as operand.

For Eg: int p = 200 / 40;

The numbers 200 and 40 are operands and the sign / is an operator.
The operators in Java are divided based on the functionality they offer. They are:


Arithmetic Operators

These operators have the role of performing simple arithmetic operations on primitive data types

+ : Addition
 : Subtraction
* : Multiplication
/ : Division
% : Modulo


Assignment Operators


Assignment operators are applied to assign a value to any variable. It has a right to left connectivity. The value provided on right side of operator is assigned to the value to the variable on the left side. So you have to declare the value on right hand side before applying it. Otherwise it should be constant. The highlight of assignment operators is that in several instances it can be combined with other operators to develop a brief version.

Give example of compound statement


Relational Operators

These operators are applied to check for relations including equality, less than, greater than. They result boolean outcome following the comparison and are widely applied in looping statements and conditional if else statements. We will study about these two statements shortly.


Unary Operators

As the name implies these operators require only one operand. They can either increment, decrement or negate a value.

Ternary Operators

These operators assess a boolean expression and assign the value depending on the result.

Logical Operators

These operators are used along with binary variables. They are chiefly applied in conditional statements and loops for assessing a condition. &&, ||, ! are logical operators in Java.

Bitwise Operators

These operators are applied to carry out operations on single bitwise values. They can be used along with any of the integer types. Six bitwise operators are available in Java: &, |, ^, ~, <<, >>

Shift Operators

You can shift the bits of a number left or right thus multiplying the number by two. The shift operator can be left shift operator, right shift operator, and unsigned right shift operator,

Java Tutorial: Case-sensitivity in Java

The upper and lower case of letters in Java programs count a lot. For example, you have formed the variables named myNum and mynum. These variables may have been composed of the same letters that too in the same order. However, Java does not regard them as equal.

Java Tutorial: Java Virtual Machine

Well you would be familiar with the “Write once, run anywhere” principle of Java. This is where the role of Java Virtual Machine comes. It lets Java programs to run on an operating system. Besides, it goes a step further and controls and optimizes program memory. At the time of introduction of Java, all computer programs were coded to a particular operating system. The program memory was controlled by the software developer. Hence the JVM came as a relief.


Decision Constructs

Decision making is an important thing in real life. In programming also it is found and is significant. For example, in Java programming language, we should enforce conditions to take decisions. Now we have to understand what a loop is. It is a method of repeating lines of code. The block of code comprised within the loop will be executed again and again. This is done until the condition needed by the loop is fulfilled.

Benefits of looping:

  • Decreases the memory consumption
  • Decreases the length of code
  • There is no requirement to write same code again for executing lot of times
Java Tutorial: Decision making statements
If Statement

This statement is the simplest form of selection statement in Java. It verifies the condition and then the loop is executed.



if(<condition>) { –statement–}


int i=1;



System.out.println(“i value is “+i);



If … else statement and else if

In the if …else statement the condition is assessed. Suppose the condition is true then the true block of the statement is executed. Otherwise the false block is executed.

class IfElseStatement


public static void main(String[] args)


int i=4;



System.out.println(“i is greather than 4”);




System.out.println(“i is less than 4”);





This is applied in program when the if statement consists of several decisions.


Nested if statement

What do you mean by nested? It means if something is stored one inside the other. So in java nested implies a block inside another block.

if(condition 1)


if(condition 2)


if(condition 3)






Switch Case Statement

This is applied when we have lot of choices and there may be a requirement to carry out a different task for each choice.



case <value 1>:



case <value 2>:



default :




Jump statement

Imagine that there is a normal flow going on for a program. A jump statement suspends this flow. There are three jump statements in Java:

  • Break
  • Continue
  • Return

These are committed to shifting the control to another part of the program.



You can end the program using Java break statement. It can also be applied as a type of goto statement.



This statement is applied to continue an iteration of a loop


Java tutorials: Looping statements

While loop

A while loop in Java executes a statement “while” a given condition is true. This loop can be termed as a repeating if statement.


Do … while loop

Well, relax. You might be wondering from where did this come from? This loop is also similar to while loop. But the difference is lies in the time of execution. While in while loop the condition is assessed before the execution of the loop’s body, in do-while loop, condition is assessed after the assessment of loop’s body.


For loop

  • A for loop lets repeating specific operations by incrementing and assessing a loop counter. The loop counter becomes initialized before the first iteration.
  • There are three types of for loop: Simple, enhanced, and labeled.
  • In simple for loop, there is initialization of variable, checking of condition and increasing or decreasing the value. The increment or decrement is purely your choice.
  • In nested for loop, there is a loop inside another loop. There is a harmony between inner and outer loop because the inner loop executes entirely whenever outer loop executes.
  • In labeled for loop, there is a name (label) before the for loop.




// statement




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





Nested loops

The underlying concept behind nest loop is similar to nested decision-making statement. One loop can comprise another looping statement.


Java Tutorial: Encapsulation


If I try to explain to you about encapsulation in a definition, it will be hard to grasp for you. I will try to explain it as simple as I can.

Encapsulation is a very important concept of OOPS. It is a means of making the fields in a class private and giving access to the field through public methods. It can be very well considered as a safeguarding technique that prevents the code and data being accessed by other code defined outside the class. An interface manages the access to the data and code.

One of the main advantages of encapsulation is that it can help the programmer to hide the inner classes. Besides, the user can give access to only the needed codes. The data can be made as read-only or write-only as we wish to be. Moreover, you can apply the program repeatedly with encapsulation.

Encapsulation is a technique that combines the class members and prevents them from being reached by other classes. These class members are nothing but variables and methods. We can maintain the variables and methods safe from external interference.

Encapsulation is also called as data hiding since the data in the class is not shown to any other class. Moreover, they can be accessed only by means of member function of own class in which they are declared.

We declare the fields as private in the class for the purpose of preventing other classes from accessing them straight.

Now let’s take a real-world example of encapsulation. When you press the power button in your washing machine it starts working. But you are not aware of the inside mechanism. There is no need for the inside mechanism until the washing machine performs well. Wrapping is the key term here which is used for the object (it is wrapped) and the inner information is hidden. But the wrapping and hiding doesn’t stop the object from being called and used.

You can achieve encapsulation by the following approach in Java:

  • Private declaration of the variables in a class
  • Giving public setter and getter methods to change and view the variable values

The striking feature of encapsulation is that it lets you to modify the part of the code without disturbing any other function or code available in the program.

Java Tutorial: Static Keyword

In Java, we use static keyword to a great extent. It is because it is very useful in memory management. We can declare data only once and access it in the total program. This is done when we require the same data more than once in a program. Once you create the static keyword you needn’t declare that data repeatedly.

The static keyword is applicable for the following:



We can apply static keyword with a class level variable.  This variable belongs to the class. It does not belong to the object. There is only a single initialization of the static variable.


This is a block of statement within a Java class and it will be executed when a class is first loaded into the Java Virtual Machine.


This method belongs to the class. However, it does not belong to object. This method can access only static data.

Nested classes

Suppose the nested class is static then it is termed as static nested class. The static nested class doesn’t have any difference from top-level class. It is nested just for packaging convenience.

Performing method overloading in Java

By modifying number of arguments



class OuterClass


class InnerClass







Java Tutorial: Constructors in Java

Before going through constructors in Java, lets understand what is a method. A method is a set of statements that are grouped together to carry out an operation. Now let’s see what a constructor is. A constructor is applied to initialize an object.

Constructors form and initialize objects that are not in existence. On the other hand, methods carry out operations on objects that are already present. Keep in mind that constructors must be given the name same as the class name.

Syntax for constructor

<class name>(list of formal parameter)





Now let’s at the different types of constructors:


Default constructors


A constructor is termed as a default constructor when it does not consist of any parameter. Besides, when an object if formed and constructor is not declared the compiler itself offers a constructor and hence the name default constructor.

It is also called as no args constructor The Java complier includes a default constructor only when you don’t give any other constructor. So you should add a no arg constructor suppose you are adding explicit constructor.


Parameterized constructors


As explicit from its name, a constructor that consists of a specific number of parameters (or you can call them as arguments) is known as parameterized constructor. There can be innumerable of parameterized constructors in a class.


Java Tutorial: Overload Constructors


We have seen method overloading in Java. Now we will see constructor overloading.

Constructor overloading consists of more than one constructor with different argument list.  Here each constructor carries out a different task. In other words, there is the presence of more than one constructor inside a specific class.


Java Tutorial: Modifiers in Java

As implicit from the name, access modifiers in Java point out accessibility of a method, constructor, class or data member. There Now lets see the types of access modifiers in Java:


Java Tutorial: Access Modifiers in Java


The scope of this access modifier does not go beyond the package. Suppose you don’t mention any access modifier, then it takes the role of a default access modifier.

Private The scope of this type of access modifier is only within the classes. This is the most restrictive access modifier. Class and interfaces cannot come under the scope of private modifier.

Protected access modifier has similarity with default access modifier in terms of access. The inclusion in protected access modifier is that sub classes can access protected methods besides the member variables of the super class.



Here all code can conveniently access the class, constructor, field or method. This access is done irrespective of the place of the accessing code. The accessing code can be found in a different class and a different package.

Java Tutorials: Non access modifiers in Java


Static Modifier

When you declare a member as static then it is common to every instance of a class. These class level members are maintained in the class memory.


Abstract Modifier

You can use an abstract modifier either with a method or a class. For making a class abstract, at least one abstract method should be defined within a class.


Final Modifier

The final modifier is applied to restrict the further change of a method or a variable or a class. It should be initialized at the time of declaration.


Transient Modifier

This is applied in case of serialization process. The JVM will ignore this variable while serializing the object that comprises this variable.


Synchronized Modifier

A method which is synchronized can be accessed by only a single thread at a time.  This is done only with regard to methods. The striking thing of this modifier is that it can be used with any of the four access level modifiers.


Volatile Modifier

The volatile modifier suggests to the compiler that the volatile variable can be modified unexpectedly by other parts of your program. During multithreading programs, the volatile variables are used. The unique aspect of volatile modifier is that it is applied threads and maintains the variable in main memory. It does not cache the variable in each thread.


Java Tutorial: Inheritance in Java

When one class obtains the property of another class, then it is called inheritance in Java. We can use the fields and methods of the existing class again with inheritance, Reusability is very important for programming languages and inheritance is a significant concept of OOPs.

You can form new classes that are created on exiting classes with inheritance. Inheritance is also called as the parent-child relationship. Just like a child inherits the qualities of his/her parent, the inherited class will also inherit the qualities of the existing class.


Important terms in inheritance

Superclass: The parent class whose characteristics are inherited

Subclass: The child class that inherits the other class


Java Tutorial: Types of inheritance in Java

Single inheritance:

A single class inherits the properties of another class. Such an extension will facilitate cod reusability besides including new features to the existing code.

Multi-level inheritance

Let’s take this instance. A class is derived from a specific class. This specific class is also derived from another specific class. This is called multi-level inheritance. Here, the class can have more than a single parent class but note that this is at varied levels.

Hierarchical inheritance

A class may consist of more than one child classes (These child classes are also called subclasses). This type of inheritance is called as hierarchical inheritance.

Hybrid inheritance

This is a blend of two or more types of inheritance.

An important point is that Java does not support multiple inheritance.

Java Tutorial: Inheritance and method overriding

Now lets see the difference between method overloading and method overloading since these two concepts can be confusing at the beginning. For this, first recap what we have studied in method overloading.
Method overriding can take place only via inheritance. Well, what is this method overriding? Method overriding means that we define the same function of parent class in child class.

Java Tutorial: Polymorphism

Polymorphism is an OOP feature that lets us to carry out a single action in varied ways. The two Greek words poly (many) and morphs (forms) give the meaning of polymorphism.

Types of polymorphism in Java:

Static polymorphism or compile-time polymorphism

A polymorphism that is fixed during compile time is called as static polymorphism. Method overloading is a case of compile time polymorphism.


Dynamic Polymorphism or Run Time Polymorphism

Here, the call to an overridden method is fixed at run time. Method overriding is one method to achieve dynamic polymorphism.

Coercion, operator overloading, and polymorphic parameters are the other features of polymorphism in Java.

Coercion polymorphism refers to implicit type conversion. What is implicit type conversion? It is the conversion of a data type which is performed automatically by the compiler. This is done to prevent type errors when the programmer doesn’t intervene.

In operator overloading, the operator has varied meanings as per the context.

In polymorphic parameters, you can have a name of a parameter or method in a class to be linked with different types.


Java Tutorial: Handing exceptions

Sometimes when you execute a program you may get an undesired or unexpected event. This event which occurs at run time disturbs the normal flow of the program’s instructions. This powerful event is called an exception.

Exception handling is a process to deal with run-time errors. The major benefit of exception handling is to keep up the normal flow of the application.


Java Tutorial: Types of Java Exceptions

There are three types of exceptions: checked, unchecked, and error.

Checked exception: Also referred as compile-time exception, this exception is checked by the compiler during compilation time. As a programmer, one should diligently handle these exceptions.

Unchecked exception: Also known as run time exceptions, this exception takes place during the time of execution. These exceptions are ignored while compiling.



You might be wondering why errors come here. The issue is not within the control of the programmer. Errors are generally ignored in your code since you cannot mostly do anything with these errors..

“Throwable” acts as the basis for Java’s error and exception hierarchy. Keep in mind that an error takes place when there is inadequacy of system resources while an exception is caused when a code consists of some issue. The program will be terminated in an abnormal manner in the case of error. However, when there is an exception, the program will throw an exception. You can apply the try and catch block to take care of this.


Java Tutorial: Exception handling

Exception handling in Java is handled through five keywords: try, catch, finally, throw, throws

Try: The “try” block comprises a group of statements where an exception can take place. It will be typically followed by a “catch” block. The “catch” block takes care of the exception that takes place in the relevant try block. Even a “finally” block can follow the “try” block.

catch: A “catch” block handles the exception. The “try” block must take place before the “catch” block. So you would realize by now that the “catch” block cannot be used in isolation. A “finally” block can follow it.

finally: A “finally” block can be applied only with try-catch block. You may consider the “finally” block optional but it is good practice to use it. This block is a last chance for performing any type of cleanup before the method returns. For example, you can use “finally” block for closing a file.

Throw: When you “throw” an exception explicitly, then it is called as “throw” exception. It throws from a method or block code.

Throws: Suppose a method is capable of causing exception, it should give a list of all the exceptions possible at the time of its execution. The advantage of this is that the user calling that method gets knowledge beforehand regarding the exceptions to be handled.



In this Java tutorial, I have covered all the essential concepts of Java. I hope you are clear about everything discussed in the tutorial. Go through the concepts diligently and write the programs many times. The topic covered in this tutorial are the basics of Java and will be very useful when you work as a Java programmer. All the best!