Monday, 9 May 2016

Learn Spring with Annotation


Learn Java from begins


Java Tutorial

Java is one of the programming language or technology used for developing distributed application by making use of client server architecture. In other word Java is a programming language suitable to the development of web applications.

Java Born

Java language developed at SUN Micro systems in the year 1995 under the guidance of James Gosling and there team.
Sun micro System Started by group of the students who are studding in Standard University. These peoples found the problem in their room with electronic consumable remote. That means one electronic consumable control is not worked on another electronics consumable. These people want to develop a common remote control which is controlling all the electronic consumables so their contacted James Gosling and requested for the projects. Sun Micro System started by group of students out of them one person also Indian whose name "Vinode Khosla".

Prerequisites

Before learning of java no need to learn any programming language like C and C++. But you have knowledge of programming language and why we use programming languages.

Overview of Java

Java is one of the programming language or technology used for developing distributed application by making use of client server architecture. In other word Java is a programming language suitable to the development of web applications.
Java language developed at SUN Microsystems in the year 1995 under the guidance of James Gosling and there team.
Originally SUN Microsystems is one of the Academic university (Standford University Network)
Developed the rules for java and those rules are programmatically implemented or developed by java soft, INC, USA, JAVASOFT is one of the software division of SUN Microsystems.
Whatever the software developed in the year 1990, SUN Microsystems has released on the name of oak, which is original name of java (scientifically oak is one of the tree name). The OAK has taken 18 months to develop.
The software oak is able to fulfill few requirement of the industry and unable to fulfill some other requirements of the industry. The software oak revised at SUN Microsystems under the guidance of James Gosling and released to the industry on the name of java in the year 1995. Scientifically java is one of the coffee seed name.
The software java is available in the industry in three categories, they are
  1. J2SE (Java 2 Standard Edition)
  2. J2EE (Java 2 Enterprise Edition)
  3. J2ME (Java 2 Micro or Mobile Edition)

J2SE

J2SE is used for developing client side applications.

J2EE

J2EE is used for developing server side applications. To exchange the data between client side application and server side applications we use a protocol called http. In general to extends the data between J2SE and J2EE applications we use a predefined protocol called http.

J2ME

J2ME is used for developing mobile or wireless application by making use of a predefined protocol called WAP(wireless Access / Application protocol).

All versions of java

Java Version SE 7

J2SE 1.2 is called as Dolphin and it is released on 28 July, 2011.
Features
  1. Strings in switch Statement
  2. Type Inference for Generic Instance Creation
  3. Multiple Exception Handling
  4. Support for Dynamic Languages
  5. Try with Resources
  6. Java nio Package
  7. Binary Literals, underscore in literals
  8. Diamond Syntax
  9. Automatic null Handling
Java Version SE 6
J2SE 1.2 is called as Mustang and it is released on 11 December, 2006.
Features
  1. Scripting Language Support
  2. JDBC 4.0 API
  3. Java Compiler API
  4. Pluggable Annotations
  5. Native PKI, Java GSS, Kerberos and LDAP support.
  6. Integrated Web Services.
  7. Lot more enhancements.
J2SE Version 5.0
J2SE 1.2 is called as Tiger and it is released on 30 September, 2004.
Features
  1. Generics
  2. Enhanced for Loop
  3. Autoboxing/Unboxing
  4. Typesafe Enums
  5. Varargs
  6. Static Import
  7. Metadata (Annotations)
  8. Instrumentation
J2SE Version 1.4
J2SE 1.2 is called as Merlin and it is released on 6 February, 2002.
Features
  1. XML Processing
  2. Java Print Service
  3. Logging API
  4. Java Web Start
  5. JDBC 3.0 API
  6. Assertions
  7. Preferences API
  8. Chained Exception
  9. IPv6 Support
  10. Regular Expressions
  11. Image I/O API
J2SE Version 1.3
J2SE 1.2 is called as Kestrel and it is released on 8 May, 2000.
Features
  1. Java Sound
  2. Jar Indexing
  3. A huge list of enhancements in almost all the java area.
J2SE Version 1.2
J2SE 1.2 is called as playground and it is released on 8 December, 1998.
Features
  1. Collections framework.
  2. Java String memory map for constants.
  3. Just In Time (JIT) compiler.
  4. Jar Signer for signing Java ARchive (JAR) files.
  5. Policy Tool for granting access to system resources.
  6. Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java 2D class libraries.
  7. Java Plug-in
  8. Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
  9. Audio support in Applets.
JDK Version 1.1
JDK 1.1 is released on 19 januray, 1997
Features
  1. JDBC (Java Database connectivity)
  2. Inner Classes
  3. Java Beans
  4. RMI (Remote Method Invocation)
  5. Reflection(introspection only)
JDK Version 1.0
JDK 1.0 is called as OAK, and it is released on 23 januray, 1996.

Java Environment Setup

Path

The following programming error is general for all java programmers when they compile any java program.
‘javac’ is not recognized as an internal or external command, operable program or batch file.
When you get this type of error, then your operating system cannot find the java compiler (javac). To solve this error you need to set the PATH variable.
Javac is a tool which is available in bin folder so you must set the PATH upto bin folder. In a bin folder all tools are available like javap, javah, jar, javac, java, appletviewer etc. These all tools are used for different-different purpose.
path and classpath

How to set the PATH variable

Steps for set the PATH
  1. Click on Start button > right click on ‘my computer’ > properties
  2. Click advanced > environment variable
Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A typical value for PATH is:
C:\jdk< version>\bin (jdk< version is nothing but the name of the directory where jdk is installed)
Example
“C:\Program Files\Java\jdk1.6.0\bin” when we put .; (dot semicolon ) at end then it select all the tools which is present in bin folder.
If there are already some entries in the PATH variable then you must add a semicolon and then add the above value (Version being replaced with the version of JDK). The new path takes effect in each new command prompt window you open after setting the PATH variable.
Mycomputer propertiesAdvance settingsadvanceEnvoriment variableEnvoriment variableEnvoriment variableEnvoriment variableEnvoriment variableEnvoriment variableNote: Finally after set classpath Restart your system, or you can reopen command prompt.

Difference between Path and ClassPath

Path variable is set for all the tools like java, javac, javap, javah, jar, appletviewer etc.
“C:\Program Files\Java\jdk1.6.0\bin”
Envoriment variableAll the tools are present in bin folder so we set path upto bin folder.
Classpath variable is used for all the classes which is used in our program so we set classpath upto rj.jar. in rt.jar file all the .class files are present. When we decompressed rt.jar file we get all the .class files.
"C:\Program Files\Java\jre1.6.0\lib\rt.jar" here rt.jar is a jar file where all the .class files are present so we set the classpath upto rt.jar.
Envoriment variable
First Java Program

