Вы находитесь на странице: 1из 112

ankitemails@gmail.

com

Java Beginners Tutorial

Contents
INTRODUCTION ...................................................................................................................................................... 3
JAVA BASICS: GETTING STARTED WITH JAVA ..................................................................................................... 4
VARIABLES IN JAVA ................................................................................................................................................ 8
CLASS & OBJECT ................................................................................................................................................... 16
HELLO JBT ............................................................................................................................................................. 26
HELLO JBT (ECLIPSE) ............................................................................................................................................ 29
ACCESS MODIFIER ................................................................................................................................................ 35
NON ACCESS MODIFIER(NON AM) ...................................................................................................................... 41
STATIC KEYWORD................................................................................................................................................. 45
CONSTRUCTORS ................................................................................................................................................... 49
JAVA STATEMENTS .............................................................................................................................................. 56
OPERATORS IN JAVA ............................................................................................................................................ 65
OVERLOADING...................................................................................................................................................... 69
METHOD OVERRIDE ............................................................................................................................................. 72
SERIALIZATION ..................................................................................................................................................... 74
TRANSIENT VS. STATIC VARIABLE JAVA ............................................................................................................ 79
EXCEPTIONS .......................................................................................................................................................... 88
INNER CLASS ......................................................................................................................................................... 91
STRING ................................................................................................................................................................... 97
JAVA INTERFACE ................................................................................................................................................ 100
THE KEYWORD .................................................................................................................................................... 105

2
ankitemails@gmail.com

Java Beginners Tutorial

Introduction
Oracle & Java are registered trademarks of Oracle and/or its affiliates. Other
names may be trademarks of their respective owners. Java Beginners Tutorial is
not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
The Examples & Tutorial provided here are for learning purpose only. I do not
warrant the correctness of its content. The risk from using it lies entirely with the
user. We are not liable to any user for Any loss or damages of any kind, as a result
of using our products and services or other information provided on the
website(javabeginnerstutorial.com) or in this tutorial. By reading to this tutorial you
agreed to all terms of javabeginnerstutorial.com

3
ankitemails@gmail.com

Java Beginners Tutorial

Java Basics: Getting Started with Java


Here we will discuss some basics topics related to Java.
1.
2.
3.
4.
5.
6.
7.

Where to download Java.


How to install Java.
Setting up the Environment Variables.
Our First Java Program.
How to compile a Java application.
How to run a Java Application.
Difference between important terms in Java (JDK vs. JRE or J2SE vs. J2EE..).

How to Download Java


Latest version of Java can be downloaded from Java Website.

Java Installation
Once java is downloaded, it can be installed like any other software (.exe) in your Windows
system.

Setting up the Environment Variables


After installing Java there are some environment variables that need to be set.

CLASSPATH : This environment variable points the location of JDK home directory. It also

contains the address of the folder from where the jars get loaded by the ClassLoader (For
more details of ClassLoader visit here)

JAVA_HOME : This environment variable will point the location of Java home directory.

4
ankitemails@gmail.com

Java Beginners Tutorial

How to set environment variable in different platforms


Windows XP
To set up environment variables in Windows XP right click on the "My Computer" icon and select
Properties. In the Property window select the "ADVANCED" tab and click on "ENVIRONMENT
VARIABLES" . A window will appear were you can enter a new environment variable under System
Variables by clicking on the New button.
Windows Vista / 7
To set up environment variables in Windows Vista / 7 right click on the "Computer" and select
Properties. In the Property window select the "ADVANCED SYSTEM SETTINGS" and then select
the "ADVANCED" tab and click "ENVIRONMENT VARIABLES". A window will appear were you can
enter a new environment variable under User/System Variables by clicking on the New button.

How to Check if Java is Installed


To check if your java is installed properly open Command Prompt . To open command prompt
write "CMD" in run command and hit enter. In the command prompt window write "java -version". If
your java is installed properly and all environment variables are configured correctly it will show
the version of Java installed . Information reflected on the command prompt will be like
C:UsersJbt>java -version
java version "1.6.0_25"
Java(TM) SE Runtime Environment (build 1.6.0_25-b06)
Java HotSpot(TM) Client VM (build 20.0-b11, mixed mode, sharing)
If there is any problem while installing or in setting up the environment variables output on the
command prompt will be like
'java' is not recognized as an internal or external command,
operable program or batch file.

How to check if Java is up to date


To know if the Java installed on your system is up to date or not Click Here.

5
ankitemails@gmail.com

Java Beginners Tutorial

Our First Java Program


It is highly common that the very first Java program would be to print " Hello World !! " . But here
we will write a program to print " Hello JBT !! ". :)
If everything till now was configured properly then we can start writing our first application. Open
any editor and write the below code.
public class FirstProgramme {
public static void main(String args[]) {
System.out.println("Hello JBT!");
}
}
Once done save the file with the name "FirstProgramme.java". Please note that the name of the
file should be the same as the name given to the public class. Once the file is saved, open the
command prompt and change its current directory to where the file is saved with the help of cd
command. And fire "javac" command which is used to compile the java code as below.
C:UsersJBT>cd C:JBT
C:JBT>javac FirstProgramme.java
C:JBT>
If the java file is compiled properly the compiler will create a class file for the java source file. It
will be saved in the same location as the source file or maybe some other location depending on
its package declaration. Since there is no package declared in the given code so the .class file
will be created in the same folder location.

How to Run Java Application


Now that your java file is compiled we can execute the application with the help of "java"
command as below .
C:JBT>java FirstProgramme
Hello JBT!
C:JBT>
Note*: For the "java" command we use only the class file name without its extension(.class). With
this we are done with creating and running our very first Java application. In the next section we
will learn the difference between JDK and JRE.

6
ankitemails@gmail.com

Chapter 2
VARIABLES IN JAVA
IN THIS SECTION:

ankitemails@gmail.com

Introduction
Variable Definition
Variable Initialization
Primitive Data type
Type of Variable

Java Beginners Tutorial

Variables in Java
Introduction
In Java, objects store their states in variables. Variables are used as containers to hold values
(int, long, string...) during the life cycle of an application.

Variable Definition
To define a variable, we need to assign a data type for that variable. Data type defines the kind
of value this variable can hold (int, long or String etc.).

Example of variable definition


public final int var ;
Keyword
public

Definition
Access Modifier applied to variable

final

Non Access Modifier applied to this variable

int

Data type. It defines kind of value this


variable can hold (int in this case)
Name of the variable

var

Variable Initialization
Now that we are done defining a variable, we can initialize the above variable by assigning a
value to it . In this case, we assign the variable an integer value.
public final int var = 9;

8
ankitemails@gmail.com

Java Beginners Tutorial

Different Primitive Data Types


Java supports the below mentioned primitive data types.

byte
short
int
long
float
double
char
boolean

Note*: Corresponding Wrapper Classes is also available.

Variable Types in Java


Variables in Java can be defined anywhere in the code (inside a class, inside a method or as a
method argument) and can have different modifiers. Depending on these conditions variables in
Java can be divided into four categories.

Instance Variable
Static Variable
Local Variable
Method Parameter

Instance Variable(Non Static Fields)


Instance variables are used by objects to store their states. Variables which are defined without
the STATIC keyword and are outside any method declaration are object specific and are known
as Instance Variables. Such variables are called as instance variables because their values are
instance specific and values of these variables are not shared among instances.
package com.jbt;
/*
* Here we will discuss about different type of Variables
available in Java
*/

9
ankitemails@gmail.com

Java Beginners Tutorial

