0% found this document useful (0 votes)
3 views288 pages

Java Programming Framework Guide

The document provides a comprehensive overview of Java programming, covering its framework, features, and core concepts such as JVM, JRE, JDK, and OOP principles. It includes detailed sections on Java syntax, control statements, exception handling, and the collection framework, along with practical examples and explanations. Additionally, it discusses Java's history, its advantages like portability and security, and its application in distributed environments.

Uploaded by

mathan raj.R
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views288 pages

Java Programming Framework Guide

The document provides a comprehensive overview of Java programming, covering its framework, features, and core concepts such as JVM, JRE, JDK, and OOP principles. It includes detailed sections on Java syntax, control statements, exception handling, and the collection framework, along with practical examples and explanations. Additionally, it discusses Java's history, its advantages like portability and security, and its application in distributed environments.

Uploaded by

mathan raj.R
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Contents

Framework ......................................................................................................................................... 14
It helps developers to develop programs for different platforms. In short, Framework reduces the
need for coding in the application ......................................................................................................... 14
Differentiate JVM JRE JDK JIT ................................................................................................................. 18
What is JVM ...................................................................................................................................... 20
What it does ...................................................................................................................................... 20
Web specifications: .......................................................................................................................... 25
Web service specifications: ............................................................................................................ 26
Enterprise specifications: ................................................................................................................ 26
How to set the Temporary Path of JDK in Windows ....................................................................... 28
For Example: ..................................................................................................................................... 28
2) How to set Permanent Path of JDK in Windows ........................................................................ 28
Source File Declaration Rules.............................................................................................................. 28
Java Package......................................................................................................................................... 29
Import Statements............................................................................................................................... 29
First Java Program ........................................................................................................................... 29
Output ............................................................................................................................................... 30
Java Access Modifiers: ............................................................................................................................ 42
Type Casting ..................................................................................................................................... 45
[Link] Package Classes..................................................................................................................... 51
Object class : ......................................................................................................................................... 52
getClass() method : ........................................................................................................................ 54
Understanding Object Ordering in Java with Comparable and Comparator:................ 54
1. Understanding Natural Ordering or Comparable ........................................................................ 55
2. Understanding Comparator ............................................................................................................ 57
Operators:.............................................................................................................................................. 57
Java - Character Class ............................................................................................................................ 59
Why String is immutable in Java? .......................................................................................................... 60

Author:[Link]
String Pool in Java .................................................................................................................................. 61
String Pool in java is a pool of Strings stored in Java Heap Memory. We know that
String is special class in java and we can create String object using new operator as
well as providing values in double quotes. ................................................................................ 61
2) By new keyword ........................................................................................................................... 64
Java String Example ........................................................................................................................ 65
Java String class methods .............................................................................................................. 65
String class function ......................................................................................................................... 68
StringBuffer class ............................................................................................................................. 73
StringBuilder class ........................................................................................................................... 76
static keyword in java............................................................................................................................... 79
[Link] static variable ....................................................................................................................... 80
[Link] static method ........................................................................................................................ 81
[Link] static block ............................................................................................................................. 82
[Link] Static Class........................................................................................................................... 83
Java static import ............................................................................................................................. 85
Control Statements in Java.......................................................................................................................... 86
Different types of control statements: the decision making statements (if-then, if-then-else and
switch), looping statements (while, do-while and for) and branching statements (break, continue,
return) supported by the Java programming language. ..................................................................... 86
Java for loop(repetition Statements) ..................................................................................................... 89
Java for loop example ..................................................................................................................... 89
Java for each loop ............................................................................................................................ 90
Java for loop with label .................................................................................................................... 91
Java while loop ......................................................................................................................................... 91
Java while loop example ................................................................................................................. 92
Java while loop with Iterator ........................................................................................................... 92
while true java ................................................................................................................................... 93
Java do while loop ................................................................................................................................ 93
Java break ............................................................................................................................................. 94
Array in Java: .............................................................................................................................................. 95

Author:[Link]
Size Limit: We can store only fixed size of elements in the array. It doesn’t grow its size at runtime.
To solve this problem, collection framework is used in java. Initializing an array in java –
primitive type ..................................................................................................................................... 95
Initializing an array in java – object type ....................................................................................... 97
Initializing a multidimensional array in java .................................................................................. 97
How to initialize an array in java using shortcut syntax .............................................................. 97
Invalid ways to initialize an array in java ....................................................................................... 97
Java Array of ArrayList ........................................................................................................................ 99
Java ArrayList of Array .................................................................................................................... 99
How to Convert String to Array in Java ............................................................................................... 100
Wrapper class in Java ........................................................................................................................... 103
Why do we need wrapper classes?............................................................................................. 103
primitive into wrapper-Object:............................................................................................................... 106
Wrapper-Object To Primitive: ............................................................................................................... 106
Wrapper-Object To String: .................................................................................................................... 106
Autoboxing in Java ................................................................................................................................. 107
Java Autoboxing Example ............................................................................................................ 107
Call by Value and Call by Reference in Java ..................................................................................... 108
Types of Constructor in Java ............................................................................................................ 109
Default Constructor in Java .......................................................................................................... 109
No-Args Constructor ...................................................................................................................... 110
Parameterized Constructor ........................................................................................................... 110
Constructor Overloading in Java...................................................................................................... 111
Private Constructor in Java............................................................................................................... 112
Constructor Chaining in Java ........................................................................................................... 112
Java Super Constructor..................................................................................................................... 114
Java Copy Constructor ...................................................................................................................... 115
Java Method ............................................................................................................................................ 117
Java Method Components ................................................................................................................ 117
Java Method Signature ..................................................................................................................... 118
Calling a Java Method ....................................................................................................................... 119
Java Method Examples ..................................................................................................................... 119

Author:[Link]
OOPs (Object-Oriented Programming System) ............................................................................ 122
Difference between object and class .................................................................................................. 123
Inheritance ....................................................................................................................................... 124
Polymorphism ................................................................................................................................. 125
Encapsulation ................................................................................................................................. 125
Coupling ........................................................................................................................................... 125
Cohesion:......................................................................................................................................... 126
Association ...................................................................................................................................... 126
Aggregation ..................................................................................................................................... 127
Composition .................................................................................................................................... 127
What is an object in Java .............................................................................................................. 127
What is a class in Java ...................................................................................................................... 128
Why use inheritance in java .......................................................................................................... 133
Terms used in Inheritance ............................................................................................................ 133
The syntax of Java Inheritance .................................................................................................... 133
Java Inheritance Example ............................................................................................................. 134
Java Inheritance Important Points ................................................................................................... 136
Types of inheritance in java .............................................................................................................. 137
Single Inheritance Example .............................................................................................................. 138
Multilevel Inheritance Example ........................................................................................................ 139
Hierarchical Inheritance Example .................................................................................................... 140
Q) Why multiple inheritance is not supported in java? ................................................................. 140
Aggregation in Java ............................................................................................................................... 147
Why use Aggregation? .................................................................................................................. 147
When use Aggregation? ................................................................................................................ 147
Understanding meaningful example of Aggregation ................................................................. 148
Polymorphism is the concept with the help of which single action in different ways
can be performed............................................................................................................................... 149
Method Overloading in Java ................................................................................................................. 151
Different ways to overload the method ....................................................................................... 151
1) Method Overloading: changing no. of arguments ................................................................ 151
2) Method Overloading: changing data type of arguments ..................................................... 152

Author:[Link]
How Runtime Polymorphism works in Java? .............................................................................. 152
Ways to achieve Abstraction ........................................................................................................ 162
Abstract Class: ................................................................................................................................ 163
Let’s Study Abstraction concept with an Example ........................................................................ 163
How to achieve Abstraction? ............................................................................................................ 164
Abstract Class ................................................................................................................................. 164
Abstract Method ............................................................................................................................. 164
Difference between Abstraction and Encapsulation ................................................................. 165
Difference between Abstract Class and Interface ..................................................................... 166
Advantages of Abstraction ............................................................................................................ 167
When to use Abstract Methods & Abstract Class? ................................................................... 167
Abstract class in Java Important Points ............................................................................................ 168
Why use Java interface? ................................................................................................................... 169
interface Vs abstract class in Java. .................................................................................................... 170
Important Points about Interface in Java........................................................................................... 172
Java Interface Example: Bank .......................................................................................................... 174
Multiple inheritance in Java by interface......................................................................................... 174
Java 8 Default Method & static in Interface.................................................................................... 175
Q) What is marker or tagged interface?.......................................................................................... 176
Java 8 interface changes .................................................................................................................... 179
Learn Encapsulation with an Example ............................................................................................ 180
Data Hiding in Java ............................................................................................................................ 182
Getter and Setter Methods in Java .................................................................................................. 183
Abstraction vs. Encapsulation .......................................................................................................... 184
Advantages of Encapsulation in Java ............................................................................................. 184
Read-Only class ............................................................................................................................. 186
Write-Only class ............................................................................................................................. 186
Built-in annotations in Java .................................................................................................................. 187
Constructor in Java ................................................................................................................................ 187
Exception Handling in Java .................................................................................................................. 190
What is Exception in Java ................................................................................................................. 190

Author:[Link]
Advantage of Exception Handling................................................................................................ 191
Exception class Hierarchy................................................................................................................. 191
Java Exception Handling Keywords Details:.................................................................................... 204
Exception Handling in Java – Useful Methods ................................................................................. 206
Types of Java Exceptions ............................................................................................................. 207
Difference between Checked and Unchecked Exceptions .......................................................... 208
1) Checked Exception ................................................................................................................... 208
2) Unchecked Exception ............................................................................................................... 208
3) Error ............................................................................................................................................. 208
Java Exception Keywords ................................................................................................................. 208
Common Scenarios of Java Exceptions ......................................................................................... 209
1) A scenario where ArithmeticException occurs ...................................................................... 209
2) A scenario where NullPointerException occurs .................................................................... 209
3) A scenario where NumberFormatException occurs ............................................................. 209
4) A scenario where ArrayIndexOutOfBoundsException occurs ............................................ 209
Try with Resource Statement ....................................................................................................... 211
Method Overriding with Exception Handling .............................................................................. 213
Introduction to Multithreading ....................................................................................................... 225
Java – Preemptive & Non Preemptive ................................................................................................ 229
Java – Thread Scheduler........................................................................................................................ 230
Java – Thread Life Cycle........................................................................................................................ 230
Java – Creating a Thread ....................................................................................................................... 232
Java – Thread Priorities ......................................................................................................................... 232
Java – Thread Name .............................................................................................................................. 232
Java – Yield Method............................................................................................................................... 233
Java – join() Method .............................................................................................................................. 233
Java – sleep() Method ............................................................................................................................ 233
[Link] 234
Collection Framework:................................................................................................................ 234
What is a Collection? ................................................................................................................................ 234
Real-time Examples: ......................................................................................................................... 234

Author:[Link]
Why need collection framework? ............................................................................................................. 235
Types of Objects Stored in Collection Object................................................................................... 235
1. Homogeneous objects: .................................................................................................................. 235
2. Heterogeneous objects: ................................................................................................................. 235
1. Duplicate objects:.......................................................................................................................... 236
2. Unique objects: ............................................................................................................................. 236
What is need of Collection in Java? ...................................................................................................... 237
1. Using a variable approach: ............................................................................................................ 237
2. Using a class object approach: ...................................................................................................... 237
3. Using an array object approach:.................................................................................................... 238
4. Using a collection object: .............................................................................................................. 240
What is Framework in Java? ................................................................................................................. 240
Using a collection object: .................................................................................................................. 241
What is Framework in Java? ................................................................................................................. 241
What is Collections Framework in Java ............................................................................................... 241
List of Interfaces defined in [Link] package ............................................................................ 241
List of classes defined in [Link] package ................................................................................ 242
Difference between Arrays & Collections in Java ................................................................................ 242
Advantages of Collection Framework in Java ...................................................................................... 243
Limitations of Collection Framework in Java....................................................................................... 244
Collection Hierarchy in Java ................................................................................................................. 244
Collection Interface in Java .................................................................................................................. 246
Methods of Collection Interface in Java ........................................................................................... 249
Collections Class in Java ...................................................................................................................... 250
Interfaces of Collection Framework ........................................................................................ 253
Collections class declaration ............................................................................................................ 254
Characteristics of a Set collection: .............................................................................................. 262
2. Set Implementations ...................................................................................................................... 262
Introduction to JDBC ...................................................................................................................... 267
JDBC 4.0 API .................................................................................................................................. 272
Steps to connect a Java Application to Database ..................................................................... 274
Connecting to Access Database using Type-1 Driver .............................................................. 275

Author:[Link]
Connecting to Oracle Database using Thin Driver .................................................................... 279
Example ........................................................................................................................................... 280
Connecting to MySQL Database using Thin Driver .................................................................. 282
Example ........................................................................................................................................... 283

History:
James Gosling initiated the Java language project in June 1991 for use in one of his
many set-top box projects. The language, initially called Oak after an oak tree that
stood outside Gosling’s office, also went by the name Green and ended up later
renamed as Java, from a list of random words.

Sun released the first public implementation as Java 1.0 in 1995. It promised Write
Once, Run Anywhere(WORA), providing no-cost run-times on popular platforms.
Java Features:

Object Oriented : In java everything is an Object. Java can be easily extended


since it is based on the Object model.

Platform independent: Unlike many other programming languages including C


and C++ when Java is compiled, it is not compiled into platform specific machine,
rather into platform independent byte code. This byte code is distributed over the
web and interpreted by virtual Machine (JVM) on whichever platform it is being
run.

Distributed :Java is designed for the distributed environment of the internet.

What Is java?

Java is a general-purpose, concurrent, class-based, object-oriented computer


programming language .

It is intended to let application developers “write once, run anywhere” (WORA),


meaning that code that runs on one platform does not need to be recompiled to run
on another.

Author:[Link]
Java is a high-level object oriented programming language.
Java is a very simple compared to earlier programming languages.
Java has following features
1) Simple
2) Robust
3) Secure
4) High Performance
5) Distributed
6) Portability
7) Architecture neutral
8) Multithreaded
9) Dynamic
10) Object Oriented
1) Simple

Java is simple because it has


no pointers, structures, unions, operator overloading and virtual base classes as in C++.
It does not require header files at the starting of source code.
2) Robust

Author:[Link]
Java can deal effectively with errors during execution & with erroneous input.
It need not have to worry about problems like bad pointers, memory allocation problems and memory leakages
problems because Java uses Garbage collection for memory deallocation.
It has strong type checking mechanism.
Exception handling mechanism, help programmers to get rid of system crashing problems.
These all features help to make Java Robust.
3) Secure

The main reason for making Java more secure and portable is BYTECODE, which is the set of instructions
used by Java Virtual Machine (JVM).
Thus, Java prevents generating changes in a program outside the authorized system.
If changes are made in BYTECODE by unauthorized user and system, JVM discards the file.
Java does not make use of pointers which prevents unauthorized access to memory.
Therefore, Java is one of the most secured high-level programming languages.
4) High Performance

Author:[Link]
Just In Time (JIT) compiler is mainly used for achieving high performance of Java programs while
running.
Initially, Java was using a straight forward approach in JVM for converting BYTECODE into machine
language and then running it on a computer.
JVM used to convert line by line BYTECODE into machine language and run it.
Even if the same BYTECODE is present at different lines, JVM used to convert these BYTECODE lines into
machine language every time they appear. That is JVM was doing same work, again and again, resulting in the
wastage of time.
After introducing JIT compiler in Java, JVM checks the code initially to find out whether same BYTECODE
appears repeatedly. If yes, JVM converts that BYTECODE into machine language only once and use the same
converted machine code where ever the same BYTECODE appears.
This approach helps Java in saving time by doing the same type of work only once and using its result where
ever it needs.
5) Distributed

Distributed applications are those applications that are divided into different parts for different systems. But act
as a single application running on a single system.
It is like a football team where all players are scattered throughout the field but work as a single team.
Java is mainly used to create distributed applications.
Java uses TCP/IP and UDP/IP protocol with socket programming for distributed communication.
These protocols are very useful in making the connection between those distributed parts of the application and

Author:[Link]
try to interact with each other to work as a single application.
Java also uses RMI (Remote Method Invocation) & helps to make Java application distributed across a
network.
Example
1) Internet-based remote access and support applications.
2) Banking Application, etc.
6) Portability

BYTECODE is the main reason for making Java language, portable.


It allows Java programs to run in a wide variety of environments like Windows, Linux, Mac, etc.
JVM acts as an interpreter for BYTECODE.
JVM is developed separately for every distinct environment.
Suitable JVM needs to be installed on every different environment/operating system.
Therefore, by creating .class file (containing BYTECODE) of Java program in one environment can be run on
different environments.
7) Architectural neutral

The main aim of Java is Write Once; Run Anywhere (WORA).


Therefore it is made platform independent & does not rely on the Operating system & its underlying processor.

Author:[Link]
8) Multithreaded

Thread is a part of the program that can run separately without depending on other parts of the program.
The program which contains two or more threads (parts of the program), that can run separately and
simultaneously without depending on each other is called multithreaded program.
Java supports Multi-threading, that is one program, multiple tasks at a time.
Multithreading increases the speed of program execution.
9) Dynamic

Java loads the byte code dynamically at runtime and executes that code.
Java programs carry large amounts of Run-time type information that is used to verify and resolve accesses to
objects at Run-time.
This feature makes Java possible to dynamically link code in a safe, practical and beneficial manner.
10) Object Oriented
Java is a programming language mainly based on Objects rather than primitive data types.
Java is one of the easiest object oriented programming language.
These days Object oriented programming has become the most preferred programming approach by software
industries.

Author:[Link]
Framework
It helps developers to develop programs for different platforms. In
short, Framework reduces the need for coding in the application

Google web toolkit


It is a free and open-source framework that is used to write complex browser

applications. With this framework, one can write Java code and deploy it to

JavaScript.

Hibernate,spring,jsf,structs

Mybatis: Maven

Angular
Developed by Google, Angular is one of the popular JavaScript frameworks for

development.

Spark Framework
It is used for Kotlin and Java Programming language. With the help of this

Microframework, one can easily develop many web applications, microservice,

and REST APIs.

Author:[Link]
TestingFrame Work:

Junit

Jasmine

Selenium
Cucumber

Java Monitoring Tool:

The java monitoring tool is defined as a monitoring tool used for tracking the

performance of the applications developed in a java programming language

The tool is also capable of tracking the performance of servers.

Deeloping Tool:

Spark

Author:[Link]
Spark is a robust web application development framework based on Java. It

allows developers to build internet apps without boilerplate code writing.

Spark is running on Hadoop, Apache Mesos, Cubans, standalone and in the

cloud. Different data sources may be available. Spark provides more than 80

operators that make parallel applications simple to construct.

Features of Spark:

 Spark has an ability to supports several languages.

 It includes interactive/declarative query instruments, information

streaming, machine learning.

 Active, gradual and expanding community.

 Spark can not only work separately, but it can also work on Hadoop.

 In RAM Server sparks stores the information, enabling quick access and

in turn speeding up analysis speeds.

Gradle

Author:[Link]
Gradle is a Java tool for project automation. It builds on Apache

Ant and Apache Maven features.

Features of Gradle:

 Better dependency modeling with the Java Library plugin decreases the

volume of the classpath compile

 Gradle Wrapper allows Gradle to be performed on computers that are

not assembled

 Its intelligent classpath helps prevent the need to build when a library’s

binary interface has not changed.

Groovy

Groovy is a powerful object-oriented language for the Java platform. The

primary goal of this Groovy is to increase the production speed of developers.

It runs on JVM i.e. Java Virtual Machine

Features of Groovy:

Author:[Link]
 It highlights syntax and error automatically like NetBeans which helps to

avoid mistakes in programming.

 It can integrate with java or any third party libraries

 Groovy supports AST transformation

 It supports static as well as dynamic typing.

 It automatically generates getters and setters

11. Oracle JDeveloper

Differentiate JVM JRE JDK JIT


Java Virtual Machine (JVM) is an abstract computing machine. Java Runtime Environment
(JRE) is an implementation of the JVM. Java Development Kit (JDK) contains JRE along with
various development tools like Java libraries, Java source compilers, Java debuggers,
bundling and deployment tools.

Author:[Link]
JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing
etc)+runtime libraries.
Java Runtime Environment contains JVM, class libraries, and other supporting files. It does
not contain any development tools such as compiler, debugger, etc. Actually JVM runs the
program, and it uses the class libraries, and other supporting files provided in JRE. If you
want to run any java program, you need to have JRE installed in the system.

Note : If u just want to run applets (ex: Online games or puzzles), JRE needs to be installed
on the machine.

JDK (Java Development Kit):

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:

o Standard Edition Java Platform(J2SE)


o Enterprise Edition Java Platform(J2EE)
o Micro Edition Java Platform(JME)

JVM (Java Virtaul Machine)

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

Author:[Link]
JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).

What is JVM
It is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its implementation
has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command prompt to
run the java class, an instance of JVM is created.

What it does
The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

What is J2SE?
J2SE is a collection of Java Programming Language API (Application
programming interface) that is very useful to many Java platform programs.

Author:[Link]
1. Java 2 Standard Edition (J2SE): J2SE is used primarily for writing applets
and other Java-based applications.

2. Java 2 Enterprise Edition (J2EE): J2EE is the Java architecture for developing
multitier enterprise applications. As part of J2EE, JSP pages have access to all
J2EE components, including JavaBeans and Enterprise JavaBeans components and
Java servlets. JSP pages are actually compiled into servlets, so they have all of the
benefits of these flexible, server-side Java applications.

3. Java 2 Micro Edition (J2ME): J2ME is a technology that allows programmers


to use the java programming language and related tools to develop programs for
mobile wireless information devices such as cellular phones and personal digital
assistants (PDAs).

Java Application Types:

There are different types of Java applications before moving on to Servlets.


Java can be used to develop different types of applications:

1. Standalone Applications
2. Applets
3. Web Applications
4. Distributed Applications

Standalone Applications-
A standalone application is a program that runs on your computer. It is more or
less like a C or C++ program.

Web Applications-
Web applications run on the Web Server. Web applications are accessed through
web clients i.e. web browsers like Internet Explorer or Netscape. Whenever you
access some web site by specifying the URL (Universal Resource Locator), you
are accessing some web application.

The main components of a web application:

Java Servlets
Java Server Pages (JSP), and
HTML

Author:[Link]
Distributed Applications-
Java application can be divided into a number of modules/components (Java
programs), which can run on different machines. The Java programs/applications
running on different machines can communicate with each other.

Java Virtual Machine (JVM):

A Java virtual machine (JVM) is a virtual machine that can execute Java bytecode.
It is the code execution component of the Java software platform. Sun
Microsystems has stated that there are over 5.5 billion JVM-enabled devices.

JVMs are available for many hardware and software platforms. The use of the
same bytecode for all JVMs on all platforms allows Java to be described as a write
once, run anywhere programming language, versus write once, compile anywhere,
which describes cross-platform compiled languages. Thus, the JVM is a crucial
component of the Java platform..

Stack and Heap—Quick Review


For most people, understanding the basics of the stack and the heap makes it
far easier to understand topics like argument passing, polymorphism, threads,
exceptions, and garbage collection. In this section, we'll stick to an overview, but
we'll expand these topics several more times throughout the book.
For the most part, the various pieces (methods, variables, and objects) of Java
programs live in one of two places in memory: the stack or the heap. For now, we're
going to worry about only three types of things: instance variables, local variables,
and objects:

■ Instance variables and objects live on the heap.


■ Local variables live on the stack.
Let's take a look at a Java program, and how its various pieces are created and
map into the stack and the heap:
1. class Collar { }
2.
3. class Dog {
4. Collar c; // instance variable
5. String name; // instance variable
6.
7. public static void main(String [] args) {
8.
9. Dog d; // local variable: d
10. d = new Dog();

Author:[Link]
11. [Link](d);
12. }
13. void go(Dog dog) { // local variable: dog
14. c = new Collar();
15. [Link]("Aiko");
16. }
17. void setName(String dogName) { // local var: dogName
18. name = dogName;
19. // do more stuff
20. }
21. }
Figure 3-1 shows the state of the stack and the heap once the program reaches

line 19. Following are some key points:

Different Versions:

 Released on 23 January 1996, JDK 1.0 version.


 Released on 19 February 1997 JD33K 1.1 version.
New features in JDK 1.1
1. JDBC (Java Database Connectivity)
2. Inner Classes
3. Java Beans
4. RMI (Remote Method Invocation)
5. Reflection (introspection only)

 1998 J2SE 1.2 version.


New features in J2SE 1.2
1. Collections framework.
2. BLOB, CLOB, batch update, user-defined types in JDBC.
 Released on 8 May 2000 J2SE 1.3 version.
New features in J2SE 1.3
1. Java Sound
2. Jar Indexing
3. A huge list of enhancements in almost all the java area.
 Released on 6 February 2002 J2SE 1.4 version.
New features in J2SE 1.4
1. XML Processing
2. Java Print Service
3. Logging API

Author:[Link]
4. Java Web Start
5. JDBC 3.0 API
6. Assertions
7. Preferences API
8. Chained Exception
9. IPv6 Support
[Link] Expressions
[Link] I/O API
 2004 J2SE 1.5 version.
New features in J2SE 1.5
1. Generics
2. Enhanced for Loop
3. Autoboxing/Unboxing
4. Typesafe Enums
5. Varargs
6. Static Import
7. Metadata (Annotations)
8. Scripting Language Support
9. JDBC 4.0 API
[Link] Web Services.
[Link] in switch Statement
[Link] Exception Handling

Java SE 8 was released in early 2014. In java 8


1. 1. Lambda Expression
2. 2. Functional Interface
3. 3. Default Methods
4. 4. Streams
5. 5. Date/Time API Changes

Java SE 9

Java SE 10

Java SE 11 (LTS) September 2018

Author:[Link]
Java SE 12 March 2019

JavaEE:( Enterprise Edition)

 specifications for enterprise features such as distributed


computing and web services.

 Java EE applications are run on reference runtimes, that can be


microservices or application servers, which handle transactions, security,
scalability, concurrency and management of the components it is deploying.

 Java EE was maintained by Oracle.

 The Java EE APIs include several technologies that extend the functionality
of the base Java SE APIs, such as EJB,
JavaBeans, connectors, servlets, JavaServer Pages and several web
service technologies.

Versions:
J2EE 1.2 (December 12, 1999)
J2EE 1.3 (September 24, 2001)
J2EE 1.4 (November 11, 2003)
Java EE 5 (May 11, 2006)
Java EE 6 (December 10, 2009)
Java EE 7 (May 28, 2013)
Java EE 8 (August 31, 2017)

JAVA EE Specifications:

1. WEB [Link] [Link]

Web specifications:

 Servlet: defines how to manage HTTP requests, in a synchronous or


asynchronous way. It is low level and other Java EE specifications rely on it;

Author:[Link]
 Java Server Faces: a technology for constructing user interfaces out of
components;

Web service specifications:

 Java API for XML Web Services can be used to create SOAP web services.
 Java API for RESTful Web Services provides support in creating web services
according to the Representational State Transfer (REST) architectural pattern;
 Java API for JSON Processing is a set of specifications to manage information
encoded in JSON format;
 Java API for JSON Binding provides specifications to convert JSON
information into or from Java classes;
 Java Architecture for XML Binding allows mapping XML into Java objects;

Enterprise specifications:

 Contexts and Dependency Injection is a specification to provide a dependency


injection container, as in Spring;
 Enterprise JavaBean (EJB) specification defines a set of lightweight APIs
that an object container (the EJB container)

 Java Persistence API are specifications about object-relational mapping


between relation database tables and Java classes.(Hibernate,iBatics …. )
 Java Transaction API
 JMS
WebProfile:
Specification JAVA EE 6 Java EE 7 Java EE 8

JavaServer
2.0 2.2 2.3
Faces (JSF)

JavaServer
2.2 2.3 2.3
Pages (JSP)

Author:[Link]
Servlet 3.0 3.1 4.0

Java Persistence
2.0 2.1 2.2
API (JPA)

Java API for