Requirements for java Program

For executing any java program we need given things.
  • Install the JDK any version if you don't have installed it.
  • Set path of the jdk/bin directory.
  • Create the java program
  • Compile and run the java program

Steps For compiling and executing the java program

Java is very simple programming language first we write a java program and save it with program class name.
In below program we create a java program with "First" name so we save this program with "First.java" file name. We can save our java program anywhere in our system or computer.

Create First program

class First
{
public static void main(String[] args) 
{
System.out.println("Hello Java");  
System.out.println("My First Java Program");  
}
}
To compile: javac First.java
To execute: java First
Output:
Hello Java
My First Java Program

Save the java program

Syntax:
        Filename.java
Example:
 First.java

Compile the java program.

Syntax:
 Javac  Filename.java
Example:
 Javac First.java
Note: Here Javac and Java are called tools or application programs or exe files developed by sun micro system and supply as a part of jdk 1.5/1.6/1.7 in bin folder (starting directory of java is called java home directory). Javac is used for compile the java program and java is used for run the java program.

During the program execution internally following steps will be occurs.

  1. Class loader subsystem loads or transfer the specified class into main memory from secondary memory (First.class)
  2. JVM takes the loaded class
  3. JVM looks for main method because each and every java program start executing from main() method.
  4. Since main() method of java is static in nature, JVM call the main() method with respect to loaded class (Example: First as First.main(--))
Note: A java program can contain any number of main method but JVM start execution from that main() method which is taking array of object of String class.


Compile and RunIn the Java programming language, all source code is first written in plain text files and save with the .java extension. After compilation, .class files are generated by javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes (it is machine language of the Java Virtual Machine1 (JVM)).
Compile Java CodeThe java launcher tool then runs your application with an instance of the Java Virtual Machine (JVM).
Run Java Program

Steps For compile Java Program

  • First Save Java program with same as class name with .java extension.
    Example: Sum.java
  • Compile: javac Filename.java
    Example, javac Sum.java
Note: Here javac is tools or application programs or exe files which is used for Compile the Java program.

Steps For Run Java Program

  • For run java program use java tool.
  • Run by: java Filename
    Example: java sum
Note: Here java is tools or application programs or exe files which is used for run the Java program.

Steps For compiling and executing the java program

The following sequence of steps represented in the diagram use compiling the java program and executing the java programs.
Compile and run javaIn the above diagram javac and java are called tools or application programs or exe files developed by sun micro system and supply as a part of jdk 1.5/1.6/1.7 in bin folder (starting directory of java is called java home directory).

JVM Architecture

JVM (Java Virtual Machine) is a software. It is a specification that provides runtime environment in which java bytecode can be executed.
JVM Architecture

Operation of JVM

JVM mainly performs following operations.
  • Allocating sufficient memory space for the class properties.
  • Provides runtime environment in which java bytecode can be executed
  • Converting byte code instruction into machine level instruction.
JVM is separately available for every Operating System by installing java software so that JVM is platform dependent.
Note: Java is platform Independent but JVM is platform dependent because every Operating system have different different JVM which is install along with JDK Software.

Class loader subsystem:

Class loader subsystem will load the .class file into java stack and later sufficient memory will be allocated for all the properties of the java program into following five memory locations.
  1. Heap area
  2. Method area
  3. Java stack
  4. PC register
  5. Native stack

Heap area:

In which object references will be stored.

Method area

In which static variables non-static and static method will be stored.

Java Stack

In which all the non-static variable of class will be stored and whose address referred by object reference.

Pc Register

Which holds the address of next executable instruction that means that use the priority for the method in the execution process?

Native Stack

Native stack holds the instruction of native code (other than java code) native stack depends on native library. Native interface will access interface between native stack and native library.

Execution Engine

Which contains Interpreter and JIT compiler whenever any java program is executing at the first time interpreter will comes into picture and it converts one by one byte code instruction into machine level instruction JIT compiler (just in time compiler) will comes into picture from the second time onward if the same java program is executing and it gives the machine level instruction to the process which are available in the buffer memory.
Note: the main aim of JIT compiler is to speed up the execution of java program.
Object and ClassObject is the physical as well as logical entity where as class is the only logical entity.
Class: Class is a blue print which is containing only list of variables and method and no memory is allocated for them. A class is a group of objects that has common properties.
A class in java contains:
  • Data Member
  • Method
  • Constructor
  • Block
  • Class and Interface
Object: Object is a instance of class, object has state and behaviors.
An Object in java has three characteristics:
  • State
  • Behavior
  • Identity

State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.
Class is also can be used to achieve user defined data types.
In real world many examples of object and class like dog, cat, and cow are belong to animal’s class. Each object has state and behaviors. For example a dog has state – color, name, height, age as well as behaviors – barking, eating, and sleeping.
Animal class

Vehicle class

Car, bike, truck these all are belongs to vehicle class. These Objects have also different different states and behaviors. For Example car has state - color, name, model, speed, Mileage. as we;; as behaviors - distance travel
Vehicle classSimple example of class and object related to girls and boy's
Object class

Difference between Class and Object

 ClassObject
1Class is a container which collection of variables and methods.object is a instance of class
2No memory is allocated at the time of declarationSufficient memory space will be allocated for all the variables of class at the time of declaration.
3One class definition should exist only once in the program.For one class multiple objects can be created.

Syntax to declare a Class

 class Class_Name
  {  
    data member;  
    method;  
  }  

Simple Example of Object and Class

In this example, we have created a Employee class that have two data members eid and ename. We are creating the object of the Employee class by new keyword and printing the objects value.
class Employee
{
 int eid;  //data member (also instance variable)
 String ename;  //data member(also instance variable)
  
 public static void main(String args[])
 { 
  Employee e=new Employee();//creating an object of Employee
  System.out.println(e.eid+" "+e.ename);
 }  
}
Note: A new keyword is used to allocate memory at runtime, new keyword is used for create an object of class, later we discuss all the way for create an object of class.
Data TypeData type is a spacial keyword used to allocate sufficient memory space for the data, in other words Data type is used for representing the data in main memory (RAM) of the computer.
In general every programming language is containing three categories of data types. They are
  1. Fundamental or primitive data types
  2. Derived data types
  3. User defined data types.