public class VariablesInJava {


/*
* Below variable is INSTANCE VARIABLE as it
* is outside any method and it is not using
* STATIC modifier with it. It is using
* default access modifier. To know more about
* ACCESS MODIFIER visit appropriate section
*/
int instanceField;
/*
* Below variable is STATIC variable as it is
* outside any method and it is using STATIC
* modifier with it. It is using default
* access modifier. To know more about ACCESS
* MODIFIER visit appropriate section
*/
static String staticField;
public void method() {
/*
* Below variable is LOCAL VARIABLE as it
* is defined inside method in class. Only
* modifier that can be applied on local
* variable is FINAL. To know more about
* access and non access modifier visit
* appropriate section.
*
* Note* : Local variable needs to
* initialize before they can be used.
* Which is not true for Static or
* Instance variable.
*/
final String localVariable = "Initial Value";
System.out.println(localVariable);
}
public static void main(String args[]) {
VariablesInJava obj = new VariablesInJava();
/*
* Instance variable can only be accessed
* by Object of the class only as below.
*/
System.out.println(obj.instanceField);
/*

10
ankitemails@gmail.com

Java Beginners Tutorial

* Static field can be accessed in two


* way. 1- Via Object of the class 2- Via
* CLASS name
*/
System.out.println(obj.staticField);
System.out.println(VariablesInJava.staticField);

Class Variable(Static Fields)


Variables which are declared with a STATIC keyword inside a class (outside any method) are
known as Class variable / Static variable. They are known as Class level variable because values
of these variables are not specific to any instance but are common to all instances of a class.
Such variables will be shared by all instances of an object.
package com.jbt;
/*
* Here we will discuss about different type of Variables
available in Java
*/
public class VariablesInJava {
/*
* Below variable is INSTANCE VARIABLE as it
* is outside any method and it is not using
* STATIC modifier with it. It is using
* default access modifier. To know more about
* ACCESS MODIFIER visit appropriate section
*/
int instanceField;
/*
* Below variable is STATIC variable as it is
* outside any method and it is using STATIC
* modifier with it. It is using default
* access modifier. To know more about ACCESS
* MODIFIER visit appropriate section
*/
static String staticField;
public void method() {
/*
* Below variable is LOCAL VARIABLE as it
* is defined inside method in class. Only

11
ankitemails@gmail.com

Java Beginners Tutorial

* modifier that can be applied on local


* variable is FINAL. To know more about
* access and non access modifier visit
* appropriate section.
*
* Note* : Local variable needs to
* initialize before they can be used.
* Which is not true for Static or
* Instance variable.
*/
final String localVariable = "Initial Value";
System.out.println(localVariable);

public static void main(String args[]) {


VariablesInJava obj = new VariablesInJava();
/*
* Instance variable can only be accessed
* by Object of the class only as below.
*/
System.out.println(obj.instanceField);

/*
* Static field can be accessed in two
* way. 1- Via Object of the class 2- Via
* CLASS name
*/
System.out.println(obj.staticField);
System.out.println(VariablesInJava.staticField);

Local Variables(Method Local)


When a variable is declared inside a method it is known as method local variable. Scope of local
variables is only inside the method, which means local variables cannot be accessed outside that

12
ankitemails@gmail.com

Java Beginners Tutorial

method. There are some restrictions on access modifier that can be applied on Local variables.
To know more about access modifier CLICK HERE.
package com.jbt;
/*
* Here we will discuss about different type of Variables
available in Java
*/
public class VariablesInJava {
/*
* Below variable is INSTANCE VARIABLE as it
* is outside any method and it is not using
* STATIC modifier with it. It is using
* default access modifier. To know more about
* ACCESS MODIFIER visit appropriate section
*/
int instanceField;
/*
* Below variable is STATIC variable as it is
* outside any method and it is using STATIC
* modifier with it. It is using default
* access modifier. To know more about ACCESS
* MODIFIER visit appropriate section
*/
static String staticField;
public void method() {
/*
* Below variable is LOCAL VARIABLE as it
* is defined inside method in class. Only
* modifier that can be applied on local
* variable is FINAL. To know more about
* access and non access modifier visit
* appropriate section.
*
* Note* : Local variable needs to
* initialize before they can be used.
* Which is not true for Static or
* Instance variable.
*/
final String localVariable = "Initial Value";
System.out.println(localVariable);
}
public static void main(String args[]) {

13
ankitemails@gmail.com

Java Beginners Tutorial

VariablesInJava obj = new VariablesInJava();


/*
* Instance variable can only be accessed
* by Object of the class only as below.
*/
System.out.println(obj.instanceField);

/*
* Static field can be accessed in two
* way. 1- Via Object of the class 2- Via
* CLASS name
*/
System.out.println(obj.staticField);
System.out.println(VariablesInJava.staticField);

Parameters
Parameters are variables that are passed in methods. For example, String args[] variable in main
method is a parameter.
package com.jbt;
/*
* Here we will discuss about different type of
* Variables available in Java
*/
public class VariablesInJava {

public static void main(String args[]) {


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

14
ankitemails@gmail.com

Chapter 3
CLASS & OBJECT
IN THIS SECTION:

ankitemails@gmail.com

Syntax of Class Creation


Internal Structure of Class
Example of Class
Rules applied to java file
Create Object from class
Access member of class

Java Beginners Tutorial

Class & Object


Class is a template for creating objects which defines its state and behaviour. A class contains
field and method to define the state and behaviour of its object.

Syntax for Declaring Class


<Access_Modifier> class <Class_Name> extends
<Super_Class_Name> implements <Interface_Name>

Syntax
Access_Modifier
Class_Name
Super_Class_Name
Interface_Name

Definition
It defines who in java world can access the class and the members
of the class.
Unique name for class in specific package.
Name of the class which above class extends.( extends keyword
is used for this purpose)
Name of an Interface which above class implements.( implements
keyword is used for this purpose)

Internal structure of Class


<Access Modifier> class <Class_Name> extends <Super_Class_Name>
implements <Interface_Name>{
<static initilizar block>
<ananymous block>
<constructor declarations>
<field declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<Inner class declarations>
<nested interface declarations>
Access variables inside class
}

Example of Java Class


package test;
/*
* This is Multi Line Comment and Comment can appear at any place
*/
//package com.jbt;
import java.lang.*;

16
ankitemails@gmail.com

Java Beginners Tutorial

/*
* As this file contains public class.
* Then the name of this file should be TestClass.java
*/
public class TestClass {
public int i;
static {
System.out.println("This is static block");
}
{
}

System.out.println("This is ananuymous block");

TestClass() {
System.out.println("This is constructor");
}

void methid() {
System.out.println("This is method");
}

class AnotherClass {
}

Classes are written in a java source file. A source file can contain more than one java class. Below
are the rules related to java source code files.

Rules applied to Source code file


There can be only one public class per source code file but it can have multiple non
public classes.

In case there is any public class present in the source code file, name of the file should
be the name of the class.

Sequence of statements in a source code file should be package >> import >> Class
declaration.

No Sequence rule is applied for Comments. Comments can be there in any part of the
source code file at any location.

Files with no public class can have any name for the class, there is no rule applied for
the same.

17
ankitemails@gmail.com

Java Beginners Tutorial

Import and package statements should be applied to all the classes in the same source
code file.

How to Create an Object of Class


To create object of a class <new> Keyword can be used.

Syntax
<Class_Name>

ClassObjectReference = new <Class_Name>();

Here constructor of the class(Class_Name) will get executed and object will be
created(ClassObjectRefrence will hold the reference of created object in memory).

How to Access Member of a Class


(ClassObjectReference.member ). You call a method of an object by naming the object followed
by a period (dot), this should be followed by the name of the method and its argument list.
objectName.methodName(arg1, arg2, arg3).

Class Variables Static Fields


Class variables also known as static fields share characteristics across all objects within a class.
When you declare a field to be static, only a single instance of the associated variable is created,
which is common to all the objects of that class. Hence when one object changes the value of a
class variable, it affects all the objects of the class. We can access a class variable by using the
name of the class, and not necessarily using a reference to an individual object within the class.
Static variables can be accessed even though no objects of that class exists. It is declared using
the static keyword.

18
ankitemails@gmail.com

Java Beginners Tutorial

Class Methods Static Methods


Class methods, similar to Class variables can be invoked without having an instance of the class.
Class methods are often used to provide global functions for Java programs. For example,
methods in the java.lang.Math package are class methods. You cannot call non-static methods
from inside a static method.

Java Objects
The Object Class is the super class for all classes in Java. Some of the object class methods are
equals()
toString()
wait()
notify()
notifyAll()
hashcode()
clone()

An object is an instance of a class created using a new operator. The new operator returns a
reference to a new instance of a class. This reference can be assigned to a reference variable of
the class. The process of creating objects from a class is called instantiation. An object
encapsulates state and behavior.
An object reference provides a handle to an object that is created and stored in memory. In Java,
objects can only be manipulated via references, which can be stored in variables.
Creating variables of your class type is similar to creating variables of primitive data types, such
as integer or float. Each time you create an object, a new set of instance variables comes into
existence which defines the characteristics of that object. If you want to create an object of the
class and have the reference variable associated with this object, you must also allocate memory
for the object by using the new operator. This process is called instantiating an object or creating
an object instance.
When you create a new object, you use the new operator to instantiate the object. The new
operator returns the location of the object which you assign a reference type.

Different ways to create an object in Java


You must have used the "new" operator to create an Object of a Class. But is it the only way to
create an Object?
Simple Answers is NO, then in how many ways we can create Object of a Class. There are several
like

19
ankitemails@gmail.com

Java Beginners Tutorial

Using New keyword


Using New Instance (Reflection)
Using Clone
Using Deserilization
Using ClassLoader
... don't know :)

Now we will explore the different ways of creating the Object except new Operator.

Using New Keyword


Using new keyword is the most basic way to create an object. Use new keyword to create and
Object of class.
public class ObjectCreationExample {

public static void main(String[] args) {


// Here we are creating Object of JBT
// using new keyword
JBT obj = new JBT();
}

class JBT {
String Owner;
}

Using New Instance (Reflection)


Have you ever tried to connect to any DB using JDBC driver in Java, If your answer is yes then
you must have seen "Class.forName". We can also use it to create the object of a class.
Class.forName actually loads the class in Java but doesn't create any Object. To Create an
Object of the Class you have to use newInstance method of Class class.
/*
* Here we will learn to create Object of a class without using
new Operator.
* But newInstance method of Class class.
*/
class CreateObject {

20
ankitemails@gmail.com

Java Beginners Tutorial

public static void main(String[] args) {


try {
Class cls = Class.forName("JBTClass");
JBTClass obj = (JBTClass) cls.newInstance();
JBTClass obj1 = (JBTClass) cls.newInstance();

System.out.println(obj);
System.out.println(obj1);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}

class JBTClass {
static int j = 10;
JBTClass() {
i = j++;
}
int i;

@Override
public String toString() {
return "Value of i :" + i;
}

Note*: If you want to create Object in this way class needs to have public default Constructor.

Using Clone
We can also use Clone() method to create a copy of an existing Object.
/*
* Here we will learn to create an Object of a class without
using new Operator.
* For this purpose we will use Clone Interface
*/
class CreateObjectWithClone {

21
ankitemails@gmail.com

Java Beginners Tutorial

public static void main(String[] args) {

JBTClassClone obj1 = new JBTClassClone();


System.out.println(obj1);
try {
JBTClassClone obj2 = (JBTClassClone) obj1
.clone();
System.out.println(obj2);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}

}
class JBTClassClone implements Cloneable {
@Override
protected Object clone()
throws CloneNotSupportedException {
return super.clone();
}
int i;
static int j = 10;
JBTClassClone() {
i = j++;
}

@Override
public String toString() {
return "Value of i :" + i;
}

Note*:

Here we are creating the clone of an existing Object and not any new Object.
Clone method is declared protected in Object class. So it can be accessed only in

subclass or in same package. That is the reason why it has been overridden here in
Class.

Class need to implement Cloneable Interface otherwise it will


throw CloneNotSupportedException.

22
ankitemails@gmail.com

Java Beginners Tutorial

Using Object Deserialization


Object deserialization can also be used to create an Object. It is just the opposite of serializing an
Object.

Using ClassLoader
We can also use Class Loader to create Object of a Class. This way is some what same as
Class.forName option.
/*
* Here we will learn to Create an Object using Class Loader
*/
public class CreateObjectWithClassLoader {
public static void main(String[] args) {

JBTClassLoader obj = null;


try {
obj = (JBTClassLoader) new
CreateObjectWithClassLoader()
.getClass().getClassLoader()
.loadClass("JBTClassLoader")
.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(obj);
}

class JBTClassLoader {
static int j = 10;
JBTClassLoader() {
i = j++;
}
int i;

23
ankitemails@gmail.com

Java Beginners Tutorial

@Override
public String toString() {
return "Value of i :" + i;
}
}

24
ankitemails@gmail.com

Chapter 4
HELLO JBT
IN THIS SECTION:
Create Hello JBT Class
Run a class
Explanation of main method

ankitemails@gmail.com

Java Beginners Tutorial

Hello JBT
Here we will learn to write first java application in Textpad. Open any editor write below code
and save it as "HelloJBT.java" file.
public class HelloJBT {
/*
* Below Method is using STATIC KEYWORD to make this method
Static so that JVM can call this method without
* creating any object of the class.
*
* This method should not return any thing that is why void
keyword is used in method signature.
*
* This method accepts Array of Strings which can be used to pass
values to this method.
*
* This method signature is required to execute it.
*/
public static void main(String[] args) {
System.out.println("Hello JBT!");
}
}
Open command prompt and run below code to check if java is installed properly or not.
java -version
Output should be something like below.
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) Client VM (build 25.31-b07, mixed mode, sharing)
Again run below code to check if javac is working properly or not.
javac -version
Output should be something like below
javac 1.8.0_25

26
ankitemails@gmail.com

Java Beginners Tutorial

If output is not like above reinstall JDK again and verify.


If everything is working properly move to folder where java files is saved and compile the file
using command "javac HelloJBT.java". A class file should be created. To run application
execute class file with "java HelloJBT".
Note*: Here .class should not be used while executing java.

If everything is good you will see output as below on command prompt.


Hello JBT

public static void main(string args[]) Explanation


In Above application we are using public static void main keyword. Each keyword has different meaning
and different purpose.

Syntax

Definition

Public

It is an Access Modifier, which(AM) defines who can access this


method(In Java World). Public means that this method will be accessible
to any class(If other class can access this class.).

Static

Keyword which identifies the class related this. It means that this class is
not instance related but class related. It can be accessed without
creating the instance of Class.
Return Type, It defined what this method can return. Which is void in this
case it means that this method will not return anything.

Void
main

Name of the method. This method name is searched by JVM as starting


point for an application.

String args[]

Parameter to main method.

27
ankitemails@gmail.com

Chapter 5
ECLIPSE HELLO WORLD
IN THIS SECTION:

ankitemails@gmail.com

Install Eclipse
Run Eclipse
Create Workspace and Project
Create class and run it

Java Beginners Tutorial

Hello JBT (Eclipse)


1.1 Install Eclipse
Download platform dependent eclipse from Eclipse.org .

1.2 Run Eclipse


Once eclipse is downloaded extract zip and look for eclipse.exe inside extracted folder, this is the file
which will run eclipse application on your system.
Note*: Eclipse doesnt require to get installed on local system. It will run
without installing by clicking eclipse.exe file.

1.3 Create Workspace


Double-click on file eclipse.exe (eclipse on Linux and Mac) and eclipse will ask for location of
workspace to create. In text field (Workspace) you need to provide the location on local system. Provide
the location and click OK. Once clicked you will see below screen.

Workspace is the place where eclipse create projects and stores configuration options related to
projects. Eclipse will create .metadata folder @ give location which will be used to save the
configuration related to this workspace & which can be used be in further development

29
ankitemails@gmail.com

Java Beginners Tutorial

1.4 Create Project


To create project select File >> New >> Java Project from menu. In case you cant find Java
Project option from menu then click Other.
And select Java Project from "Select a Wizard" window and click Next. Provide project name in
next window("New Java Project") as shown below.

Click Finish. Eclipse will ask you to change the perspective to Java Perspective. Say Yes. As you
can see a new Java project will appear in Package Explorer view in Java Perspective.

30
ankitemails@gmail.com

Java Beginners Tutorial

1.5 Create Package


Now we will create package in Java project. Packages are used to avoid naming conflicts, to
control access (Access Modifier) and to bundle groups of related types.
To create package select src folder in Java project (JBTProject), right click on it and select New
>> Package.

Enter the package name in dialog box and click finish.

31
ankitemails@gmail.com

Java Beginners Tutorial

1.6 Create Java Class


Once package is created we can create Java class inside package. Right click on package in
which java class is to be create and select New >> Class.

Provide the class name in dialog box and click Finish button. There are other options available
to choose from. We have chosen to create main method and newly created class.
Once Class is created structure of the project would be.

32
ankitemails@gmail.com

Java Beginners Tutorial

1.7 Compile the code


To compile code use keyboard short cut CTRL+B. It will build all the java application. If you
want to build single application then click the application and select Project >> Build Project
from menu.

1.8 Run the code


To run the code you can either use keyboard shortcut ALT+SHIFT+X and J.
Or you can click the file to run and select Run >> Run As >> Java Application from Menu like
below.

Once you click run Hello World application will get executed and output will get displayed in
console view as below.

33
ankitemails@gmail.com

Chapter 6
ACCESS MODIFIER
IN THIS SECTION:

ankitemails@gmail.com

Type of Access Modifier


Access Modifier for Class
Access Modifier for Member
Difference between direct &
Inheritance Access

Java Beginners Tutorial

ACCESS MODIFIER
Access modifiers help you set the level of access you want for your class, variables or methods.
Three are 3 access modifiers available in Java. But there exists a fourth one called the default
access modifier . Default is an access control which will be set when one does not specify any
access modifier.

Access Control:

Public
Private
Protected
Default

Access modifiers(Some or All) can be applied to Class, Variable, Methods.

Access Modifiers for Class


Classes in java can use only public and default access modifiers.

Public
When set to public, the given class will be accessible to all classes(In Same or different package).

Default
When set to default, the given class will be accessible to the classes which are defined in the
same package only.

35
ankitemails@gmail.com

Java Beginners Tutorial

Access Modifier Table for Class


Public Access Modifier

Visibility

Default Access Modifier

Within Same Package

Yes

Yes

From Outside the Same


Package

Yes

No

Access Modifier for Variable (Instance / Static Variable) or Method


Variables/Method are eligible for all of the above mentioned modifiers.

Default
Public
Protected
Private
Note*: Visibility of the class should be checked before checking the
visibility of Variables/Method defined inside that class. If the class is
visible only then the Variables/Method defined inside that class will be
visible . If the class is not visible then no Variables/Method will be
accessible, even if it is set to public.

Default
If a Variables/Method is set to default, it will be accessible to the classes which are defined in the
same package. Any method in any class which is defined in the same package can access the
variable via Inheritance or Direct access.

Public
If a Variables/Method is set to public it can be accessible from any class available in Java world.
Any method in any class can access the given variable via Inheritance or Direct access.

Protected
If a v is set to protected inside a class, it will be accessible from its sub classes defined in the
same or different package only via Inheritance.
Note*: The only difference between protected and default is that
protected access modifiers respect class subclass relation while default
does not.

36
ankitemails@gmail.com

Java Beginners Tutorial

Private
A Variables/Method if defined private will be accessible only from within the class it is defined.
Such Variables/Method are not accessible from outside the defined class, not even its subclass .
Visibility

Public Access
Modifier

Private Access
Modifier

Protected Access
Modifier

Default Access
Modifier

Within Same Class

Yes

Yes

Yes

Yes

From Any Class in


Same Package

Yes

No

Yes

Yes

From Any Sub


Class in Same
Package

Yes

No

Yes

Yes

From Any Sub


Class in Same
Package

Yes

No

Yes

Yes

From Any Sub


Class from
Different Package

Yes

No

Yes(Only By
Inheritance)

No

From Any Non


Sub Class in
Different Package

Yes

No

No

No

Access Modifier for Local Variable


No Access Modifiers can be applied to local variables. Only final can be applied to a local variable
which is a Non Access Modifer .

Access Modifier for Method Parameter


Method parameter will be treated as local variable hence only final Non Access Modifier will be
applicable and no Access Modifier is applicable.

37
ankitemails@gmail.com

Java Beginners Tutorial

Difference between Inheritance or Direct Access


I will explain the difference with the help of a code mentioned below.

Super Class
package jbt1;
public class FirstClass {
public int i;
protected int j;
private int k;
}

Sub Class
package jbt;
import jbt1.FirstClass;
class SecondClass extends FirstClass {
void method() {
System.out.println(i);
/*
* Here property j is accessed via
* Inheritance hence it will be
* accessible. But same variable can not
* be accessed if you try to access via
* instance because modifier used here is
* protected so it will be available to
* sub class only via inheritance.
*/
System.out.println(j);
/*
* As k is private so it will not be
* accisible to subclass neither way.
* Neither it can be accessed via
* Inheritance nor direct.
*/
System.out.println(k); // Compilation
// Error
FirstClass cls = new FirstClass();
/*
* Here you are trying to access protected
* variable directly. So it will not be

38
ankitemails@gmail.com

Java Beginners Tutorial

* accessible and compile will give an


* error.
*/
System.out.println(cls.j);
// Private variable will not be accessible
// here also.
System.out.println(cls.k); // Compilation
// error

39
ankitemails@gmail.com

Chapter 7
NON ACCESS MODIFIER(NON AM)
IN THIS SECTION:

ankitemails@gmail.com

Final Non AM
Abstract Non AM
Synchronized Non AM
Native Non AM
Strict Non AM

Java Beginners Tutorial

NON ACCESS MODIFIER(NON AM)


Non Access Modifiers available in Java.

Final
Abstract
Static
Strictfp
Native
Synchronized
Transient

Final Non Access Modifiers


Keyword : final
Applicability
1.
2.
3.
4.
5.

Class
Method
Instance Variable
Local Variable
Method arguments
Definition

Final Class

Final Method

Final Variable

A class when set to final cannot be extended by


any other class.
Example: String Class in java.lang package
A method when set to final cannot be overridden by
any subclass.
When a variable is set to final, its value cannot be
changed. Final variables are like constants.
Example : public static final int i = 10;

41
ankitemails@gmail.com

Java Beginners Tutorial

Abstract Non Access Modifier


Keyword: abstract
Applicability
1. Class
2. Method
Definition
Abstract Class

Abstract Method

An abstract class can have abstract methods. A


class can also be an abstract class without having
any abstract methods in it. If a class has an
abstract method , the class becomes an abstract
class.
Abstract methods are those methods which does
not have a body but only a signature.
Example : public abstract void method();

Synchronized Non Access Modifier


Keyword
synchronized

Applicability
1.

Method
Definition

Synchronized Method

Synchronized methods can be accessed by only


one thread at a time.

42
ankitemails@gmail.com

Java Beginners Tutorial

Native Non Access Modifier


Native modifiers are applicable to
1.

Method
Definition

Native Method

Naive method indicates that a method is


implemented on a platform dependent code.

Strictfp Non Access Modifier


Keyword
strictfp

Strictfp modifiers are applicable to


1. Class
2. Method
Definition
Strictfp Class / Method

Strictfp non access modifier forces floating point


or floating point operation to adhere to IEEE 754
standard.
Note*: Strictfp non access modifier cannot be
applied on a variable.

43
ankitemails@gmail.com

Chapter 8
STATIC KEYWORD
IN THIS SECTION:

ankitemails@gmail.com

What is Static keyword


Applicability
Purpose of Static keyword
How to invoke Static member
Rule Applicable

Java Beginners Tutorial

STATIC KEYWORD
What is Static
Static is a Non Access Modifier.

Applicability
Static keyword can be applied on

Method
Variable
Class nested within another Class
Initialization Block

Not Applicable to
Static keyword cannot be applied to

Class (Not Nested)


Constructor
Interfaces
Method Local Inner Class(Difference then nested class)
Inner Class methods
Instance Variables
Local Variables

Purpose of Static Keyword


Used to attach Variable / Method to class. Variable and Method marked static belong to the class
rather than to any particular instance.

45
ankitemails@gmail.com

Java Beginners Tutorial

How to Invoke
Static variable / methods can be used without having any Instance of the class. Only class is
required to invoke a static method or static variable.
/*
* Here we will learn to access Static method and Static
Variable.
*/
public class JavaStaticExample {
static int i = 10;
static void method() {
System.out.println("Inside Static method");
}
public static void main(String[] args) {
// Accessing Static method
JavaStaticExample.method();
// Accessing Static Variable
System.out.println(JavaStaticExample.i);
/*
* No Instance is required to access
* Static Variable or Method as we have
* seen above. Still we can access the
* same static variable and static method
* using Instace references as below.
*/
JavaStaticExample obj1 = new JavaStaticExample();
JavaStaticExample obj2 = new JavaStaticExample();
/*
* Accessing static variable in Non Static
* way. Compiler will warn you with below
* warning.
*
* The static field JavaStaticExample.i
* should be accessed in a static way.
*/
System.out.println(obj1.i);
// Accessing satic method using reference.
// Warning by compiler
// "The static method method() from the type

46
ankitemails@gmail.com

Java Beginners Tutorial

// JavaStaticExample should be accessed in a static way"


obj1.method();

Output of the above programme


Inside Static method
10
10
Inside Static method

Note*: Static keyword can be used with Variables & Methods. It is not
applicable to class.

Static Keyword Rules

Variable / Methods marked static belong to the Class rather then to any particular
Instance.
Static method/variables can be used without creating any instance of the class.
If there are instances, a static variable of a class will be shared by all instances of that
class, there will be only one copy.
A static method can't access non static variable and also it can not directly invoke non
static method (But it can invoke/access method/variable via instances).

47
ankitemails@gmail.com

Chapter 9
CONSTRUCTOR
IN THIS SECTION:

ankitemails@gmail.com

Purpose of Constructor
Default Constructor
AM applied to Constructor
Constructor & Inheritance
Syntax of Constructor
Invocation of Constructor
Rules Applied
Constructor Overloading
Constructor Chaining

Java Beginners Tutorial

Constructors
Constructors in Java can be seen as Methods in a Class. But there is a big difference between
Constructors and Methods. These differences can be defined in terms of purpose, syntax and
Invocation.

Purpose of Constructor (Vs Method)


Constructors have only one purpose in life and that is to create an Instance of a Class. This
instantiation includes memory allocation and member initialization(Optional).
In contrast, methods cannot be used to create an Instance of a Class.

Constructor and <init> method


At JVM level Constructors are seen as Instance Initialization Method which has a special name
<init>, provided by compiler.

Default Constructor
It is not mandatory to define constructor for a class. If you do not define any constructor
explicitly, JVM will provide you one, without parameter and without throws clause which is
called default constructor. Default constructor will have same access modifier as class. Default
constructor in ENUM will be implicitly private.
Note*: Default constructor will be provided only when you don't define
one explicitly.

Constructor and Inheritance


Constructors cannot be inherited the way methods are inherited. Reason being is subclass may
needs to be created in different way than super class.

49
ankitemails@gmail.com

Java Beginners Tutorial

Access Modifier
Constructor's are eligible to all access modifier(public/private/protected/default). Default no-arg
constructor provided by JVM will have same access modifier as class.
Note*: Constructor can also be private.

super & this


Unless and until you specify explicitly, first call will be super() in any constructor. Explicitly you
can specify this/super keyword with or without parameter.

Syntax of Constructor(Vs Method)


/*
* Here Class name is ConstructorExample, So constructor name
needs to be the same.
*/
public class ConstructorExample {
/*
* As below signature has the name as Class
* name and it doesn't contain any return
* value so it will be treated as Constructor
* of the class
*/
public ConstructorExample() {
System.out.println("Inside Constructor");
}

/*
* Below method will be invoked only when it
* is invoked implicitly. Method has return
* type along with Non Access Modifier
*/
static void method() {
System.out.println("This is in method");
}

50
ankitemails@gmail.com

Java Beginners Tutorial

Syntax of constructor is different than Method in below aspects

Constructors cannot have Non Access Modifier while methods can have.
Constructors cannot have a return type(Not even void) while methods must have one.
Constructor name must be the same as Class name while methods can have different
names.
As per Java naming convention, method names should be camel case while constructor
names should start with caps letter.
Note*: A method can have the same name as that of Class name.

Invocation of Constructor(Vs Method)


There is a difference between how constructors and methods are called. Constructors cannot be
called explicitly, constructor will be invoked implicitly when the instance of the class is getting
created(Using new Keyword)

Constructor Invocation Example


/*
* Here Class name is ConstructorExample, So constructor name
needs to be the same.
*/
public class ConstructorExample {
/*
* As below signature has the name as Class
* name and it doesn't contain any return
* value so it will be treated as Constructor
* of the class
*/
public ConstructorExample() {
System.out.println("Inside Constructor");
}

public static void main(String args[]) {


ConstructorExample cls = new ConstructorExample();
}

Output will be...


Inside Constructor

51
ankitemails@gmail.com

Java Beginners Tutorial

Method Invocation Example


/*
* Here Class name is ConstructorExample, So constructor name
needs to be the same.
*/
public class ConstructorExample {
/*
* As below signature has the name as Class
* name and it doesn't contain any return
* value so it will be treated as Constructor
* of the class
*/
public ConstructorExample() {
System.out.println("Inside Constructor");
}
/*
* Below method will be invoked only when it
* is invoked implicitly.
*/
void method() {
System.out.println("This is in method");
}

public static void main(String args[]) {


ConstructorExample cls = new ConstructorExample();
/*
* Now method will be called explicitly as
* below. It will execute the code within
* method.
*/
cls.method();
}

//Output would be
Inside Constructor
This is in method

52
ankitemails@gmail.com

Java Beginners Tutorial

A constructor in a class has the same name as that of the given class. Constructors syntax does
not include a return type, since constructors never return a value. Constructors may include
parameters of various types. When the constructor is invoked using the new operator, the types
must match those that are specified in the constructor definition. Java provides a default
constructor which takes no arguments and performs no special actions or initializations, when no
explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using
the super() call. Constructor arguments provide you with a way to provide parameters for the
initialization of an object.

Constructor Rules

A constructor cannot have a return type.


Constructor must have the same name as that of the class.
Constructors cannot be marked static
Constructor cannot be marked abstract
Constructor cannot be overridden.
Constructor cannot be Final.
Object class also have a no arg constructor.
Anonymous class cannot have an explicit constructor.

If a clas defines an explicit constructor, it no longer has a default constructor to set the state of
the objects. If such a class requires a default constructor, its implementation must be provided.
Any attempt to call the default constructor will be a compile time error if an explicit default
constructor is not provided in such case.

Constructor Overloading:
Like methods, constructors can also be overloaded. Since the constructors in a class all have the
same name as the class, their signatures are differentiated by their parameter lists.
It is possible to use this() construct, to implement local chaining of constructors in a class. The
this() call in a constructor invokes the other constructor with the corresponding parameter list
within the same class. Java requires that any this() call must occur as the first statement in a
constructor.

53
ankitemails@gmail.com

Java Beginners Tutorial

Constructor Chaining:
Every constructor calls its superclass constructor. An implied super() is therefore included in
each constructor which does not include either this() or an explicit super() call as its first
statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first
statement of the constructor. The explicit super allows parameter values to be passed to the
constructor of its superclass and must have matching parameter types A super() call in the
constructor of a subclass will result in the call of the relevant constructor from the superclass,
based on the signature of the call. This is called constructor chaining.
The super() construct as with this() construct: if used, must occur as the first statement in a
constructor, and it can only be used in a constructor declaration. This implies that this() and super()
calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of
constructors in the same class, the super() construct leads to chaining of subclass constructors to
superclass constructors. if a constructor has neither a this() nor a super() construct as its first
statement, then a super() call to the default constructor in the superclass is inserted.
If a class only defines non-default constructors, then its subclasses will not include an implicit
super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call
a superclass constructor, using the super() construct with the right arguments to match the
appropriate constructor of the superclass.

54
ankitemails@gmail.com

Chapter 10
STATEMENT
IN THIS SECTION:

ankitemails@gmail.com

Type of Statement
Control Statement
Looping Statement
Flow Control Statement

Java Beginners Tutorial

Java Statements
Here we will learn about statements in java.

Type of Java Statement

Control Statement
Assignment Statement

In this chapter we will discuss about control statements. Visit here for assignment statement topic.

Control Statements

Conditional execution
Looping
Flow Control Statement

Types of Conditional Execution

If Statement
If - Else statement
If- Else-if statement
Switch Statement

If Statement
If statement in java encloses some code which is executed only if a condition is true. If
statement only takes a boolean expression as its condition.
Note*: Unlike other languages Java does not accept numbers as conditional operators. It only
considers Boolean expressions as conditions which returns TRUE / FALSE.

56
ankitemails@gmail.com

Java Beginners Tutorial

Syntax of If Statement

if (true)
System.out.println("Hello! This will always get
printed");
if (Boolean Expression) { Code block to
get executed }

If Else Statement
If Else statement consists of one if condition and and one else part. It encloses some code which
is executed only if the if condition is true, if its false then the else part of the code will be executed.
If else statement takes boolean expression as its condition.
Note*: Unlike other languages, Java does not accept numbers as conditional operators. It only
considers boolean expressions as conditions which returns TRUE / FALSE.
E.g if(1==1) is accepted as it is boolean expression and will return true. if(x=1) statement is not
allowed in java.
Syntax of If Else Statement
if (1 == 2)
System.out.println("Hello! This will not get
printed");
else
System.out.println("Hello! This will get printed");
if (Boolean Expression) { Code block to
get executed } else{ code block to get
executed when above condition is false
}

57
ankitemails@gmail.com

Java Beginners Tutorial

If Else If Statement
If Else If statement consists of multiple if conditions and and an else part. If the if condition is
true then the enclosed code will be executed. But if the if condition is false then it will check for
the next if condition. If the next if condition is true then the enclosed code will be executed
otherwise the else part of the code will be executed. If Else If statements takes boolean
expression as its condition .
Note*: Unlike other language Java doesn't accept numbers as conditional Operator. Only thing
that can be accepted as condition is boolean expression which returns TRUE / FALSE.
E.g If(x=1) is not allowed while if(1==1) is accepted as it is boolean expression and will return true.
Syntax of If Else If Statement
if (1 == 2)
System.out.println("Hello! This will not get
printed");
else if (1 == 1)
System.out.println("Hello! This will get printed");
else
System.out
.println("This will get executed when Above
conditio is FALSE");
if (Boolean Expression) { Code block to
get executed } else{ code block to get
executed when above condition is false
}

Types of Looping Statement

For Loop
While Loop
Do - While Loop

For Loops
As per JDK 7 we have two different versions of for loop. Basic For and Enhanced Loop.
Enhanced for loop is designed to iterate through Arrays and Collections.

58
ankitemails@gmail.com

Java Beginners Tutorial

Basic For Loop


For loop has 3 main parts.

Declaration & Initialization of Variable


Conditional check
Iteration Expression
Note*:
All 3 parts will be separated by semicolon.
None of 3 block is mandatory.
Initialization block can have more than one variable while conditional
block cannot have more than one BOOLEAN expression.
First part(Initialization & Declaration) will happen once only and that is
before anything else in for loop.
Second(Conditional Check ) & Third (Iteration Expression) part will run
with each iteration.

Example
for (int i = 0, k = 1 ; k < 5 ;
// DO SOMETHING HERE
}

Enhanced For Loop


Enhanced for loop has only 2 part.

Declaration
Expression
int[] strArr = { 1, 2, 3 };
for (int i : strArr) {
System.out.println(i);
}

59
ankitemails@gmail.com

i++, k++) {

Java Beginners Tutorial

List<String> lstObj = new ArrayList<String>();


lstObj.add("Hi");
lstObj.add("Hello");
lstObj.add("How");
for(String str : lstObj){
System.out.println(str);
}

While Loop
WHILE statement is useful when you want to execute something till a particular condition is true.

Scenario of WHILE loop


Ask user to provide input and wait till user provide the input.

Syntax of WHILE loop


while (expression) {
//Do Something
}
Here while statement will evaluate the expression and check if it is true or not. If true then execute
the statement within loop. Once completed execution in loop again check the expression. Perform
this activity unless value of expression is not TRUE.

Example Code WHILE loop


class JBT_WhileLoopExample {
public static void main(String[] args) {
System.out.println("While For Loop Example");
boolean bool = true;
/*
*
*
*
*
*

Here while will check the expression.


bool value is TRUE so statement within
loop will get executed. Inside loop for
first iteration, value of bool is set
to FALSE. Hence in next iteration while

60
ankitemails@gmail.com

Java Beginners Tutorial

* loop will check if value of bool is


* true or false, now it is FALSE so there
* will not be next execution within loop.
*/
while (bool) {
System.out.println("Expression value is TRUE");
bool = false;
}
}

System.out.println("Expression value is FALSE NOW");

Output of above code would be


While For Loop Example
Expression value is TRUE now
Expression value is now FALSE

Do While loop
Do - While loop is same as While loop except in this case loop is confirmed to execute once(Means
in any case statements in Do-While block will execute at least once).

Syntax of Do-While Loop


do {

// Do Something Here
} while (expression);

As you can see in this loop expression is evaluated in the end. So for the first time block will
executed irrespective of the value of expression.

61
ankitemails@gmail.com

Java Beginners Tutorial

Sample code
/*
* Here we will learn about the Do-While loop in Java.
*/
class JBT_DoWhileLoop {
public static void main(String[] args) {
/*
* Create do-while loop to Print the
* string until var is 4
*/
int i = 0;
do {
System.out.println("Inside Do-While Loop");
System.out.println("Value of expression is :"
+ (i < 5));
i++;
} while (i < 5);

System.out.println("Outside of Do-While Loop");


System.out.println("Value of expression is :"
+ (i < 5));

Output of the above program would be


Inside Do-While Loop
Value of expression is :true
Inside Do-While Loop
Value of expression is :true
Inside Do-While Loop
Value of expression is :true
Inside Do-While Loop
Value of expression is :true
Inside Do-While Loop
Value of expression is :true
Outside of Do-While Loop
Value of expression is :false

62
ankitemails@gmail.com

Java Beginners Tutorial

Types of Flow Control Statement

Return Statement
Continue Statement
Break Statement

63
ankitemails@gmail.com

Chapter 11
OPERATOR
IN THIS SECTION:

ankitemails@gmail.com

Operator Precedence
Example of Operator Precedence
Operator Associativity
Example of Operator Associativity

Java Beginners Tutorial

Operators in java
In this chapter we will learn about Operator Precedence and Operator Associativity.

Operator Precedence
Precedence decides which operator will be evaluated first in a case where more than one
operators are present in the same calculation.
Operator Precedence Table
Operators
Postfix
Unary
multiplicative
Additive
Shift
Relational
Equality
bitwise AND
bitwise exclusive OR
bitwise inclusive OR
logical AND
logical OR
Ternary
assignment

Precedence(High to Low)
expr++ expr-++expr --expr +expr -expr ~ !
* / %
+ << >> >>>
< > <= >= instanceof
== !=
&
^
|
&&
||
? :
= += -= *= /= %= &= ^= |= <<= >>=
>>>=

Example of Precedence
/*
* Here we will see the effect of precedence in operators life
*/
class OperatorPrecedenceExample {
public
int
int
int

static void main(String args[]) {


i = 40;
j = 80;
k = 40;

int l = i + j / k;
/*
* In above calculation we are not using

65
ankitemails@gmail.com

Java Beginners Tutorial

* any bracket. So which operator will be


* evaluated first is decided by
* Precedence. As precedence of divison(/)
* is higher then plus(+) as per above
* table so divison will be evaluated
* first and then plus.
*
* So the output will be 42.
*/
System.out.println("value of L :" + l);
int m = (i + j) / k;
/*
* In above calculation brackets are used
* so precedence will not come in picture
* and plus(+) will be evaluated first and
* then divison()/. So output will be 3
*/

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

Operator Associativity
If two operators having same precedence exists in the calculation then Associativity of the
operators will be used to decide which operator will be executed first.

Example of Associativity
package jbt.bean;
/*
* Here we will see the effect of precedence in operators life
*/
public class OperatorAssociativityExample {
public static void main(String args[]) {
int i = 40;

66
ankitemails@gmail.com

Java Beginners Tutorial

int j = 80;
int k = 40;
int l = i / k * 2 + j;
/*
* In above calculation we are not using
* any bracket. And there are two operator
* of same precedence(divion and
* multiplication) so which operator(/ or
* *) will be evaluated first is decided
* by association. Associativity of * & /
* is left to right. So divison will be
* evaluated first then multiplication.
*
* So the output will be 82.
*/
System.out.println("value of L :" + l);
int m = i / (k * 2) + j;
/*
* In above calculation brackets are used
* so associativity will not come in
* picture and multiply(*) will be
* evaluated first and then divison()/. So
* output will be 80
*/
}

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

Operators in Java
Let us discuss about each operator individually.
Assignment (=) and Arithmetic operators(+, -, *, /) will work the same way as they do in other
programming language. So we will not discuss about them. The precedence for '/' & '*' operators
is higher than sum(+) or minus(-) or modular division(%)

67
ankitemails@gmail.com

Chapter 12
OVERLOADING
IN THIS SECTION:
Overloading Method Rules
Overloading Method Example
Invoking Overloaded method

ankitemails@gmail.com

Java Beginners Tutorial

Overloading
Overloaded method gives you an option to use the same method name in a class but with different
argument.

Overloading Method Rules


There are some rules associated with overloaded method.
Overloaded methods

Must change the argument list


Can change the return type
Can change the access modifier(Broader)
Can declare new or broader checked exception

A method can be overloaded in Class or in SubClass.

Overloading Method Example


//Overloaded method with one argument
public void add(int input1, int input2) {
System.out.println("In method with two argument");
}
//Overloaded method with one argument
public void add(int input1) {
System.out.println("In method with one argument");
}

69
ankitemails@gmail.com

Java Beginners Tutorial

Invoking Overloaded Method


Out of several available overloaded method which method to invoke is based on the arguments.
add(3,4);
add(5);

First call will execute the first method and second will execute the second method.
Note*: Reference type decided which overloaded method to invoke and
not the Object as opposed to Overriding.

70
ankitemails@gmail.com

Chapter 13
OVERLOADING
IN THIS SECTION:

ankitemails@gmail.com

What is Method Overriding


Method Overriding Example
Override Rules
Invoke Super Class method

Java Beginners Tutorial

Method Override
A Class inheriting method from its super class has the option to override it. Benefit of overriding
is the ability to define behaviour specific to particular subclass.

Method Overriding Example


public class ParentClass {
public void show() {
System.out.println("Show method of Super class");
}
}
public class SubClass extends ParentClass {
// below method is overriding the ParentClass
// version of show method
public void show() {
System.out.println("Show method of Sub class");
}
}

Method Override Rules

Overriding method cannot have more restrictive access modifier than the method being
overridden but it can be less.
The argument list must exactly match that of the overridden method, if they don't it is more
likely that you are overloading the method.
Return type must be the same as, or subtype of the return type declared in overridden
method in Super class.
Overriding method can throw any unchecked exception(Runtime) but it can throw checked
exception which is broader or new than those declared by the overridden method but it
cannot throw fewer or narrow checked exception.
Final method cannot be overridden.
Static methods cannot be overridden.
If a method cannot be inherited then it cannot be overridden.

Invoke super class method


What if you have overridden method in subclass and you still want to access parent class
method. In this case you can use SUPER keyword.

72
ankitemails@gmail.com

Chapter 14
SERIALIZATION
IN THIS SECTION:

ankitemails@gmail.com

What is Serialization
Use of Serialization
Serialization & De-Serialization
Use of serialVersionUID
Use of Transient
Serialziable effect on Class Hierarchy
Transient vs. Static Variable
Final Modifier Effect on Serialization

Java Beginners Tutorial

SERIALIZATION
What is Serialization
Serialization is a process in which current state of Object will be saved in stream of bytes. As byte
stream create is platform neutral hence once objects created in one system can be desterilized
in other platform.

What is the use of Serialization


As written above serialization will translate the Object state to Byte Streams. This Byte stream
can be used for different purpose.

Write to Disk
Store in Memory
Sent byte stream to other platform over network
Save byte stream in DB(As BLOB)

Serialization and Deserialization in Java


Now we know what is serialization. But in terms of Java how this serialization will work and how
to make a class serializable. Java has already provided out of the box
way(java.io.Serializable Interface) to serialize an Object. If you want any class to be serialized
then that class needs to implement give interface.
Note*: Serializable Interface is a Marker Interface. Hence there is no method in Serializable
interface.

Code for Serialization of Java Class


Employee.java
package com.jbt;
import java.io.Serializable;
public class Employee implements Serializable {
public String firstName;
public String lastName;
private static final long serialVersionUID = 5462223600l;
}

74
ankitemails@gmail.com

Java Beginners Tutorial

SerializaitonClass.java
package com.jbt;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializaitonClass {
public static void main(String[] args) {
Employee emp = new Employee();
emp.firstName = "Vivekanand";
emp.lastName = "Gautam";
try {

FileOutputStream fileOut = new FileOutputStream(


"./employee.txt");
ObjectOutputStream out = new ObjectOutputStream(
fileOut);
out.writeObject(emp);
out.close();
fileOut.close();
System.out
.printf("Serialized data is saved in
./employee.txt file");
} catch (IOException i) {
i.printStackTrace();
}
}

DeserializationClass.java
package com.jbt;
import java.io.*;
public class DeserializationClass {
public static void main(String[] args) {
Employee emp = null;
try {
FileInputStream fileIn = new FileInputStream(
"./employee.txt");

75
ankitemails@gmail.com

Java Beginners Tutorial

ObjectInputStream in = new ObjectInputStream(


fileIn);
emp = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserializing Employee...");
System.out.println("First Name of Employee: "
+ emp.firstName);
System.out.println("Last Name of Employee: "
+ emp.lastName);

First run "SerializaitonClass" and you will get "employee.txt" file created.
Second run "DeserializationClass" and java will deserialize the class and value will be printed in
console.
Output would be
Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam

Use of serialVersionUID
You must have seen a variable named "serialVersionUID" have been used in source code. There
is a specific reason behind using this variable.
serialVersionUID is a version number associated to each serializable class by serialization
runtime. This version number is used during deserialization process to verify that the sender and
receiver of a serialized object have loaded class for that object which is compatible with respect
to serialization.

Defining a serialVersionUID field in serializable class is not mandatory.

76
ankitemails@gmail.com

Java Beginners Tutorial

If a serializable class have explicit serialVersionUID then this field should be of type long
and must be static and final.
If there is no serialVersionUID field defined explicitly then serialization runtime will
calculate default value for that class. Which can vary based on compiler implementation.
Hence it is advisable to define serialVersionUID.
It is advised to use private access modifier for serialVersionUID.
Array classes cannot declare an explicit serialVersionUID, so they always have the default
computed value, but the requirement for matching serialVersionUID values is waived for
array classes.
If there is a difference between serialVersionUID of loaded reciever class and
corresponding sender class then InvalidClassException will be thrown.

Use of Transient
We can save the state of an object using Serializable. But what if i don't want to save state of a
field? In this case transient modifier can be used like below. Transient fields state will not be saved
while serialization process and default value will be assigned to same variable while deserialization.
Changing the Employee class with transient variable.
package com.jbt;
import java.io.Serializable;
public class Employee implements Serializable {
public String firstName;
/*
* Here transient modifier is used for
* lastName variable. This variable's state
* will not be saved while serialzation. While
* De-Serialization process default value will
* be provide. null in this case.
*/
transient public String lastName;
private static final long serialVersionUID = 5462223600l;
}

77
ankitemails@gmail.com

Java Beginners Tutorial

If you execute the same class(SerializaitonClass & DeserializationClass) output will be different
then previous code.
Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: null

As you can see above last name is coming as null because state of that variable was not saved
while serialization process.

Class Hierarchy and Serializable


Here I will discuss about the effect of Serializable interface on Class hierarchy. If a class has
implemented Serializable interface then state of this class can be saved. But if same class extend
another class which didn't implement Serializable interface then Super class's state will not be
saved.
To see the difference we will update original Employee class. Now this class will extend another
class superEmployee . This super class will not implement Serializable interface.
package com.jbt;
import java.io.Serializable;
public class Employee extends superEmployee implements
Serializable {
public String firstName;
private static final long serialVersionUID = 5462223600l;
}
class superEmployee {
public String lastName;
}

If you execute "SerializaitonClass" and "DeserializationClass" one after another then output
would be like below
Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: null

78
ankitemails@gmail.com

Java Beginners Tutorial

Transient vs. Static variable java


Static Variable
Static variables belong to a class and not to any individual instance. The concept of serialization
is concerned with the object's current state. Only data associated with a specific instance of a
class is serialized, therefore static member fields are ignored during serialization.

Transient Variable
While serialization if you don't want to save state of a variable. You have to mark that variable as
Transient. Environment will know that this variable should be ignored and will not save the value
of same.
Note*: Even concept is completely different and reason behind not
saving is different still people get confused about the existence of both.
As in both the case variables value will not get saved.

Difference between these two


Source code : Pay attention to every single code change.
Employee.java
package com.jbt;
import java.io.Serializable;
public class Employee extends superEmployee {
public String firstName;
private static final long serialVersionUID = 5462223600l;
}
class superEmployee implements Serializable {
public String lastName;
static String companyName;
transient String address;
static transient String companyCEO;
}

79
ankitemails@gmail.com

Java Beginners Tutorial

SerializaitonClass.java
package com.jbt;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializaitonClass {
public static void main(String[] args) {
Employee emp = new Employee();
emp.firstName = "Vivekanand";
emp.lastName = "Gautam";
emp.companyName = "JBT";
// Below part needs to be removed in case
// address field is made final
emp.address = "MUM";
emp.companyCEO = "ME CEO";
try {

FileOutputStream fileOut = new FileOutputStream(


"./employee.txt");
ObjectOutputStream out = new ObjectOutputStream(
fileOut);
out.writeObject(emp);
out.close();
fileOut.close();
System.out
.printf("Serialized data is saved in
./employee.txt file");
} catch (IOException i) {
i.printStackTrace();
}
}

DeserializationClass.java
package com.jbt;
import java.io.*;
public class DeserializationClass {

80
ankitemails@gmail.com

Java Beginners Tutorial

public static void main(String[] args) {


Employee emp = null;
try {
FileInputStream fileIn = new FileInputStream(
"./employee.txt");
ObjectInputStream in = new ObjectInputStream(
fileIn);
emp = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserializing Employee...");
System.out.println("First Name of Employee: "
+ emp.firstName);
System.out.println("Last Name of Employee: "
+ emp.lastName);
System.out.println("Company Name: "
+ emp.companyName);
System.out
.println("Company CEO: " + emp.companyCEO);
System.out.println("Company Address: "
+ emp.address);
}

First Execute "SerializaitonClass" and you will get below output.


Serialized data is saved in ./employee.txt file

Second execute "DeserializationClass" and you will get below output


Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Company Name: null
Company CEO: null
Company Address: null

81
ankitemails@gmail.com

Java Beginners Tutorial

As you can see from output only last name value has been saved. Neither Static nor Transient
variables value has been saved.
Now change the code a little bit and see what happens.
Employee.java
package com.jbt;
import java.io.Serializable;
public class Employee extends superEmployee {
public String firstName;
private static final long serialVersionUID = 5462223600l;
}
class superEmployee implements Serializable {
public String lastName;
/*
* Here i am providing the value of company
* name,companyCEO and address while defining
* these variables.
*/
static String companyName = "TATA";
transient String address = "DEL";
static transient String companyCEO = "Jayshree";
}

Again execute the same code and see the output


Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Company Name: TATA
Company CEO: Jayshree
Company Address: null

See the output very carefully. Here value of companyName, companyCEO has been saved but
not of address. Also check the saved value of these variable.
Company Name: TATA
Company CEO: Jayshree
In both the case value stored here are taken from class(Employee class) and not from Object(emp
object). Also companyCEO variabls value is saved even when it is transient. Because static
modifier change the behavior of this variable.

82
ankitemails@gmail.com

Java Beginners Tutorial

Bullet Point
1.

Static variables value can be stored while serializing if the same is provided while
initialization.
2. If variable is defined as Static and Transient both, than static modifier will govern the
behaviour of variable and not Transient.

Final modifier effect on Serialization


To see the effect of Final modifier again change the code of Employee class.
Employee.java
package com.jbt;
import java.io.Serializable;
public class Employee extends superEmployee {
public String firstName;
private static final long serialVersionUID = 5462223600l;
}
class superEmployee implements Serializable {
public String lastName;
/*
* Here i am providing the value of company
* name,companyCEO and address while defining
* these variables. I am making address as
* final here
*/
static String companyName = "TATA";
transient final String address = "DEL";
static transient String companyCEO = "Jayshree";
}

Again execute the code and see the difference. Output for above code would be
Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Company Name: TATA
Company CEO: Jayshree
Company Address: DEL

83
ankitemails@gmail.com

Java Beginners Tutorial

As you can see now address fields is also saved while serialization because it is now Final.

Interface and Final


I have seen a scenario when you can serialize variables inside an Interface which is not serialized.
Employee.java
package com.jbt;
import java.io.Serializable;
public class Employee extends superEmployee implements
variableConstant {
public String firstName;
private static final long serialVersionUID = 5462223600l;
}
class superEmployee implements Serializable {
public String lastName;
/*
* Here i am providing the value of company
* name,companyCEO and address while defining
* these variables. I am making address as
* final here
*/
static String companyName = "TATA";
transient final String address = "DEL";
static transient String companyCEO = "Jayshree";
}
interface variableConstant {
public static final String education = "MCA";
}

84
ankitemails@gmail.com

Java Beginners Tutorial

DeserializationClass.java
package com.jbt;
import java.io.*;
public class DeserializationClass {
public static void main(String[] args) {
Employee emp = null;
try {
FileInputStream fileIn = new FileInputStream(
"./employee.txt");
ObjectInputStream in = new ObjectInputStream(
fileIn);
emp = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserializing Employee...");
System.out.println("First Name of Employee: "
+ emp.firstName);
System.out.println("Last Name of Employee: "
+ emp.lastName);
System.out.println("Company Name: "
+ emp.companyName);
System.out
.println("Company CEO: " + emp.companyCEO);
System.out.println("Company Address: "
+ emp.address);
System.out.println("Education: " + emp.education);
}
}

Execute above code and see the output.


Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Company Name: TATA
Company CEO: Jayshree

85
ankitemails@gmail.com

Java Beginners Tutorial

Company Address: DEL


Education: MCA

Here you can see that education's value is saved. This value is part of an Interface. But as this is
constant hence it is saved while serialization.

86
ankitemails@gmail.com

Chapter 15
EXCEPTION
IN THIS SECTION:

ankitemails@gmail.com

What is Exception
Exception Origination
Exception Hierarchy
Exception Handling
Checked vs. Unchecked

Java Beginners Tutorial

Exceptions
Exception are used in Java to handle errors or any other exceptional event that occurs in the
normal flow of program. There are several way Exception can occur in Java.

Data provided is not in expected format(e.g. int instead of String).


DB can not connected.
Network connection Lost.
Operation to be performed on Object is null.
.....

Exception Origination
Exception can be thrown either from JVM or Programmatically.

JVM Exception
Exception which are thrown by JVM exclusively at runtime.

Programmatic Exception
Exception which are thrown by application explicitly.

Java Exception Hierarchy


Every Exception in Java is sub type of Exception class which in turn is the subclass of Throwable.
And as we know everything in Java derived from Object class. Throwable also derived from class
Object. Exception and Error are two different classes that derived from Throwable. Errors
represent situation which doesn't occur because of Programming error but that might happen at
the time of program execution and these are abnormal behaviour which java program cannot
handle and shouldn't bother to handle. JVM running out of memory is a type of Error which can
occur at runtime.

Exception Handling
We know that exception could be thrown at any point. So we either handle it or delegate
exception to handle at another level.

Delegate Exception
Once we get exception we can say that we won't handle exception here but calling method will
handle given exception. To identify this we need to use throws clause.

88
ankitemails@gmail.com

Java Beginners Tutorial

Process Exception
We can process exception using try-catch block. Code which you expect to throw exception
needs to be surrounded by try keyword and catch block is where you will do what needs to be
done after exception thrown.

Checked Vs Unchecked Exception


Checked exceptions are subclasss of Exception excluding RuntimeException and its
subclasses.
2. Checked Exceptions force programmers to deal with the exception that may be thrown.
3. When a checked exception occurs in a method, the method must either catch the
exception and take the appropriate action, or pass the exception on to its caller.
1.

Example of Checked exception


Arithmetic exception.
1. Unchecked exceptions are RuntimeException and any of its subclasses.
2. Compiler doesn't force the programmers to either catch unchecked exception or declare
it in a throws clause.
3. Programmers may not even know that the exception could be thrown.
4. Checked exceptions must be caught at compile time.
5. Runtime exceptions do not need to be.

Example of Unchecked Exception


ArrayIndexOutOfBounds Exception.

Java Exception Handling


Now we know that exception can occur in Java programme at any time(or Any Location). So we
need to know how to handle these exceptions. Handling exception is required attribute in
developing robust application. We can handle exception by

89
ankitemails@gmail.com

Chapter 16
INNER CLASS
IN THIS SECTION:

ankitemails@gmail.com

Syntax of Inner class


Type of Inner Class
Access Inner class
Modifiers Applied to Inner Class

Java Beginners Tutorial

Inner Class
Inner classes are class within Class. Inner class instance has special relationship with Outer class.
This special relationship gives inner class access to member of outer class as if they are the part
of outer class.
Note: Inner class instance has access to all member of the outer
class(Public, Private & Protected)

Syntax for creating Inner Class


//outer class
class OuterClass {
// inner class
class InnerClass {
}
}

Type of Inner class

Static
Method Local
Anonymous
Normal inner class (Inner classes which doesn't fall under any of above category)

Normal Inner Class


Inner classes which are not method local , static or anonymous are normal inner class.
//outer class
class OuterClass {
// inner class
class InnerClass {
}
}

If you compile above code it will produce two class file.


outer.class
inner$outer.class

91
ankitemails@gmail.com

Java Beginners Tutorial

Note: You can't directly execute the inner class's .class file with java command.
As it is not static inner class so we can't use static keyword with it.

How to access Inner Class


Inner class can be accessed only through live instance of outer class.

Within Outer Class


Outer class can create instance of the inner class in the same way as normal class member.
class OuterClass {
private int i = 9;
// Creating instance of inner class and
// calling inner class function
public void createInner() {
InnerClass i1 = new InnerClass();
i1.getValue();
}

// inner class declarataion


class InnerClass {
public void getValue() {
// accessing private variable from
// outer class
System.out.println("value of i -" + i);
}
}

92
ankitemails@gmail.com

Java Beginners Tutorial

From Outside Outer Class


Create outer class instance and then inner class instance.
class MainClass {

public static void main(String[] args) {


// Creating outer class instance
OuterClass outerclass = new OuterClass();
// Creating inner class instance
OuterClass.InnerClass innerclass = outerclass.new
InnerClass();
// Classing inner class method
innerclass.getValue();
}

Above code can also be replaced with


OuterClass.InnerClass innerClass = new OuterClass.new InnerClass();

this keyword
There are some rules associated with this and it refer the currently executing Object. So in case
of Inner class this keyword will refer the currently executing inner class Object. But to get this
for outer class use OuterClass.this.

Modifiers Applied
Normal inner class will be treated like member of the outer class so it can have several Modifiers
as opposed to Class.
o
o
o
o
o
o

final
abstract
public
private
protected
strictfp

Note: Don't get confused with the modifiers of Class and Inner Class.
They are completely different.

93
ankitemails@gmail.com

Java Beginners Tutorial

Method Local Inner Class


When an inner class is defined inside the method of Outer Class it becomes Method local inner
class.

Syntax for Creating Method Local Inner Class


class OuterClass {
private int i = 9;

// Creating instance of inner class and


// calling inner class function
public void innerMethod() {
// inner class declarataion inside method
class InnerClass {
public void getValue() {
// accessing private variable from
// outer class
System.out.println("value of i -" + i);
}
}
// inner class instance creation
InnerClass i1 = new InnerClass();
i1.getValue();
}

Now definition of inner class is inside a method in Outer class. Still the instance of the outer class
can be created but only after definition of inner class as you can see above.
Note:
Method local inner class can be instantiated within the method where it
is defined and nowhere else.
Method local inner class cannot use the variable defined in method
where it id defined still it can use the instance variable.
If method local variable is Final method local inner class can use it.(*
Now variable is Final)

94
ankitemails@gmail.com

Java Beginners Tutorial

Modifiers Applied to Method Local Inner Class


Method local inner classes are eligible for modifiers like local variable so an method local inner
class can have final or abstract.

95
ankitemails@gmail.com

Chapter 17
STRING
IN THIS SECTION:
String Literal & Object
How to Create String
Garbage Collection of String

ankitemails@gmail.com

Java Beginners Tutorial

String
String class represents character strings. All string literals in Java programs, such as "abc", are
implemented as instances of this class. Strings are like constants, once created its value cannot
be changed. String objects are immutable and hence it can be shared. String Buffer and Difference
between String Buffer and String Builder can be used in place of String if lot of String Operation
is to be performed.

Important Aspect of String


1.Immutable

Important Method
1.intern()
2.length()
3.toString()
4.trim

String Storage
As you must be knowing, everything in java except primitives are Object. This is true for String too.
String is also an Object, hence it will reside on Heap only. But there is one more term used for
String storage and that is String Pool/ String Literal Pool. Most of the time people think of it as a
separate pool of String Object(True for me too). But this is not true. String Pool/ String Literal Pool
are nothing but a collection of references to String objects. As we know that String object is
immutable its good to "share" the same String object with multiple references. (Vice versa is true
also as String objects are shared between different references that is the reason String Objects
are made Immutable.)

String Literal & Object


So when we are saying String literal, we are actually referring the reference in String Pool and
when we are saying String Object we are directly referring the String Object in Heap. But in both
cases we are referring the Object in Heap only(Directly/ Indirectly).

97
ankitemails@gmail.com

Java Beginners Tutorial

How to Create
Now question arises how to create String Literal and String Object. As we know that we can create
String Object in 2 ways.
String str=new String("abc");
String str1="abc";
When we are using new operator to create String, we are actually creating the String object in
Heap like in First option. Here we are creating a String Object in Heap memory with value as
"abc". and a reference named "str". Also note that as we are using ""(literals) for creating this String
Object, a literal will also be created. In total there will be 1 String Object 1 String literal and
reference will be created. But reference will refer only the String object in Heap and not the literal
in
String
pool.
And when we are using "" we are creating the literals(Everything inside "" are treated as literals).
In this case(2nd scenario) JVM will look for all the references in String Pool and check if any of
them pointing to String object in heap with value "abc", if it finds any, it will return the reference of
that object. Otherwise JVM will create a new String Object in Heap and interned it (Using inter()
method) in String Pool(Reference for this object will be added in String Pool) for later reference.
And reference of the newly created object will be returned. Now if we again write the same code
to create String literal.
String str2="abc";
This time JVM look in String Pool to search for any object having same value to abc as there is
already one in String Pool JVM will just return the reference of existing String Object with value
"abc"(Which was created in Second line) and no new String object will be created in Heap.

Garbage Collection for String


You might have heard that String literals are never eligible for Garbage Collection. Note we have
mentioned String literal and not String Object. There is a difference. An object is eligible for
garbage collection when it is no longer referenced from an active part of the application. String
literals always have a reference to them from the String Literal Pool. That means that they always
have a reference to them and are, therefore, not eligible for garbage collection. But there may be
some String Object which dont have any reference then they will be eligible for garbage
collection.

98
ankitemails@gmail.com

Chapter 18
INTERFACE
IN THIS SECTION:

ankitemails@gmail.com

What is Interface
Declare an Interface
Access an Interface
Rules Applied to Interface
Interface vs. Abstract Class

Java Beginners Tutorial

Java Interface
Creating an Interface means defining a Contract. This Contract states what a class can do without
forcing how it should do.

Declaring an Interface
Interface can be defined with Interface keyword.

Java Interface Example


public interface MyInterface {
int i = 0;
public void Height(int height);
public abstract void setHeight();
}

Rules for Declaring Interface


There are some rules that needs to be followed by Interface.

All Interface methods are implicitly public and abstract. Even if you write these keyword
it will not create problem as you can see in second method declaration.
Interfaces can declare only Constant. Instance variables are not allowed. It means all
variables inside Interface must be public, static, final. Variables inside interface are
implicitly public static final.
Interface methods can not be static.
Interface methods can not be final, strictfp or native.
Interface can extend one or more other interface. Note: Interface can only extend other
interface.

100
ankitemails@gmail.com

Java Beginners Tutorial

Interface vs. Abstract Class


Interface are like 100% Abstract Class. Interface can not have non abstract methods while abstract
class can have. A Class Can implement more than one interface while Class can extend only one
class. As Abstract class comes in hierarchy of Classes it can extend other classes too while
Interface can only extend Interfaces.

Use Interface in Class


How can we take the advantage of Interface after creating it in Java. To take the advantage we
need to implement or class with given Interface. Implement keyword can be used for this
purpose.

Examples of Class Implementing Interface


Example 1:
public class InterfaceExampleOne implements interfaceOne {
}
interface interfaceOne {
}
Example 2:
/*
* As implemented Interface have any abstract
* method so this class
* need to implement any method.
*/
class InterfaceExampleTwo implements interfaceTwo {
@Override
public void methhod() {
System.out.println(var);
}
}

101
ankitemails@gmail.com

Java Beginners Tutorial

/*
* Below interface has an abstract method so
* implemented class needs to
* implement this method unless and unti
* it is abstract itself
*/
interface interfaceTwo {
public final int var = 9;
}

public abstract void methhod();

Example 3:
package test;
/*
* As below class is not abstract class and it is extending
abstract class which
* has not yet implemented the method from interface so this
class is FORCED to
* implement method from Interface in hierarachy(interfaceTwo).
*/
class InterfaceExampleTwo extends InterfaceExampleThree {
@Override
public void methhod() {
System.out.println(var);
}
}
/*
* Below interface has an abstract method so
* implemented class needs to implement this
* method unless and untill it is abstract itself
*/
interface interfaceTwo {
public final int var = 9;
}

public abstract void methhod();

/*
* Even if Interface has abstract method ABSTRACT

102
ankitemails@gmail.com

Java Beginners Tutorial

* CLASS is not forced to implement it. Abstract


* class may/may not navigate this responsibility
* of implementing abstract method to class which
* is not abstract.
*/
abstract class InterfaceExampleThree implements
interfaceTwo {
// Method from Interface is not implemented
// here
}

103
ankitemails@gmail.com

Chapter 19
THIS KEYWORD
IN THIS SECTION:
What is this keyword
Applicability
Example of this keyword

ankitemails@gmail.com

Java Beginners Tutorial

The Keyword
What is this keyword
this is a keyword in Java. Which can be used inside method or constructor of class. It(this) works
as a reference to current object whose method or constructor is being invoked. this keyword can
be used to refer any member of current object from within an instance method or a constructor.

Applicability
this keyword can be applied on

Method
Variable (Instance Variable / Method Parameter)
Constructor

this keyword with field(Instance Variable)


this keyword can be very useful in case of Variable Hiding. We cannot create two Instance/Local
Variable with same name. But it is legal to create One Instance Variable & One Local Variable or
Method parameter with same name. In this scenario Local Variable will hide the Instance Variable
which is called Variable Hiding.

Example of Variable Hiding


class JBT {
int variable = 5;
public static void main(String args[]) {
JBT obj = new JBT();

obj.method(20);
obj.method();

void method(int variable) {


variable = 10;
System.out.println("Value of variable :" + variable);

105
ankitemails@gmail.com

Java Beginners Tutorial

void method() {
int variable = 40;
System.out.println("Value of variable :" + variable);
}

Output of the above programme


Value of variable :10
Value of variable :40

As you can Instance Variable is hiding here and value getting displayed is the value of Local
Variable(or Method Parameter) and not Instance Variable. To solve this problem this keyword
can be used with field to point Instance Variable instead of Local Variable.

Example of this keyword for Variable Hiding


class JBT {
int variable = 5;
public static void main(String args[]) {
JBT obj = new JBT();

obj.method(20);
obj.method();

void method(int variable) {


variable = 10;
System.out.println("Value of Instance variable :" +
this.variable);
System.out.println("Value of Local variable :" + variable);
}

void method() {
int variable = 40;
System.out.println("Value of Instance variable :" +
this.variable);
System.out.println("Value of Local variable :" + variable);
}

106
ankitemails@gmail.com

Java Beginners Tutorial

Output of the above programme


Value
Value
Value
Value

of
of
of
of

Instance variable :5
Local variable :10
Instance variable :5
Local variable :40

this keyword with Constructor


this keyword can be used inside Constructor to call another overloaded Constructor in same
class. It is called Explicit Constructor Invocation. If a class has two overloaded constructor one
without argument and another with argument. Then this keyword can be used to call Constructor
with argument from Constructor without argument. As constructor can not be called explicitly.

Example of this with Constructor


class JBT {
JBT() {
this("JBT");
System.out.println("Inside Constructor " +
"without parameter");
}
JBT(String str) {
System.out
.println("Inside Constructor with " +
"String parameter as " + str);
}

public static void main(String[] args) {


JBT obj = new JBT();
}

Output of above programme


Inside Constructor with String parameter as JBT
Inside Constructor without parameter

As you can see this can be used to invoke overloaded constructor in the same class.

107
ankitemails@gmail.com

Java Beginners Tutorial

Note*:
this keyword can only be the first statement in Constructor.
A constructor can have either this or super keyword but not both.

this keyword with Method


this keyword can also be used inside methods to call another method from same class.

Example of this keyword with Method


class JBT {
public static void main(String[] args) {
JBT obj = new JBT();
obj.methodTwo();
}
void methodOne() {
System.out.println("Inside Method ONE");
}

void methodTwo() {
System.out.println("Inside Method TWO");
this.methodOne();// same as calling
// methodOne()
}

Output of above programme


Inside Method TWO
Inside Method ONE

108
ankitemails@gmail.com

Java Beginners Tutorial

Example of this keyword as method parameter


public class JBTThisAsParameter {
public static void main(String[] args) {
JBT1 obj = new JBT1();
obj.i = 10;
obj.method();
}
}
class JBT1 extends JBTThisAsParameter {
int i;
void method() {
method1(this);
}

void method1(JBT1 t) {
System.out.println(t.i);
}

109
ankitemails@gmail.com

Chapter 20
ARRAYS
IN THIS SECTION:
Array Declaration
Construction of Arrays
Initialization of Array

ankitemails@gmail.com

Java Beginners Tutorial

Arrays are a data structure type which is used to store multiple variables of the same type. Arrays
can hold Primitives as well as Object.
Note*: Array will always be an Object in Heap.

Array Declaration (Syntax)


Array of Primitives
//Single Dimensional Array
int[] arr; //recommended
int arr[];
//Multi Dimensional Array
int[][] arr; //recommended
int arr[][];
int[] arr[];Array Of Objects

Array Of Object
//Single Dimensional Array
String[] arr; //recommened
String arr[];
//Multi Dimensional Array
String[][] arr; //recommened
String arr[][];
String[] arr[];

Note: You cannot include size of array in declaration.


Declaration only doesn't create array object in heap.

Constructing an Array
This is the step where array object will be created on heap. As once created size of the array can
not be changed, hence size of the array needs to be provided at the time of constructing it.
Note: Size of the array means how much element an array can contains.

111
ankitemails@gmail.com

Java Beginners Tutorial

One Dimensional Array


New keyword will be used to construct one dimensional array.
int[] arr; //declares a new array
arr = new int[10]; Multi Dimensional Array

One Dimensional Array


These are arrays of arrays. So a two dimensional array of array is array of array of int.
int[][] arr;
arr = new int[10][];

Note: Only first part(First Dimension is required) needs the size and not the all.

Initializing Array
Once arrays created and space assigned to it next thing would be to add elements in it.
Initialization of array is the place where we can do this(Adding Element in array).

Single Dimensional Array


int[] arr = new int[10];
arr[0] = 0;
arr[0] = 1;Multi Dimensional Array
int[][] arr = new int[10][];
arr[0][0] = 0;
arr[0][1] = 1;

112
ankitemails@gmail.com

Вам также может понравиться