RESTful Web 1.1 2.0 2.1
Services (JAX-RS)
Compatable Server List:

Server Developer Version Licence

Glashfish Oracle javeEE8/7/.. free

WebLogic Oracle payment

Wildfly Redhot free

JBoss Redhot payment

Websphere IBM Javaee6/5/4.. Pay

Tomcat Apache All versions free

Module 2: Introduction To Java Programming


Environment
Set Path:
There are two ways to set the path in Java:

1. Temporary

Author:[Link]
2. Permanent

Temporary:

How to set the Temporary Path of JDK in Windows


To set the temporary path of JDK, you need to follow the following steps:

o Open the command prompt


o Copy the path of the JDK/bin directory
o Write in command prompt: set path=copied_path

For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin

2) How to set Permanent Path of JDK in Windows


For setting the permanent path of JDK, you need to follow these steps:

o Go to MyComputer properties -> advanced tab -> environment variables -> new tab
of user variable -> write path in variable name -> write path of bin folder in variable
value -> ok -> ok -> ok

Source File Declaration Rules


As the last part of this section, let's now look into the source file declaration
rules. These rules are essential when declaring classes, import statements
and package statements in a source file.

 There can be only one public class per source file.

 A source file can have multiple non-public classes.

 The public class name should be the name of the source file as well which should
be appended by .java at the end. For example: the class name is public class
Employee{} then the source file should be as [Link].

Author:[Link]
 If the class is defined inside a package, then the package statement should be
the first statement in the source file.

 If import statements are present, then they must be written between the
package statement and the class declaration. If there are no package
statements, then the import statement should be the first line in the source file.

 Import and package statements will imply to all the classes present in the
source file. It is not possible to declare different import and/or package
statements to different classes in the source file.

Classes have several access levels and there are different types of classes;
abstract classes, final classes, etc. We will be explaining about all these in
the access modifiers chapter.

Apart from the above mentioned types of classes, Java also has some
special classes called Inner classes and Anonymous classes.

Java Package
In simple words, it is a way of categorizing the classes and interfaces. When
developing applications in Java, hundreds of classes and interfaces will be
written, therefore categorizing these classes is a must as well as makes life
much easier.

Import Statements
In Java if a fully qualified name, which includes the package and the class
name is given, then the compiler can easily locate the source code or
classes. Import statement is a way of giving the proper location for the
compiler to find that particular class.

First Java Program


Let us look at a simple code that will print the words Hello World.

public class MyFirstJavaProgram {

/* This is my first java program.*/

public static void main(String []args) {

Author:[Link]
[Link]("Hello World"); // prints Hello World

Output
C:\> javac [Link]
C:\> java MyFirstJavaProgram
Hello World

Understanding first java program:

 Let’s see what is the meaning of class, public, static, void, main, String[],
[Link]().
 class is used to declare a class in java.
 public is an access modifier which represents visibility, it means it is visible
to all.
 static is a keyword, if we declare any method as static, it is known as static
method. The core advantage of static method is that there is no need to create
object to invoke the static method. The main method is executed by the JVM,
so it doesn’t require to create object to invoke the main method. So it saves
memory.
 void is the return type of the method, it means it doesn’t return any value.
 main represents startup of the program.
 String[] args is used for command line argument. We will learn it later.
 [Link]() is used print statement.

Basic Syntax:
About Java programs, it is very important to keep in mind the following points.

Case Sensitivity – Java is case sensitive which means identifier Hello and hello
would have different meaning in Java.

Class Names – For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter
should be in Upper Case. Example class MyFirstJavaClass

Method Names – All method names should start with a Lower Case letter.

Author:[Link]
If several words are used to form the name of the method, then each inner word’s
first letter should be in Upper Case.

Example public void myMethodName()

Program File Name – Name of the program file should exactly match the class
name.
When saving the file you should save it using the class name (Remember java is
case sensitive) and append ‘.java’ to the end of the name. (if the file name and the
class name do not match your program will not compile).

Example : Assume ‘MyFirstJavaProgram‘ is the class name. Then the file should
be saved as ‘[Link]‘
public static void main(String args[]) – java program processing starts from the
main() method which is a mandatory part of every java program.

Classess & Objects:


When you design a class,think about the objects that will be created from that class
type.

 Think the object knows


 Things the object does.

Thinks an obj knows about itself are called Instance variables.[STATE-data] and
can have unique values for each objects of that type.

Author:[Link]
Thinks an obj can do are called methods.[BEHAVIER].

When we design a class,we think about data an object will need to know about
itself,and we also design the methods that operate on that data.

It is common for an obj to have methods that read or write the values of the
instance variables.

For example ,Alarm obj, have an instance variable to hold the alarm time and two
methods for getting and setting the alarm time.

Another example address book, Each card has same blank fields (instance
variable).When you fill out a card creating an instance(objects) and entries make
on that card represent its State.

Class Dog{
Int size;
String breed;
String name;

Void bark() {
[Link](“wow wow….”);
}
}

The Dot operator(.) to access to an obj’s state and behavior .


Dog d=new Dog(); //make a new object
[Link]();
[Link]=20;
[Link]=”puppy”;

Bullet point:
 Oops lets you extend a program without having to touch previously-
tested,working code and resued.
 All java code is defined in a CLASS.
 An objects knows things and does things.

1. I am compiled from .java file ________.

Author:[Link]
2. My instance variable values can be different from my buddy’s values ___
3. I behave like a template.
4. I like to do stuff.
5. I can have many methods
6. I represent state
7. I have behaviors
8. I am located in objects
9. I have live in heap
10. I am used to create object instances.
[Link] state can change
12.I declared methods
13.I can change at runtime

Answers:

1. class
2. Object
3. class
4. obj,class
[Link],obj
6. instance variable
7,obj,class
[Link],instance variable
[Link].
[Link]
[Link],instance variable
[Link]
[Link],instance variable

Author:[Link]
Java Variables:

Variable come in two flavors:


1. Primitive
2. Reference (object)

[Link]

so far used varialbes in 2 places – as object state(instance variable) & local


variable(within methods).

Variable is a name of memory location.

There are two types of datatypes in java, 1. primitive and 2. non-primitive.

Author:[Link]
Primitive:-

The Primitive are ,

There are three types of variables: 1. local, 2. instance and 3. static.


int var = 10;//type & name of varaible

Local Variable:-

A variable that is declared inside the method is called local variable.


 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor or
block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor or
block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables so local variables should be
declared and an initial value should be assigned before the first use.
Following example uses sum without initializing it, so it would give an error at the time of compilation.

Instance Variable:-
A variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.

 Instance variables are declared in a class, but outside a method, constructor or


any block.
 When a space is allocated for an object in the heap a slot for each instance
variable value is created.
 Instance variables are created when an object is created with the use of the
key word ‘new’ and destroyed when the object is destroyed.

Author:[Link]
 Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an [Link] that must
be present through out the class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in
the class. Normally it is recommended to make these variables private (access
level).However visibility for subclasses can be given for these variables with
the use of access modifiers.
 Instance variables have default values. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned
during the declaration or within the constructor.
Ex:
Int a=0; boolean=false; Student student=null;

class PoorDog {
private int size;
private String name;

public int getSize() {


return size;
}

public String getName() {


return name;
}
}
public class PoorDogTestDrive {
public static void main (String[] args) {
PoorDog one = new PoorDog();
[Link](“Dog size is “ + [Link]());
[Link](“Dog name is “ + [Link]());
}
}

 Instance variables can be accessed directly by calling the variable name


inside the class. However within static methods and different class ( when
instance variables are given accessibility) the should be called using the fully
qualified name . [Link].

Author:[Link]
Primitive:

int a = 3;
byte b = 3;
if (a == b) { // true } //content check

Reference:

Foo a = new Foo();


Foo b = new Foo();
Foo c = a;
if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false } //reference check

Static variable:
A variable that is declared as static is called static variable. It cannot be local.
 Class variables also known as static variables are declared with
the static keyword in a class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
 Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final and static.
Constant variables never change from their initial value.
 Static variables are stored in static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the
program stops.
 Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
 Default values are same as instance variables. For numbers the default value
is 0, for Booleans it is false and for object references it is null. Values can be
assigned during the declaration or within the constructor. Additionally values
can be assigned in special static initializer blocks.

Author:[Link]
 Static variables can be accessed by calling with the class name
. [Link].
 When declaring class variables as public static final, then variables names
(constants) are all in upper case. If the static variables are not public and final
the naming syntax is the same as instance and local variables.

import [Link].*;

public class Employee{

// salary variable is a private static variable

private static double salary;

// DEPARTMENT is a constant

public static final String DEPARTMENT = "Development ";

public static void main(String args[]){

salary = 70000;

[Link](DEPARTMENT+"average salary:"+salary); }}

This would produce following result:

output:
Development average salary:70000
Note: If the variables are access from an outside class the constant should be
accessed as [Link]
In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:

type identifier [ = value][, identifier [= value] ...] ;

The type is one of Java’s datatypes. The identifier is the name of the variable. To
declare more than one variable of the specified type, use a comma-separated list.
Here are several examples of variable declarations of various types. Note that some
include an initialization.

Author:[Link]
II .Object Reference : [Non-Primitive]

-----------> create a obj


Dog myDog=new Dog();
---------------- > declare reference variable

Book b = new Book();

Book c = new Book();


Create 2 book reference ,now living on heap.

Book d=c;
C variable copy into d.

c=b;
b& c refer same obj.

A class can have any number of these. instance variables, getter, setter,method
A method can have only one of these. return
This can be implicitly promoted. return, argument
I prefer my instance variables private. encapsulation
It really means ‘make a copy’. pass by value
Only setters should update these. instance variables
A method can have many of these. argument
I return something by definition. getter
I shouldn’t be used with instance variables public
I can have many arguments. method
By definition, I take one argument. setter
These help create encapsulation. getter, setter, public, private

Java Identifiers:

All java components require names. Names used for classes, variables and methods
are called identifiers.

Author:[Link]
In java there are several points to remember about identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z ), currency character
($) or an underscore (-).
 After the first character identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers:age, $salary, _value, __1_value
 Examples of illegal identifiers : 123abc, -salary

Class Access modifiers:

Visibility P
Access within within outside package by outside
Modifier class package subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
ublic Protected Default Private
Visibility Public Protected Default Private
What does it mean to access a class? When we say code from one class (class A)
has access to another class (class B), it means class A can do one of three things:
■ Create an instance of class B.
■ Extend class B (in other words, become a subclass of class B).
■ Access certain methods and variables within class B, depending on the
access control of those methods and variables.
In effect, access means visibility. If class A can't see class B, the access level of the
methods and variables within class B won't matter; class A won't have any way to
access those methods and variables.
In effect, access means visibility.

Default Access :A class with default access has no modifier preceding it in the
declaration! It's the access control you get when you don't type a modifier in the
class declaration.

Protected Access:
The protected and default access control levels are almost identical, but with one

Author:[Link]
critical difference. A default member may be accessed only if the class accessing
the
member belongs to the same package, whereas a protected member can be
accessed
(through inheritance) by a subclass even if the subclass is in a different package.

Public Access:
gives all classes from all packages access to the public class

Private Access:
Members marked private can't be accessed by code in any class other than the
class in which the private member was declared. Let's make a small change to the

Roo class from an earlier example.

package cert;
public class Roo {
private String doRooThings() {
// imagine the fun code that goes here, but only the Roo
// class knows
return "fun";
}
}
The doRooThings() method is now private, so no other class can use it. If we
try to invoke the method from any other class, we'll run into trouble:

Members marked private can't be accessed by code in any class other than the
class in which the private member was declared. Let's make a small change to the
Roo class from an earlier example.
package cert;
public class Roo {
private String doRooThings() {
// imagine the fun code that goes here, but only the Roo
// class knows
return "fun";
}
}

Author:[Link]
The doRooThings() method is now private, so no other class can use it. If we
try to invoke the method from any other class, we'll run into trouble:

[Link] a private method be overridden by a subclass? That's an interesting


question, but the answer is technically no. Since the subclass, as we've seen, cannot
inherit a private method, it therefore cannot override the method

[Link] access modifiers be applied to local variables? NO!

Java Access Modifiers:

 Like other languages it is possible to modify classes, methods etc by using


modifiers. There are two categories of modifiers.
1. Access Modifiers : defualt, public , protected, private
2. Non-access Modifiers : final, abstract, strictfp

 A public member can be accessed by all other class even from other packages.
 Private members can be accessed only by the code in the same class.
 Default members are not visible to subclasses outside package while protected
members are visible to subclassed even when they are in the different package.
 Different between protected and default comes into picture only in the case of
subclass outside a package.
 Local variables can not have access modifiers.

Author:[Link]
 Local variables can have only final non-access modifiers that can be applied.

Private:

Members marked private can't be accessed by code in any class other than the
class in which the private member was declared. Let's make a small change to
the

What about a subclass that tries to inherit a private member of its superclass?
When a member is declared private, a subclass can't inherit it.

Can a private method be overridden by a subclass? That's an interesting


question, but the answer is technically no.

Protected and Default Members:

The protected and default access control levels are almost identical, but with one
critical difference. A default member may be accessed only if the class accessing the
member belongs to the same package, whereas a protected member can be accessed
(through inheritance) by a subclass even if the subclass is in a different package.

Local Variables and Access Modifiers


Can access modifiers be applied to local variables? NO!

Author:[Link]
Visibility Public Protected Default private

From the same class Yes Yes Yes Yes

From any class in the Yes Yes Yes No


same package
From a subclass in the Yes Yes Yes No
same package
From a subclass outside Yes Yes throuth No No
the same package inheritance

From any non-subclass Yes No No NO


class
outside the package

Nonaccess Member Modifies:

Final , abstract,synchronized,native,strictrp

Final:

final class cannot be subclassed.


final method cannot be overridden by a subclass.
final variable cannot be assigned a new value, once the initial method is made
(the initial assignment of a value must happen before the constructor completes).
Ex:
final int size = 42;
void changeSize( ){
size = 16; //can’t be changed
}

Note:

you need to know that instance variables

Author:[Link]
■ Can use any of the four access levels (which means they can be marked with
any of the three access modifiers)
■ Can be marked final
■ Can be marked transient
■ Cannot be marked abstract
■ Cannot be marked synchronized
■ Cannot be marked strictfp
■ Cannot be marked native

Comparison of modifiers on variables vs. methods

Local varialbe Instance variable methods


final final final
public public
protected protected
private private
static static
transient abstract
volatile synchronized
strictfp
native

Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,

 Widening Casting(Implicit)

Author:[Link]
 Narrowing Casting(Explicitly done)

Widening or Automatic type converion


Automatic Type casting take place when,
 Widening primitives conversions
 Widening reference conversionss
 Narrowing primitive conversions
 Narrowing reference conversions

Widening primitives conversions


Example :
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
double d=f; //no explicit type casting require

Author:[Link]
[Link]("Int value "+i);
[Link]("Long value "+l);
[Link]("Float value "+f);
}

Int value 100

Long value 100

Float value 100.0

Widening reference conversionss

This is applicable inheritance scenario where parant-child relationship exists.

Ex:

If there is a class A and child class B that extands class A then reference type A can safely hold
reference type of class B.

A a;

B b=new B();

a=b //widening conversion from sub type to super type

Narrowing or Explicit type conversion (narrowing primitives conversion)


When you are assigning a larger type value to a variable of smaller type, then you need to perform
explicit type casting.
Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;

Author:[Link]
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

[Link]("Double value "+d);


[Link]("Long value "+l);
[Link]("Int value "+i);
}

Double value 100.04

Long value 100


Int value 100

Narrowing Reference type conversion:

A a;

B b=new B();

a=b ;//ok implicite

b=a; //compile-time error

b=(B) a;//avoid compile time error

Command line argument:

Most of the object using string obj,then easily convert other types.

Class Test{

Public static void main(String args[]) {

1) Int i=[Link](args[0]); //dynamic value getting from command prompt

2) for(int i=0;i<=[Link];i++) sop(args[i]);

}}

Author:[Link]
Strictfp keyword:

Restricts floting point calculations to ensure portablility.

It is used only class,interfaces,methods.

Ex:

Strictfp class Test{}

Strictfp interface Test{}

Class car{

Strictfp void calculaeSpeed();


}

Final objectives:
Identifiers
❑ Identifiers can begin with a letter, an underscore, or a currency character.
❑ After the first character, identifiers can also include digits.

❑ Identifiers can be of any length.

Declaration Rules
❑ A source code file can have only one public class.
❑ If the source file contains a public class, the filename must match the
public class name.

❑ A file can have only one package statement, but multiple imports.
❑ The package statement (if any) must be the first (non-comment) line in a
source file.
❑ The import statements (if any) must come after the package and before
the class declaration.
❑ If there is no package statement, import statements must be the first (noncomment)
statements in the source file.
❑ package and import statements apply to all classes in the file.

Author:[Link]
❑ A file can have more than one nonpublic class.
❑ Files with no public classes have no naming restrictions.

Class Access Modifiers


❑ There are three access modifiers: public, protected, and private.
❑ There are four access levels: public, protected, default, and private.
❑ Classes can have only public or default access.
❑ A class with default access can be seen only by classes within the same package.

❑ A class with public access can be seen by all classes from all packages.

❑ Class visibility revolves around whether code in one class can


❑ Create an instance of another class
❑ Extend (or subclass), another class

❑ Access methods and variables of another class

Class Modifiers (Nonaccess)


❑ Classes can also be modified with final, abstract, or strictfp.
❑ A class cannot be both final and abstract.
❑ A final class cannot be subclassed.
❑ An abstract class cannot be instantiated.
❑ A single abstract method in a class means the whole class must be abstract.
❑ An abstract class can have both abstract and nonabstract methods.
❑ The first concrete class to extend an abstract class must implement all of its
abstract methods.

Member Access Modifiers


❑ Methods and instance (nonlocal) variables are known as "members."
❑ Members can use all four access levels: public, protected, default, private.
❑ Member access comes in two forms:
❑ Code in one class can access a member of another class.
❑ A subclass can inherit a member of its superclass.
❑ If a class cannot be accessed, its members cannot be accessed.
❑ Determine class visibility before determining member visibility.
❑ public members can be accessed by all other classes, even in other packages.
❑ If a superclass member is public, the subclass inherits it—regardless of package.

Author:[Link]
❑ Members accessed without the dot operator (.) must belong to the same class.
❑ this. always refers to the currently executing object.
❑ [Link]() is the same as just invoking aMethod().
❑ private members can be accessed only by code in the same class.
❑ private members are not visible to subclasses, so private members cannot
be inherited.
Default and protected members differ only when subclasses are involved:
❑ Default members can be accessed only by classes in the same package.
❑ protected members can be accessed by other classes in the same
package, plus subclasses regardless of package.
❑ protected = package plus kids (kids meaning subclasses).
❑ For subclasses outside the package, the protected member can be
accessed only through inheritance; a subclass outside the package cannot
access a protected member by using a reference to a superclass instance
(in other words, inheritance is the only mechanism for a subclass
outside the package to access a protected member of its superclass).
❑ A protected member inherited by a subclass from another package is
not accessible to any other class in the subclass package, except for the

subclass' own subclasses.

[Link] Package Classes


The following are some of important classes present in [Link] package.

Object class
String class
StringBuffer class
StringBuilder class (1.5 v)
Wrapper Classes

Author:[Link]
Autoboxing and Autounboxing(1.5 v)

Object class :

As object class acts as a root (or) parent (or) super for all java classes.
The following is the list of all methods present in [Link] Object class :
public String toString();
public native int hashCode();
public boolean equals(Object o);
protected native Object clone()throws CloneNotSupportedException;
public final Class getClass();
protected void finalize()throws Throwable;
public final void wait() throws InterruptedException;
public final native void wait()throws InterruptedException;
public final void wait(long ms,int ns)throws InterruptedException;
public final native void notify();
public final native void notifyAll();

toString():

Whenever we are try to print any object reference internally toString() method will be
executed.

If our class doesn't contain toString() method then Object class toString() method will be
executed.

Example 1:
class Student
{
String name;
int rollno;
Student(String name, int rollno)
{
[Link]=name;
[Link]=rollno;
}
public static void main(String args[]){
Student s1=new Student("saicharan",101);
Student s2=new Student("ashok",102);
[Link](s1);
[Link]([Link]());
[Link](s2);
}
}
Output:
Student@3e25a5
Student@3e25a5
Student@19821f

hashCode():

Author:[Link]
For every object jvm will generate a unique number which is nothing but hashCode.
If we didn't override hashCode() method then Object class hashCode() method.
Based on our programming requirement we can override hashCode() method to generate
our own hashcode

class Student class Student


{ {
public int hashCode() int rollno;
{ public int hashCode()
return 100; {
} return rollno;
} }
It is improper way of overriding hashCode() }
method because for every object we are It is proper way of overriding hashcode()
generating same hashcode. method because for every object we are
generating a different hashcode.

equals() method:

1. We can use this method to check equivalence of two objects.


2. If our class doesn't contain .equals() method then object class .equals() method will
be executed which is always meant for reference comparison[address comparison].
i.e., if two references pointing to the same object then only .equals( ) method
returns true

EX:

Student s1=new Student("vijayabhaskar",101);

Student s2=new Student("bhaskar",102);

Student s3=new Student("vijayabhaskar",101);

Student s4=s1; // if two references pointing to the same object then only .equals(()
method returns true

[Link]([Link](s2));

[Link]([Link](s3));
[Link]([Link](s4));
}}
Output:
False
False
True

Based on our programming requirement we can override .equals() method for


content comparison purpose.

Author:[Link]
Note :So in our code implement >> public boolean equals(Object obj) { .. } after that
it will check instead of address CONTENT will be check.

Differences between == (double equal operator) and .equals() method

== (double equal operator) .equals() method


It is an operator applicable for both It is a method applicable only for object
primitives and object references. references but not for primitives.
In the case of primitives == (double equal By default .equals() method present in
operator) meant for content comparison, but object class is also meant for reference
in the case of object references == operator comparison.
meant for reference comparison

Int a=10,b=10;

If(a==b) //content check

[Link](s1==s3);//reference
check

We can't override== We can override .equals() method for


content comparison.

getClass() method :

This method returns runtime class definition of an object.


Object o=new String("ashok");
[Link]("Runtime object type of o is :"+[Link]().getName());

Output:

Runtime object type of o is: [Link]. String

Understanding Object Ordering in Java with Comparable and


Comparator:

Author:[Link]
[Link]
comparable-and-comparator

how sorting actually works with elements in collections and arrays, and more interestingly, you will
be able to write your own code for sorting elements by the ways you want.

 [Link](list): sorts a List collection.


 [Link](array): sorts an array.

List<String> names = [Link](


"Tom", "Peter", "Alice", "Bob", "Sam",
"Mary", "Jane", "Bill", "Tim", "Kevin");
[Link]("Before sorting: " + names);
[Link](names);
[Link]("After sorting: " + names);

the collections are sorted by natural ordering of its elements:


- The natural ordering of String objects is alphabetic order.
- The natural ordering of Integer objects is alphanumeric order.
- The natural ordering of Date objects is chronological order.
Let’s dive into the concept of natural ordering.

1. Understanding Natural Ordering or Comparable

Natural ordering is the default ordering of objects of a specific type when they are sorted in an
array or a [Link] Java language provides the Comparable interface that allows us define
the natural ordering of a class. This interface is declared as follows:

public interface Comparable<T> {


public int compareTo(T object);
}

 compare value = 0: two objects are equal.


 compare value > 0: the first object (the current object) is greater than the second one.
 compare value < 0: the first object is less than the second one.

Classes whose objects used in collections or arrays should implement


the Comparableinterface for providing the natural ordering of its objects when being sorted.
Otherwise we will get an error at runtime.

A class that implements the Comparable interface is said to have class natural ordering.

Author:[Link]
And the compareTo() method is called the natural comparison method.

In the above examples, we don’t have to write code to implement the Comparable interface
because the String, Integerand Date classes already implemented this interface. Hence we can
sort a collection containing objects of these types.

Other wrapper types in Java are also comparable: Long, Double, Float, etc.

List<Employee> listEmployees = new ArrayList<>();

Employee employee1 = new Employee("Rajkumar", "govind");


Employee employee2 = new Employee("Suresh", "Arumugam");
Employee employee3 = new Employee("Zion", "Charles");
Employee employee4 = new Employee("Bill", "Gates");
Employee employee5 = new Employee("ram", "murugan");

[Link](employee1);
[Link](employee2);
[Link](employee3);
[Link](employee4);
[Link](employee5);

[Link](listEmployees);

We will get an error at runtime: no suitable method found for sort(List<Emmployee>)…


WHY?
It’s because the Employee class doesn’t implement the Comparable interface so
the sort() method cannot compare the objects.
Now, let’s have the Employee class implements the Comparable interface, and we define the
natural ordering is first name - last name, meaning the employees are sorted by first name first, then
by last name.

Here’s the updated version of the Employee class:

public class Employee implements Comparable<Employee> {


// fields...
// constructors...
// getters...
// setters...
// implement the natural comparison method:

public int compareTo(Employee another) {


int compareValue = [Link]([Link]);
if (compareValue == 0) {
return [Link]([Link]);
}
return compareValue;
}
}

Author:[Link]
We cannot compare objects of different types, e.g. a String object cannot be compared with an
Integer object.

2. Understanding Comparator
The Collections utility class provides a method for sorting a list using an external comparator:
[Link](list, comparator)

This overloaded version takes two parameters: a list collection and a comparator, which is any
object that implements the Comparatorinterface. This interface declares this method:
public interface Comparator <T> {
public int compare(T obj1, T obj2);
}

Operators:
||

T T =F

T F =T

F T =T

F F =T

&&

T T =T

T F =F

F T =F

F F=F

Author:[Link]
[Link]

Java ternary operator is a one liner replacement for if-then-else statement and used a lot in java
programming. We can use ternary operator to replace switch also as shown in below example

public class TernaryOperator {

public static void main(String[] args) {

[Link](getMinValue(4,10));

[Link](getAbsoluteValue(-10));

[Link](invertBoolean(true));

String str = "Australia";


String data = [Link]("A") ? "Str contains 'A'" : "Str doesn't contains 'A'";
[Link](data);

int i = 10;
switch (i){
case 5:
[Link]("i=5");
break;
case 10:
[Link]("i=10");
break;
default:
[Link]("i is not equal to 5 or 10");
}

[Link]((i==5) ? "i=5":((i==10) ? "i=10":"i is not equal to 5 or 10"));


}

private static boolean invertBoolean(boolean b) {


return b ? false:true;
}

private static int getAbsoluteValue(int i) {


return i<0 ? -i:i;
}

private static int getMinValue(int i, int j) {


return (i<j) ? i : j;
}

Author:[Link]
As you can see that we are using java ternary operator to avoid if-then-else and switch case
statements. This way we are reducing the number of lines of code in java program.

Numbers:
[Link]

Java - Character Class


[Link]

Data & Time:


[Link]

Java - Strings Class


[Link]

[Link]

String class in java:


String is probably the most commonly used class in java library. String class is encapsulated
under [Link] package. In java, every string that you create is actually an object of type String.
One important thing to notice about string object is that string objects are immutable that means once
a string object is created it cannot be altered.

String str =”abc”;

is equivalent to:

char data[] = {‘a’, ‘b’, ‘c’};


String str = new String(data);

Author:[Link]
Why String is immutable in Java?
In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable

1. String pool is possible only because String is immutable in Java. This way Java
Runtime saves a lot of heap space because different String variables can refer to the
same String variable in the pool. If String would not have been immutable, then
String interning would not have been possible because if any variable would have
changed the value, it would have been reflected in the other variables too.
2. If String is not immutable then it would cause a severe security threat to the
application. For example, database username, password are passed as String to get
database connection and in socket programming host and port details passed as
String. Since String is immutable, its value can’t be changed otherwise any hacker
could change the referenced value to cause security issues in the application.
3. Ahaar card ,

Once string object is created its data or state can't be changed but a new string object is
created.

An object whose state cannot be changed after it is created is known as an Immutable object. String,
Integer, Byte, Short, Float, Double and all other wrapper classes objects are immutable.

Creating an Immutable class


public final class MyString
{
final String str;
MyString(String s)
{
[Link] = s;
}
public String get()
{
return str;
}
}

In this example MyString is an immutable class. MyString's state cannot be changed once it is
created.

Creating a String object

Author:[Link]
String can be created in number of ways, here are a few ways of creating string object.
1) Using a String literal
String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String
object.
String str1 = "Hello";