datatype

Primitive data types

Primitive data types are those whose variables allows us to store only one value but they never allows us to store multiple values of same type. This is a data type whose variable can hold maximum one value at a time.
int a;  // valid
a=10;  // valid
a=10, 20, 30;  // invalid
Here "a" store only one value at a time because it is primitive type variable.

Derived data types

Derived data types are those whose variables allow us to store multiple values of same type. But they never allows to store multiple values of different types. These are the data type whose variable can hold more than one value of similar type. In general derived data type can be achieve using array.
Example:
int  a[] = {10,20,30};  // valid
int b[] = {100, A’, "ABC"};   //  invalid
Here derived data type store only same type of data at a time not store integer, character and string at same time.

User defined data types

User defined data types are those which are developed by programmers by making use of appropriate features of the language.
User defined data types related variables allows us to store multiple values either of same type or different type or both. This is a data type whose variable can hold more than one value of dissimilar type, in java it is achieved using class concept.
Note:In java both derived and user defined data type combindly name as reference data type.
Example:
In C language, user defined data types can be developed by using struct, union, enum etc. In java programming user defined data type can be developed by using the features of classes and interfaces.
Student  s = new  Student();
User defined datatypeIn java we have eight data type which are organized in four groups. They are
  1. Integer category data types
  2. Character category data types
  3. Float category data types
  4. Boolean category data types

Integer category data types

These category data types are used for storing integer data in the main memory of computer by allocating sufficient amount of memory space. In other words, these category data types are used for representing whole numbers in the memory of computer.
Integer category data types are divided into four types which are given in following table
 Data TypeSizeRange
1Byte1+ 127 to -128
2Short2+ 32767 to -32768
3Int4+ x to – (x+1)
4Long8+ y to – (y+1)

Character category data types

  1. A character is an identifier which is enclosed within single quotes.
  2. In java to represent character data, we use a data type called char. This data type takes two byte since it follows Unicode character set.

Data TypeSize(Byte)Range
Char2232767 to -32768
  1. Java is available in 18 international languages and it following Unicode character set.
  2. Unicode character set is one which contains all the characters which are available in 18 international languages and it contains 65536 characters.

Why Java take 2 byte of memory for store character ?

Java support more than 18 international languages so java take 2 byte for characters, because for 18 international language 1 byte of memory is not sufficient for storing all characters and symbols present in 18 languages. Java supports Unicode but c support ascii code. In ascii code only English language are present, so for storing all English latter and symbols 1 byte is sufficient.

Float category data types

Float category data type are used for representing the data in the form of scale, precision that is these category data type are used for representing float values. This category contains two data types, they are in the given table

Data TypeSizeRangeNumber of decimal places
Float4+2147483647 to -21474836488
Double8+ 9.223*101816

Boolean category data types

Boolean category data type is used for representing or storing logical values is true or false. In java programming to represent Boolean values or logical values, we use a data type called Boolean. Boolean data type takes zero bytes of main memory space because Boolean data type of java implemented by Sun Micro System with a concept of flip – flop. A flip – flop is a general purpose register which stores one bit of information (one true and zero false).
Note : in C, C++ (Turbo) Boolean data type is not available for representing true false values but a true value can be treated as non-zero value and false values can be represented by zero
Note : all the keywords in java must starts with small letters. A keyword is one which will have a special meaning to the compiler of a language.
Example:
do, while, for, int etc.

VariableVariable is an identifier which holds data or another one variable is an identifier whose value can be changed at the execution time of program. Variable is an identifier which can be used to identify input data in a program.
Syntax:
VariableSyntax:
Variable_name = value;

Rules to declare a Variable

  1. Every variable name should start with either alphabets or underscore ( _ ) or dollar ( $ ) symbol.
  2. No space are allowed in the variable declarations.
  3. Except underscore ( _ ) no special symbol are allowed in the middle of variable declaration
  4. Variable name always should exist in the left hand side of assignment operators.
  5. Maximum length of variable is 64 characters.
  6. No keywords should access variable name.

Variable declarations

In which sufficient memory will be allocated and holds default values.
Syntax:
Datatype  variable_name;
byte  b1;
Variable

Variable initialization

It is the process of storing user defined values at the time of allocation of memory space.
Variable

Variable assignment

Value is assigned to a variable if that is already declared or initialized.
Syntax :
 Variable_Name = value
 int a = 100;
Variable
int  a= 100;
int b;
b = 25;  //  ------>  direct assigned variable
b = a;    //  ------>  assigned value in term of variable
b = a+15;  //  ------>  assigned value as term of expression

EncapsulationEncapsulation is a process of wrapping of data and methods in a single unit is called encapsulation. Encapsulation is achieved in java language by class concept. The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.
Combining of state and behavior in a single container is known as encapsulation. In java language encapsulation can be achieve using “class” keyword, state represents declaration of variables on attributes and behavior represents operations in terms of method.
Encapsulation

Benefits of encapsulation

  1. Provides abstraction between an object and its clients.
  2. Protects an object from unwanted access by clients.
  3. Example: A bank application forbids a client to change an Account's balance.
InheritanceThe process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming.
In the inheritance process the class which is giving data members and methods is known as base/super/parent class.
The class which is taking the data members and methods is known as sub/derived/child class.
The data members and methods of a class are known as features.
The concept of inheritance is also known as re-usability/extendable classes/sub classing/derivation.

Why use Inheritance ?

  • For Method Overriding (used for Runtime Polymorphism).
  • It's main uses are to enable polymorphism and to be able to reuse code for different classes by putting it in a common super class
  • For code Re-usability

Syntax of Inheritance

class Subclass-Name extends Superclass-Name  
{  
   //methods and fields  
}
The following diagram use view about inheritance.
inheritanceIn the above diagram data members and methods are represented in broken line are inherited from faculty class and they are visible in student class logically.

Advantage/benefits of inheritance

If we develop any java application with the concept of inheritance than such application will get the following advantages.
  1. Application development time is less
  2. Application memory time is less
  3. Application execution time is less
  4. Application performance is enhance (improved)
  5. Redundancy (repetition) of the code is reduced/minimized so that we get consistence results and less storage cost.
  6. We are able to get slogan of java that is WARA (write once reuse any time).
Note: In Inheritance the scope of access modifier increasing is allow but decreasing is not allow. Suppose in parent class method access modifier is default then it's present in child class with default or public or protected access modifier but not private(it decreased scope).

