Академический Документы
Профессиональный Документы
Культура Документы
com
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
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 Installation
Once java is downloaded, it can be installed like any other software (.exe) in your Windows
system.
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
5
ankitemails@gmail.com
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
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.).
Definition
Access Modifier applied to variable
final
int
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
byte
short
int
long
float
double
char
boolean
Instance Variable
Static Variable
Local Variable
Method Parameter
9
ankitemails@gmail.com
10
ankitemails@gmail.com
11
ankitemails@gmail.com
/*
* 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);
12
ankitemails@gmail.com
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
/*
* 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 {
14
ankitemails@gmail.com
Chapter 3
CLASS & OBJECT
IN THIS SECTION:
ankitemails@gmail.com
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)
16
ankitemails@gmail.com
/*
* 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");
}
{
}
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.
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
Import and package statements should be applied to all the classes in the same source
code file.
Syntax
<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).
18
ankitemails@gmail.com
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.
19
ankitemails@gmail.com
Now we will explore the different ways of creating the Object except new Operator.
class JBT {
String Owner;
}
20
ankitemails@gmail.com
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
}
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.
22
ankitemails@gmail.com
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) {
class JBTClassLoader {
static int j = 10;
JBTClassLoader() {
i = j++;
}
int i;
23
ankitemails@gmail.com
@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
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
Syntax
Definition
Public
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
String args[]
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
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
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
31
ankitemails@gmail.com
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
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
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
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
Visibility
Yes
Yes
Yes
No
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
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
Yes
Yes
Yes
Yes
Yes
No
Yes
Yes
Yes
No
Yes
Yes
Yes
No
Yes
Yes
Yes
No
Yes(Only By
Inheritance)
No
Yes
No
No
No
37
ankitemails@gmail.com
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
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
Final
Abstract
Static
Strictfp
Native
Synchronized
Transient
Class
Method
Instance Variable
Local Variable
Method arguments
Definition
Final Class
Final Method
Final Variable
41
ankitemails@gmail.com
Abstract Method
Applicability
1.
Method
Definition
Synchronized Method
42
ankitemails@gmail.com
Method
Definition
Native Method
43
ankitemails@gmail.com
Chapter 8
STATIC KEYWORD
IN THIS SECTION:
ankitemails@gmail.com
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
45
ankitemails@gmail.com
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
Note*: Static keyword can be used with Variables & Methods. It is not
applicable to class.
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
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.
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.
49
ankitemails@gmail.com
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.
/*
* 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
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.
51
ankitemails@gmail.com
//Output would be
Inside Constructor
This is in method
52
ankitemails@gmail.com
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
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
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 Statements
Here we will learn about statements in java.
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
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
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
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
}
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
Example
for (int i = 0, k = 1 ; k < 5 ;
// DO SOMETHING HERE
}
Declaration
Expression
int[] strArr = { 1, 2, 3 };
for (int i : strArr) {
System.out.println(i);
}
59
ankitemails@gmail.com
i++, k++) {
While Loop
WHILE statement is useful when you want to execute something till a particular condition is true.
60
ankitemails@gmail.com
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).
// 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
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);
62
ankitemails@gmail.com
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
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
int l = i + j / k;
/*
* In above calculation we are not using
65
ankitemails@gmail.com
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
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
*/
}
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
Overloading
Overloaded method gives you an option to use the same method name in a class but with different
argument.
69
ankitemails@gmail.com
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
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.
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.
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
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.
Write to Disk
Store in Memory
Sent byte stream to other platform over network
Save byte stream in DB(As BLOB)
74
ankitemails@gmail.com
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 {
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
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.
76
ankitemails@gmail.com
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
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.
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
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.
79
ankitemails@gmail.com
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 {
DeserializationClass.java
package com.jbt;
import java.io.*;
public class DeserializationClass {
80
ankitemails@gmail.com
81
ankitemails@gmail.com
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";
}
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
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.
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
As you can see now address fields is also saved while serialization because it is now Final.
84
ankitemails@gmail.com
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);
}
}
85
ankitemails@gmail.com
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
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.
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.
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
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.
89
ankitemails@gmail.com
Chapter 16
INNER CLASS
IN THIS SECTION:
ankitemails@gmail.com
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)
Static
Method Local
Anonymous
Normal inner class (Inner classes which doesn't fall under any of above category)
91
ankitemails@gmail.com
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.
92
ankitemails@gmail.com
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
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
95
ankitemails@gmail.com
Chapter 17
STRING
IN THIS SECTION:
String Literal & Object
How to Create String
Garbage Collection of String
ankitemails@gmail.com
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 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.)
97
ankitemails@gmail.com
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.
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 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.
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
101
ankitemails@gmail.com
/*
* 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;
}
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;
}
/*
* Even if Interface has abstract method ABSTRACT
102
ankitemails@gmail.com
103
ankitemails@gmail.com
Chapter 19
THIS KEYWORD
IN THIS SECTION:
What is this keyword
Applicability
Example of this keyword
ankitemails@gmail.com
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
obj.method(20);
obj.method();
105
ankitemails@gmail.com
void method() {
int variable = 40;
System.out.println("Value of variable :" + variable);
}
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.
obj.method(20);
obj.method();
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
of
of
of
of
Instance variable :5
Local variable :10
Instance variable :5
Local variable :40
As you can see this can be used to invoke overloaded constructor in the same class.
107
ankitemails@gmail.com
Note*:
this keyword can only be the first statement in Constructor.
A constructor can have either this or super keyword but not both.
void methodTwo() {
System.out.println("Inside Method TWO");
this.methodOne();// same as calling
// methodOne()
}
108
ankitemails@gmail.com
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
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 Of Object
//Single Dimensional Array
String[] arr; //recommened
String arr[];
//Multi Dimensional Array
String[][] arr; //recommened
String arr[][];
String[] arr[];
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
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).
112
ankitemails@gmail.com