2) Using another String object


String str2 = new String(str1);

3) Using new Keyword


String str3 = new String("Java");

4) Using + operator (Concatenation)


String str4 = str1 + str2;
or,
String str5 = "hello"+"Java";

Each time you create a String literal, the JVM checks the string pool first. If the string literal already
exists in the pool, a reference to the pool instance is returned. If string does not exist in the pool, a
new string object is created, and is placed in the pool. String objects are stored in a special memory
area known as string constant pool inside the heap memory.

String Pool in Java


String Pool in java is a pool of Strings stored in Java Heap Memory. We know that
String is special class in java and we can create String object using new operator as
well as providing values in double quotes.

Here is a diagram which clearly explains how String Pool is maintained in java heap space and
what happens when we use different ways to create Strings.

Author:[Link]
When we use double quotes to create a String, it first looks for String with the same value in the String
pool, if found it just returns the reference else it creates a new String in the pool and then returns the
reference.

However using new operator, we force String class to create a new String object in heap space. We can
use intern() method to put it into the pool or refer to another String object from the string pool
having the same value.

Concatenating String
There are 2 methods to concatenate two or more string.

1. Using concat() method


2. Using + operator

1) Using concat() method


string s = "Hello";
string str = "Java";
string str2 = [Link](str);
String str1 = "Hello".concat("Java"); //works with string literals too.

Author:[Link]
2) Using + operator
string str = "Rahul";
string str1 = "Dravid";
string str2 = str + str1;
string st = "Rahul"+"Dravid";

String Comparison
String comparison can be done in 3 ways.

1. Using equals() method


2. Using == operator
3. By CompareTo() method

Using equals() method


equals() method compares two strings for equality. Its general syntax is,
boolean equals (Object str)
It compares the content of the strings. It will return true if string matches, else returns false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
[Link](s2); //true
[Link](s1) ; //false

Using == operator
== operator compares two object references to check whether they refer to same instance. This also,
will return true on successful match.
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(s1 == s2) //true
test(s1 == s3) //false

Author:[Link]
Reason:
Its because we are creating a new object using new operator, and thus it gets created in a non-pool
memory area of the heap. s1 is pointing to the String in string pool while s3 is pointing to the String
in heap and hence, when we compare s1 and s3, the answer is false.
The following image will explain it more clearly.

By compareTo() method
compareTo() method compares values and returns an int which tells if the string compared is less
than, equal to or greater than the other string. It compares the String based on natural ordering i.e
alphabetically. Its general syntax is,
int compareTo(String str)
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
[Link](S2); //return -1 because s1 < s2
[Link](S3); //return 0 because s1 == s3
[Link](s1); //return 1 because s2 > s1

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool) heap memory, and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer to
the object in a heap (non-pool).

Author:[Link]
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}}
Test it Now

java
strings
example

Java String class methods


The [Link] class provides many useful methods to perform operations on
sequence of char values.

No. Method Description

1 char charAt(int index) returns char value for the


particular index

2 int length() returns string length

3 static String format(String format, Object... returns a formatted string.


args)

4 static String format(Locale l, String format, returns formatted string with


Object... args) given locale.

Author:[Link]
5 String substring(int beginIndex) returns substring for given
begin index.

6 String substring(int beginIndex, int endIndex) returns substring for given


begin index and end index.

7 boolean contains(CharSequence s) returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, returns a joined string.


Iterable<? extends CharSequence>
elements)

10 boolean equals(Object another) checks the equality of string


with the given object.

11 boolean isEmpty() checks if string is empty.

12 String concat(String str) concatenates the specified


string.

13 String replace(char old, char new) replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, replaces all occurrences of the


CharSequence new) specified CharSequence.

15 static String equalsIgnoreCase(String compares another string. It


another) doesn't check case.

Author:[Link]
16 String[] split(String regex) returns a split string matching
regex.

17 String[] split(String regex, int limit) returns a split string matching


regex and limit.

18 String intern() returns an interned string.

19 int indexOf(int ch) returns the specified char


value index.

20 int indexOf(int ch, int fromIndex) returns the specified char


value index starting with given
index.

21 int indexOf(String substring) returns the specified substring


index.

22 int indexOf(String substring, int fromIndex) returns the specified substring


index starting with given
index.

23 String toLowerCase() returns a string in lowercase.

24 String toLowerCase(Locale l) returns a string in lowercase


using specified locale.

25 String toUpperCase() returns a string in uppercase.

26 String toUpperCase(Locale l) returns a string in uppercase


using specified locale.

Author:[Link]
27 String trim() removes beginning and ending
spaces of this string.

28 static String valueOf(int value) converts given type into string.


It is an overloaded method.

String class function


The following methods are some of the most commonly used methods of String class.
charAt()
charAt() function returns the character located at the specified index.
String str = "studytonight";
[Link]([Link](2));
Output: u
NOTE: Index of a String starts from 0, hence [Link](2) means third character of the String str.

equalsIgnoreCase()
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower case
doesn't matters with this fuction ).
String str = "java";
[Link]([Link]("JAVA"));

true

indexOf()
indexOf() function returns the index of first occurrence of a substring or a
character. indexOf()method has four forms:

 int indexOf(String str): It returns the index within this string of the first occurrence of the

specified substring.

Author:[Link]
 int indexOf(int ch, int fromIndex): It returns the index within this string of the first

occurrence of the specified character, starting the search at the specified index.
 int indexOf(int ch): It returns the index within this string of the first occurrence of the

specified character.
 int indexOf(String str, int fromIndex): It returns the index within this string of the first

occurrence of the specified substring, starting at the specified index.

Example:
public class StudyTonight {
public static void main(String[] args) {
String str="StudyTonight";
[Link]([Link]('u')); //3rd form
[Link]([Link]('t', 3)); //2nd form
String subString="Ton";
[Link]([Link](subString)); //1st form
[Link]([Link](subString,7)); //4th form
}
}

11

-1

NOTE: -1 indicates that the substring/Character is not found in the given String.

length()
length() function returns the number of characters in a String.
String str = "Count me";
[Link]([Link]());

Author:[Link]
replace()
replace() method replaces occurances of character with a specified new character.
String str = "Change me";
[Link]([Link]('m','M'));

Change Me

substring()
substring() method returns a part of the string. substring() method has two forms,
public String substring(int begin);

public String substring(int begin, int end);


/*
character of begin index is inclusive and character of end index is exclusive.
*/
The first argument represents the starting point of the subtring. If the substring() method is called
with only one argument, the subtring returned, will contain characters from specified starting point to
the end of original string.
But, if the call to substring() method has two arguments, the second argument specify the end point
of substring.
String str = "0123456789";
[Link]([Link](4));

456789

[Link]([Link](4,7));

456

toLowerCase()
toLowerCase() method returns string with all uppercase characters converted to lowercase.
String str = "ABCDEF";
[Link]([Link]());

Author:[Link]
abcdef

toUpperCase()
This method returns string with all lowercase character changed to uppercase.
String str = "abcdef";
[Link]([Link]());

ABCDEF

valueOf()
Overloaded version of valueOf() method is present in String class for all primitive data types and for
type Object.
NOTE: valueOf() function is used to convert primitive data types into Strings.
public class Example{
public static void main(String args[]){
int num = 35;
String s1 = [Link](num); //converting int to String
[Link](s1+"IAmAString");
}
}

35IAmAString

But for objects, valueOf() method calls toString() function.

toString()
toString() method returns the string representation of the object used to invoke this
method. toString() is used to represent any Java Object into a meaningful string representation. It is
declared in the Object class, hence can be overrided by any java class. (Object class is super class of
all java classes.)
public class Car {
public static void main(String args[])
{

Author:[Link]
Car c = new Car();
[Link](c);
}
public String toString()
{
return "This is my car object";
}
}

This is my car object

Whenever we will try to print any object of class Car, its toString() function will be called.
toString() can also be used with normal string objects.
String str = "Hello World";
[Link]([Link]());

Hello World

NOTE: If we don't override the toString() method and directly print the object, then it would print
the object id.
Example:
public class Car {
public static void main(String args[])
{
Car c = new Car();
[Link](c);
}
}

[Link]@15db9742 (here studytonight is a user-defined package).

toString() with Concatenation


Whenever we concatenate any other primitive data type, or object of other classes with a String
object, toString() function or valueOf() function is called automatically to change the other object
or primitive type into string, for successful concatenation.

Author:[Link]
int age = 10;
String str = "He is" + age + "years old.";
In above case 10 will be automatically converted into string for concatenation
using valueOf()function.

trim()
This method returns a string from which any leading and trailing whitespaces has been removed.
String str = " hello ";
[Link]([Link]());

hello

NOTE: If the whitespaces are between the string, for example: String s1 = "study
tonight"; then [Link]([Link]()); will output "study tonight".

trim() method removes only the leading and trailing whitespaces.

StringBuffer class
StringBuffer class is used to create a mutable string object i.e its state can be changed after it is
created. It represents growable and writable character sequence. As we know that String objects are
immutable, so if we do a lot of changes with String objects, we will end up with a lot of memory
leak.
So StringBuffer class is used when we have to make lot of modifications to our string. It is also
thread safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4 constructors.
They are,

1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )

Author:[Link]
 StringBuffer() creates an empty string buffer and reserves room for 16 characters.

 stringBuffer(int size) creates an empty string and takes an integer argument to set capacity

of the buffer.

Example showing difference between String and StringBuffer


class Test {
public static void main(String args[])
{
String str = "study";
[Link]("tonight");
[Link](str); // Output: study

StringBuffer strB = new StringBuffer("study");

[Link]("tonight");
[Link](strB); // Output: studytonight
}
}
Reason:
Output is such because String objects are immutable objects. Hence, if we concatenate on the same
String object, it won't be altered(Output: study). But StringBuffer creates mutable objects. Hence, it
can be altered(Output: studytonight)

Important methods of StringBuffer class


The following methods are some most commonly used methods of StringBuffer class.
append()
This method will concatenate the string representation of any type of data to the end of the
invoking StringBuffer object. append() method has several overloaded forms.
StringBuffer append(String str)

Author:[Link]
StringBuffer append(int n)

StringBuffer append(Object obj)


The string representation of each parameter is appended to StringBuffer object.
StringBuffer str = new StringBuffer("test");
[Link](123);
[Link](str);

test123

insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)

StringBuffer insert(int index, int num)

StringBuffer insert(int index, Object obj)


Here the first parameter gives the index at which position the string will be inserted and string
representation of second parameter is inserted into StringBuffer object.
StringBuffer str = new StringBuffer("test");
[Link](4, 123);
[Link](str);

test123

reverse()
This method reverses the characters within a StringBuffer object.
StringBuffer str = new StringBuffer("Hello");
[Link]();
[Link](str);

olleH

Author:[Link]
replace()
This method replaces the string from specified start index to the end index.
<

StringBuffer str = new StringBuffer("Hello World");


[Link]( 6, 11, "java");
[Link](str);

Hello java

capacity()
This method returns the current capacity of StringBuffer object.
StringBuffer str = new StringBuffer();
[Link]( [Link]() );

16

Note: Empty constructor reserves space for 16 characters. Therefore the output is 16.

ensureCapacity()
This method is used to ensure minimum capacity of StringBuffer object.
If the argument of the ensureCapacity() method is less than the existing capacity, then there will be
no change in existing capacity.
If the argument of the ensureCapacity() method is greater than the existing capacity, then there will
be change in the current capacity using following rule: newCapacity = (oldCapacity*2) + 2.
StringBuffer str = new StringBuffer();
[Link]( [Link]()); //output: 16 (since empty constructor reserves
space for 16 characters)
[Link](30); //greater than the existing capacity
[Link]( [Link]()); //output: 34 (by following the rule -
(oldcapacity*2) + 2.) i.e (16*2)+2 = 34.

StringBuilder class
StringBuilder is identical to StringBuffer except for one important difference that it is not
synchronized, which means it is not thread safe. Its because StringBuilder methods are not
synchronised.

Author:[Link]
StringBuilder Constructors

1. StringBuilder ( ), creates an empty StringBuilder and reserves room for 16 characters.


2. StringBuilder ( int size ), create an empty string and takes an integer argument to set capacity of
the buffer.
3. StringBuilder ( String str ), create a StringBuilder object and initialize it with string str.

Difference between StringBuffer and StringBuilder class

StringBuffer class StringBuilder class

StringBuffer is synchronized. StringBuilder is not


synchronized.

Because of synchronisation, StringBuffer operation is slower than StringBuilder operates faster.


StringBuilder.

Example of StringBuilder
class Test {
public static void main(String args[])
{
StringBuilder str = new StringBuilder("study");
[Link]( "tonight" );
[Link](str);
[Link]( 6, 13, "today");
[Link](str);
[Link]();
[Link](str);
[Link]( 6, 13, "today");

Author:[Link]
}
}

studytonight

studyttoday

yadottyduts

String equals , CONTENT CHECK

STINRG == , REFERECNE CHECK.

Questions:

[Link] is diff between Stirng and stringBuffer?

String-immtability StringBufer-mutablilty

[Link] mutability & Immutability with examples?

[Link] is diff. between

String s=new String(“raj”); //2 obj create heap,scp

String s1=”raj”;//just point to ref. of scp

[Link] immutability and mutability Is any other diff betweeh string & stringbuffer?

In string equals meant for contain comparison.

In SB reference comparision.

5. What is SCP ? specially designed memory area string objects,

6. What is advantage of SCP? Memory utilition and performacd increased

7. What is dis-advantage of SCP? Immutability of objects.

8. why scp concept like avail only for string but not for SB?

String is most commonly object so special memory space allotted.(SCP)

9. In addition to String obj any other objs are immutable in java?

All wrapper classes objects immtable in java.

[Link] it possible t o crate own immutable class?explain with example?

Author:[Link]
[Link] means non-changble where as final means also [Link] what is
different between final and immutable?

static keyword in java


static keyword in Java is used a lot in java programming. Java static keyword is used to create a
Class level variable in java. static variables and methods are part of the class, not the
instances of the class.

EX:

Public class Employee {

Private Integer empIdl

Private String empName;

Private Double salary;

Private String email;

Public static final String COMPANY_NAME=”JP Morgan”;

Public Employee(Interger empId,….)

Super();

[Link]=empId; …

Author:[Link]
}