Tpyes of Inheritance

Based on number of ways inheriting the feature of base class into derived class we have five reusable technique/inheritance type they are:
  1. Single inheritance
  2. Multiple inheritance
  3. Hierarchical inheritance
  4. Multiple inheritance
  5. Hybrid inheritance

Single inheritance

In single inheritance there exists single base class and single derived class.
single inheritance

Multiple inheritances

In multiple inheritances there exists single base class, single derived class and multiple intermediate base classes.
Single base class + single derived class + multiple intermediate base classes.

Intermediate base classes

An intermediate base class is one in one context with access derived class and in another context same class access base class.
multilevel inheritanceHence all the above three inheritance types are supported by both classes and interfaces.

Multiple inheritance

In multiple inheritance there exist multiple classes and singel derived class.
multiple inheritanceThe concept of multiple inheritance is not supported in java through concept of classes but it can be supported through the concept of interface.

Hybrid inheritance

Combination of any inheritance type
In the combination if one of the combination is multiple inheritance then the inherited combination is not supported by java through the classes concept but it can be supported through the concept of interface.
hybrid inheritance

Inheriting the feature from base class to derived class

In order to inherit the feature of base class into derived class we use the following syntax
class ClassName-2 extends ClasssName-1
{
variable  declaration;
Method declaration;
}
extends keyword

Explanation

  1. ClassName-1 and ClassName-2 represents name of the base and derived classes respectively.
  2. extends is one of the keyword used for inheriting the features of base class into derived class it improves the functionality of derived class.

Important Points for Inheritance:

  • In java programming one derived class can extends only one base class because java programming does not support multiple inheritance through the concept of classes, but it can be supported through the concept of interface.
  • Whenever we develop any inheritance application it is highly recommended to the java programmer to create an object of bottom most derived class because of intermediate base classes and top most base class.
  • When we create an object of bottom most derived class, first we get the memory space for the data members of top most base class, second we get the memory space for data member of intermediate base class. And at last we get the memory space for data member of bottom most derived class. Bottom most derived class contains logical appearance for the data members of intermediate and top most base classes.
  • If we do not want to give the features of base class to the derived class then the definition of the base class must be preceded by final hence final base classes are not reusable or not inheritable.
  • If we are don’t want to give some of the features of base class to derived class than such features of base class must be as private hence private features of base class are not inheritable or not visible or not accessible in the context of derived class.
  • Data members and methods of a base class can be inherited into the derived class but constructors of base class can’t be inherited because every constructor of a class is made for initializing its own data members but not made for initializing the data members of other classes.
  • An object of base class can contain details about features of same class but an object of base class never contains the details about special features of its derived class (this concept is known as scope of base class object).
  • For each and every class in java there exists an implicit predefined super class called java.lang.Object. because it providers garbage collection facilities to its sub classes for collecting unused memory space and improved the performance of java application.

A java program which illustrate the concept of inheritance.

class Faculty
{  
float salary=30000;  
}  
class Science extends Faculty
{ 
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science(); 
System.out.println("Salary is:"+obj.salary);  
System.out.println("Bonous is:"+obj.bonous);  
}  
}
Output:
Salary is: 30000.0
Bonous is: 2000.0

Why multiple inheritance is not supported in java?

Due to ambiguity problem java does not support mutiple inheritance at class level.
class A
{
void disp()
{
System.out.println("Hello");
}
}
class B
{
void disp()
System.out.println("How are you ?");
}
}
class C extends A,B  //suppose if it were
{
Public Static void main(String args[])
{  
C obj=new C();  
obj.disp();//Now which disp() method would be invoked?  
}  
}
In above code we call both class A and class B disp() method then it confusion which class method is call. So due to this ambiguity problem in java do not use multiple inheritance at class level, but it support at interface level.

Polymorphism

Polymorphism is one of the distinct principal of Oops the process of representing one Form in multiple forms is known as polymorphism here one form represent original form or original method always resides in base class and multiple forms represents overridden method which resides in derived classes.
Polymorphism is not a programming concept but it is one of the principal of OOPs for many objects oriented programming language polymorphism principle is common but whose implementations are varying from one objects oriented programming language to another object oriented programming language.
Real life example of polymorphism
Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person present in different-different behaviors.
In java programming the polymorphism principal is implemented with method overriding concept of java. We know that method overriding is equal to method heading is some method body is different.
Polymorphism principal is divided into two sub principal they are:
  1. Static / Compile time polymorphism
  2. Dynamic / Runtime polymorphism
Java programming does not support static polymorphism because of its limitations and java always supports dynamic polymorphism.
Let us consider the following diagram
polymorphismIn the above diagram the sum method which is present in BC class is called original form and the sum() method which are present in DC1 and DC2 are called overriden form hence Sum() method is originally available in only one form and it is further implemented in multiple forms. Hence Sum() method is one of the polymorphism method.

Dynamic Binding

Dynamic binging always says create an object of base class but do not create the object of derived classes.
The advantages of dynamic binding along with polymorphism with method overriding are.
  1. Less memory space
  2. Less execution time
  3. More performance
Dynamic binding principal is always used for executing polymorphic applications.

Definition

The process of binding appropriate versions (overridden method) of derived classes which are inherited from base class with base class object is known as dynamic binding.
When we are dynamic binding principal for executing polymorphism based application, internally JVM considers the following two points.
  1. What type of object?
  2. What type of reference / address object contains?
In other words when we create an object indirectly, JVM internally considers the above two points.
Note: To create an object indirectly, there must exists super-sub base-derived parent-child relationship.
Faculty fo=new Sudent();
Parent p=new Child();>
Here fo objects is of type faculty class and fo object contains the reference of student class let us consider the following set of executable statement for executing the program represented in figure 1.
polymorphismIn the above example bo1 is containing the references of BC, DC1, DC2 classes hence bo1 is known as polymorphism object.
Here sum() method is actually available in one from and it is implemented in multiple forms. Hence sum() method is known as polymorphism method.
The statement bo1.sum() is actually only one statement but it gives different sum() int, float, char, sum. This statement is known as polymorphism statement. In real world applications a java program can be developed by using the following cases.
Case 1: Business logic will be developed in independent class and execution logic class can be developed by using plain old logic (direct object creation)
Case 2: Business logic will be developed in dependent classes contains the logics of polymorphic along with method overriding and execution logic developed with plain old execution logic. If we develop any java application by using the above two cases then that application will get the following limitations.
  1. Application memory space is more (main memory)
  2. Application execution time is more
  3. Application performance is reduced
Case 3: Business logic will be developed in dependent classes contain (polymorphism + method overriding logic) and execution logic will be developed by using dynamic binding principal. If we developed any java application by using the above case 3 then such application will get the following advantages.
  1. Application memory space is less (main memory)
  2. Application execution time is less
  3. Application performance is enhance(improve)

Static polymorphism

It is one of the sub principal of polymorphism one of the object oriented programming language supports even static polymorphism.
The language C, C++ supports static polymorphism principal by using its C++ programming concepts called function overloading and operator overloading as per as standalone mechanism are concerned there is no difference in performance of static polymorphism and dynamic polymorphism application but there is a significant difference in execution of there applications in busy environment like client server environment.

Definition

The process of finding the overloaded method within object at compile time is known as static polymorphism due to static polymorphism utilization of resources (main memory space) is poor because for each and every overloaded method a memory space is created at compile time when it binds with an object. In C++ environment the above problem can be solve by using dynamic polymorphism by implementing with virtual and pure virtual function so most of the C++ developer in real worlds follows only dynamic polymorphism.

Dynamic polymorphism

In dynamic polymorphism method of the program binds with an object at runtime the advantage of dynamic polymorphism is allocating the memory space for the method (either for overloaded method or for override method) at run time.

Conclusion

The advantage of dynamic polymorphism is effective utilization of the resources effectively java programming does not support static polymorphism because of its limitation. It is always dynamic polymorphism because of its advantages.

ackage

A package is a collection of similar types of classes, interfaces and sub-packages.

Purpose of package

The purpose of package concept is to provide common classes and interfaces for any program. In other words if we want to develop any class or interface which is common for most of the java programs than such common classes and interfaces must be place in a package.
PackagePackages in Java are the way to organize files when a project has many modules. Same like we organized our files in Computer. For example we store all movies in one folder and songs in other folder, here also we store same type of files in a particular package for example in awt package have all classes and interfaces for design GUI components.
Package

Advantage of package

  • Package is used to categorize the classes and interfaces so that they can be easily maintained
  • Application development time is less, because reuse the code
  • Application memory space is less (main memory)
  • Application execution time is less
  • Application performance is enhance (improve)
  • Redundancy (repetition) of code is minimized
  • Package provides access protection.
  • Package removes naming collision.

Type of package

Package are classified into two type which are given below.
  1. Predefined or built-in package
  2. User defined package

Predefined or built-in package

These are the package which are already designed by the Sun Microsystem and supply as a part of java API, every predefined package is collection of predefined classes, interfaces and sub-package.

User defined package

If any package is design by the user is known as user defined package. User defined package are those which are developed by java programmer and supply as a part of their project to deal with common requirement.

Rules to create user defined package

  • package statement should be the first statement of any package program.
  • Choose an appropriate class name or interface name and whose modifier must be public.
  • Any package program can contain only one public class or only one public interface but it can contain any number of normal classes.
  • Package program should not contain any main class (that means it should not contain any main())
  • modifier of constructor of the class which is present in the package must be public. (This is not applicable in case of interface because interface have no constructor.)
  • The modifier of method of class or interface which is present in the package must be public (This rule is optional in case of interface because interface methods by default public)
  • Every package program should be save either with public class name or public Interface name
Package

Compile package programs

For compilation of package program first we save program with public className.java and it compile using below syntax:
javac -d . className.java
javac -d path className.java
Explanations: In above syntax "-d" is a specific tool which is tell to java compiler create a separate folder for the given package in given path. When we give specific path then it create a new folder at that location and when we use . (dot) then it crate a folder at current working directory.
Note: Any package program can be compile but can not be execute or run. These program can be executed through user defined program which are importing package program.

Example of package program

Package program which is save with A.java and compile by javac -d . A.java
package mypack;
public class A
{
public void show()
{
System.out.println("Sum method");
}
}
Import above class in below program using import packageName.className
import mypack.A;
public class Hello
{
public static void main(String arg[])
{
A a=new A();
a.show();
System.out.println("show() class A");
}
}
Explanations: In the above program first we create Package program which is save with A.java and compiled by "javac -d . A.java". Again we import class "A" in class Hello using "import mypack.A;" statement.

Difference between Inheritance and package

Inheritance concept always used to reuse the feature within the program between class to class, interface to interface and interface to class but not accessing the feature across the program.
Package concept is to reuse the feature both within the program and across the programs between class to class, interface to interface and interface to class.

Difference between package keyword and import keyword

Package keyword is always used for creating the undefined package and placing common classes and interfaces.
import is a keyword which is used for referring or using the classes and interfaces of a specific package.
Exception HandlingThe process of converting system error messages into user friendly error message is known as Exception handling.

Exception

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Hierarchy of Exception classes

Exception

Type of Exception

  1. Checked Exception
  2. Un-Checked Exception

Checked Exception

These are the exception are checked at compile-time. In general checked exception also can be handle by Exception class. The classes that extend Throwable class except RuntimeException are known as checked exceptions
Only for remember: Checked means checked by compiler so checked exception are checked at compile-time.
Checked Exception

Un-Checked Exception

These are the exception both identifies or raised at run time, these can be handle using RunTimeException class.
Note: In real time application mostly we can handle unchecked exception.
Only for remember: Un-checked means not checked by compiler so un-checked exception are checked at run-time not compile time.
Unchecked Exception

Difference between checked Exception and un-checked Exception

 Checked ExceptionUn-Checked Exception
1checked Exception are checked at compile timeun-checked Exception are checked at run time
2for checked Exception Extend Throwable class except RuntimeException.for un-checked Exception extend RuntimeException.
3e.g.
IOException, SQLException, FileNotFoundException etc.
e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberNotFoundException etc.

Handling the Exception

Handling the exception is nothing but converting system error message into user friendly error message in other word whenever an exception occurs in the java, JVM will create an object appropriate exception of sub class and generates system error message of by default which are not recommended in real industry. Industry is highly recommended to convert system error message into user friendly error message by using exception handling feature.
As a part of exception handling we have five keywords for handling the exception they are:
  1. try
  2. catch
  3. finally
  4. throws
  5. throw
Syntax for handling the exception
try
{
/* Block of statements causes problem at run time */
}
catch(Type of exception-1 object-1)
{
/* Block of statements provides user friendly error message */
}
catch(Type of exception-2 object-2)
{
/* Block of statements provides user friendly error message */
}
finally
{
/* Block of statements which will execute compulsary */
}