P v s main(){

Employee e1=new Employee(1001,….);

E1. COMPANY_NAME;

Ex2:

Public class Countert {

Private static int counter;

Public Counter(){

counter++;

P s v main(_{

New Counter();

Sop([Link]);

New Counter();

Sop([Link]);

1 static keyword in java

 Java static variable


 Java static method
 Java static block
 Java Static Class
 Java static import

[Link] static variable


We can use static keyword with a class level variable. A static variable is a class
variable and doesn’t belong to Object/instance of the class.

Author:[Link]
Since static variables are shared across all the instances of Object, they are not thread
safe.

Usually, static variables are used with the final keyword for common resources or
constants that can be used by all the objects. If the static variable is not private, we can
access it with [Link]

//static variable example


private static int count;
public static String str;
public static final String DB_USER = "myuser";

[Link] static method


Same as static variable, static method belong to class and not to class instances.

A static method can access only static variables of class and invoke only static methods
of the class.

Usually, static methods are utility methods that we want to expose to be used by other
classes without the need of creating an instance. For example Collections class.

Java Wrapper classes and utility classes contains a lot of static methods. The main()
method that is the entry point of a java program itself is a static method.

//static method example


public static void setCount(int count) {
if(count > 0)
[Link] = count;
}

//static util method


public static int addInts(int i, int...js){
int sum=i;
for(int x : js) sum+=x;
return sum;
}
From Java 8 onwards, we can have static methods in interfaces too. For more details
please read Java 8 interface changes.

Ex:

Author:[Link]
It should not associate any indivial object ,it common for all classes.

Public class DateUtil {

Public static Date getDate(String date) throws ParseException {

SimpleDateFormat dateFormat=new SimpleDataFormat(“dd/MM/yyyy”);

Date parseDate= [Link](date);

Retrun parseDate;

Main(){

Employee emp=new Employee(1001,”raj”,8000.00,raj@[Link],


[Link](“27/07/2019”))

[Link] static block


Java static block is the group of statements that gets executed when the class is loaded
into memory by Java ClassLoader.

Static block is used to initialize the static variables of the class. Mostly it’s used to create
static resources when the class is loaded.

We can’t access non-static variables in the static block. We can have multiple static
blocks in a class, although it doesn’t make much sense. Static block code is executed
only once when the class is loaded into memory.

Private static final int iniValue;

Author:[Link]
Private static int calValue;

static{
//can be used to initialize resources when class is loaded
[Link]("StaticExample static block");
//can access only static variables and methods
str="Test";
setCount(2);
iniValue=5;
calValue=iniValue*5;
}

[Link] Static Class


We can use static keyword with nested classes. static keyword can’t be used with
top-level classes.

A static nested class is same as any other top-level class and is nested for only
packaging convenience.

Read: Java Nested Classes

Let’s see all the static keyword in java usage in a sample program.

package [Link];

public class StaticExample {

//static block
static{
//can be used to initialize resources when class is loaded
[Link]("StaticExample static block");
//can access only static variables and methods
str="Test";
setCount(2);
}

//multiple static blocks in same class


static{
[Link]("StaticExample static block2");
}

//static variable example

Author:[Link]
private static int count; //kept private to control its value through setter
public static String str;

public int getCount() {


return count;
}

//static method example


public static void setCount(int count) {
if(count > 0)
[Link] = count;
}

//static util method


public static int addInts(int i, int...js){
int sum=i;
for(int x : js) sum+=x;
return sum;
}

//static class example - used for packaging convenience only


public static class MyStaticClass{
public int count;

Let’s see how to use static variable, method and static class in a test program.

package [Link];

public class TestStatic {

public static void main(String[] args) {


[Link](5);

//non-private static variables can be accessed with class name


[Link] = "abc";
StaticExample se = new StaticExample();
[Link]([Link]());
//class and instance static variables are same
[Link]([Link] +" is same as "+[Link]);
[Link]([Link] == [Link]);

//static nested classes are like normal top-level classes


[Link] myStaticClass = new
[Link]();
[Link]=10;

Author:[Link]
[Link] myStaticClass1 = new
[Link]();
[Link]=20;

[Link]([Link]);
[Link]([Link]);
}

Java static import


Normally we access static members using Class reference, from Java 1.5 we can use
java static import to avoid class reference. Below is a simple example of Java static
import.

public class A {

public static int MAX = 1000;

public static void foo(){


[Link]("foo static method");
}
}

package [Link];

import static [Link];


import static [Link];

public class B {

public static void main(String args[]){


[Link](MAX); //normally [Link]
foo(); // normally [Link]()
}
}
Notice the import statements, for static import we have to use import static followed
by the fully classified static member of a class. For importing all the static members of a
class, we can use * as in import static [Link].A.*;. We should use it
only when we are using the static variable of a class multiple times, it’s not good for
readability.

Author:[Link]
Control Statements in Java
Different types of control statements: the decision making statements (if-then, if-then-
else and switch), looping statements (while, do-while and for) and branching statements
(break, continue, return) supported by the Java programming language.

Control Statements:
The control statement are used to controll the flow of execution of the program .
This execution order depends on the supplied data values and the conditional logic.
Java contains the following types of control statements:

1- Selection Statements
2- Repetition Statements
3- Branching Statements

The if-then Statement:

if(conditional_expression){
<statements>;
…;
…;
}

Example 1:

int i=100;
if(i>0)
[Link](“bigger positive number”);

Example 2:

Int age=10;

Author:[Link]
If(age >17){

[Link](“He is minor”);
[Link](“He is Not eligible for license”);
}

The if-then-else Statement:

Syntax:
if(conditional_expression){
<statements>;
…;
…;
}
else{
<statements>;
….;
….;
}

Example:

Int mark=75;

If(mark >35)

Sop(“pass”);

Else

Sop(“fail”);

Switch Statement:
Unlike if-then and if-then-else statements, the switch statement can have a number
of possible execution paths.

switch(control_expression)
{
case expression 1: <statement>;
case expression 2: <statement>;

Author:[Link]


case expression n: <statement>;
default: <statement>;
}
Example:

int month = 8;

String monthString;

switch (month) {

case 1: monthString = "January"; break;

case 2: monthString = " February "; break;

..

default: monthString = "Invalid month"; break;

[Link](monthString);

Using Strings in switch Statements:


In Java SE 7 and later, you can use a String object in the switch statement’s expression.

public class StringSwitchDemo {

public static int getMonthNumber(String month) {

int monthNumber = 0;

switch ([Link]()) {

case "january": monthNumber = 1; break;

Author:[Link]
..

default:

monthNumber = 0;

break;

return monthNumber;

Java for loop(repetition Statements)


Java for loop is used to iterate over a range of values. We can use for loop to iterate over an
array, a list, java set etc

There are three types of for loop in java.

1. General for loop


2. for-each or enhanced for loop
3. Java For loop with label

Let’s look into different type of java for loop example.

Java for loop example


General for loop in java have following form.

for (variable initialization; termination condition; increment/decrement operation)


{
// statements to be executed
}

 “variable initialization” happens only once when for loop begins execution.
 “termination condition” should result in boolean expression, if it returns false then for
loop terminates.
 “increment/decrement” operation is performed after each for loop execution. In most of
the scenarios, it should lead towards the termination condition unless you want for loop to
not terminate at all.

Author:[Link]
 Suppose we want to print integers 5 to 10, in this case we can use basic for loop.

public class JavaForLoop {

public static void main(String[] args) {

//print integers 5 to 10
for (int i=5; i<=10; i++) {
[Link]("Java for loop example - " + i);
}
}

Java for each loop


Java for each loop is also called enhanced for loop. We can use for each loop to iterate
over array or collection elements. Java for each loop is the recommended way wherever
it’s possible to use it. It’s very easy and compact to write.

import [Link];
import [Link];

public class JavaForEachLoopExample {

public static void main(String[] args) {


int[] intArray = { 1, 2, 3, 4, 5 };

for (int i : intArray)


[Link]("Java for each loop with array - " + i);

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


[Link]("Apple");
[Link]("Banana");
[Link]("Orange");

for (String f : fruits)


[Link]("Java for each loop with collection - " + f);
}

Notice from above example is that if there is only one statement in the for loop, then we don’t
need to put them inside curly braces {}.

Author:[Link]
Java for loop with label
We can add a label to for loop, it’s useful with break and continue statements to get out
of outer loop. Note that by default break and continue statements work with inner loop
only. Here is an example of for loop with label and how it’s used with continue
statement.

int[][] intArr = { { 1, -2, 3 }, { 0, 3 }, { 1, 2, 5 }, { 9, 2, 5 } };

process: for (int i = 0; i < [Link]; i++) {


boolean allPositive = true;
for (int j = 0; j < intArr[i].length; j++) {
if (intArr[i][j] < 0) {
allPositive = false;
continue process;
}
}
if (allPositive) {
// process the array
[Link]("Processing " + [Link](intArr[i]));
}
allPositive = true;
}

Example 2:
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = [Link]();
int numPs = 0;

for (int i = 0; i < max; i++) {


// interested only in p's
if ([Link](i) != 'p')
continue;

// process p's
numPs++;
}
[Link]("Found " + numPs + " p's in the string.");

That’s all about java for loop

Java while loop


Java while loop is used to execute a block of statements continuously till the given condition is
true.

Author:[Link]
Java while loop example
Here is a simple java while loop example to print numbers from 5 to 10.

public class JavaWhileLoop {

public static void main(String[] args) {

int i = 5;
while (i <= 10) {
[Link](i);
i++;
}
}
}
Notice that I am increasing value of i inside while loop, otherwise the while loop will
never terminate and we will have an infinite loop. The only way to terminate the program
running in infinite loop is to manually quit it or when the JVM runs out of memory.

Also note that if boolean expression returns false then statements inside while loop
won’t execute. So there is a chance that statement inside while loop will never execute.

Java while loop with Iterator


Java while loop is used a lot with iterator in java. Let’s see a short example of iterating
over an ArrayList using while loop.

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


[Link]("Spinach");
[Link]("Potato");
[Link]("Tomato");

Iterator<String> it = [Link]();

while([Link]()) {
[Link]([Link]());
}

It will print output as below.

Spinach
Potato
Tomato

Author:[Link]
while true java
Sometimes we intentionally want our while loop to run infinitely. In that case we can use
while true loop. An example could be looking for a file at specific location continuously
and if found then process it. Below is a pseudo code example of while true loop in java.

package [Link];

public class WhileTrueJava {

public static void main(String[] args) {


while(true) {
[Link]("Start Processing");
// look for a file at specific directory
// if found then process it, say insert rows into database
[Link]("End Processing");

// wait for 10 seconds and look again


try {
[Link](10*1000);
} catch (InterruptedException e) {
[Link]("Thread Interrupted, exit now");
[Link](0);
}
}
}

}
If we run above program, we will have to manually quit it using Ctrl+C on terminal. If
you are using Eclipse then there is a red button to terminate the current running
program.

But there is another way to achieve this, use a dummy boolean variable and the
compiler error will be gone.

boolean mutex = false;


while(mutex) {
[Link]("incomplete code");
}
That’s all about java while loop

Java do while loop


Java do while loop syntax is as follows:

Author:[Link]
do {
// statements
} while (expression);
The expression for the do-while loop must return a boolean value, otherwise, it will
throw compile time error

Here is a simple java do while loop example to print numbers from 5 to 10.

package [Link];

public class JavaDoWhileLoop {

public static void main(String[] args) {

int i = 5;
do {
[Link](i);
i++;
} while (i <= 10);
}
}

Java break
There are two forms of break statement – unlabeled and labeled.

public class JavaBreak {

public static void main(String[] args) {


String[] arr = { "A", "E", "I", "O", "U" };

// find O in the array using for loop


for (int len = 0; len < [Link]; len++) {
if (arr[len].equals("O")) {
[Link]("Array contains 'O' at index: " + len);
// break the loop as we found what we are looking for
break;
}
}

// use of break in while loop


int len = 0;
while (len < [Link]) {
if (arr[len].equals("E")) {
[Link]("Array contains 'E' at index: " + len);
// break the while loop as we found what we are looking for
break;

Author:[Link]
}
len++;
}

len = 0;
// use of break in do-while loop
do {
if (arr[len].equals("U")) {
[Link]("Array contains 'U' at index: " + len);
// break the while loop as we found what we are looking for
break;
}
len++;
} while (len < [Link]);
}

Array in Java:
Today we will learn how to initialize an array in java. An array in java is a container that
can hold a fixed number of values of the same type. The values can be of the primitive
type like int, short, byte or it can be an object like String, Integer etc.

one – dimensional,
two – dimensional or can say multi – dimensional.

Features of Array

 It is always indexed. Index begins from 0.


 It is a collection of similar data types.
 It occupies a contiguous memory location.

Disadvantage of Array
Size Limit: We can store only fixed size of elements in the array. It doesn’t grow
its size at runtime. To solve this problem, collection framework is used in java.

Initializing an array in java – primitive type


//initialize primitive one dimensional array

Author:[Link]
int[] arrInt = new int[5];

Array Declaration
Syntax :
datatype[] identifier;
or
datatype identifier[];
Both are valid syntax for array declaration. But the former is more readable.
Example :
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr; // two dimensional array.

foreach or enhanced for loop


J2SE 5 introduces special type of for loop called foreach loop to access elements of array. Using
foreach loop you can access complete array sequentially without using index of array. Let us see an
example of foreach loop.
class Test
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40};
for(int x : arr)
{
[Link](x);
}
}
}

Author:[Link]
Initializing an array in java – object type

//initialize Object one dimensional array


String[] strArr; //declaration

strArr = new String[4]; //initialization

Initializing a multidimensional array in java


//initialize multidimensional array
int[][] twoArrInt = new int[4][5];

//multidimensional array initialization with only leftmost dimension


int[][] twoIntArr = new int[2][];
twoIntArr[0] = new int[2];
twoIntArr[1] = new int[3]; //complete initialization is required before we use the array

How to initialize an array in java using shortcut syntax


//array initialization using shortcut syntax
int[] arrI = {1,2,3};
int[][] arrI2 = {{1,2}, {1,2,3}};

If you notice above, the two dimensional array arrI2 is not a symmetric matrix. It’s
because a multidimensional array in java is actually an array of array. For complete
explanation, refer Two Dimensional Array in Java.

Invalid ways to initialize an array in java


Here are some invalid ways to initialize an array.

//invalid because dimension is not provided


int[] a = new int[];

//invalid because leftmost dimension value is not provided


int[][] aa = new int[][5];

Here are some other variations of declaring arrays in java but they are strongly
discouraged to avoid confusion.

Author:[Link]
Example 1:

double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element: myList) {
[Link](element);
}
Example 2:

Passing Arrays to Methods:


printArray(new int[]{3, 1, 2, 6, 4, 2});

public static void printArray(int[] array) {


for (int i = 0; i < [Link]; i++) {
[Link](array[i] + " ");
}
}

Example 3:

Example of Multidimensional java array


Let’s see the simple example to declare, instantiate, initialize and print the
2Dimensional array.

class B{
public static void main(String args[]){

//declaring and initializing 2D array


int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<[Link];i++)
{
for(int j=0;j<arr[i].length;j++)
{
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}

Author:[Link]
Java Array of ArrayList

import [Link];
import [Link];

public class JavaArrayOfArrayList {

public static void main(String[] args) {


List<String> l1 = new ArrayList<>();
[Link]("1");
[Link]("2");

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


[Link]("3");
[Link]("4");
[Link]("5");

List<String>[] arrayOfList = new List[2];


arrayOfList[0] = l1;//here using Array but stored ArrayList
arrayOfList[1] = l2;

for (int i = 0; i < [Link]; i++) {


List<String> l = arrayOfList[i];
[Link](l);
}

Output:

[1,2]

[3,4,5]

Java ArrayList of Array


We can also create an array whose elements are a list. Below is a simple example
showing how to create a list of array elements in java.

Author:[Link]
public class JavaArrayListOfStringArray {

public static void main(String[] args) {

// List of String arrays

List<String[]> list = new ArrayList<String[]>();

String[] arr1 = { "a", "b", "c" };

String[] arr2 = { "1", "2", "3", "4" };

[Link](arr1);

[Link](arr2);

// printing list of String arrays in the ArrayList

for (String[] strArr : list) {

[Link]([Link](strArr));

How to Convert String to Array in Java


Sometimes we have to split String to array based on delimiters or some regular
expression. For example, reading a CSV file line and parsing them to get all the data to
a String array.

package [Link];

import [Link];

import [Link];

public class StringToArrayExample {

Author:[Link]
/**

* This class shows how to convert String to String Array in Java

* @param args

*/

public static void main(String[] args) {

String line = "My name is Rajkumar";

//using String split function

String[] words = [Link](" ");

[Link]([Link](words));

//using [Link] Pattern

Pattern pattern = [Link](" ");

words = [Link](line);

[Link]([Link](words));

Note that Java provides a legacy class StringTokenizer also but you should not use it
because it doesn’t have an option for a regular expression and using it is confusing.

Array Sorting in Java

Sometimes we need to sort array in java, we can use Arrays class to sort the array.
Arrays is a utility class that provides a lot of useful methods to work with arrays in java.

public class JavaArraySort {

public static void main(String[] args) {

int[] intArr = {1, 4, 2, 6, 3};

String[] strArr = {"E", "A", "U","O","I"};

//sort int array

[Link](intArr); //Using Arrays Class

Author:[Link]
[Link](strArr);

[Link]([Link](intArr));

[Link]([Link](strArr));

Java ArrayList to Array:

public class ArrayListToArray {

public static void main(String[] args) {

List<String> strList = new ArrayList<String>();//ArrayList

[Link]("1");

[Link]("2");

[Link]("3");

String[] strArr = null; //String Array Declaration

strArr = [Link](new String[[Link]()]);//convert arrayList to array

[Link]([Link](strArr));

Do It executed :
[Link]

Author:[Link]
Wrapper class in Java
Wrapper class in java are the Object representation of eight primitive types in java. All
the wrapper classes in java are immutable and final.

Java 5 autoboxing and unboxing allows easy conversion between primitive types and
their corresponding wrapper classes in java programs.

Why do we need wrapper classes?


I think it was a smart decision to keep primitive types and Wrapper classes separate to
keep things simple.

We need wrapper classes when we need a type that will fit in the Object-Oriented
Programming like Collection classes. We use primitive types when we want things to be
simple.

o Serialization: We need to convert the objects into streams to perform the


serialization. If we have a primitive value, we can convert it in objects through the
wrapper classes.

o Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

Author:[Link]
short Short

int Integer

long Long

float Float

double Double

Here is a simple program showing different aspects of wrapper classes in java.

[Link]

import [Link];
import [Link];

public class WrapperClasses {

private static void doSomething(Object obj){

public static void main(String args[]){


int i = 10;
char c = 'a';
double dd=3.3;

//primitives are simple to use


int j = i+3;

//polymorphism achieved by Wrapper classes, we can't pass primitive here


doSomething(new Character(c));
List list = new ArrayList();

// List<Integer> list = new ArrayList<Integer>();


//wrapper classes can be used in Collections
Integer in = new Integer(i);
[Link](in);

//autoboxing takes care of primitive to wrapper class conversion


[Link](j);

Author:[Link]
//wrapper classes can be null
in = null;
}
}

Variable Arguments(var-args):
JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in
the method is declared as follows:

typeName... parameterName

In the method declaration, you specify the type followed by an ellipsis (…) Only one variable-length parameter
may be specified in a method, and this parameter must be the last parameter. Any regular parameters must
precede it.

public class VarargsDemo {

public static void main(String args[]) {


// Call method with variable args
printMax(34, 3, 3, 2, 56.5); //
printMax(new double[]{1, 2, 3}); //
}

public static void printMax( double... numbers) {


if ([Link] == 0) {
[Link]("No argument passed");
return;
}

double result = numbers[0];

for (int i = 1; i < [Link]; i++)


if (numbers[i] > result)
result = numbers[i];
[Link]("The max value is " + result);
}
}
output:
The max value is 56.5
The max value is 3.0

Author:[Link]
String a=”10”;
float aa=[Link](a);
String a1=[Link]();

String

parseXXX()
toString()
toString
valueOf()

Primitive
Wrapper object

xxxValue()

valueOf()

primitive into wrapper-Object:

int i=10;

Integer L=new Integer(i);//1 way

Integer l1=new Integer(“10”); //ok but “10.a” not ok

Integer m=new [Link](10); //2

Wrapper-Object To Primitive:

Integer aa=new Integer(12);

Int a=[Link]();

Wrapper-Object To String:

Integer i=new Integer(10);

String s=[Link]();

Author:[Link]
String to Primitive:

Int I =[Link](“10”);

Autoboxing in Java
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.

//Converting int into Integer


int a=20;
Integer i=[Link](a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write [Link](a) internally

Unboxing:
Wrapper type into Primitive data type. It is the reverse process of autoboxing.

//Converting Integer to int


Integer a=new Integer(3);
int i=[Link]();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write [Link]() internally

Java Autoboxing Example


Here is a small java program showing examples of autoboxing and unboxing in java

import [Link];
import [Link];

Author:[Link]
public class AutoboxingUnboxing {

public static void main(String[] args) {


int i = 5;
long j = 105L;

// passed the int, will get converted to Integer object at Runtime using
// autoboxing in java
doSomething(i);

List<Long> list = new ArrayList<>();

// java autoboxing to add primitive type in collection classes


[Link](j);
}

private static void doSomething(Integer in) {


// unboxing in java, at runtime [Link]() is called implicitly to
// return int
int j = in;

// java unboxing, Integer is passed where int is expected


doPrimitive(in);
}

private static void doPrimitive(int i) {

}
}

Call by Value and Call by Reference in Java


There is only call by value in java, not call by reference. If we call a method passing a value,
it is known as call by value. The changes being done in the called method, is not affected in
the calling method.

Author:[Link]
Types of Constructor in Java
There are three types of constructor in java.

1. Default Constructor
2. No-Args constructor
3. Parameterized constructor

Let’s look into all these constructor types with example programs.

Default Constructor in Java


It’s not required to always provide a constructor implementation in the class code. If we
don’t provide a constructor, then java provides default constructor implementation for us
to use. Let’s look at a simple program where default constructor is being used since we
will not explicitly define a constructor.

public class Data {

public static void main(String[] args) {


Data d = new Data();
}
}

1. Default constructor only role is to initialize the object and return it to the calling code.
2. Default constructor is always without argument and provided by java compiler only when
there is no existing constructor defined.
3. Most of the time we are fine with default constructor itself as other properties can be
accessed and initialized through getter setter methods.

Author:[Link]
No-Args Constructor
Constructor without any argument is called no-args constructor. It’s like overriding the
default constructor and used to do some pre-initialization stuffs such as checking
resources, network connections, logging etc. Let’s have a quick look at the no-args
constructor in java.

public class Data {


//no-args constructor
public Data() {
[Link]("No-Args Constructor");
}
public static void main(String[] args) {
Data d = new Data();
}
}
Now when we will call new Data(), then our no-args constructor will
be called. Below
image illustrates this behaviour, check the console output of program.

Parameterized Constructor
Constructor with arguments is called parameterized constructor. Let’s look at the
example of parameterized constructor in java.

public class Data {

private String name;

public Data(String n) {
[Link]("Parameterized Constructor");
[Link] = n;
}

public String getName() {


return name;
}

public static void main(String[] args) {


Data d = new Data("Java");
[Link]([Link]());
}

Author:[Link]
Constructor Overloading in Java
When we have more than one constructors, then it’s constructor overloading in java.
Let’s look at an example of constructor overloading in java program.

public class Data {

private String name;


private int id;

//no-args constructor
public Data() {
[Link] = "Default Name";
}
//one parameter constructor
public Data(String n) {
[Link] = n;
}
//two parameter constructor
public Data(String n, int i) {
[Link] = n;
[Link] = i;
}

public String getName() {


return name;
}

public int getId() {


return id;
}

@Override
public String toString() {
return "ID="+id+", Name="+name;
}
public static void main(String[] args) {
Data d = new Data();
[Link](d);

d = new Data("Java");
[Link](d);

d = new Data("Rajkumar", 25);


[Link](d);

Author:[Link]
Private Constructor in Java
Note that we can’t use abstract, final, static and synchronized keywords with
constructors.

However we can use access modifiers to control the instantiation of class object.
Using publicand default access is still fine, but what is the use of making a
constructor private? In that case any other class won’t be able to create the instance of
the class.

Well, a constructor is made private in case we want to implement singleton design


pattern. Since java automatically provides default constructor, we have to explicitly
create a constructor and keep it private. Client classes are provided with a utility static
method to get the instance of the class. An example of private constructor
for Data class is given below.

// private constructor
private Data() {
//empty constructor for singleton pattern implementation
//can have code to be used inside the getInstance() method of class
}

Constructor Chaining in Java


When a constructor calls another constructor of the same class, it’s called constructor
chaining. We have to use this keyword to call another constructor of the class.
Sometimes it’s used to set some default values of the class variables.

Note that another constructor call should be the first statement in the code block. Also
there should not be a recursive calls that will make infinite loop. Let’s see an example of
constructor chaining in java program.

public class Employee {

private int id;


private String name;

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

Author:[Link]
public String getName() {
return name;
}

public void setName(String name) {


[Link] = name;
}
@Override
public String toString() {
return "ID = "+id+", Name = "+name;
}

public Employee() {
this("John Doe", 999);//call 2 arg constrctors
[Link]("Default Employee Created");
}

public Employee(int i) {
this("John Doe", i);
[Link]("Employee Created with Default Name");
}
public Employee(String s, int i) {
[Link] = i;
[Link] = s;
[Link]("Employee Created");
}

public static void main(String[] args) {

Employee emp = new Employee();


[Link](emp);

Employee emp1 = new Employee(10);


[Link](emp1);

Employee emp2 = new Employee("Pankaj", 20);


[Link](emp2);
}

}
I have overridden the toString() method to print some useful information about
Employee object. Below is the output produced by above program.

Employee Created
Default Employee Created

Author:[Link]
ID = 999, Name = John Doe
Employee Created
Employee Created with Default Name
ID = 10, Name = John Doe
Employee Created
ID = 20, Name = Pankaj
Notice how one constructor is being called from another constructor, that’s called
constructor chaining process.

Java Super Constructor


Sometimes a class is inherited from a super class, in that case if we have to call super
class constructor then we can do it using super keyword. Let’s have a look at an
example of using super class constructor.

Note that super constructor call should be the first statement in the child class
constructor. Also when instantiating child class constructor, java first initializes the super
class and then child class. So if super class constructor is not explicitly called then
default or no-args constructor is called by java runtime. Let’s understand these concepts
through some example program.

Let’s assume we have two classes like below.

package [Link];

public class Person {

private int age;

public Person() {
[Link]("Person Created");
}

public Person(int i) {
[Link] = i;
[Link]("Person Created with Age = " + i);
}

package [Link];

public class Student extends Person {

private String name;

Author:[Link]
public Student() {
[Link]("Student Created");
}

public Student(int i, String n) {


super(i); // super class constructor called
[Link] = n;
[Link]("Student Created with name = " + n);
}

}
Now if we create a Student object like below;

Student st = new Student();


What will be the output produced? The output of above code will be:

Person Created
Student Created
So call went to no-args constructor of Student class, since there was no super call in
first statement the no-args or default constructor of Person class is called. Hence the
output. What if we are using parameterized constructor of Student class as Student st
= new Student(34, "Pankaj");, the output will be:

Person Created with Age = 34


Student Created with name = Pankaj
Here output is clear because we are explicitly calling super class constructor, so java
doesn’t need to do any extra work from their side.

Java Copy Constructor


Java copy constructor takes the object of same class as argument and creates a copy
of it. Sometimes we need a copy of another object to do some processing. We can do
this by following ways:

1. implement cloning
2. providing a utility method for deep copy of the object.
3. Having a copy constructor

Now let’s see how to write a copy constructor. Suppose we have a class Fruits like
below.

Author:[Link]
package [Link];

import [Link];
import [Link];

public class Fruits {

private List<String> fruitsList;

public List<String> getFruitsList() {


return fruitsList;
}

public void setFruitsList(List<String> fruitsList) {


[Link] = fruitsList;
}

public Fruits(List<String> fl) {


[Link] = fl;
}

public Fruits(Fruits fr) {


List<String> fl = new ArrayList<>();
for (String f : [Link]()) {
[Link](f);
}
[Link] = fl;
}
}
Notice thatFruits(Fruits fr) is performing a deep copy to return the copy of the
object. Let’s look at a test program to understand why it’s better to have copy
constructor to copy an object.

package [Link];

import [Link];
import [Link];

public class CopyConstructorTest {

public static void main(String[] args) {


List<String> fl = new ArrayList<>();
[Link]("Mango");
[Link]("Orange");

Fruits fr = new Fruits(fl);

[Link]([Link]());

Fruits frCopy = fr;


[Link]().add("Apple");

Author:[Link]
[Link]([Link]());

frCopy = new Fruits(fr);


[Link]().add("Banana");
[Link]([Link]());
[Link]([Link]());

}
Output of above program is:

[Mango, Orange]
[Mango, Orange, Apple]
[Mango, Orange, Apple]
[Mango, Orange, Apple, Banana]
Notice that when copy constructor is used, both the original object and it’s copy are
unrelated to each other and any modifications in one of them will not reflect into other.

That’s all for constructor in java.

Java Method
Java Method is a collection of statements to process some specific task and return the
response to the caller. Methods allow us to write reusable code and dividing our
program into several small units of work. Java Method promotes clean and more
readable code.

i. 1 Java Method
ii. 2 Java Method Components
iii. 3 Java Method Signature
iv. 4 Calling a Java Method
v. 5 Java Method Examples

Java Method Components


Let’s look at the various components of a java method.

Author:[Link]
1. Access Modifiers: Java Method access modifiers defines who can call the method. It’s
used to restrict the scope of the method. There are four access modifiers in java – private,
protected, public and default. Apart from access modifiers, we can also specify a method
to be static, in that case, we don’t need to create an object to call the method. We can
directly call a static method through class. Static methods are useful for creating utility
methods.
2. Return Type: Java Methods must specify the return type. They can be any primitive type
or an object. If the method is not returning anything, then we must use void as return
type.
3. Method Name: Every method in Java must have a name. It’s used to identify the method.
We should provide descriptive names for our method to give some idea about the task
performed by the method. If you have written any Java program, I am sure you would
have seen java main method.
4. Method Parameters: We can pass parameters to a method, they are defined in the
parenthesis after the method name. Usually, method statements work on these
parameters to achieve their tasks.
5. Exceptions List: Sometimes a java method can throw exceptions. We can define them
using throws keyword. If there are multiple exceptions that can be thrown, then we can
separate them using comma.
6. Method Body: This is where all the method operations take place. Method body contains
statements to be executed by the method and they are inside the curly brackets.

Below image shows the different components of a java main method.

Java Method Signature


Java Method Signature consists of its name and parameter types in the declared order.
In a class, there can be multiple methods but each of them should have a different
signature otherwise it won’t compile. Java Method signature is used by JRE to identify
the exact method to be called when invoked in our program.

public void print(String s) {}


private static int print(String s) {}

If we have above methods in a class, it won’t compile because both the methods have same
signature.

Author:[Link]
public void print(String s, int i) {}
private static void print(int i, String s) {}

Above methods are different because the parameters order are not the same.

Calling a Java Method


Let’s see an example where we will create a main method and call some other method.

public class MathUtils {

public int add (int x, int y) {


return x + y;
}
public static void print(String s) {}

public static void main(String args[]) throws Exception {


MathUtils mu = new MathUtils();
[Link]([Link](5, 2));
[Link]("Static Method");
}

}
When we will run above program, java main method will execute and it will call
MathUtils methods. Notice that if the method is not static, we need an object to call it.
However, if the method is static then we can simply call it using the class name.

Also, notice that println() method is defined in the [Link] object. It’s a
standard java library method where as add() and print() methods in MathUtils class are
called as user defined method.

Java Method Examples


Let’s look at some java method examples.

 Overloaded Methods: If a class have multiple methods with the same name, they are
called as overloaded methods.

public void print(String s) {
[Link](s);
}
public void print(String s, int times) {

Author:[Link]
for (int i=0; i< times; i++) {
[Link](s);
}
}

 Method Throwing Exception: Let's look at an example where we will throw exception.

public int divide(int x, int y) throws IllegalArgumentException {
if(y==0) throw new IllegalArgumentException("Can't divide by 0");
return x/y;
}

 Recursive Method: When a method calls itself, it's called as a recursive method. We
should be very careful in defining recursive method because it can go into infinite look if
there is no terminal condition. Let's look at a method that returns factorial of a number
using recursion.

public static long factorial(long n) {
if (n == 1)
return 1;
else
return (n * factorial(n - 1));
}

 Method Calling Another Method: We can call another method from a method, let's
redefine the above overloaded methods by reusing the print(String s) method.

public void print(String s) {
[Link](s);
}
public void print(String s, int times) {
for (int i=0; i< times; i++) {
print(s);}}

 Java Interface Static Method: Java interfaces can have static method from Java
8 onwards. Here is a small example of the interface static method.

public interface MyData {

static boolean isNull(String str) {


[Link]("Interface Null Check");

return str == null ? true : "".equals(str) ? true : false;


}
}

 Java Interface Default Method: From Java 8 onwards, interfaces can have default
method implementations.

public interface MyData {

Author:[Link]
default void print(String str) {
if (!isNull(str))
[Link]("MyData Print::" + str);
}
}
Read more at Java 8 Interface Changes.

 Java Getter Setter Methods: Java Getter Setter Methods are conventional methods to
access and update an object properties. These methods create abstraction and we can
restrict access to different properties. Most of the IDEs support easy creation of getter-
setter methods of a property.

private String name;

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

 Java Abstract Methods: Java abstract class and interface can declare methods without
its body. The class extending or implementing them have the responsibility to provide
method definition. These methods are declared using abstract keyword in abstract
class. Java interface methods are explicity abstract.

public abstract class Person {
public abstract void work();
}

public interface Shape {


//interface methods are implicitly abstract and public
void draw();

double getArea();
}
That's all for methods in java

Author:[Link]
JAVA Object Oriented (OOPS Concepts):

OOPS Concepts or Object Oriented Programming Concepts are very important. Without
having an idea about OOPS concepts, you will not be able to design systems in the object-
oriented programming model

Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by providing
some concepts:

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by providing
some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Apart from these concepts, there are some other terms which are used in Object-Oriented
design:

o Coupling
o Cohesion
o Association
o Aggregation
o Composition

Java supports the following fundamental concepts


 Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.

Class is logical entity ,contain logic of applications whereas Object is physical


entity, It is create memory for class logic

Author:[Link]
A class can contain following properties:

 Variables
 Methods
 Constructors
 Instance block
 Static block

 Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An
object is an instance of a class.

Object is physical entity, It is create memory for class logic

Difference between object and class


There are many differences between object and class. A list of differences between object
and class are given below:

No. Object Class

1) Object is an instance of a class. Class is a blueprint or


templatefrom which
objects are created.

2) Object is a real world entity such as pen, laptop, Class is a group of


mobile, bed, keyboard, mouse, chair etc. similar objects.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new keyword mainly Class is declared


e.g. using class
Student s1=new Student(); keyword e.g.
class Student{}

Author:[Link]
5) Object is created many times as per requirement. Class is declared once.

6) Object allocates memory when it is created. Class doesn't allocated


memory when it is
reated.

7) There are many ways to create object in java There is only one way to
such as new keyword, newInstance() method, define class in java
factory method and deserialization. using class keyword.

Let's see some real life example of class and object in java to understand the difference
well:

Class: Human Object: Man, Woman

Class: Fruit Object: Apple, Banana, Mango, Guava wtc.

Class: Mobile phone Object: iPhone, Samsung, Moto

Class: Food Object: Pizza, Burger, Samosa

Inheritance
Inheritance is the object oriented programming concept where an object is based on
another object. Inheritance is the mechanism of code reuse. The object that is getting
inherited is called superclass and the object that inherits the superclass is called subclass.

It reduce duplication of code.

It reduce length of the code.

We use extends keyword in java to implement inheritance. Below is a simple example of


inheritance in java.

Author:[Link]
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation
Hiding and security the details

Advanced OOPS:

Coupling
This is advanced concept of OOPS [Link] it can be used structs,spring,webservices.

Loosely coupling : depends on very less.

Tightly coupling : Depends are very high.

Author:[Link]
Ex:
Class A { static int i=B.j;}
Class B { static int j=C.k;}
Class C { static int k() { …}
Suppose we will changed class c all the class should be changed.

[Link]

Cohesion:
Cohesion refers to the level of a component which performs a single well-defined task. A
single well-defined task is done by a highly cohesive method. The weakly cohesive method
will split the task into separate parts. The [Link] package is a highly cohesive package
because it has I/O related classes and interface. However, the [Link] package is a weakly
cohesive package because it has unrelated classes and interfaces.

Ex: db functionality /log fun/business func etc..

Low Cohesion:

TotalServlet

[Link],validation,inbox,error pages all function in single file.

High Cohesion:

[Link] -- [Link]  db function … or validation separate

High cohesion is always very good programme practice.

Enhancement very easy bec everything separate compontes so maintaince also very easy.

Reusability coding is very high.

Association
Association

represents the relationship between the objects. Here, one object can be associated with
one object or many objects. There can be four types of association between the objects:

o One to One
o One to Many

Author:[Link]
o Many to One, and
o Many to Many

Let's understand the relationship with real-time examples. For example, One country can
have one prime minister (one to one), and a prime minister can have many ministers (one
to many). Also, many MP's can have one prime minister (many to one), and many ministers
can have many departments (many to many).

Association can be undirectional or bidirectional.

Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where
one object contains other objects as a part of its state. It represents the weak relationship
between objects. It is also termed as a has-a relationship in Java. Like, inheritance
represents the is-a relationship. It is another way to reuse objects.

Composition
The composition is also a way to achieve (Strong relationship )Association. The composition
represents the relationship where one object contains other objects as a part of its state.
There is a strong relationship between the containing object and the dependent object. It is
the state where containing objects do not have an independent existence. If you delete the
parent object, all the child objects will be deleted automatically.

What is an object in Java

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical (tangible and intangible). The example of an
intangible object is the banking system.

An object has three characteristics:

o State:represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.

Author:[Link]
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is
used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects


are created. So, an object is the instance(result) of a class.
Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class in Java


A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface & abstract class

Java Rules of Object Casting:


When can a certain object be cast into another object when we should follow some rules
and regulation.

Suppose we want to cast d object to A,

A a = (C)d;
So internally 3 rules have been checked by Compiler and JVM. The compiler is checking
first 2 rules at Compile time and JVM will check last one rule at Runtime.

Rule 1 (Compile time checking): check C -> d relation?


Type of 'd' and C must have some relation (child to parent or parent to child or same time).If
there is no relationship then we will get a compile error(inconvertible types).

Author:[Link]
Rule 2 (Compile time checking): check C -> A realtion ?
'C' must be either same type or derived type(subclass) of 'A' otherwise we will get a compile
error(incompatible types).

Rule 3 (Runtime Exception):


Runtime object type of 'd' must be same or derived(subclass) a type of 'C' otherwise we will
get a runtime exception (ClassCastException Exception).
Ex:

String s = new String("hello");


StringBuffer sb = (StringBuffer)s; // Compile error : Invertible types because there is no
relationship between.

Object o = new String("hello");


StringBuffer sb = (String)o;// Compile error : Incompatible types because String is not child
class of StringBuffer.

Object o = new String("hello");


StringBuffer sb = (StringBuffer)o; // Runtime Exception : ClassCastException because 'o' is
string type and trying to cast into StingBuffer and there is no relationship between String
and StringBuffer.

In Java there are two types of reference variable casting:

Upcasting: You can assign a reference variable to a supertype reference variable


explicitly or implicitly. This is an inherently safe operation because the assignment
restricts the access capabilities of the new variable

Cat c = new Cat(); //subclass instance


Animal a = c; //upcasting, it's fine since Cat is also an Animal(super class)

Downcasting: If you have a reference variable that refers to a subtype object, you can
assign it to a reference variable of the subtype. You must make an explicit cast to do
this, and the result is that you can access the subtype's members with this new
reference variable.

Cat c = new Cat();


Animal a = c;
Cat c1 = (Cat) a; //explicit casting, works fine because "c" is actually of type Cat
Note that Compiler won’t complain even if we are doing it wrong, because of explicit
casting. Below are some of the cases where it will throw ClassCastException at runtime.

Dog d = new Dog();//dog not a subclass of animal or any relevant class

Author:[Link]
Animal a = d;
Cat c1 = (Cat) a; //ClassCastException at runtime

Animal a1 = new Animal();


Cat c2 = (Cat) a1; //ClassCastException because a1 is actually of type Animal,can’t cast
parent to child.

Examples: Object

Base 2
Base 1

Der 1 Der 2 Der3 Der4

Base2 b=new Der4();

[Link] o=(Base2) b;
Runtime Der4 is a Child of Base2 so -Correct (b is a Der4)

[Link] o=(Base1) b;
In convertible type error: Der4 ,Base1 –No Realttion

[Link] o=(Der3) b;
RE: ClassCaseError b is base2,
Base2 & Der3 is relating –yes
Der3 child of Object- yes,
b underline object=der4,so der4 & der3 is relation=no.

4.Base2 b=(Base1) b;
Base2 & base1 – no realtion , so convertible error

5.Base1 b=(Der4) b;
Base2 & Der4 relation? Yes,

Base1 & Der4 relation ?No ,so convertible error

6.Base1 b=(Der1) b;
Der4 & Der1 realtion ? no ,compatalbe error

Author:[Link]
Example2:

B is the Chidle of A

C is the child of B

B b=new C(); <> (B)c //child object always accept parent of type

A a=new C(); OR

(A)((B) c) //single line

Parent reference can be used to hold child object but using reference we can’t call child
specific method and we can call only methods avaialbe in parent class.

Author:[Link]
Java Inheritance:
Instance variables are not overridden because they don’t need to be.

Using IS-A and HAS-A

Is-A:

Cat is a Animal.
Ex: Cat extends Animal.

Keep in mind that the inheritance IS-A relationship works in only one direction!
Animal extends Cat -NO

Has-A:

In cat & animal has some relation that all.

Bullet points:

A subclass inherits all public instance variables and methods of the superclass, but
does not inherit the private instance variables and methods of the superclass.

Author:[Link]
Inherited methods can be overridden; instance variables cannot be overridden.

The IS-A relationship works in only one direction. A Hippo is an Animal, but not all
Animals are Hippos.

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.

Author:[Link]
Java Inheritance Example
public class Animal {

private boolean vegetarian;

private String eats;

private int noOfLegs;

public Animal(){}

public Animal(boolean veg, String food, int legs){


[Link] = veg;
[Link] = food;
[Link] = legs;
}

public boolean isVegetarian() {


return vegetarian;
}

public void setVegetarian(boolean vegetarian) {


[Link] = vegetarian;
}

public String getEats() {


return eats;
}

public void setEats(String eats) {


[Link] = eats;
}

public int getNoOfLegs() {


return noOfLegs;
}

public void setNoOfLegs(int noOfLegs) {


[Link] = noOfLegs;
}

The Animal is the base class here. Let’s create a Cat class that inherits from Animal class.
Subclass: Cat

package [Link];

Author:[Link]
public class Cat extends Animal{

private String color;

public Cat(boolean veg, String food, int legs) {


super(veg, food, legs);
[Link]="White";
}

public Cat(boolean veg, String food, int legs, String color){


super(veg, food, legs);
[Link]=color;
}

public String getColor() {


return color;
}

public void setColor(String color) {


[Link] = color;
}

Java Inheritance Test Program

Let’s write a simple test class to create Cat object and use some of its methods.

public class AnimalInheritanceTest {

public static void main(String[] args) {


Cat cat = new Cat(false, "milk", 4, "black");

[Link]("Cat is Vegetarian?" + [Link]());


[Link]("Cat eats " + [Link]());
[Link]("Cat has " + [Link]() + " legs.");
[Link]("Cat color is " + [Link]());
}

Cat class doesn’t have getEats() & getNoOfLegs & isVagetarian methods but still it works
because it’s inherited from Animal class.

Author:[Link]
Java Inheritance Important Points
1. Code reuse is the most important benefit of inheritance because subclasses inherits the
variables and methods of superclass.
2. Private members of superclass are not directly accessible to subclass. As in this example,
Animal variable noOfLegs is not accessible to Cat class but it can be indirectly
accessible via getter and setter methods.
3. Superclass members with default access is accessible to subclass ONLY if they are in
same package.
4. Superclass constructors are not inherited by subclass.(so used super keyword)
5. If superclass doesn’t have default constructor, then subclass also needs to have an
explicit constructor defined. Else it will throw compile time exception. In the subclass
constructor, call to superclass constructor is mandatory in this case and it should be the
first statement in the subclass constructor.
6. Java doesn’t support multiple inheritance,(so that introduced by INTERFACE) a
subclass can extends only one class. Animal class is implicitly extending Object class and
Cat is extending Animal class but due to java inheritance transitive nature, Cat class also
extends Object class.
7. We can create an instance of subclass and then assign it to superclass variable, this is
called upcasting. Below is a simple example of upcasting:
8.
9. Cat c = new Cat(); //subclass instance
10. Animal a = c; //upcasting, it's fine since Cat is also an
Animal
11. When an instance of Superclass is assigned to a Subclass variable, then it’s
called downcasting. We need to explicitly cast this to Subclass. For example;
12.
13. Cat c = new Cat();
14. Animal a = c;
15. Cat c1 = (Cat) a; //explicit casting, works fine because
"c" is actually of type Cat
Note that Compiler won’t complain even if we are doing it wrong, because of
explicit casting. Below are some of the cases where it will
throw ClassCastException at runtime.

Dog d = new Dog();


Animal a = d;
Cat c1 = (Cat) a; //ClassCastException at runtime

Animal a1 = new Animal();


Cat c2 = (Cat) a1; //ClassCastException because a1 is
actually of type Animal at runtime

16. We can override the method of Superclass in the Subclass. However we should always
annotate overridden method with @Override annotation. The compiler will know that we

Author:[Link]
are overriding a method and if something changes in the superclass method, we will get a
compile-time error rather than getting unwanted results at the runtime.
17. We can call the superclass methods and access superclass variables
using super keyword. It comes handy when we have the same name variable/method in
the subclass but we want to access the superclass variable/method. This is also used
when Constructors are defined in the superclass and subclass and we have to explicitly
call the superclass constructor.
18. We can use instanceof instruction to check the inheritance between objects, let’s see
this with below example.
19.
20. Cat c = new Cat();
21. Dog d = new Dog();
22. Animal animal = c;
23.
24. boolean flag = c instanceof Cat; //normal case, returns
true
25.
26. flag = c instanceof Animal; // returns true since c is-an
Animal too
27.
28. flag = animal instanceof Cat; //returns true because
animal is of type Cat at runtime
29.
30. flag = animal instanceof Dog; //returns false for obvious
reasons.
31. We can’t extend Final classes in java.
32. If you are not going to use Superclass in the code i.e your Superclass is just a base to
keep reusable code then you can keep them as Abstract class to avoid unnecessary
instantiation by client classes. It will also restrict the instance creation of base class.

Types of inheritance in java

Note: Multiple inheritance is not supported in Java through class.

Author:[Link]
When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Note: multiple & hybrid not support in java.(NOT SUPPORT)

Single Inheritance Example


File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
Class Cow extends Dog{
Void milk(){[Link](“given milk”);

}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
Cow c=new Cow();
c.
}}

Output:

barking...
eating...

Author:[Link]
 Animal is the superclass of Dog class.
 Animal is the superclass of Cow class.
 Dog and Cow are sub classes of Animal class.

Now if we consider the IS-A relationship we can say:


 Dog IS-A Animal
 Cow IS-A Animal
 Dog IS-A Cow

With use of the extends keyword the subclasses will be able to inherit all the
properties of the superclass except for the private properties of the superclass.

Note: A very important fact to remember is that Java only supports only single inheritance. This means that a
class cannot extend more than one class. Therefore following is illegal:

public class puppy extends Dog, Animal{ // not allowed}

Multilevel Inheritance Example


File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}

Author:[Link]
Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.

Author:[Link]
Since compile-time errors are better than runtime errors, Java renders compile-time error if
you inherit 2 classes. So whether you have same method or different, there will be compile
time error.

class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
[Link]();//Now which msg() method would be invoked?
}
}
Test it Now

Compile Time Error

How to prevent inheritance ?


Declare final that class can’t inheritance in child class.

Public final Class A {}

Class b extends A{} //can’t accessed properties of A [Link] final

How to Parent class variable visible in child class?


Ex1:
Class Parent{
int a=10;
int b=20; }

Class Child extends Parent


{
Int a=100,b=200;
void add(int a,int b)
{
Sysout(a+b);//local
Sysout(this.a+this.b);//instance

Author:[Link]
Sysout(super.a+super.b+a);//super
}

Public static void main(){


// new Child().add(1000,2000);

Child child=new Child();

[Link](102,304);

HAS – A Relationship:
One of the advantages of an Object-Oriented programming language is code
reuse. There are two ways we can do code reuse either by the vimplementation
of inheritance (IS-A relationship), or object composition (HAS-A relationship).
Although the compiler and Java virtual machine (JVM) will do a lot of work for
you when you use inheritance, you can also get at the functionality of inheritance
when you use composition.

Association in java:

Author:[Link]
1. Composition
2. Aggregation

Association refers to the relationship between multiple objects. It refers to how objects are
related to each other and how they are using each other's functionality.

IS-A Relationship:

In object-oriented programming, the concept of IS-A is a totally based on


Inheritance, which can be of two types Class Inheritance or Interface Inheritance.
It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a
Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But
Building is not a House.

It is a key point to note that you can easily identify the IS-A relationship.
Wherever you see an extends keyword or implements keyword in a class
declaration, then this class is said to have IS-A relationship.

HAS-A Relationship:

Composition(HAS-A) simply mean the use of instance variables that are


references to other objects. For example Maruti has Engine, or House has
Bathroom.

Let’s understand these concepts with an example of Car class.

package relationships;
class Car {
// Methods implementation and class/Instance members
private String color;
private int maxSpeed;

Author:[Link]
public void carInfo(){
[Link]("Car Color= "+color + " Max Speed= " +
maxSpeed);
}
public void setColor(String color) {
[Link] = color;
}
public void setMaxSpeed(int maxSpeed) {
[Link] = maxSpeed;
}
}

As shown above, Car class has a couple of instance variable and few methods.
Maruti is a specific type of Car which extends Car class means Maruti IS-A Car.
class Maruti extends Car{

//Maruti extends Car and thus inherits all methods from Car (except final
and static)

//Maruti can also define all its specific functionality

public void MarutiStartDemo(){

//composition has-a strong relationship


Engine MarutiEngine = new Engine();

[Link]();

Maruti class uses Engine object’s start() method via composition. We can say
that Maruti class HAS-A Engine.

package relationships;

public class Engine {

public void start(){

[Link]("Engine Started:");

public void stop(){

Author:[Link]
[Link]("Engine Stopped:");

RelationsDemo class is making object of Maruti class and initialized it. Though
Maruti class does not have setColor(), setMaxSpeed() and carInfo() methods still
we can use it due to IS-A relationship of Maruti class with Car class.

package relationships;

public class RelationsDemo {

public static void main(String[] args) {

Maruti myMaruti = new Maruti();

[Link]("RED");

[Link](180);

[Link]();

[Link]();

f we run RelationsDemo class we can see output like below.

Comparing Composition and Inheritance

 It is easier to change the class implementing composition than inheritance. The change of a
superclass impacts the inheritance hierarchy to subclasses.

Author:[Link]
 You can't add to a subclass a method with the same signature but a different return type as a
method inherited from a superclass. Composition, on the other hand, allows you to change
the interface of a front-end class without affecting back-end classes.

 Composition is dynamic binding (run-time binding) while Inheritance is static binding (compile
time binding)

 It is easier to add new subclasses (inheritance) than it is to add new front-end classes
(composition) because inheritance comes with polymorphism. If you have a bit of code that
relies only on a superclass interface, that code can work with a new subclass without
change. This is not true of composition unless you use composition with interfaces. Used
together, composition and interfaces make a very powerful design tool.

 With both composition and inheritance, changing the implementation (not the interface) of
any class is easy. The ripple effect of implementation changes remains inside the same
class.

o Don't use inheritance just to get code reuse If all you really want is to reuse code
and there is no is-a relationship in sight, use composition.

o Don't use inheritance just to get at polymorphism If all you really want is a
polymorphism, but there is no natural is-a relationship, use composition with
interfaces.

Summary

 IS-A relationship based on Inheritance, which can be of two types Class Inheritance or
Interface Inheritance.

 Has-a relationship is composition relationship which is a productive way of code reuse.

Composition
The composition is the strong Has-A relationship type of association. Same as Employee &
Address,Employee can contain or without contain the Address but without Employee object,
no meaning of Address.

If Employee is destroyed then the Address also be destroyed.

Aggregation

Author:[Link]
Aggregation is a weak Has-A relationship association. An association is said to be
aggregation if both Objects can exist independently. For example, a Team object and a
Player object. The team contains multiple players but a player can exist without a team.

Aggregation in Java
Aggregation is a weak association.

An association is said to be aggregation if both Objects can exist independently. For


example, a Team object and a Player object. The team contains multiple players but a
player can exist without a team.

If a class have an entity reference, it is known as Aggregation. Aggregation represents


HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId
etc. It contains one more object named address, which contains its own informations such
as city, state, country, zipcode etc. as given below.

Sometime we need to define a “whole/part” relationship where one class(whole) consists of


smaller classes (Part). This kind of relationship is called aggregation.

1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }

In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.

Why use Aggregation?


o For Code Reusability.

When use Aggregation?


o Code reuse is also best achieved by aggregation when there is no is-a relationship.

Author:[Link]
o Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation


In this example, Employee has an object of Address, address object contains its own
informations such as city, state, country etc. In such case relationship is Employee HAS-A
address.

[Link]

public class Address {


String city,state,country;

public Address(String city, String state, String country) {


[Link] = city;
[Link] = state;
[Link] = country;
}

[Link]

public class Emp {

int id;
String name;
Address address; //aggregation

public Emp(int id, String name,Address address) {


[Link] = id;
[Link] = name;
[Link]=address;
}

void display(){
[Link](id+" "+name);
[Link]([Link]+" "+[Link]+" "+[Link]);
}

Author:[Link]
public static void main(String[] args) {
Address address1=new Address("gzb","UP","india");
Address address2=new Address("gno","UP","india");

Emp e=new Emp(111,"varun",address1);


Emp e2=new Emp(112,"arun",address2);

[Link]();
[Link]();

}
}
Test it Now

Output:111 varun
gzb UP india
112 arun
gno UP india

Java Polymorphism

Polymorphism is the concept with the help of which single action in different ways can be
performed.

The two types of polymorphism are

compile-time polymorphism(method overloading or EarlyBinding)

run time polymorphism(method overriding or Late binding )

Author:[Link]
How does Polymorphism make working so easy?

different functionalities even when they have a common interface.

Static Binding (Early Binding): When the type of object is determined at compile-time.

Dynamic Binding (Late Binding): When the type of object is determined at run-time.

Consider a real-world scenario for polymorphism. Take an example of a button. We know that by
applying some pressure we can click the button but we do not know the output of pressing the button
or the reference of its use.

What can you do with Polymorphism?

OverRiding:

When child class has the same method as one declared in the parent class, we call it a method
overriding.

* The method must have the same name as one mentioned in the parent class

* The method must also have the same parameter as one mentioned in the parent class.

* There must be the inheritance, that is, the IS-A relationship.

OverLoading:

When a class has multiple methods that have the same name but different parameters, it is referred to
as Method Overloading.

*Changing the number of arguments

*Changing the data type

Author:[Link]
With polymorphism, the reference type can be a superclass of the actual object type.

I declare the method parameter as superclass type,I can Pass in any sub-class object at
runtime.

EX:

test(Animal animal) {}

call test(CAT cat) -- so this valid.. CAT extends Animal

When declare a reference variable,any object that passes [mean no any


relationship parent & child ] ?
No. only association with super class and child class reference type only allowed.

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments


class Adder{
//method hiding
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){

Author:[Link]
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}}

How Runtime Polymorphism works in Java?

functionality of method is dynamically decided in run time as per the object by


JVM.

It is also called “Late binding”, because binding of method and object, which
means the functionality of which object’s method will be displayed, is decided
late i.e. after compilation.

Rules of Runtime Polymorphism


 Methods of child and parent class must have the same name.

 Methods of child and parent class must have the same parameter.

 IS-A relationship is mandatory (inheritance).

Limitations of Runtime Polymorphism

Author:[Link]
 One cannot override private methods of a parent class.

 One cannot override Final methods.

 One cannot override static methods.

code examples of Run time polymorphism.

Simple Runtime poly:

class Parents {

public void showcase () {

[Link]("I am Parent");

class Children extends Parents {

@Override

public void showcase () {

[Link]("I am Children");

public class RunTimePolymorphism {

public static void main(String args[]) {

Parents superObject = new Parents();

[Link](); //method of super class or parent class is called

Parents subObject = new Children(); // upcasting

[Link]();//method of sub class or child class is called by Parent reference, this is

called "Run time Polymorphism"

Children subObject2 = new Children();

[Link](); //method of sub class or child class is called

Author:[Link]
multilevel inheritance:(Over Riding)

class OperatingSytem{

void feature() {

[Link]("This is Operating Sytem");

}}

class DOS extends OperatingSytem{

void feature(){

[Link]("This is DOS");

}}

class Windows extends DOS{

void feature(){

[Link]("This is Windows");

} }

class WindowsMobile extends Windows{

void feature(){

[Link]("This is Windows Mobile");

public class RunTimePolymorphism {

public static void main(String args[]){

OperatingSytem superObject=new OperatingSytem();

OperatingSytem subObject=new DOS(); // child object type : first level of heritance

OperatingSytem sub2Object=new Windows(); // child object type : second level of heritance

OperatingSytem sub3Object=new WindowsMobile(); // child object type : third level of heritance

[Link]();

[Link](); //run time polymorphism happening in first level of heritance

[Link](); //run time polymorphism happening in second level of heritance

[Link](); //run time polymorphism happening in third level of heritance

Author:[Link]
Overrding:
An instance method in a subclass with the same signature (name, plus the number and the
type of its parameters) and return type as an instance method in the
superclass overrides the superclass’s method.

When overriding a method, you might want to use the @Override annotation that instructs
the compiler that you intend to override a method in the superclass. If, for some reason,
the compiler detects that the method does not exist in one of the superclasses, it will
generate an error. For more information on @Override

Class Methods

If a subclass defines a class method with the same signature as a class method in the
superclass, the method in the subclass hides the one in the superclass.

The distinction between hiding and overriding has important implications . The
version of the overridden method that gets invoked is the one in the subclass. The version
of the hidden method that gets invoked depends on whether it is invoked from the
superclass or the subclass. Let’s look at an example that contains two classes. The first is
Animal, which contains one instance method and one class method:

public class Animal {

public static void testClassMethod() {

[Link]("The class" + " method in Animal.");

public void testInstanceMethod() {

[Link]("The instance " + " method in Animal.");

Author:[Link]
The second class, a subclass of Animal, is called Cat:

public class Cat extends Animal {

//hiding both are static

public static void testClassMethod() {

[Link]("The class method" + " in Cat.");

//over riding

public void testInstanceMethod() {

[Link]("The instance method" + " in Cat.");

public static void main(String[] args) {

Cat myCat = new Cat();

Animal myAnimal = myCat;//Animal ref but cat Object

[Link]();//hiding

[Link]();//over riding

The Cat class overrides the instance method in Animal and hides the class method in
Animal. The main method in this class creates an instance of Cat and calls
testClassMethod() on the class and testInstanceMethod() on the instance.

The output from this program is as follows:

output:
The class method in Animal.
The instance method in Cat.

Author:[Link]
As promised, the version of the hidden method that gets invoked is the one in the
superclass, and the version of the overridden method that gets invoked is the one in the
subclass.

Over Riding Rules:


 Method name,argument name must be same and method signature same.
 OR return type must be same but rules applicable 1.4 only but 1.5 co-varient return types are
different.

OverRiding var..arg methods:


We can OR var..arg but it not overriding ,it is called overloading

Ex:

Class P{

public void m1(int ... x) { //var..args method

sop(“parent”);

Class Q extends P {

P v m1(int x) {

sop(“child”);

Class Test{

P s v main(args..){

P p=new p();

p.m1(10);

Q q=new Q();

a.m1(20);

P p1=new Q(); //parent ref.

Author:[Link]
P1.m1(10); //parent

 Private not applicalble for OR


 Parent class private method same as child class no compiler time exception but not prefrebble
 FINAL keyword we can’t override
 Abstract,synchronized is override
 Scope of modifier decreased in parent with child is ok
 Child class throws any checked exception must be same exception or higher can be allowed

OverRiding with Static:


Class P{

Public static void m1() {} //static method

Class c extends P {

Public void m1(); } //not static methids

Not Allowed error coming because

Static method is class level method but non-static method Object level method so class level method
how is allowed override ? so not possible.

But Both are STATIC it no problem it called method Hiding.(not a overriding)

Method hiding OverRiding


Both methods static Both non-static
Compiler based ref Jvm based ref.
Static Poly or Early binding OR Compile time Runtime poly or dynamic poly or late Binding
Polymorphisn is called

Overrding and overloading different:


Property Overloading Overriding
Methods name Must be same Must be same
Argument types Must be diff.(atlease order) Must be same(including order)
Method signature Must be diff Must be same
Return types No rules Must be same until 1.4 version
but 1.5 onward co-var return
alloed

Author:[Link]
Private,static,final methods Can be overloaded Can’t be overloaded
Access modifer First method private ,second Modifier can’t be reduced but
method public no problem we can increade
Throws Class No restriction Parent and child same exception
level.
Method resolution Compiler based Jvm based
It is also known as CTP or Static Poly OR Early bindig RTP or Dynamic OR late binding

Exercices:

Consider the following Methods in Parent Class:

Public void m1(int x) throws IOException


In the child class which of following methods we can take. Say overriding or over loading?

[Link] void m1(int i)

[Link] static int m1(long l)

[Link] static void m1(int i) >

[Link] void m1(int i) throws Exception

5. Public static abstract void m1(double d)

Result:

1) Correct – yes possible OR


2) Not able to OR but Possible OL bec argument diff. and parent is non static and
child is a static
3) Error =bec non-static and static not able to OR
4) Error –bec child is paraent Exception,But parent class ia a child exception not
allowed
5) OL

Did We forget about something when we designed


then what to do?

Author:[Link]
Before we defined in superclass color,size,eat …

Author:[Link]
But that new species what color,size,eat how to handled ?

When come to picture abstract class.

abstract newSpices or Canine extends Animal {

public void eat();

An a bstract class has virtually* no use, no value, no purpose in life, unless it is extended.

Author:[Link]
Java Abstration:
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Author:[Link]
Abstract Class:

abstract keyword is used to create a abstract class and method. Abstract


class in java can’t be instantiated. An abstract class is mostly used to
provide a base for subclasses to extend and implement the abstract methods
and override or use the implemented methods in abstract class

Let’s Study Abstraction concept with an Example


Suppose you want to create a banking application and you are asked to
collect all the information about your customer. There are chances that you
will come up with following information about the customer

But, not all of the above information is required to create a banking


application.

So, you need to select only the useful information for your banking application
from that pool. Data like name, address, tax information, etc. make sense for
a banking application

Author:[Link]
Since we have fetched/removed/selected the customer information from a
larger pool, the process is referred as Abstraction.

However, the same information once extracted can be used for a wide range
of applications. For instance, you can use the same data for hospital
application, job portal application, a Government database, etc. with little or no
modification. Hence, it becomes your Master Data. This is an advantage of
Abstraction.

How to achieve Abstraction?


At a higher level, Abstraction is a process of hiding the implementation details
and showing only functionality to the user. It only indicates important things to
the user and hides the internal details, ie. While sending SMS, you just type
the text and send the message. Here, you do not care about the internal
processing of the message delivery. Abstraction can be achieved using
Abstract Class and Abstract Method in Java.

Abstract Class
A class which is declared “abstract” is called as an abstract class. It can have
abstract methods as well as concrete methods. A normal class cannot have
abstract methods.

Class Test {

Public abstract m1() {} This is totally illegal,not allowed

Abstract Method
A method without a body is known as an Abstract Method. It must be declared
in an abstract class. The abstract method will never be final because the
abstract class must implement all the abstract methods.

abstract class Bike{


abstract void run(); //abstract method

Rules of Abstract Method

Author:[Link]
 Abstract methods do not have an implementation; it only has method
signature
 If a class is using an abstract method they must be declared abstract.
The opposite cannot be true. This means that an abstract class does
not necessarily have an abstract method.
 If a regular class extends an abstract class, then that class must
implement all the abstract methods of the abstract parent

Difference between Abstraction and Encapsulation


Abstraction Encapsulation

Abstraction is about hiding unwanted Encapsulation means hiding the code


details while showing most essential and data into a single unit.
information.

Abstraction hides details at Encapsulation hides details at


the design level. the implementation level.

Ex: Vehicle which can move, you Ex: Encapsulation is all about
don't tell how Vehicle will move, implementation. Its sole purpose is to
whether it will move by using tires or it hide internal working of objects from
will fly or it will water. It just moves.
outside world so that you can change
This is called Abstraction
it later without impacting outside
clients.

For example, we have a HashMap


which allows you to store the object
using put() method and retrieve the
object using the get() method. How
HashMap implements this method
(see here) is an internal detail of
HashMap, the client only cares that

Author:[Link]
put stores the object and get return it
back, they are not concerned whether
HashMap is using an array, how it is
resolving the collision, whether it is
using linked list or binary tree to store
object landing on same bucket etc.

Java 8,
the [Link] changes its
implementation to use a binary tree
instead of LinkedList

Difference between Abstract Class and Interface


Abstract Class Interface

An abstract class can have both The interface can have only abstract
abstract and non-abstract methods. methods.

It does not support multiple It supports multiple inheritances.


inheritances.

It can provide the implementation of It can not provide the implementation


the interface. of the abstract class.

An abstract class can have protected An interface can have only have
and abstract public methods. public abstract methods.

An abstract class can have final, The interface can only have a public
static, or static final variable with any static final variable.
access specifier.

Author:[Link]
Advantages of Abstraction
 The main benefit of using an abstract class is that it allows you to group
several related classes as siblings.

 Abstraction helps to reduce the complexity of the design and


implementation process of software.

When to use Abstract Methods & Abstract Class?


Abstract methods are mostly declared where two or more subclasses are also
doing the same thing in different ways through different implementations. It
also extends the same Abstract class and offers different implementations of
the abstract methods.

Abstract classes help to describe generic types of behaviors and object-


oriented programming class hierarchy. It also describes subclasses to offer
implementation details of the abstract class.

Ex: ATM , infront of ATM machine of some debit,credit ..operation found in screen but inside how is
working everything is hiding the process.

Points to Remember

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Note: implementation must be all methods in abstract class otherwise error occurred.

Example of abstract class

abstract class Bike{


abstract void run();

Author:[Link]
}
class Honda extends Bike
{
void run()
{
[Link]("Honda running safely");
}

}
class Hero extends Bike
{
void run()
{
[Link]("Hero running safely");
}

}
Class TestAbstraction1{
public static void main(String args[]){
Bike obj = new Honda(); //or Hero
[Link]();
} }

Ex 2:

TestBank ….. rateOfInterest various bank ….

Abstract class in Java Important Points


1. abstract keyword is used to create an abstract class in java.
2. Abstract class in java can’t be instantiated.
3. We can use abstract keyword to create an abstract method, an abstract method
doesn’t have body.
4. If a class have abstract methods, then the class should also be abstract using abstract
keyword, else it will not compile.
5. It’s not necessary for an abstract class to have abstract method. We can mark a class
as abstract even if it doesn’t declare any abstract methods.
6. If abstract class doesn’t have any method implementation, its better to use interface
because java doesn’t support multiple class inheritance.
7. The subclass of abstract class in java must implement all the abstract methods unless
the subclass is also an abstract class.
8. All the methods in an interface are implicitly abstract unless the interface methods are
static or default. Static methods and default methods in interfaces are added in Java 8

Author:[Link]
9. Java Abstract class can implement interfaces without even providing the
implementation of interface methods.
10. Java Abstract class is used to provide common method implementation to all the
subclasses or to provide default implementation.
11. We can run abstract class in java like any other class if it has main() method.

Interfaces
just try to imagine how you’d like to solve the problem of modifying some of your Animal
classes to include Pet behaviors.A pets needs methods ike beFriendly() and play(). But don’t
modify existing design.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling
o Suppose we want added easy for Un-related class without affect exiting design .

Real time example of abstract class and interface in java projects. abstract class real
world example. real time example of Interface in java.

Author:[Link]
[Link]
[Link]

interface Vs abstract class in Java.

Interface:

Interface is used when you want to define a contract and you don't know anything about implementation.
(here it is total abstraction as you don't know anything.)

Abstract class:

Abstract class is used when you know something and rely on others for what you don't know.(here it is
partial abstraction as some of the things you know and some you don't know.)
Now, Let's understand above difference between Interface and Abstract class with real world project
example.

When to use Interface


Scenario,
Consider we want to start a service like "[Link]" or "[Link]", where we are responsible for
displaying the flights from various flight service company and place an order from customer.
Lets keep our service as simple as,

1. Displaying flights available from vendors like "airasia", "british airways" and "emirates".
2. Place and order for seat to respective vendor.

How should we design our application considering interfaces and abstract class? In this scenario, interface is
useful or abstract class?

Remember, In this application, we don't own any flight. we are just a middle man/aggregator and our task is to first
enquire "airasia", then enquire "british airways" and at last enquire "emirates" about the list of flights available and
later if customer opts for booking then inform the respective flight vendor to do booking.

For this, first we need to tell "airasia", "british airways" and "emirates" to give us list of flights, internally how they
are giving the list that we don't care.

1. This means I only care for method "getAllAvailableFlights()"

"getAllAvailableFlights()" from "airasia" may have used SOAP service to return list of flights.
"getAllAvailableFlights()" from "british airways" may have used REST service to return list of flights.
"getAllAvailableFlights()" from "emirates" may have used CORBA service to return list of flights.

Author:[Link]
but we don't care how it is internally implemented and what we care is the contract method
"getAllAvailableFlights" that all the flight vendor should provide and return list of flights.

2. Similarly, for booking I only care for method "booking()" that all vendors should have, internally how this
vendors are doing booking that I don't care.

To conclude: We know contract.


So we can say that we know the contract that irrespective of who the Flight vendor is, we need
"getAllAvailableFlights()" and "booking()" method from them to run our aggregator service.

In this situation, Interface is useful because we are not aware of the


implementation of all the 2 methods required, and what we know is the contract
methods that vendor(implementer) should provide. so due to this total
abstraction and for defining the contract, interface is useful in this place.
Technically, we need to design our interface somewhat like below,

[Link](Contract):

interface FlightOpeartions{
void getAllAvailableFlights();
void booking(BookingObject bookingObj);
}

[Link]

class BookingObject{}

Author:[Link]
Important Points about Interface in Java
1. It can’t instantiated so constructors not required.
2. an interface as a 100-percent abstract class.

3. Interface methods must not be static

4. An class can implements one or more other interfaces

Ex: public class Ball implements Bounceable, Serializable, Runnable{..}

5. An abstract class extends interface – yes

6. An interface can itself extend another interface

Interface Moveable {}

Interface Test {}

Ex: public interface Bounceable extends Moveable,Test { }

Author:[Link]
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Author:[Link]
Java Interface Example: Bank
Let's see another example of java interface which provides the implementation of Bank
interface.

File: [Link]

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
Class BankDemo{
Public static void main(String args[]){
Bank sbi=new SBI();
Sysout([Link]());
Bank pnb=new PNB();
Sysout([Link]());

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

Author:[Link]
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){[Link]("Hello");}
9. public void show(){[Link]("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. [Link]();
14. [Link]();
15. }
16. }

Java 8 Default Method & static in Interface


Since Java 8, we can have method body in interface. But we need to make it default
method. Let's see an example:

File: [Link]

interface Drawable{
void draw();

Author:[Link]
default void msg(){[Link]("default method");}
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
[Link]();
[Link]();
1. [Link]([Link](3));

}}

Q) What is marker or tagged interface?


An interface which has no member is known as a marker or tagged interface, for example,
Serializable, Cloneable, Remote, etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.

1. //How Serializable interface is written?


2. public interface Serializable{
3. }

Points to Note:

 Interface achieving help of full abstracton.


 For top level interface only default and public access modifiers are permitted.
 All the variable inside interface are implicity public ,static,final
 All the methods of inside interface are implicity public ,static,final
 The methods of an interface that are implemented by a class must be declared public
 If a class implements an interface but doesn’t implemt all t he methods ofthat interface
than that class must be declared abstract.
 A class can extents only one class but interface extends lot

Author:[Link]
Difference between abstract class and interface in Java

[Link] of new keyword and constructor?

New – just creator of object (empty)

Constructor – initialize of obj (supply input values corresponding fields)

Ex: Student stu=new Student(int rollno,String name);

First new operator create a new object, then value supply to that objects.

[Link] cannot create obj for abstract class but abstract class contain constructor why?

2. whenever we created child class obj,whether automatically paranet obj will be created or
not ?

3. whenever we created child class obj ,what is the need of excuting paraent class
constructor?

Yes both constructor created but first paraent constrvtor initialize values then child class
constructor initialized but finally only one Object created but constructor more time
excectued.

Note: but parent Object won’t be created …this important.

Ex:

Author:[Link]
Person {

Person(int stuId,String stuName) {…}}

Student{

Int age;String addr;

Student(int studId,String stuName,int Age,String addr) {

Super(studId,stuName);

[Link]=age;[Link]=addr;

3A whenever we created child class obj ,when paranet class object automatically created
or not ?

Parent constructor will be executed but not a create separate obj [assume if created
different value send back lot confusing occurred].

[Link] we cannot create obj for abstract class either directly or indirectly ,but abstract
class can contain [Link] is need???

[Link] we cannot create obj for abstract class and [Link] class can contain
construot but interface does not .why?

[Link] interface we can take only abstract [Link] in abstract class also we can take
only abstract methods based on our requirement. Then what is the need of interface? i.e is
is possible to replace interface concopts iwht abstract.

[Link] can replace interface and abstract class but it is not good programming practice (this
is like requesting IAS officer for sweeping activity)

Abstract class X { } interface X {}

Class Test extends X {} class Test implements X {}

While extending X we can’t extend any other class.

While implementing interace we can extend any other class and hence we won’t miss any
inheritance benefit.

In the case Object creation is costly.

Author:[Link]
Test t=new Test(); -> 2 min

In the case Object creation is not Costly

Test t=new Test(); // 2 sec

Hence if evetthing is abstract highly recommended to use interface but not abstract class.

If we are talking about implementation of course partial implemetntation then only we


should go for abstract class.

When to use interface and abstract class in Java

Java 8 interface changes


From Java 8 onwards, we can have method implementations in the interfaces. We can create
default as well as static methods in the interfaces and provide an implementation for them.
This has bridged the gap between abstract classes and interfaces and now interfaces are the way
to go because we can extend it further by providing default implementations for new methods.
For more details, check out Java 8 interface default static methods.

Java Encapsulation:
The concept of encapsulation means to keep implementation(code) and
data(variables) both are safe from misuse by outside entity.

So class will have private instance variable and only the methods within that
class can access those variable.

Achieved through access modifier public,private, protected,default.

Author:[Link]
Learn Encapsulation with an Example
To understand what is encapsulation in detail consider the following bank
account class with deposit and show balance methods

class Account {
private int account_number;
private int account_balance;

public void show Data() {


//code to show data
}

public void deposit(int a) {


if (a < 0) {
//show error
} else
account_balance = account_balance + a;
}
}

Suppose a hacker managed to gain access to the code of your bank account.
Now, he tries to deposit amount -100 into your account by two ways. Let see
his first method or approach.

Approach 1: He tries to deposit an invalid amount (say -100) into your bank
account by manipulating the code.

Now, the question is – Is that possible? Let investigate.

Usually, a variable in a class are set as "private" as shown below. It can only
be accessed with the methods defined in the class. No other class or object
can access them.

Author:[Link]
If a data member is private, it means it can only be accessed within the same
class. No outside class can access private data member or variable of other
class.

So in our case hacker cannot deposit amount -100 to your account.

Approach 2: Hacker's first approach failed to deposit the amount. Next, he


tries to do deposit a amount -100 by using "deposit" method.

But method implementation has a check for negative values. So the second
approach also fails.

Author:[Link]
Thus, you never expose your data to an external party. Which makes your
application secure.

The entire code can be thought of a capsule, and you can only communicate
through the messages. Hence the name encapsulation.

Data Hiding in Java


Frequently, Java encapsulation is referred as data hiding. But more than data
hiding, encapsulation concept is meant for better management or grouping of
related data.

Author:[Link]
To achieve a lesser degree of encapsulation in Java, you can use modifiers
like "protected" or "public". With encapsulation, developers can change one
part of the code easily without affecting other.

Getter and Setter Methods in Java


If a data member is declared "private", then it can only be accessed within the
same class. No outside class can access data member of that class. If you
need to access these variables, you have to use public "getter" and "setter"
methods.

If you make a field public, it means you provide direct access to the caller.
Then, the caller can do anything with your field, either knowingly or
unknowingly.

Getter and Setter's methods are used to create, modify, delete and view the
variables values.

The following code is an example of getter and setter methods:

class Account{
private int account_number;
private int account_balance;
// getter method
public int getBalance() {
return this.account_balance;
}
// setter method
public void setNumber(int num) {
this.account_number = num;
}
}

In above example, getBalance() method is getter method that reads value of


variable account_balance and setNumber() method is setter method that sets
or update value for variable account_number.

Why Getter/Setter method?

By using getter and setter, the programmer can control how his important
variables are accessed and updated in a correct manner, such as changing

Author:[Link]
value of a variable within a specified range. Consider the following code of a
setter method:

// setter method
public void setNumber(int num) {
if (num < 10 || num > 100) {

throw new IllegalArgumentException();


}
this.account_number = num;
}

Advantage of Setter/getter method:-

1. we can achieve Encapsulation.


2. it is called as DTO (Data Transfer Object) design pattern. it is used to transfer data
from one layer to another layer in MVC based applications

Abstraction vs. Encapsulation


Often encapsulation is misunderstood with Abstraction. Lets study-

 Encapsulation is more about "How" to achieve a functionality


 Abstraction is more about "What" a class can do.

A simple example to understand this difference is a mobile phone. Where the


complex logic in the circuit board is encapsulated in a touch screen, and the
interface is provided to abstract it out.

Advantages of Encapsulation in Java


 Encapsulation is binding the data with its related functionalities. Here
functionalities mean "methods" and data means "variables"
 So we keep variable and methods in one place. That place is "class."
Class is the base for encapsulation.
 With Java Encapsulation, you can hide (restrict access) to critical data
members in your code, which improves security

Author:[Link]
 As we discussed earlier, if a data member is declared "private", then it
can only be accessed within the same class. No outside class can
access data member (variable) of other class.
 However, if you need to access these variables, you have to use public
"getter" and "setter"methods.
The encapsulate class is easy to test. So, it is better for unit testing.

Example 2:

File: [Link]

//A Java class which is a fully encapsulated class.


//It has a private data member and getter and setter methods.
package [Link];
public class Student{
private String name;
public String getName(){
return name;
}
public void setName(String name){
[Link]=name
}
}

File: [Link]

1. //A Java class to test the encapsulated class.


package [Link];
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
[Link]("vijay");
//getting value of the name member
[Link]([Link]());
}
}

Output:

vijay

Author:[Link]
Read-Only class
//A Java class which has only getter methods.
public class Student{
//private data member
private String college="AKG";
//getter method for college
public String getCollege(){
return college;
}
}

Now, you can't change the value of the college data member which is "AKG".

[Link]("KITE");//will render compile time error

Write-Only class
//A Java class which has only setter methods.
public class Student{
//private data member
private String college;
//getter method for college
public void setCollege(String college){
[Link]=college;
}
}

Now, you can't get the value of the college, you can only change the value of college data
member.

1. [Link]([Link]());//Compile Time Error, because there is no such method


2. [Link]([Link]);//Compile Time Error, because the college data member is pri
vate.
3. //So, it can't be accessed from outside the class

Annotation:
Java 1.5 introduced annotations and now it’s heavily used in Java EE frameworks like Hibernate, Jersey,
and Spring.

Annotations metadata can be available at runtime too.

Author:[Link]
For example, in Jersey webservice we add PATH annotation with URI string to a method and at runtime,
jersey parses it to determine the method to invoke for given URI pattern.

Built-in annotations in Java


Java Provides five built-in annotations.

1. @Override – When we want to override a method of Superclass, we should use this annotation
to inform compiler that we are overriding a method. So when superclass method is removed or
changed, compiler will show error message. Learn why we should always use java override
annotation while overriding a method.
2. @Deprecated – when we want the compiler to know that a method is deprecated, we should
use this annotation. Java recommends that in javadoc, we should provide information for why this
method is deprecated and what is the alternative to use.
3. @SuppressWarnings – This is just to tell compiler to ignore specific warnings they produce,
for example using raw types in java generics. It’s retention policy is SOURCE and it gets discarded
by compiler.
4. @FunctionalInterface – This annotation was introduced in Java 8 to indicate that the
interface is intended to be a functional interface.
5. @SafeVarargs – A programmer assertion that the body of the annotated method or
constructor does not perform potentially unsafe operations on its varargs parameter.

Constructor in Java
Constructor in java is used to create the instance of the class. Constructors are almost
similar to methods except for two things – it’s name is same as class name and it has
no return type. Sometimes constructors are also referred as special methods to initialize
an object.

Constructor not create intantance of object ,it just initialize of the obeject variables.

1 Constructor in Java
2 Types of Constructor in Java
2.1 Default Constructor in Java
2.2 No-Args Constructor
2.3 Parameterized Constructor
3 Constructor Overloading in Java
4 Private Constructor in Java
5 Constructor Chaining in Java
6 Java Super Constructor

Author:[Link]
7 Java Copy Constructor

Whenever we use new keyword to create an instance of class, constructor is invoked


and object of class is returned. Since constructor can only return object to class, it’s
implicitly done by java runtime and we are not supposed to add return type to it.

If we add return type to a constructor, then it will become a method of class. This is the
way java runtime distinguish between a normal method and a constructor. Let’s assume
we have following code in Employee class.

public Employee() {
[Link]("Employee Constructor");
}

public Employee Employee() {


[Link]("Employee Method");
return new Employee();
}

Here first one is a constructor, notice that there is no return type and no return
statement. Second one is a normal method where we are again calling the first
constructor to get Employee instance and return it. It’s recommended to not have
method name same as class name because it creates confusion.

class Foo2 {
// legal constructors
Foo2() { }
private Foo2(byte b) { }
Foo2(int x) { }
Foo2(int x, int... y) { }

// illegal constructors
void Foo2() { } // it's a method, not a constructor
Foo() { } // not a method or a constructor
Foo2(short s); // looks like an abstract method
static Foo2(float f) { } // can't be static
final Foo2(long x) { } // can't be final
abstract Foo2(char c) { } // can't be abstract
Foo2(int... x, int t) { } // bad var-arg syntax

Author:[Link]
JAVA Advanced:

Java Serialization

Exception Handling:

Java JDBC:

Java Collections

Java MultiThreading

I/o

Java Date:

Reflection

Interview Questions:

Author:[Link]
Exception Handling in Java
Exception is an error event that can happen during the execution of a program and disrupts
its normal flow. Java provides a robust and object oriented way to handle exception
scenarios, known as Java Exception Handling.

Note that Java Exception handling is a framework that is used to handle runtime
errors only, compile time errors are not handled by exception handling in java.
Overview:

What is Exception in Java


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime. An exception is an unwanted or unexpected event, which
occurs during the execution of a program i.e at run time, that disrupts the normal flow of
the program’s instructions.

Exception handling doesn’t mean repairing exception .we have provide alternative way to continue rest
of code normal flow .This is concept of exception handling.

Why Exception Handling?

A Java Exception is an object that describes the exception that occurs in a program. When an
exceptional events occurs in java, an exception is said to be thrown. The code that's responsible for
doing something about the exception is called an exception handler.

Graceful Termination of programme, graceful means we should not missing anything .

Author:[Link]
Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed. That
is why we use exception handling in Java.

Exception class Hierarchy


All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.
Error: An Error indicates serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to catch

Author:[Link]
Author:[Link]
 Exception class is for exceptional conditions that program should catch. This class is extended to
create user specific exception classes.
 RuntimeException is a subclass of Exception. Exceptions under this class are automatically
defined for programs.
 Exceptions of type Error are used by the Java run-time system to indicate errors having to do
with the run-time environment, itself. Stack overflow is an example of such an error.

List of checked exception

 ClassNotFoundException Class not found.

 CloneNotSupportedException Attempt to clone an object that does not implement theCloneable interface.
 IllegalAccessException Access to a class is denied.

 InstantiationException Attempt to create an object of an abstract class or interface.

 InterruptedException One thread has been interrupted by another thread.

 NoSuchFieldException A requested field does not exist.

 NoSuchMethodException A requested method does not exist.

List of unchecked exception

 ArithmeticException Arithmetic error, such as divide-by-zero. Ex: 100/0

 ArrayIndexOutOfBoundsException Array index is out-of-bounds. A[10] a[11]=200;

 ArrayStoreException Assignment to an array element of an incompatible type. Int a[] a[0]=4.0

 ClassCastException Invalid cast. Student s; m=(Emp) s;

 IllegalArgumentException Illegal argument used to invoke a method. M1(int a) m1(30.0)

 IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.

 IllegalStateException Environment or application is in incorrect state.

 IllegalThreadStateException Requested operation not compatible with current thread state.

 IndexOutOfBoundsException Some type of index is out-of-bounds.

 NegativeArraySizeException Array created with a negative size.

 NullPointerException Invalid use of a null reference. String s=”” l=s,length() …

 NumberFormatException Invalid conversion of a string to a numeric format.

 SecurityException Attempt to violate security.

 StringIndexOutOfBounds Attempt to index outside the bounds of a string.

 UnsupportedOperationException An unsupported operation was encountered.

Author:[Link]
How JVM handled Exception?
Default Exception Handling : Whenever inside a method, if an exception has
occurred, the method creates an Object known as Exception Object and hands it
off to the run-time system(JVM).
The exception object contains name and description of the exception, and current
state of the program where exception has occurred.
Creating the Exception Object and handling it to the run-time system is called
throwing an Exception.
class ThrowsExecp{

public static void main(String args[]){

String str = null;


[Link]([Link]());

}
}

Exception are categorized into 3 category.

 Checked Exception

The exception that can be predicted by the programmer at the compile [Link] : File that
need to be opened is not found. These type of exceptions must be checked at compile time.

 Unchecked Exception

Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are
ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out
of Bound exception. Unchecked exceptions are checked at runtime.

 Error

Author:[Link]
Errors are typically ignored in code because you can rarely do anything about an error. Example
:if stack overflow occurs, an error will arise. This type of error cannot be handled in the code.

DEFAULT EXCETPION or Uncaught Exceptions

 Exceptions in java can arise from different kind of situations such as wrong data
entered by user, hardware failure, network connection failure, Database server down
etc. In this section, we will learn how exceptions are handled in java.

 Java being an object oriented programming language, whenever an error occurs


while executing a statement, creates an exception object and then the normal flow
of the program halts and JREtries to find someone that can handle the raised
exception. The exception object contains a lot of debugging information such as
method hierarchy, line number where the exception occurred, type of exception etc.
When the exception occurs in a method, the process of creating the exception object
and handing it over to runtime environment is called “throwing the exception”.

public class DemoDefaultExceptionHandler {

public static void main(String[] args) {

doStuff();

private static void doStuff() {


doStuffSomething();

private static void doStuffSomething() {


doStuffSomethingExtra();

private static void doStuffSomethingExtra() {

int c=10/0;

Author:[Link]
This will lead to an exception at runtime, hence the Java run-time system will construct an exception
and then throw it. As we don't have any mechanism for handling exception in the above program,
hence the default handler will handle the exception and will print the details of the exception on the
terminal.

How Programmer handles an exception?

Customized Exception Handling : Java exception handling is managed via five

keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program

statements that you think can raise exceptions are contained within a try block. If an

exception occurs within the try block, it is thrown. Your code can catch this exception (using

catch block) and handle it in some rational manner. System-generated exceptions are

automatically thrown by the Java run-time system. To manually throw an exception, use the

keyword throw. Any exception that is thrown out of a method must be specified as such by

a throws clause. Any code that absolutely must be executed after a try block completes is

put in a finally block.

1. try
2. catch
3. throw
4. throws
5. finally

Exception handling is done by transferring the execution of a program to an appropriate exception


handler when exception occurs.

// java program to demonstrate

Author:[Link]
// need of try-catch clause

class GFG {

public static void main (String[] args) {

// array of size 4.

int[] arr = new int[4];

// this statement causes an exception

int i = arr[4];

// the following statement will never execute

[Link]("Hi, I want to execute");

}
Explanation : In the above example an array is defined with size i.e. you can access
elements only from index 0 to 3. But you trying to access the elements at index 4(by
mistake) that’s why it is throwing an [Link] this case, JVM terminates the
program abnormally. The statement [Link](“Hi, I want to execute”); will
never execute. To execute it, we must handled the exception using try-catch. Hence to
continue normal flow of the program, we need try-catch clause.

How to use try-catch clause


try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}

Author:[Link]
// optional
finally {
// block of code to be executed after try block ends
}

Points to remember :
 In a method, there can be more than one statements that might throw exception,
So put all these statements within its own try block and provide separate exception
handler within own catch block for each of them.
 If an exception occurs within the try block, that exception is handled by the
exception handler associated with it. To associate exception handler, we must
put catch block after it. There can be more than one exception handlers.
Each catch block is a exception handler that handles the exception of the type
indicated by its argument. The argument, ExceptionType declares the type of the
exception that it can handle and must be the name of the class that inherits
from Throwable class.
 For each try block there can be zero or more catch blocks, but only one finally
block.
 The finally block is [Link] always gets executed whether an exception occurred
in try block or not . If exception occurs, then it will be executed after try and catch
blocks. And if exception does not occur then it will be executed after
the try block. The finally block in java is used to put important codes such as clean
up code e.g. closing the file or closing the connection.

Author:[Link]
Using try and catch
Try is used to guard a block of code in which exception may occur. This block of code is called
guarded region. A catch statement involves declaring the type of exception you are trying to catch. If
an exception occurs in guarded code, the catch block that follows the try is checked, if the type of
exception that occured is listed in the catch block then the exception is handed over to the catch
block which then handles it.

Example using Try and catch

Author:[Link]
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
[Link]("This line will not be executed");
}
catch(ArithmeticException e)
{
[Link]("Divided by zero");
}
[Link]("After exception is handled");
}
}

Divided by zero

After exception is handled

An exception will thrown by this program as we are trying to divide a number by zero
inside try block. The program control is transferred outside try block. Thus the line "This line will
not be executed" is never parsed by the compiler. The exception thrown is handled in catch block.
Once the exception is handled, the program control is continue with the next line in the program i.e
after catch block. Thus the line "After exception is handled" is printed.

Multiple catch blocks:


A try block can be followed by multiple catch blocks. You can have any number of catch blocks after
a single try [Link] an exception occurs in the guarded code the exception is passed to the first catch
block in the list. If the exception type of exception, matches with the first catch block it gets caught,
if not the exception is passed down to the next catch block. This continue until the exception is
caught or falls through all catches.

Author:[Link]
Example for Multiple Catch blocks
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(ArithmeticException ae)
{
[Link]("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("array index out of bound exception");
}
catch(Exception ex)
{
[Link](“exception occurred”);
}
}
}

divide by zero

Note: Although both ArrayIndexOutOfBoundsException and ArithmeticException occured, but


since first catch is of Arithmetic Exception, It will be caught there and program control will be
continued after the catch block.
Note: At a time, only one exception is processed and only one respective catch block is executed.

Example for Unreachable Catch block


While using multiple catch statements, it is important to remember that sub classes of class
Exception inside catch must come before any of their super classes otherwise it will lead to compile
time error. This is because in Java, if any code is unreachable, then it gives compile time error.

Author:[Link]
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(Exception e) //This block handles all Exception
{
[Link]("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
{
[Link]("array index out of bound exception");
}
}
}

Generic exception

Nested try statement


try statement can be nested inside another block of try. Nested try block is used when a part of a
block may cause one error while entire block may cause another error. In case if inner try block does
not have a catch handler for a particular exception then the outer try catch block is checked for
match.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{

Author:[Link]
int x=arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
[Link]("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("array index out of bound exception");
}
}
}

divide by zero

array index out of bound exception

Important points to Remember

1. If you do not explicitly use the try catch blocks in your program, java will provide a default
exception handler, which will print the exception details on the terminal, whenever exception
occurs.
2. Super class Throwable overrides toString() function, to display error message in form of string.
3. While using multiple catch block, always make sure that sub-classes of Exception class comes
before any of their super classes. Else you will get compile time error.
4. In nested try catch, the inner try block uses its own catch block as well as catch block of the outer
try, if required.
5. Only the object of Throwable class or its subclasses can be thrown.

Author:[Link]
Java Exception Handling Keywords Details:
Java provides specific keywords for exception handling purposes, we will look after them
first and then we will write a simple program showing how to use them for exception
handling.

1. throw – We know that if any exception occurs, an exception object is getting created
and then Java runtime starts processing to handle them. Sometime we might want to
generate exception explicitly in our code, for example in a user authentication
program we should throw exception to client if the password is null. throw keyword is
used to throw exception to the runtime to handle it.

We will throw only exception & error object only not a normal java obj.

Some methods throw exception object (default & userdefined exception


obj) but other method should be catch.

So hand over created exeption object to jvm manually.

2. throws – When we are throwing any exception in a method and not handling it, then
we need to use throws keyword in method signature to let caller program know the
exceptions that might be thrown by the method. The caller method might handle
these exceptions or propagate it to it’s caller method using throws keyword. We can
provide multiple exceptions in the throws clause and it can be used
with main() method also.

To delegate responsibility exception handling to the caller

Example:
Class DemoThrow_Throws{

//2 exception created then throws to calling method

void check_Number(int numer)throws IOException,ArithmeticException


{
if (number>5)
throw new IOException("device error");//checked exception
else {
throw new ArithmeticException("Arithmatic
exception");//checked exception
} }

//This calling method(not handled exeption) just redirect exception obj to another calling
method using throws keyword
void check(int number)throws IOException,ArithmeticException

Author:[Link]
{
check_Number ( number);
}

//This calling method handled exception,using try..catch getting 2 exception objects


void validateNumber(int age)
{
try{
check(age);
}catch(Exception e){
[Link]();

[Link]("exception handled >>"+[Link]());


}
}

public static void main(String args[]) //throws IOException,ArithmeticException


{
DemoThrow_Throws obj=new DemoThrow_Throws ();
obj. validateNumber (6);
[Link]("normal flow...");
}

3. try-catch – We use try-catch block for exception handling in our code. try is the start
of the block and catch is at the end of try block to handle the exceptions. We can have
multiple catch blocks with a try and try-catch block can be nested also. catch block
requires a parameter that should be of type Exception.

To maintain risky code.

4. finally – finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that
will not get closed, so we can use finally block. finally block gets executed always,
whether exception occurred or not.

To maintain Cleanup code

Rules:

 We can’t have catch or finally clause without a try statement.


 A try statement should have either catch block or finally block, it can have both
blocks.
 We can’t write any code between try-catch-finally block.
 We can have multiple catch blocks with a single try statement.
 try-catch blocks can be nested similar to if-else statements.
 We can have only one finally block with a try-catch statement.

 Within the try…catch


Try{
Line1 … //suppose line1 getting error ,remaining line upto 1000 not
executed then running outside block state3.

Author:[Link]
.. ..
Line 1000
} Catch (…){}

Stat3.

 Highly recommended to take separate catch block. Try with multiple catch block
bec we don’t @runtime which exception occurred that time very useful of multiple
catch block.
Try{
}
Catch(ArithmaticExcetpion ex){}
Catch(SQLExcetpion sql){}
Catch(FileNotFoundException fnof){} ….
Catch(Exception ex){} //Mostly last using this

Try..catch…finally

Try{ } catch{} finally{ clean up code };

Exception Handling in Java – Useful Methods


Java Exception and all of it’s subclasses doesn’t provide any specific methods and all of the
methods are defined in the base class Throwable.

Some of the useful methods of Throwable class are;

1. public String getMessage() – This method returns the message String of Throwable
and the message can be provided while creating the exception through it’s constructor.

getMessage=DescriptionName only (division by Zer)

[Link]:

2. public String getLocalizedMessage() – This method is provided so that subclasses can


override it to provide locale specific message to the calling program. Throwable class
implementation of this method simply use getMessage() method to return the
exception message.

Author:[Link]
3. public synchronized Throwable getCause() – This method returns the cause of the
exception or null id the cause is unknown.

4. public String toString() – This method returns the information about Throwable in
String format, the returned String contains the name of Throwable class and localized
message.

toString = ExceptionName+Descrion

Ex: [Link]: / by zero

5. public void printStackTrace() – This method prints the stack trace information to
the standard error stream, this method is overloaded and we can pass PrintStream or
PrintWriter as argument to write the stack trace information to the file or stream.

printStackTrace print=ExceptionName+Desription+StackTraceDetails

[Link]: / by zero
at
[Link](DemoDe
[Link])
at
[Link](DemoDefault
[Link])
at
[Link](DemoDefaultExceptionH
[Link])

at
[Link](DemoDefaultExceptio
[Link])

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:

1. Checked Exception

Author:[Link]
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked


Exceptions
1) Checked Exception

The exception which are checked by compiler for smooth execution of the code are called
checked exception.

In our code, if there is an chance of raising checked exception then compulsory we should
handled either by try ..catch, throws key word. Otherwise we will get compile time error.

Ex: FileNotFoundException, RemoteException , IOException, SQLException etc.

Example of CE:

PrintWriter pw;

try {
pw = new PrintWriter("[Link]"); // may throw exception
[Link]("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {

[Link](e);
}
[Link]("REst of the code......");

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time,

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.

Author:[Link]
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as
follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

1. String s=null;
2. [Link]([Link]());//NullPointerException

3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException. Suppose I have a
string variable that has characters, converting this variable into digit will occur
NumberFormatException.

1. String s="abc";
2. int i=[Link](s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Author:[Link]
Customized Exception:
//it is highly recommed to define customized exception as unchecked that is we
have extends
//runtime exception but not excetpion
class InvalidAgeException extends RuntimeException{

//s means we will define customized error message coming here.


InvalidAgeException(String s) {
super(s);//To make our own message obj to default exception method
so this overriding
//InvalidAgeException >RuntimeException>Exception >
Throwable(stactTrace() method override)
}

public String toString() {


return "Candidate is less than 18 year is not allowed to vote.";
}

class ExceptionHandling2{

void validate(int age) throws InvalidAgeException{


if(age < 18)
throw new InvalidAgeException("invalid candidate not allowed polling");
else
[Link]("welcome to vote");
}

public static void main(String args[]){

ExceptionHandling2 dem0=new ExceptionHandling2();

try{
[Link](9);

}catch(InvalidAgeException ex){
[Link]("Exception occured: "+[Link]());

Author:[Link]
}

[Link]("rest of the code...");


}

Try with Resource Statement


JDK 7 introduces a new version of try statement known as try-with-resources statement. This
feature add another way to exception handling with resources management. It is also referred to
as automatic resource management.
Syntax
try(resource-specification(there can be more than one resource))
{
//use the resource
}catch()
{...}
This try statement contains a parenthesis in which one or more resources is declared. Any object
that implements [Link] or [Link], can be passed as a parameter
to try statement. A resource is an object that is used in program and must be closed after the
program is finished. The try-with-resources statement ensures that each resource is closed at the
end of the statement of the try block. You do not have to explicitly close the resources.

Example without using try with Resource Statement


import [Link].*;
class Test
{
public static void main(String[] args)
{
try{
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br=new BufferedReader(new FileReader("d:\\[Link]"));
while((str=[Link]())!=null)
{
[Link](str);
}

Author:[Link]
[Link](); //closing BufferedReader stream
}catch(IOException ie)
{ [Link]("exception"); }
}
}

Example using try with Resource Statement


import [Link].*;
class Test
{
public static void main(String[] args)
{
try(BufferedReader br=new BufferedReader(new FileReader("d:\\[Link]")))
{
String str;
while((str=[Link]())!=null)
{
[Link](str);
}
}catch(IOException ie)
{ [Link]("exception"); }
}
}
NOTE: In the above example, we do not need to explicitly call close() method to
close BufferedReader stream.

Points to Remember

1. A resource is an object in a program that must be closed after the program has finished.
2. Any object that implements [Link] or [Link] can be passed as a
parameter to try statement.
3. All the resources declared in the try-with-resources statement will be closed automatically when
the try block exits. There is no need to close it explicitly.

Author:[Link]
4. We can write more than one resources in the try statement.
5. In a try-with-resources statement, any catch or finally block is run after the resources declared
have been closed.

Method Overriding with Exception Handling


There are few things to remember when overriding a method with exception handling. If super class
method does not declare any exception, then sub class overriden method cannot declare checked
exception but it can declare unchecked exceptions.

Example of Subclass overriden Method declaring Checked Exception


import [Link].*;
class Super
{
void show() {
[Link]("parent class"); }
}

public class Sub extends Super


{
void show() throws IOException //Compile time error
{ [Link]("parent class"); }

public static void main( String[] args )


{
Super s=new Sub();
[Link]();
}
}
As the method show() doesn't throw any exception while in Super class, hence its overridden version
also cannot throw any checked exception.

Example of Subclass overriden Method declaring Unchecked Exception

Author:[Link]
import [Link].*;
class Super
{
void show(){ [Link]("parent class"); }
}

public class Sub extends Super


{
void show() throws ArrayIndexOutOfBoundsException //Correct
{ [Link]("child class"); }

public static void main(String[] args)


{
Super s=new Sub();
[Link]();
}
}

child class

Because ArrayIndexOutOfBoundsException is an unchecked exception hence,


overrided show()method can throw it.

More about Overriden Methods and Exceptions


If Super class method throws an exception, then Subclass overriden method can throw the same
exception or no exception, but must not throw parent exception of the exception thrown by Super
class method.
It means, if Super class method throws object of NullPointerException class, then Subclass method
can either throw same exception, or can throw no exception, but it can never throw object
of Exception class (parent of NullPointerException class).

Example of Subclass overriden method with same Exception


import [Link].*;
class Super
{

Author:[Link]
void show() throws Exception
{ [Link]("parent class"); }
}

public class Sub extends Super {


void show() throws Exception //Correct
{ [Link]("child class"); }

public static void main(String[] args)


{
try {
Super s=new Sub();
[Link]();
}
catch(Exception e){}
}
}

child class

Example of Subclass overriden method with no Exception


import [Link].*;
class Super
{
void show() throws Exception
{ [Link]("parent class"); }
}

public class Sub extends Super {


void show() //Correct
{ [Link]("child class"); }

public static void main(String[] args)


{
try {

Author:[Link]
Super s=new Sub();
[Link]();
}
catch(Exception e){}
}
}

child class

Example of Subclass overriden method with parent Exception


import [Link].*;
class Super
{
void show() throws ArithmeticException
{ [Link]("parent class"); }
}

public class Sub extends Super {


void show() throws Exception //Cmpile time Error
{ [Link]("child class"); }

public static void main(String[] args)


{
try {
Super s=new Sub();
[Link]();
}
catch(Exception e){}
}
}

10 Important Exception during project development:


[Link] exception

Author:[Link]
[Link] Exception

[Link] developmer

Jvm Exception:

Example:

Sop(10/0) ;AE

Programmetic Exception:

Excplicity reasied via Throw & throws is called programmatic exception.

API developemer:

Throws,String class raised api dev.

Thread t=new Thread();

[Link](5); //ok 1..10 only allowed

[Link](15); IllegalArgument Exception

Who wrote the AE exception? Api developer write inside [Link] file.

Ex:

Class Thread {

setPriority(int newPriority)

{ if(newPriority > MAX_PRIORITY | newPriority < MIN_PRIORITY)

Throw new IllegalArgumentException;


}

So Inside thread API developer Some Exceptions.

[Link]: (unchecked)

Whenever accessed array element out of range when this occurred.

Int [] x=new int[4];

Sop(x[10]); //when this exception occurred.

Author:[Link]
[Link]:

String s=null;

Sop([Link]());

[Link]: (unchecked)

Child obj can be type cast to parent not a problem

Ex 1: Ex:String s=new String(“raj”);

Object 0=(Object)s;

but Parent obj can’t type cast into child.

Ex:2 Object o=new Object();//internally parent obj

String s=(String) o;

So this error occurred.

Ex3: Object o=new String(“raj”); //internally child obj (Str)

String s=(String) o; //no problem (o is child obj )

[Link]();

Recursive method called when this error occurred.

[Link](); (child class of ERROR)

> Java Test

Jvm immediately try to run [Link] when no found when this error
occurred.

[Link]: (subclass of Error)

When executed static block or static variable assignment.

Class Test{

Static int x=10/0; }

Author:[Link]
[Link]:

Refer above.

[Link]:

Int i=[Link](“10”);

Int i=[Link](“ten”);//string not represent number

So this error occurred .

[Link]:

A method has called wrong time or dead state when this error [Link] for
example an thread dead state when don’t call it.

Example

Thread r=new Thread();

[Link]();

[Link]();

above 2 times called ,it is illegal.

10.

Java 1.7 exception upgraded:

Try with resource

Multi-catch-blocks

Try with Resources:

Resources means,

Bufferreader,database connection,network connection,file connector etc.

Until 1.6 version we had follow below:

Connection con=null;

Try{..

Author:[Link]
}finally{ if(con != null ) [Link](); }

What is complexity above code?

Any resources (connection,file reader …) declared it will compulsory closed


finally [Link] should not closed if forget it will problem.

So what is advantage of 1.7 resouce?

What ever resource we will initiazed inside try cat block ,it will automatically
closed.

So finally block not requied in 1.7 onwards.

II) Multi resource also auto closed:

Try(resource1;resource2;resource2)

Ex:

Try(FileWriter fw=new FileWriter(“[Link]”);

FileReader fr=new FileReader(“[Link]”);

{} -> it automatically closed ,not requied finally.

III)

2)MultiCatch handling:

Catch(AE | Null | AIBE) {} //single line of all exception

3)ReThrowingException:

We can used this approach to convert one exception type to another exception
type.

Ex:

Try { sop(10/0); }

Catch(AE e) {

Throw new NullpointerException;

Author:[Link]
Generic :
Generics added type safety to Collection framework. Earlier collections stored Object class
references which meant any collection could store any type of object.
Hence there were chances of storing incompatible types in a collection, which could result in run
time mismatch. Hence Generics was introduced through which you can explicitly state the type of
object being stored.

Generics Type Parameter naming Convention


These helps us as distinguishing between type parameter and normal variable

T – Type
E – Element
K – Key
V - Values
N – Numbers
S,U,V etc.. 2nd,3rd,4th types.

Author:[Link]
Benefits of Generics in Java:
 Stronger type check at compile type
 Casting not required

List items = new ArrayList();


[Link]("chocolates");
String item = (String) [Link](0) //cast required

List<String> items = new ArrayList(); //using generics


[Link]("biscuits");
String item = [Link](0) //no cast required

Further reading below links:


Generics:
[Link]
[Link]
[Link]

Generic in Java is added to provide compile time type-safety of code and removing
risk of ClassCastException at runtime.
Rules and Examples of Generics in Java
Let’s see some rule of using Generics in Java on Collections, Type safe class and type safe
methods with simple examples

Genercs wildCards 3 types:

[Link]
[Link]
[Link] or unbounded wildcards

[Link] : <? Extends Number>


Ex:

Number is superclass of Integer,Double …


private static void uppderBounded() {

Author:[Link]
List<Integer> ints = new ArrayList<>();
[Link](3);[Link](5); [Link](10);
double sum = sum(ints);
[Link]("Sum of ints="+sum);

List<Double> a3 = new ArrayList<>();


[Link](1.0); [Link](23.0); [Link](40.0);
sum(a3);

public static double sum(List<? extends Number> list){


double sum = 0;
for(Number n : list){
sum += [Link]();
}
return sum;
}

[Link] : <? Super Number>


Ex:
ArrayList<Integer> a1 = new ArrayList<>();

[Link](10);[Link](20); [Link](30);
processElements(a1);
--
ArrayList<Double> a2 = new ArrayList<>(); //This is NOT Working same or not a super class
// ArrayList<Number> a2 = new ArrayList<>(); //This working bec Number is superclass of
Integer

//Integer and its superclass will work but lower class not work.
static void processElements(ArrayList<? super Integer> a)
{
for (Object element : a)
{
[Link](element);
}
}

[Link] : <?> unknow types any types.


Ex:
List<Integer> ints1 = new ArrayList<>();
List<Double> ints2 = new ArrayList<>();

[Link](3); [Link](5);

[Link](3.12); [Link](55.123);

printData(ints1);
printData(ints2);

1. unKnown type working with all types


public static void printData(List<?> list){
for(Object obj : list){
[Link](obj + ",");
}

Author:[Link]
[Link]("\n");
}

Generics Class;
Class name<T1,T2, … Tn) {
/*….*/
}
Generics Interface:
Points to Remember:
[Link] type check at compiler time.
[Link] don’t work at primitive type.
3.A generics class inside don’t use static member variable or methods….

Serialization:

Object Serialization is the mechanism of converting object into byteStrem .Whereas


the reverse process of recreating the object from those serialized bytes is known
as De-serialization.

When a serialized object is tranmistted across the network the serialization


mechanism will take into account the different operating system. Thus an object
converted into byte streams in windowos os can be transmitted across the network
and deserialized into object in the unix [Link] is portability.

Saved to a File

Object bytes
Serialization
Stored in DB

Author:[Link]
Transmitted
another Jvm

Introduction to Multithreading
[Link]

Before learning Multithreading in Java let’s see, what is Multitasking?


Multitasking
Running two or more tasks simultaneously is known as multitasking.
Multitasking consists of two types:
1) Process based Multitasking.
2) Thread based Multitasking.
1) Process based Multitasking
Running two or more programs/applications simultaneously on a single machine is called
process based multitasking.

In our day to day life, often we run multiple programs on a computer. Like, we may open Game Application,
Audio Player, etc., at the same time, so that we can listen to music while playing a game. All these processes
execute simultaneously and independently of each other. Therefore it is process based multitasking.

Author:[Link]
 It is used at an Operating System level.
 Process based multitasking is heavy weight because it uses separate address spaces for each process.
 In process based multitasking, due to separate address spaces for each process, context switching (task switching) is
difficult.
2) Thread based Multitasking
Running multiple tasks (parts of the program) simultaneously within the same program
(process) is known as thread based multitasking.

When we open some video player, we can watch the video, listen audio, can change the size of a screen, etc.,
simultaneously. Here video player is one program (application), and it works with video, audio, screen size,
etc. properties simultaneously. These properties are the part of a single program (application) that can run
simultaneously and independently. Therefore it is a thread based multitasking.
Another example of thread based multitasking application is Microsoft Word. While writing in Microsoft
Word, it can print the letters that we press on keyword as well as it can check spelling mistakes and correct
them. These all processes are done simultaneously but are independent of each other, because here each
process is a separate independent thread.
 It is used at the Programming level.
 Process based multitasking is lightweight because it uses same address space for each part of the program.
 As it shares the same space for each part of program context switching is easy.
Now let’s see Java Multithreading in detail.

Author:[Link]
Thread
A thread is a part of the program that can run separately without depending on other parts of the program.
Multithreaded Program
The program which contains two or more threads (part of programs), that can run separately and
simultaneously without depending on each other is called multithreaded program.
Why Multitasking/Multithreading?

Multithreading/Multitasking is mainly used to increase the performance


of application/program/system because it makes all the required processes execute simultaneously instead of
executing them one by one. It helps to keep the idle time of CPU/processor minimum.
For example, if we are working with some text editor, it is impossible for us to feed input from the keyboard to
CPU with the speed which CPU processes. Thus, CPU remains idle for most of the time. Instead of that, we
can use CPU for other work in its idle time, resulting in multiple tasks at the same time. For example, we can

Author:[Link]
download some file and listen to some song simultaneously while working with a text editor.
Hence multithreading/multitasking helps to reduce idle time of CPU and increase the performance of the
system.
OR
Consider that Microsoft Word is not a multithreaded but a single threaded. Therefore it will complete only
one task/process at a time. First, it will take only inputs from the keyboard for each letter. Then it will print
all letters one by one. Then it will check spelling mistakes. Then correct it. Then check grammar mistakes.
Then correct it. Hence it will take a long time to complete all these processes and will become impossible to
work with Microsoft Word. But with multithreading, it does all the process simultaneously, which reduces the
performance time and increase the speed of execution as well as making it possible to work with MS Word
very easily.

Although multithreading is very powerful and important feature to create potent programs and enhance their
speed, it should be used carefully.
Creating too many threads in the program may reduce the speed of a program instead of increasing because
creating more threads will result in more contexts switching, which will spend more and valuable time of CPU
in context switching rather than executing the program.

Author:[Link]
Java – Preemptive & Non Preemptive

Preemptive Multitasking
In preemptive multitasking, the operating system sets a specific/fix time with the technique named time
slicing for each thread or process. That is each thread /process is allowed to execute only for a certain amount
of time fixed by the operating system. When the amount of time assigned to those processes get complete,
operating system stops or suspend that process and allow another process to take over processor for its
execution.

Non-preemptive Multitasking
In non-preemptive multitasking, when a certain thread/process is allowed to execute, it does not allow any
process to execute/take over processor until it gets completed.
In this type, other process gets a chance only when running thread yields (give) control willingly to waiting
processes.

Author:[Link]
Java – Thread Scheduler

Thread scheduler is a part of Java Virtual Machine (JVM). It decides which thread should execute first among
two or more threads that are waiting for execution.
It is decided based on the priorities that are assigned to threads. The thread having highest priority gets a
chance first to execute.
If two or more threads have same priorities, we can’t predict the execution of waiting threads. It is completely
decided by thread scheduler. It depends on the type of algorithm used by thread scheduler.

Java – Thread Life Cycle


Thread started by JVM at the starting of a program is known as main thread or parent thread.
And the threads created by the programmer are called child threads.
Every thread has some different state from the moment of its creation till its death (termination).
This process of getting different states at different situations is called life cycle of the thread.
The life cycle of any thread in Java is as shown below:

Author:[Link]
New/Born Thread
The thread created by a programmer using new operator before invoking the start() method on it is called
new/born thread.
Runnable Thread
Runnable means, capable of running/execution.
After invoking the start() method by a thread and before getting it selected by thread scheduler for execution,
the thread is in a runnable state. At this stage, it is ready to get executed as soon as it gets a chance by thread
scheduler.
Running Thread
When the thread starts its execution after getting it selected by thread scheduler is said to be in running state.

Author:[Link]
Blocked Thread
The blocked state contains sleeping state, waiting state, suspended state, etc.
The thread may enter into any of these states when it is in the blocked state. It depends on the function invoked
by a thread or the condition of the program.
Here the working of a thread is stopped temporarily and not permanently.
Dead Thread
When work of thread gets over, that is when it completes run() method, the thread enters into dead state. That
is JVM terminates the thread.
Here, it may find difficult to understand the complete life cycle of a thread.
But as we will step forward to learn multithreading in detail, it will be understood very easily.

Java – Creating a Thread


In Java, Thread is created by two ways:
1) By extending a Thread class

2) By implementing the Runnable interface

[Link]

Java – Thread Priorities


[Link]

Java – Thread Name


[Link]

Java – Alive:

Author:[Link]
Java – Yield Method
[Link]

Java – join() Method

Java – sleep() Method

Author:[Link]
Java FILE I/O
[Link]

Collection Framework:
Collections Framework..
[Link]

What is a Collection?

Without using the collection concept, you cannot develop any project. Every Java
learner has to learn the collection framework.

Initially, collection framework is simply called [Link] package or Collection API.


Later on, The Sun Microsystem has introduced the collection framework in Java
1.2. It was developed and designed by "Joshua Bloch".

From Java 1.5 onwards, The Sun Microsystem added some more new concepts
called Generics.

A collection is a group of objects. In Java, these objects are called elements of


the collection.

Real-time Examples:
[Link] school time, you put all the important books in the school bag
before going to school. Here Schoolbag is a collection and books are
objects.

2. A classroom is a collection of students. So, the classroom is nothing but


a collection and students are objects.

3. We know that the entire world is the collection of humans, animals, and
different things. The world is a collection and humans, animals and
different things are different objects.

Author:[Link]
Technically, A collection is an object which stores a group of other objects
as a single unit or single entity.

Why need collection framework?


Before collection introduced 1.1 using array,vector,[Link] these 3 classes,there is no common
interface so developer working on coding very difficult. [before it is called Util classes]
Most of the vector methods are final so we can’t extend classes.
So common interface should be need,so introduced Colletion framework since jdk1.2.
 Reduce programming effort: with the reusable and useful data structures and algorithms, the
programmers do not have to re-invent the wheel, thus they can devote their time on developing
application’s business.
 Increase program speed and quality: the concrete collections implemented by Java
Collections Framework are built for high performance and high quality, thus programmers can
take this advantage into their programs.
 Foster software reuse: due to the Java Collections Framework is built into the JDK, code
written using collections framework can be re-used every where among applications, libraries
and APIs. That cuts development cost and increases interoperability among Java programs.

Types of Objects Stored in Collection Object

There are two types of objects that can be stored in a collection or container
object. They are as follows:

1. Homogeneous objects:
Homo means same. Homogeneous objects are a group of multiple objects that
belong to the same class.
For example:
Suppose we have created three objects Student s1, Student s2, and Student s3
of the same class 'Student'. Since these three objects belong to the same class
that's why they are called homogeneous objects.

2. Heterogeneous objects:
Hetero means different. Heterogeneous objects are a group of different objects
that belong to different classes.

Author:[Link]
For example:
Suppose we have created two different objects of different classes such as one
object Student s1 and another one object Employee e1. Here, student and
employee objects together are called a collection of heterogeneous objects.

These objects can also be further divided into two types. They are as follows:

1. Duplicate objects:
The multiple objects of a class that contains the same data are called duplicate
objects.
For example:
Suppose we create two person objects Person p1 and Person p2. Both of these
objects have the same data.
Person p1=new Person( "abc");
Person p2=new Person("abc");

Since the above two objects have the same data "abc" therefore, these are
called duplicate objects.

2. Unique objects:
The multiple objects of a class that contains different data are called unique
objects.
For example
Person p1=new Person("abcd");
Person p2=new Person("abcde");
Unique or duplicate object depends on its internal data.

Author:[Link]
What is need of Collection in Java?
Before going to understand the need for collection in java, first, we understand
different ways to store values in Java application by JVM. There is total of four
ways to store values in Java application by JVM.

1. Using a variable approach:

Suppose you want to store one value in the memory then you will create one
variable and assign a value like this
int x=10;
The purpose of variable x is to store one int value 10. If we want to store two int
values, we will create two variables like
int x=10;
int y=20;
Similarly, for three values, the third variable will be required and so on.

There is no problem to store until the third or fourth value. But if we want to store
5000 values then declaring 5000 variables in a program is the worst kind of
programming practice and it will not be in the readable format.

Thus, the limitations of using the variable approach are as follows:


➲ The limitation of a variable is that it can store only one value at a time.
➲ Readability and reusability of the code will be down.
➲ JVM will take more time for the execution.
Hence, the problem facing with this approach can be overcome by using the
second approach "Class object".

2. Using a class object approach:


Using a class object, we can store multiple "fixed" number of values of different
types.

Author:[Link]
For example, suppose we have created a class named Employee and declare
two variables inside the class.
class Employee {
int eNo;
String eName;
}
If we create an object of Employee class like
Employee e1=new Employee();
So can you think how many values can store in this employee object?

The answer is only two but if you will want to store the third value, it will not
possible. Therefore, this approach is only suitable to store a fixed number of
different values. To overcome this problem, we should use third technique "Array
object".

3. Using an array object approach:


We can store a group of objects into an array. Let's take an example to
understand it.
Suppose we want to store 5000 objects of Student class into an array. For this
purpose, we need to create an array object of Student type like this:
Student[ ] st=new Student[5000];
This array can store 5000 Student objects.

Author:[Link]
The biggest advantage of an array is that we can store a huge number of values
by using a single variable st and retrieve them easily. Array mechanism helps to
improve the readability of the code in java programming but there are several
types of problems and limitations with the array. They are as follows:

1. We can easily store multiple "fixed" numbers of values of homogeneous data


type i.e. Array can store only similar types of data.

Suppose if we create Employee type array object


Employee[ ] emp=new Employee[5000]; // it will hold only employee type
objects.
For example:
emp[0]=new Employee(); // valid.
emp[1]=new Customer(); // invalid because here, we are providing the
customer type object.
We can resolve this problem by using an object array.
Object[ ] ob=new Object[5000];
ob[0]=new Employee(); // valid.
ob[1]=new Customer(); // valid.

2. An array is static in nature. It is fixed in length and size. We cannot change

Author:[Link]
(increase/decrease) the size of the array based on our requirements once they
created. Hence, to use an array, it is compulsory that we should know the size of
an array to store a group of objects in advance which may not be possible
always.

3. We can add elements at the end of an array easily. But, adding and deleting
elements or objects in the middle of array is difficult.

4. We cannot insert elements in some sorting order using array concept because
array does not support any method. We will have to write the sorting code for this
but in the case of collection, ready-made method support is available for sorting
using Tree set.

5. We cannot search a particular element using an array, whether the particular


element is present or not in the array index. For this, we will have to write the
searching code using array but in the case of collection, one readymade method
called contains() method is available.

Due to all these above limitations of array, programmers need a better


mechanism to store a group of objects. So, the alternative option is a collection
object or container object in java.

4. Using a collection object:

By using a collection object, we can store the same or different data without any
size limitation. Thus, technically, we can define the collection as:

A collection in java is a container object that is used for storing multiple


homogeneous and heterogeneous, duplicate and unique elements without any
size limitation

What is Framework in Java?

A framework in java is a set of several classes and interfaces which provide a


ready-made architecture.

Author:[Link]
Using a collection object:
By using a collection object, we can store the same or different data without any
size limitation. Thus, technically, we can define the collection as:

A collection in java is a container object that is used for storing multiple


homogeneous and heterogeneous, duplicate and unique elements without any
size limitation.

What is Framework in Java?

A framework in java is a set of several classes and interfaces which provide a


ready-made architecture.

What is Collections Framework in Java

A Java collections Framework is a sophisticated hierarchy of several predefined


interfaces and implementation classes that can be used to handle a group of
objects as a single entity. It is present in [Link] package. It allows us to store,
retrieve, and update a group of objects.

The java collections framework provides an API to work with data structure such
as lists, trees, sets, and maps. The list of interfaces defined in [Link] package
is shown in the below table:

List of Interfaces defined in [Link] package

Collection List Queue

Comparator ListIterator RandomAccess

Deque Map Set

Enumeration [Link] SortedMap

Author:[Link]
EventListener NavigableMap SortedSet

Formattable NavigableSet

Iterator Observer

The list of important classes present in [Link] package is shown in the below
table:

List of classes defined in [Link] package

AbstractCollection EventObject Random

AbstractList FormattableFlags ResourceBundle

AbstractMap Formatter Scanner

AbstractQueue AbstractSequentialList HashMap

AbstractSet HashSet Stack

ArrayDeque Hashtable StringTokenizer

ArrayList LinkedList Vector

Collections EnumMap EnumSet

Calender LinkedHashMap TreeMap

Difference between Arrays & Collections in Java

Author:[Link]
The difference between arrays and collections are as follows:
1. Arrays are fixed in size but collections are growable in nature. We can
increase or decrease size.

2. Arrays are not recommended to use with respect to memory whereas


collections are recommended to use with respect to memory.

3. Arrays are recommended to use with respect to performance but collections


are not recommended to use with respect to performance.

4. Arrays can store only homogeneous data elements (similar type of data) but
collections can hold both homogeneous and heterogeneous elements.

5. Arrays do not support any method but collections support various kinds of
methods.
6. Arrays can have both hold primitives and object types but collections can hold
only objects but not primitive.

Advantages of Collection Framework in Java

The advantages of the collections framework in java are as follows:


1. The collections framework reduces the development time and the burden of
designers, programmers, and users.

2. Your code is easier to maintain because it provides useful data structure and
interfaces which reduce programming efforts.

3. The size of the container is growable in nature.


4. It implements high-performance of useful data structures and algorithms that
increase the performance.
5. It enables software reuse.

Author:[Link]
Limitations of Collection Framework in Java

There are two limitations to java collection framework. They are as follows:
1. Care must be taken to use the appropriate cast operation.
2. Compile type checking is not possible.

Collection Hierarchy in Java

The hierarchy of the entire collection framework consists of four


core interface such as Collection, List, Set, Map, and two specialized interfaces
named SortedSet and SortedMap for sorting. All the interfaces and classes for
the collection framework are located in [Link] package.

Author:[Link]
e➝ extends, I➝ implements.
Extends: Extends is a keyword that is used for developing inheritance between
two classes and two interfaces.
Implements: Implements is a keyword used for developing inheritance between
class and interface.

Author:[Link]
Collection Interface in Java
➲ The basic interface of the collections framework is the Collection interface
which is the root interface of all collections in the API (Application programming
interface) and placed at the top of the collection hierarchy.

➲ Collection interface extends the Iterable interface. The iterable interface has
only one method called iterator(). The function of the iterator method is to return
the iterator object. Using this iterator object, we can iterate over the elements of
the collection.

➲ List, Queue, and Set have three component which extends the collection
interface. A map is not inherited by the collection interface.

List Interface
➲ This interface represents a collection of elements whose elements are
arranged in sequentially ordered.
➲ List maintains an ordered of elements means the order is retained in which we
add elements, and the same sequence we will get while retrieving elements.

➲ We can insert elements into the list at any location. The list allows storing
duplicate elements in Java.
➲ ArrayList, vector, and LinkedList are three concrete subclasses which
implement list interface.

Set Interface
➲ This interface represents a collection of elements that contains unique
elements. i.e, It is used to store the collection of unique elements.

➲ Set interface does not maintain any order while storing elements and while
retrieving, we may not get the same order as we put elements. All the elements
in a set can be in any order.
➲ Set does not allow any duplicate elements.

➲ HashSet, LinkedHashSet, TreeSet classes implements the set interface and

Author:[Link]
sorted interface extends a set interface.
➲ It can be iterated by using Iterator but cannot be iterated using ListIterator.

SortedSet Interface
➲ This interface extends a set whose iterator transverse its elements according
to their natural ordering.
➲ TreeSet implements the sorted interface.

Queue Interface
➲ A queue is an ordered of the homogeneous group of elements in which new
elements are added at one end(rear) and elements are removed from the other
end(front). Just like a queue in a supermarket or any shop.

➲This interface represents a special type of list whose elements are removed
only from the head.
➲ LinkedList, Priority queue, ArrayQueue, Priority Blocking Queue, and Linked
Blocking Queue are the concrete subclasses which implement the queue
interface.

Deque Interface
➲ A deque (double-ended queue) is a sub-interface of queue interface. It is
usually pronounced "deck".
➲ This interface was added to the collection framework in Java SE 6.

➲ Deque interface extends the queue interface and uses its method to
implement deque. The hierarchy of the deque interface is shown in the below
figure.

Author:[Link]
➲ It is a linear collection of elements in which elements can be inserted and
removed from either end. i.e, it supports insertion and removal at both ends of an
object of a class that implements it.
➲ LinkedList and ArrayDeque classes implement the Deque interface.

Map Interface
➲ Map interface is not inherited by the collection interface. It represents an
object that stores and retrieves elements in the form of a Key/Value pairs and
their location within the Map are determined by a Key. The hierarchy of the map
interface is shown in the below figure.

Author:[Link]
➲ Map uses a hashing technique for storing key-value pairs.
➲ It doesn't allow to store the duplicate keys but duplicate values are allowed.
➲ HashMap, HashTable, LinkedHashMap, TreeMap classes implements a Map
interface.

SortedMap Interface
➲ This interface represents a Map whose elements are stored in their natural
ordering. It extends the Map interface which in turn is implemented by TreeMap
classes.

Methods of Collection Interface in Java

The collection interface consists of a total of fifteen methods, They are as follows:

1. add(): This method is used to add or insert an element in the collection. If the
element is added to the collection, it will return true otherwise false, if the element
is already present and the collection doesn't allow duplicates.

2. addAll(): This method adds a collection of elements to the collection. It returns

Author:[Link]
true if the elements are added otherwise returns false.

3. clear(): Clears/remove all the elements from the collection.

4. contains(): It checks that element is present or not in a collection. That is it is


used to search an element. It returns true if the element is present otherwise
false.

5. containsAll(): This method checks that specified a collection of elements are


present or not. It returns true if the calling collection contains all specified
elements otherwise return false.

6. equals(): It checks for equality with another object.


7. hashcode(): It returns the hash code number for the collection. Its return type
is an integer.
8. isEmpty(): It returns true if a collection is empty.

9. iterator(): It returns an iterator.


10. remove(): It removes a specified element from the collection.
11. removeAll(): It removes all elements from the collection.

12. retainAll(): It is used to remove all elements from the collection except the
specified collection.
13. size(): returns the total number of elements in the collection. Its return type is
an integer.

14. toArray(): It returns the elements of a collection in the form of an array. The
array elements are copies of the collection elements.

15. Object[ ] toArray(): Returns an array that contains all the elements stored in
the invoking collection. The array elements are the copies of the collection
elements.

Collections Class in Java

Author:[Link]
The collections classes implement the collection interfaces. They are defined in
[Link] package. Some of the classes provide full implementations that can be
used as it is. Others are abstract that provides basic implementations that can be
used to create concrete collections. A brief overview of each concrete collection
class is given below.

1. AbstractCollection: It implements most of the collection interface. It is a


superclass for all of the concrete collection classes.

2. AbstractList: It extends AbstractCollection and implements most of the List


interface.

3. AbstractQueue: It extends AbstractCollection and implements the queue


interface.
4. AbstractSequentialList: It extends AbstractList and uses sequential order to
access elements.

5. AbstractSet: Extends AbstractCollection and implements most of the set


interface.
6. ArrayList: It implements a dynamic array by extending AbstractList.

7. EnumSet: Extends AbstractSet for the use with enum elements.


8. HashSet: Extends AbstractSet for use with a hash table.

9. LinkedHashSet: Extends HashSet to allow insertion-order iterations.


10. LinkedList: Implements a linked list by extending AbstractSequentialList.

11. PriorityQueue: Extends AbstractQueue to support a priority based queue.


12. TreeSet: Extends AbstractSet and implements the SortedSet interface.

Different Operation Perform in Collection :

Set,list,Map,Queue perform operation below:

Adding object

Author:[Link]
Counting object

Searching object

Retrieving object

Removing object

List operation below :

Replacing object

Inserting object

Terminlogies used in Collection Programming:

[Link]

[Link] -> key,value combination

[Link] objects > same class objcts (take 2 employee class or take 2 Integer class)

[Link] objects > Different class objects

[Link] obj> 2 objs same class with different ref and diff. data

[Link] obj > 2 objs same class[ with same ref./data]

Ex: Student s1=new Student();

Student s2=new Student();

1. s1 & s2 same data = homogeneous duplicate obj

2. s1 & s2 with diff data =homogeneous unique obj.

3. Student & Employee both are totally diff [Link] it called Hetrogenours

[Link] of objects

[Link] of collections

[Link] of maps

Author:[Link]
10. default/initial Capacity: total no of objects will be store in collection. (Declare size )

[Link] : object stored in collection.

12. Load factory =measurement specifiy

Collections and Autoboxing


We have studied that Autoboxing converts primitive types into Wrapper class
Objects. As collections doesn't store primitive data types(stores only refrences), hence Autoboxing
facilitates the storing of primitive data types in collection by boxing it into its wrapper type.

Most Commonly thrown Exceptions in Collections Framework

Exception Name Description

UnSupportedOperationException occurs if a Collection cannot be modified

ClassCastException occurs when one object is incompatible with another

NullPointerException occurs when you try to store null object in Collection

IllegalArgumentException thrown if an invalid argument is used

IllegalStateException thrown if you try to add an element to an already full Collection

Interfaces of Collection Framework


The Collections framework has a lot of Interfaces, setting the fundamental nature of various
collection classes. Lets study the most important Interfaces in the Collections framework.

Collection Collections

Author:[Link]
Colletion is interface which can be Collections is an utility methods present [Link] to
used to represent a group of individual define several utility methods (like sorting,searching…).
obj as single entity.
Example : ArrayList not able to sort the element. When
Collections objects helpful to collection.

ArrayList al=new ArrayList();

[Link](al);

Collections class declaration


Let's see the declaration for [Link] class.

1. public class Collections extends Object

SN Modifier & Type Methods Descriptions

1) static <T> Boolean addAll() It is used to adds all of


the specified elements to
the specified collection.

3) static <T> int binarySearch() It searches the list for the


specified object and
returns their position in a
sorted list.

13) static <T> void copy() It is used to copy all the


elements from one list
into another list.

Author:[Link]
14) static Boolean disjoint() It returns true if the two
specified collections have
no elements in common.

15) static <T> emptyEnumeration() It is used to get an


Enumeration<T> enumeration that has no
elements.

16) static <T> emptyIterator() It is used to get an


Iterator<T> Iterator that has no
elements.

17) static <T> List<T> emptyList() It is used to get a List


that has no elements.

31) static <T extends max() It is used to get the


Object & maximum value of the
Comparable<? given collection, according
super T>> T to the natural ordering of
its elements.

32) static <T extends min() It is used to get the


Object & minimum value of the
Comparable<? given collection, according
super T>> T to the natural ordering of
its elements.

35) static <T> Boolean replaceAll() It is used to replace all


occurrences of one
specified value in a list
with the other specified
value.

Author:[Link]
36) static void reverse() It is used to reverse the
order of the elements in
the specified list.

37) static <T> reverseOrder() It is used to get the


Comparator<T> comparator that imposes
the reverse of the natural
ordering on a collection of
objects which implement
the Comparable interface.

38) static void rotate() It is used to rotate the


elements in the specified
list by a given distance.

39) static void shuffle() It is used to randomly


reorders the specified list
elements using a default
randomness.

43) static <T extends sort() It is used to sort the


Comparable<? elements presents in the
super T>>void specified list of collection
in ascending order.

44) static void swap() It is used to swap the


elements at the specified
positions in the specified
list.

45) static <T> synchronizedCollection() It is used to get a


Collection<T> synchronized (thread-
safe) collection backed by
the specified collection.

Author:[Link]
List<String> list = new ArrayList<String>();
[Link]("C");
[Link]("Core Java");
[Link]("Advance Java");
[Link]("Initial collection value:"+list);
[Link](list, "Servlet","JSP");
[Link]("After adding elements collection value:"+list);
String[] strArr = {"C#", ".Net"};
[Link](list, strArr);
[Link]("After adding array collection value:"+list);

SORT:

[Link](al);
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());

The Collection Interface

1. It is at the top of collection heirarchy and must be implemented by any class that defines a
collection. Its general declaration is,

interface Collection < E >

2. Following are some of the commonly used methods in this interface.

Methods Description

boolean add( E obj ) Used to add objects to a collection. Returns true if obj was
added to the collection. Returns false if obj is already a

Author:[Link]
member of the collection, or if the collection does not allow
duplicates.

boolean addAll( Collection C ) Add all elements of collection C to the invoking collection.
Returns true if the element were added. Otherwise, returns
false.

boolean remove( Object obj ) To remove an object from collection. Returns true if the
element was removed. Otherwise, returns false.

boolean removeAll( Collection C ) Removes all element of collection C from the invoking
collection. Returns true if the collection's elements were
removed. Otherwise, returns false.

boolean contains( Object obj ) To determine whether an object is present in collection or


not. Returns true if obj is an element of the invoking
collection. Otherwise, returns false.

boolean isEmpty() Returns true if collection is empty, else returns false.

int size() Returns number of elements present in collection.

void clear() Removes total number of elements from the collection.

Object[] toArray() Returns an array which consists of the invoking collection


elements.

boolean retainAll(Collection c) Deletes all the elements of invoking collection except the
specified collection.

Iterator iterator( ) Returns an iterator for the invoking collection.

Author:[Link]
boolean equals(Object obj) Returns true if the invoking collection and obj are equal.
Otherwise, returns false.

Object[] toArray(Object array[]) Returns an array containing only those collection elements
whose type matches of the specified array.

The List Interface


LinkedList,ArrayList -Not threadsafe
Vector,CopyOnWriteArrayList -ThreadSafe

1. It extends the Collection Interface, and defines storage as sequence of elements. Following is its
general declaration,

interface List < E >

2. Allows random access and insertion, based on position.


3. It allows Duplicate elements.
4. It maintain Order of the elements.
5. Apart from methods of Collection Interface, it adds following methods of its own.

By following this tutorial (updated and revised for Java 10) to the end, you will be able to master the
List collection in Java.
Table of content:

1. Overview of List collection


2. Creating a new list
3. Basic List operations
4. Iterating over elements in a list
5. Searching for an element in a list
6. Sorting a list
7. Copying elements from one list into another
8. Shuffling elements in a list
9. Reversing elements in a list
10. Extracting a portion of a list

Author:[Link]
11. Converting between Lists and arrays
12. List to Stream
13. Concurrent lists

[Link]

Why insertion and deletion in AL is slower compared to LL ? OR when used LL?

AL internally uses an array to store elements,when that array gets filled by inserting elements a new
array of roughly 1.5 times the size of the original array is crated and all the data of old array is copied to
new array.

Lot of shifting operation happened in Arraylist during beyond exceed reached( initial capacity ) all the
array element shifted new location .

Array Vs ArrayList

Fixed size Growable nature depending upon our requirement

Only homogenous Homogenous & heterogenous

Primitive ,object Objects only

AL vs CopyonWriteArrayList:

ArrayList CopyonWriteArrayList

Not thread safe. Thread SAfe

Iterator will not reflect add,delete operation Here possible.


during iteatring AL elements

Author:[Link]
Null not permitted Null permitted

ArrayList Vector

Non-synchronized Synchronized

50% increment size 100% increament

Enumeration Iterator

You can’t any modification while traversing Remove element only traversing

hasMoreElements(),nextElement() hasNext(),next(),remove()

Introduced jdk1.0 Introduced jdk2.0 onwards

Iterator List Iterator

Remove operation only allowed Remove,add,replace allowed

Iterator() methods is avail for all collections. Avail list interface .

The Set Interface


[Link]

Author:[Link]
Set < (extend) SortedSet <TreeSet
Set < HashSet <-(extend) LinkedHashSet
Set < EnumSet
Set <CopyonWriteArraySet

1. This interface defines a Set. It extends Collection interface and doesn't allow insertion of
duplicate elements. It's general declaration is,

interface Set < E >

2. It doen’t allow duplicate elements.


3. It doesn't define any method of its own. It has two sub interfaces, SortedSet and NavigableSet.
4. SortedSet interface extends Set interface and arranges added elements in an ascending order.
5. NavigabeSet interface extends SortedSet interface, and allows retrieval of elements based on
the closest match to a given value or values.

Characteristics of a Set collection:


The following characteristics differentiate a Set collection from others in the Java Collections
framework:

 Duplicate elements are not allowed.


 Elements are not stored in order. That means you cannot expect elements sorted in any order
when iterating over elements of a Set.

2. Set Implementations

The Java Collections Framework provides three major implementations of

the Set interface: HashSet, LinkedHashSetand TreeSet.

 HashSet: no duplication and unordered.


 LinkedHashSet: This implementation orders its elements based on insertion order. So consider
using a LinkedHashSet when you want to store unique elements in order.
 TreeSet: This implementation orders its elements based on their values, either by their natural
ordering, or by a Comparator provided at creation time.

Author:[Link]
The Queue Interface

BlockingQueue(interface):wait & run machanism

Implments
synchronousQueue,ArrayBlockingQueue,LinkedBlockQueue,PriorityBlockingQueue,DelayQueu

1. It extends collection interface and defines behaviour of queue, that is first-in, first-out. It's
general declaration is,

interface Queue < E >

2. There are couple of new and interesting methods added by this interface. Some of them are
mentioned in below table.

Methods Description

Object poll() removes element at the head of the queue and returns null if queue
is empty

Object remove() removes element at the head of the queue and


throws NoSuchElementException if queue is empty

Object peek() returns the element at the head of the queue without removing it.
Returns null if queue is empty

Object element() same as peek(), but throws NoSuchElementException if queue is


empty

boolean offer( E obj ) Adds object to queue.

Author:[Link]
The Dequeue Interface

1. It extends Queue interface and implements behaviour of a double-ended queue. Its general
declaration is,

interface Dequeue < E >

2. Since it implements Queue interface, it has the same methods as mentioned there.
3. Double ended queues can function as simple queues as well as like standard Stacks.

Map:

HashMap < linkedHashMap

WeakHashMap

EnumMap

HashTable -ThreadSafe

Map <SortedMap <ConcurrentMap <ConcurrentHashMap

TreeMap

ArrayList:

Arralylist implement of the List interface.

If initialize capacity not provided ,it automatically provice size=10.

If element removal of the AL,that space will be accomediate shift process this
drawback of array.

Author:[Link]
Ex: Constructor:

List<Integer> intArrayList1= new ArrayList<>();

List<Integer> intArrayList2= new ArrayList<>(8);

List<Integer> intArrayList3= new ArrayList<>( intArrayList2);

LikedList:

Linkedlist connects with other nodes through next and previous ref. so it is called
doubled linked list.

So it is became fast as delete operation.

[Link](1); …

Author:[Link]
Advanced Topics:

Author:[Link]
Introduction to JDBC
Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to
connect Java application with Database. JDBC is used to interact with various type of Database such
as Oracle, MS Access, My SQL and SQL Server. JDBC can also be defined as the platform-
independent interface between a relational database and Java programming. It allows java program to
execute SQL statement and retrieve result from database.

Author:[Link]
What's new in JDBC 4.0
JDBC 4.0 is new and advance specification of JDBC. It provides the following advance features

 Connection Management
 Auto loading of Driver Interface.
 Better exception handling
 Support for large object
 Annotation in SQL query.

JDBC Driver

Author:[Link]
JDBC Driver is required to process SQL requests and generate result. The following are the different
types of driver available in JDBC.

 Type-1 Driver or JDBC-ODBC bridge


 Type-2 Driver or Native API Partly Java Driver
 Type-3 Driver or Network Protocol Driver
 Type-4 Driver or Thin Driver

JDBC-ODBC bridge
Type-1 Driver act as a bridge between JDBC and other database connectivity mechanism(ODBC).
This driver converts JDBC calls into ODBC calls and redirects the request to the ODBC driver.

Advantage

 Easy to use
 Allow easy connectivity to all database supported by the ODBC Driver.

Disadvantage

 Slow execution time


 Dependent on ODBC Driver.
 Uses Java Native Interface(JNI) to make ODBC call.

Author:[Link]
Native API Driver
This type of driver make use of Java Native Interface(JNI) call on database specific native client API.
These native client API are usually written in C and C++.

Advantage

 faster as compared to Type-1 Driver


 Contains additional features.

Disadvantage

 Requires native library


 Increased cost of Application

Network Protocol Driver


This driver translate the JDBC calls into a database server independent and Middleware server-
specific calls. Middleware server further translate JDBC calls into database specific calls.

Author:[Link]
Advantage

 Does not require any native library to be installed.


 Database Independency.
 Provide facility to switch over from one database to another database.

Disadvantage

 Slow due to increase number of network call.

Thin Driver
This is Driver called Pure Java Driver because. This driver interact directly with database. It does not
require any native database library, that is why it is also known as Thin Driver.

Author:[Link]
Advantage

 Does not require any native library.


 Does not require any Middleware server.
 Better Performance than other driver.

Disadvantage

 Slow due to increase number of network call.

JDBC 4.0 API


JDBC 4.0 API is mainly divided into two package

1. [Link]
2. [Link]

[Link] package
This package include classes and interface to perform almost all JDBC operation such as creating and
executing SQL Queries.

Author:[Link]
Important classes and interface of [Link] package

classes/interface Description

[Link] Provide support for BLOB(Binary Large Object) SQL type.

[Link] creates a connection with specific database

[Link] Execute stored procedures

[Link] Provide support for CLOB(Character Large Object) SQL type.

[Link] Provide support for Date SQL type.

[Link] create an instance of a driver with the DriverManager.

[Link] This class manages database drivers.

[Link] Used to create and execute parameterized query.

[Link] It is an interface that provide methods to access the result row-by-row.

[Link] Specify savepoint in transaction.

[Link] Encapsulate all JDBC related exception.

[Link] This interface is used to execute SQL statements.

Author:[Link]
[Link] package
This package is also known as JDBC extension API. It provides classes and interface to access
server-side data.

Important classes and interface of [Link] package

classes/interface Description

[Link] Provide information about occurence of event.

[Link] Used to register event generated by PooledConnectionobject.

[Link] Represent the DataSource interface used in an application.

[Link] provide object to manage connection pools.

Steps to connect a Java Application to Database


The following 5 steps are the basic steps involve in connecting a Java application with Database
using JDBC.

1. Register the Driver


2. Create a Connection
3. Create SQL Statement
4. Execute SQL Statement
5. Closing the connection

Author:[Link]

Connecting to Access Database using Type-1 Driver


To connect a Java application with Access database using JDBC-ODBC Bridge(type-1) Driver. You
need to follow the following steps

Create DSN Name

1. Go to control panel

Author:[Link]
2. Go to Administrative tools

3. Select Data Source(ODBC)

4. Add new DSN name, select add

Author:[Link]
5. Select Access driver from the list, click on finish

6. Give a DSN name, click ok

Author:[Link]
NOTE: Here we are showing this example to create DSN in Window 7 os. For other operating
system you need to do small changes.

Example
We suppose that you have created a student table with sid and name column name in access
database.
import [Link].*;
class Test
{
public static void main(String []args)
{
try{
[Link]("[Link]");
Connection con = [Link]("jdbc:odbc:Test", "", "");
Statement s=[Link](); //creating statement

ResultSet rs=[Link]("select * from student"); //executing


statement

Author:[Link]
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}

[Link](); //closing connection

}
catch(Exception e)
{
[Link]();
}
}
}

Connecting to Oracle Database using Thin Driver


To connect a Java application with Oracle database using Thin Driver. You need to follow the
following steps

1. Load Driver Class: The Driver Class for oracle database


is [Link] and [Link]("[Link]"
) method is used to load the driver class for Oracle database.

2. Create Connection: For creating a connection you will need a Connection URL. The
Connection URL for Oracle is

Author:[Link]
You will also require Username and Password of your Oracle Database Server for creating
connection.

3. Loading jar file: To connect your java application with Oracle, you will also need to
load [Link] file. This file can be loaded into 2 ways.
1. Copy the jar file into C:\Program Files\Java\jre7\lib\ext folder.

or,

2. Set it into classpath. For more detail see how to set classpath

Download [Link] file


NOTE: Here we are discussing about Oracle 10g as database. For other version of Oracle you will
be require to do some small changes in the Connection URL.

Example
Create a table in Oracle Database
create table Student(sid number(10),sname varchar2(20));

Insert some record into the table


insert into Student values(101,'adam');
insert into Student values(102,'abhi');

Accessing record from Student table in Java application


import [Link].*;
class Test
{
public static void main(String []args)
{

Author:[Link]
try{
//Loading driver
[Link]("[Link]");

//creating connection
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:XE","username","password");

Statement s=[Link](); //creating statement

ResultSet rs=[Link]("select * from Student"); //executing statement

while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}

[Link](); //closing connection


}catch(Exception e){
[Link]();
}
}
}

101 adam

102 abhi

Inserting record into a table using java application


import [Link].*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver...
[Link]("[Link]");

Author:[Link]
//creating connection...
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:XE","username","password");

PreparedStatement pst=[Link]("insert into Student values(?,?)");

[Link](1,104);
[Link](2,"Alex");
[Link]();

[Link](); //closing connection


}catch(Exception e){
[Link]();
}
}
}

Connecting to MySQL Database using Thin Driver


To connect a Java application with MySQL database using Thin Driver. You need to follow the
following steps

1. Load Driver Class: The Driver Class for MySQL database


is [Link] and [Link]("[Link]") method is used to
load the driver class for MySQL database.
2. Create Connection: For creating a connection you will need a Connection URL. The
Connection URL for MySQL is

Author:[Link]
You will also require Username and Password of your MySQL Database Server for creating
connection.

3. Loading jar file: To connect your java application with MySQL, you will also need to
load [Link] file. This file can be loaded into 2 ways.
1. Copy the jar file into C:\Program Files\Java\jre7\lib\ext folder.

or,

2. Set it into classpath. For more detail see how to set classpath

Download [Link] file

Example
Create a table in MySQL Database
create table Student(sid int(10),name varchar(20));

Insert some record into the table


insert into Student values(102,'adam');
insert into Student values(103,'abhi');

Author:[Link]
Accessing record from Student table in Java application
import [Link].*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver
[Link]("[Link]");

//creating connection
Connection con = [Link]
("jdbc:mysql:/ /localhost:3306/test","username","password");

Statement s = [Link](); //creating statement

ResultSet rs = [Link]("select * from Student"); //executing statement

while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}

[Link](); //closing connection


}catch(Exception e){
[Link]();
}
}
}

102 adam

103 abhi

Inserting record into a table using java application

Author:[Link]
import [Link].*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver
[Link]("[Link]");

//creating connection
Connection con = [Link]
("jdbc:mysql:/ /localhost:3306/test","username","password");

PreparedStatement pst=[Link]("insert into Student values(?,?)");

[Link](1,104);
[Link](2,"Alex");
[Link]();

[Link](); //closing connection


}catch(Exception e){
[Link]();
}
}
}

Reflaction:
Reflation API in java provide the ability to examine or modify the runtime behavior of
application running in the Jvm.

-we can inspect get information about fields ,methods,constructors,interfaces and super
classes at run time.

-we can even accesss a private fields and invoke a private method from another class.

Author:[Link]
Where is reflaction API used?

-eclipse IDE using auto completing field or methods name.

-persistence framework ,your obj with fileds in the database table at runtime.

-junit getting the information a bout methods to be invoked.

-spring frmae works using DI.

Drawback:

-against oops

-secuirty restriction

-slow performance

Creating class instance using reflaction:

[Link]();

Annotation:
New feature of java jdk 5 onwards

It descripe metadata of java programmes. In metadata means,data about the data for
example coding part describe commens .

It is predefined tool used that APT (annotation processing tool)

Syntax 2 types;

[Link] ( @annoationname & members)

@Entity(name=”STUDENT”)

2. Utilitilation syntax

Variable ,methods, classes

Author:[Link]
see a comments of the java code. So comments not possible to access
programmtecially but annotation possible going last phase.

But before jdk5 , meta data access thru only xml file after introduced annotation it
can easily access to upto .class file .(not necessary xml file)

Why introduced annotation ?

bec of java developer not necessroy to learn to xml technology.

Second, every time we should check xml syntax properly.(using dom parser)

=======

Java -> compilation -> .class file execution -> output

Compilation has 4 machine there,

[Link]-processor(C++) [Link] 3,assembler [Link]/link-editor

Compiler has 6 phases:

[Link] analysis(buffering) :

it removed comments only purely take code [Link] we will open .class file we can’t

see a comments of the java code. So comments not possible to access


programmtecially but annotation possible going last phase.

But before jdk5 , meta data access thru only xml file after introduced annotation it
can easily access to upto .class file .(not necessary xml file)

Why introduced annotation ?

bec of java developer not necessroy to learn to xml technology.

Second, every time we should check xml syntax properly.(using dom parser)

[Link] analysis (tokens)

[Link] analysis

4 Intermediate code generation

[Link] optimation

[Link] generation

Author:[Link]
XML Based Annoatation Based
Up to 1.4 After jdk 1.5
Jdbc 3 Jdbc 4
Server 2.5 Servlet 3.x
Structs 1.x Struct 2.x
Jsf 1.x Jsf 2.x
Hibernate 2.4 Hibernate 3.2.x
Spring 2,x Spring 3.x
Ejb 2.x Ejb 3.x

Author:[Link]

You might also like