Try Block

It is one of the block in which we write the block of statements which causes executions at run time in other words try block always contains problematic statements.

Important points about try block

  • If any exception occurs in try block then CPU controls comes out to the try block and executes appropriate catch block.
  • After executing appropriate catch block, even through we use run time statement, CPU control never goes to try block to execute the rest of the statements.
  • Each and every try block must be immediately followed by catch block that is no intermediate statements are allowed between try and catch block.
    try
    {
    .......
    }
    /* Here no other statements are allowed 
    between try and catch block */
    catch()
    {
    }
  • Each and every try block must contains at least one catch block. But it is highly recommended to write multiple catch blocks for generating multiple user friendly error messages.
  • One try block can contains another try block that is nested or inner try block can be possible.
    try
    {
    .......
    try
    {
    .......
    }
    }

Catch block

It is one of the block in which we write the block of statements which will generates user friendly error messages in other words catch block will suppose system error messages.

Important points about catch block

  • Catch block will execute provided or exception occurs in try block.
  • It is highly recommended to write multiple catch blocks for generating multiple user friendly error messages to make our application strong.
  • At any point of time only one catch block will execute out of multiple catch blocks.
  • In programmatically in the catch block as a Java programmer we declare an object of sub class and it will be internally referenced by JVM.

Finally block

It is one of the block in which we write the block of statements which will relinquish (released or close or terminate) the resource (file or database) where data store permanently.

Important points about finally block

  • Finally block will execute compulsory
  • Writing finally block is optional.
  • It is highly recommended to the java programmer to write on finally block for the entire java program
  • In some of the circumstances one can also write try and catch block in finally block.

Example without Exception Handling

class ExceptionDemo 
{
public static void main(String[] args) 
{
int a=10, ans=0;
ans=a/0;
System.out.println("Denominator not be zero");  
}
}
Outpot
Abnormally terminate program and give a message like below:
Exception

Example of Exception Handling

class ExceptionDemo 
{
public static void main(String[] args) 
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
} 
}
}
Outpot
Denominator not be zero

checked Exception Classes

  1. FileNotFoundException
  2. ClassNotFoundException
  3. IOException
  4. InterruptedException

IOException

Try to transfer more data but less data are present. Try to read data which is corrupted. Try to write but file is read only.

Un-Checked Exception Classes

  1. ArithmeticException
  2. ArrayIndexOutOfBoundsException
  3. StringIndexOutOfBoundsException
  4. NumberFormateException
  5. NullPointerException
  6. NoSuchMethodException
  7. NoSuchFieldException

Handling of unknown Exception

Whenever developer do not known what type of exception is going to be raised in the try block is known as unknown Exception java support three mechanism to handle unknown Exception.
  1. Using Exception class
  2. Using printStackTrace()
  3. Using getMessage()

Using Exception class

It is a super class of all checked or unchecked Exception classes can be used to handle any type of synchronous Exception raised in the try block.
try
{
......
......
}
catch(Exception e)
{
System.out.err(e);
}
Exception class object display two things
  • Exception class name which is raised in try block
  • Exception message

Using printStackTrace()

It is a predefined method of throwable class used to display the three properties of Exception.
  • Exception class name
  • Exception message
  • Line number at which Exception is raised
try
{
.....
.....
}
catch(Exception e)
{
e.printStackTrace()
}

getMessage()

It is also a predefined method of throwable class used to get the system defined error message(only message) of an Exception which is raised in try block.
try
{
.....
.....
}
catch(Exception e)
{
String msg=e.printStackTrace()
System.out.println(msg);
}

Difference between throw and throws

 throwthrows
1throw is a keyword used for hitting and generating the exception which are occurring as a part of method bodythrows is a keyword which gives an indication to the specific method to place the common exception methods as a part of try and catch block for generating user friendly error messages
2The place of using throw keyword is always as a part of method body.The place of using throws is a keyword is always as a part of method heading
3When we use throw keyword as a part of method body, it is mandatory to the java programmer to write throws keyword as a part of method headingWhen we write throws keyword as a part of method heading, it is optional to the java programmer to write throw keyword as a part of method body.
 
MultithreadingThe aim of multithreading is to achieve the concurrent execution.

Thread

Thread is a lightweight components and it is a flow of control. In other words a flow of control is known as thread.

State or Life cycle of thread

State of a thread are classified into five types they are
  1. New State
  2. Ready State
  3. Running State
  4. Waiting State
  5. Halted or dead State
Lifecyle of Thread Class

New State

If any new thread class is created that represent new state of a thread, In new state thread is created and about to enter into main memory. No memory is available if the thread is in new state.

Ready State

In ready state thread will be entered into main memory, memory space is allocated for the thread and 1st time waiting for the CPU.

Running State

Whenever the thread is under execution known as running state.

Halted or dead State

If the thread execution is stoped permanently than it comes under dead state, no memory is available for the thread if its comes to dead state.
Note: If the thread is in new or dead state no memory is available but sufficient memory is available if that is in ready or running or waiting state.

Achieve multithreading in java

In java language multithreading can be achieve in two different ways.
  1. Using thread class
  2. Using Runnable interface

Using thread class

In java language multithreading program can be created by following below rules.
  1. Create any user defined class and make that one as a derived class of thread class.
class  Class_Name  extends  Thread
{
........
}
  1. Override run() method of Thread class (It contains the logic of perform any operation)
  2. Create an object for user-defined thread class and attached that object to predefined thread class object.
Class_Name obj=new Class_Name Thread t=new Thread(obj);
  1. Call start() method of thread class to execute run() method.
  2. Save the program with filename.java
Extends Thread Class

Example of multithreading using Thread class

Thread based program for displaying 1 to 10 numbers after each and every second.
// Threaddemo2.java

class Th1 extends Thread
{
public void run()
{
try
{
for(int i=1;i< =10;i++)
{
System.out.println("value of i="+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
System.err.println("Problem in thread execution");
}
}
}
class Threaddemo2
{
public static void main(String args[])
{
Th1   t1=new   Th1();
System.out.println("Execution status of t1 before start="+t1.isAlive());
t1.start();
System.out.println("Execution status of t1 before start="+t1.isAlive());
try
{
Thread.sleep(5000);
}
catch(InterruptedException ie)
{
System.out.println("Problem in thread execution");
}
System.out.println("Execution status of t1 during execution="+t1.isAlive());
try
{
Thread.sleep(5001);
}
catch(InterruptedException ie)
{
System.out.println("problem in thread execution");
}
System.out.println("Execution status of t1 after completation="+t1.isAlive());
}
}
Output
Execution status of t1 before start=false  //new state
Execution status of t1 after start=true  //ready state
1
2
3
4
5
6
Execution status of t1 during execution=true  //running state
7
8
9
10
Execution status of t1 after completation=false  //halted state

Thread class properties

Thread class contains constant data members, constructors, predefined methods.

Constant data members

  • MAX-PRIORITY
  • MIN-PRIORITY
  • NORM-PRIORITY

MAX-PRIORITY

Which represent the minimum priority that a thread can have whose values is 10.
Syntax:
public static final int MAX-PRIORITY=10

MIN-PRIORITY

Which represents the minimum priority that a thread can have.
Syntax:
public static final int MIN-PRIORITY=0

NORM-PRIORITY

Which represent the default priority that is assigned to a thread.
Syntax:
public static final int NORM-PRIORITY=5

Constructors of Thread class

  • Thread()
  • Thread(String name)
  • Thread(object)
  • Thread(object, String name)

Thread()

Which will be execute to set the predefined name for newly created thread, these names are generally in the form of thread -0, thread -1, ....
Syntax to call constructor:
Syntax
Thread t=new Thread();

Thread(String name)

Which can be used to provide user defined name for newly created thread.
Syntax
Thread t=new Thread("newthread");

Thread(object)

Which can be used to provide default name for newly created user defined thread.
Syntax
UserdefinedThreadclass  obj=new UserdefinedThreadclass();
Thread t=new Thread("obj");

object, String name

Which will be used to provide user defined name for the newly created user defined thread.
Syntax
UserdefinedThreadclass  obj=new UserdefinedThreadclass();
Thread t=new Thread(object, "secondthread");

Methods of Thread class

  • getPriority()
  • setPriority()
  • getName()
  • setName()
  • isDeamon()
  • run()
  • start()
  • sleep()
  • suspend()
  • resume()
  • stop()
  • isAlive()
  • currentThread()
  • join()
  • getState()
  • yield()

getPriority()

This method is used to get the current priority of thread.
Thread t=new Thread();
int x=t.getPriority();
System.out.println(x);

setPriority()

This method is used to set the current priority of thread.
Thread t=new Thread();
t.setPriority(any priority number between o to 10)
or
t.setPriority(Thread.MAX-PRIORITY)

getName()

This method is used to get the current executing thread name.
Thread t=new Thread();
String s=t.getName();
System.out.println(s);

setName()

This method is used to set the userdefined name for the thread.
Thread t=new Thread();
t.setName("mythread");

isDeamon()

Which returns true if the current thread is background thread otherwise return false.
Thread t=new Thread();
boolean b=t.isDeamon();

run()

Which contains the main business logic that can be executed by multiple threads simultaneously in every user defined thread class run method should be overridden.
public Class_Name extends Thread
{
public void run()
{
.....
.....
}
}

start()

Used to convert ready state thread to running state.
Thread t=new Thread();
t.start();

sleep()

Used to change running state thread to ready state based on time period it is a static method should be called with class reference.
public static final sleep(long milisecond)throws InterruptedException
{
try
{
Thread.sleep(3000);
}
catch(InterruptedException ie)
{
........
........
}
}
Once the given time period is completed thread state automatically change from waiting to running state.

suspend()

Used to convert running state thread to waiting state, which will never come back to running state automatically.
Thread t=new Thread();
t.suspend();

resume()

Used to change the suspended thread state(waiting state) to ready state.
Thread t=new Thread();
t.resume();
Note: Without using suspend() method resume() method can not be use.

What is the different between sleep() and suspend()

Sleep() can be used to convert running state to waiting state and automatically thread convert from waiting state to running state once the given time period is completed. Where as suspend() can be used to convert running state thread to waiting state but it will never return back to running state automatically.

stop()

This method is used to convert running state thread to dead state.
Thread t=new Thread();
t.stop();

isAlive()

Which is return true if the thread is in ready or running or waiting state and return false if the thread is in new or dead state.
Thread t=new Thread();
t.isAlive();

currentThread()

Used to get the current thread detail like thread name thread group name and priority
Thread t=new Thread();
t.currentThread();
Note:
  • The default thread name is thread-0, (if it is a main thread default name is main)
  • The default thread group name is main
  • Default thread priority is "5" is normal priority.

join()

Which can be used to combined more than one thread into a single group signature is public final void join()throws InterruptedException
try
{
t.join();
t2.join();
.....
.....
}

getState()

This method is used to get the current state of thread.
Thread t=new Thread();
t.getState();

yield()

Which will keep the currently executing thread into temporarily pass and allows other threads to execute

Using Runnable Interface

Runnable is one of the predefined interface in java.lang package, which is containing only one method and whose prototype is " Public abstract void run "
The run() method of thread class defined with null body and run() method of Runnable interface belongs to abstract. Industry is highly recommended to override abstract run() method of Runnable interface but not recommended to override null body run() method of thread class.
In some of the circumstance if one derived class is extending some type of predefined class along with thread class which is not possible because java programming never supports multiple inheritance. To avoid this multiple inheritance problem, rather than extending thread class we implement Runnable interface.

Rules to create the thread using Runnable interface

  • Create any user defined class and implements runnable interface within that
  • Override run() method within the user defined class.
  • call start() method to execute run() method of thread class
  • Save the program with classname.java
class  Class_Name  implement Runnable
{
public void run()
{
........
}
}
Class_Name obj=new Class_name();
Thread t=new Thread();
t.start();
Note: While implementing runnable interface it is very mandatory to attach user defined thread class object reference to predefined thread class object reference. It is optional while creating thread by extending Thread class.

Thread Synchronization

Whenever multiple threads are trying to use same resource than they may be chance to of getting wrong output, to overcome this problem thread synchronization can be used.
Definition: Allowing only one thread at a time to utilized the same resource out of multiple threads is known as thread synchronization or thread safe.
In java language thread synchronization can be achieve in two different ways.
  1. Synchronized block
  2. Synchronized method
Note: synchronization is a keyword(access modifier in java)

Synchronized block

Whenever we want to execute one or more than one statement by a single thread at a time(not allowing other thread until thread one execution is completed) than those statement should be placed in side synchronized block.
class  Class_Name  implement Runnable or extends Thread
{
public void run()
{
synchronized(this)
{
.......
.......
}
}
}

Synchronized method

Whenever we want to allow only one thread at a time among multiple thread for execution of a method than that should be declared as synchronized method.
class  Class_Name  implement Runnable or extends Thread
{
public void run()
{
synchronized void fun()
{
.......
.......
}
public void run()
{
fun();
....
}
}

Interthread Communication

The process of execution of exchanging of the data / information between multiple threads is known as Interthread communication or if an output of first thread giving as an input to second thread the output of second thread giving as an input to third thread then the communication between first second and third thread known as Interthread communication.
In order to develop Interthread communication application we use some of the methods of java.lang.Object class and these methods are known as Interthread communication methods.

Interthread communication methods

  1. public final void wait(long msec)
  2. public final void wait()
  3. public final void notify()
  4. public final void notifyAll()

public final void wait(long msec)

public final void wait (long msec) is used for making the thread to wait by specifying the waiting time in terms of milliseconds. Once the waiting time is completed, automatically the thread will be interred into ready state from waiting state. This methods is not recommended to used to make next thread to wait on the basis of time because java programmer may not be able to decide or determine the CPU burst time of current thread and CPU burst time is decided by OS but not by the programmer.

public final void wait()

public final void wait() is used for making the thread to wait without specifying any waiting time this method is recommended to use to make the next thread to wait until current thread complete its execution.

public final void notify()

public final void notify() is used for transferring one thread at a time from waiting state to ready state.

public final void notifyAll()

public final void notifyAll() is used for transferring all the threads at a time from waiting state to ready state.
Note: public final void wait (long msec) and public final void wait() throws a predefined Exception called java.lang.InterruptedException.

String HandlingThe basic aim of String Handling concept is storing the string data in the main memory (RAM), manipulating the data of the String, retrieving the part of the String etc. String Handling provides a lot of concepts that can be performed on a string such as concatenation of string, comparison of string, find sub string etc.

Character

It is an identifier enclosed within single quotes (' ').
Example: 'A', '$', 'p'

String:

String is a sequence of characters enclosed within double quotes (" ") is known as String.
Example: "Java Programming".
In java programming to store the character data we have a fundamental datatype called char. Similarly to store the string data and to perform various operation on String data, we have three predefined classes they are:
  1. String
  2. StringBuffer
  3. StringBuilder

String class

It is a predefined class in java.lang package can be used to handle the String. String class is immutable that means whose content can not be changed at the time of execution of program.
String class object is immutable that means when we create an object of String class it never changes in the existing object.
Example:
String s=new String("java"); 
s.concat("software");
System.out.println(s);
Output:
java
Explanation: Here we can not change the object of String class so output is only java.

String Compare

Compare-StringThere are three way to compare string object in java:
  • By equals() method
  • By == operator
  • By compreTo() method

By equals() method

equals() method always used to comparing contents of both source and destination String. It return true if both string are same in meaning and case otherwise it returns false. It is case sensitive method.
Equals method

By == Operator

== Operator is always used for comparing references of both source and destination objects but not there contents.
Double Equalsto Operator in java

compareTo()

comapreTo() method can be used to compare two string by taking Unicode values. It returns 0 if the string are same otherwise returns either +ve or -ve integer.

StringBuffer

It is a predefined class in java.lang package can be used to handle the String, whose object is mutable that means content can be modify.
StringBuffer class is working with thread safe mechanism that means multiple thread are not allowed simultaneously to perform operation of StringBuffer.
StringBuffer class object is mutable that means when we create an object of StringBulder class it can be change.
Example:
StringBuffer sb=new StringBuffer("java"); 
s.append("software");
System.out.println(sb);
Output:
javasoftware
Explanation: Here we can changes in the existing object of StringBuffer class so output is javasoftware.

Difference between String and StringBuffer

 StringStringBuffer
1The data which enclosed within double quote (" ") is by default treated as String class.The data which enclosed within double quote (" ") is not by default treated as StringBuffer class
2String class object is immutableStringBuffer class object is mutable
3When we create an object of String class by default no additional character memory space is created.When we create an object of StringBuffer class by default we get 16 additional character memory space.

Similarities between String and StringBuffer

  • Both of them are belongs to public final. so that they never participates in inheritance that is is-A relationship is not possible but they can always participates in As-A and Uses-A relationship.
  • We can not override the method of String and StringBuffer.

StringBuilder

It is a predefined class in java.lang package can be used to handle the String. StringBuilder class is almost similar to to StringBuffer class. It is also a mutable object.
The main difference StringBuffer and StringBuilder class is StringBuffer is thread safe that means only one threads allowed at a time to work on the String where as StringBuilder is not thread safe that means multiple threads can work on same String value.

Difference between StringBuffer and StringBuilder

All the things between StringBuffer and StringBuilder are same only difference is StringBuffer is synchronized and StringBuilder is not synchronized. synchronized means one thread is allow at a time so it thread safe. Not synchronized means multiple threads are allow at a time so it not thread safe.
 StringBufferStringBuilder
1It is thread safe.It is not thread safe.
2Its methods are synchronized and provide thread safety.Its methods are not synchronized and unable to provide thread safety.
3Relatively performance is low because thread need to wait until previous process is complete.Relatively performance is high because no need to wait any thread it allows multiple thread at a time.
1Introduced in 1.0 version.Introduced in 1.5 version.

When we use String, StringBuffer and StringBuilder

  • If the content is fixed and would not change frequently then we use String.
  • If content is not fixed and keep on changing but thread safety is required then we use StringBuffer
  • If content is not fixed and keep on changing and thread safety is not required then we use StringBuilder

StringTokenizer

It is a pre defined class in java.util package can be used to split the given string into tokens (parts) based on delimiters (any special symbols or spaces).
Suppose that we have any string like "Features of Java_Language" when we use stringTokenizer this string is split into tokens whenever spaces and special symbols present. After split string are :
Features
of 
Java
Language

Methods of StringTokenizer

  1. hasMoreTokens()
  2. nextToken()

hasMoreTokens()

It is predefined method of StringTokenizer class used to check whether given StringTokenizer having any elements or not.

nextToken()

Which can be used to get the element from the StringTokenizer.

Example of StringTokenizer:

import java.util.*;
class Stringtokenizerdemo
{
public static void main(String args[])
{
String str="He is a gentle man";
StringTokenizer st=new StringTokenizer(str," ");
System.out.println("The tokens are: ");
while(st.hasMoreTokens())
{
String one=st.nextToken();
System.otu.println(one);
}
}
}
Output:
The tokens are:
He
is
a
gentle
man