Java Programming Framework Guide
Java Programming Framework Guide
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:
What Is java?
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
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
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
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
Author:[Link]
TestingFrame Work:
Junit
Jasmine
Selenium
Cucumber
The java monitoring tool is defined as a monitoring tool used for tracking the
Deeloping Tool:
Spark
Author:[Link]
Spark is a robust web application development framework based on Java. It
cloud. Different data sources may be available. Spark provides more than 80
Features of Spark:
Spark can not only work separately, but it can also work on Hadoop.
In RAM Server sparks stores the information, enabling quick access and
Gradle
Author:[Link]
Gradle is a Java tool for project automation. It builds on Apache
Features of Gradle:
Better dependency modeling with the Java Library plugin decreases the
not assembled
Its intelligent classpath helps prevent the need to build when a library’s
Groovy
Features of Groovy:
Author:[Link]
It highlights syntax and error automatically like NetBeans which helps to
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 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:
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:
What it does
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
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.
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.
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.
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..
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
Different Versions:
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 9
Java SE 10
Author:[Link]
Java SE 12 March 2019
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:
Web specifications:
Author:[Link]
Java Server Faces: a technology for constructing user interfaces out of
components;
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:
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)
1. Temporary
Author:[Link]
2. Permanent
Temporary:
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
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
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.
Author:[Link]
[Link]("Hello World"); // prints Hello World
Output
C:\> javac [Link]
C:\> java MyFirstJavaProgram
Hello World
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.
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.
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….”);
}
}
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.
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:
[Link]
Author:[Link]
Primitive:-
Local Variable:-
Instance Variable:-
A variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.
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;
Author:[Link]
Primitive:
int a = 3;
byte b = 3;
if (a == b) { // true } //content check
Reference:
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].*;
// DEPARTMENT is a constant
salary = 70000;
[Link](DEPARTMENT+"average salary:"+salary); }}
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:
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]
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
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
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:
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.
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.
Author:[Link]
Visibility Public Protected Default private
Final , abstract,synchronized,native,strictrp
Final:
Note:
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
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)
Author:[Link]
[Link]("Int value "+i);
[Link]("Long value "+l);
[Link]("Float value "+f);
}
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();
Author:[Link]
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
A a;
B b=new B();
Most of the object using string obj,then easily convert other types.
Class Test{
}}
Author:[Link]
Strictfp keyword:
Ex:
Class car{
Final objectives:
Identifiers
❑ Identifiers can begin with a letter, an underscore, or a currency character.
❑ After the first character, identifiers can also include digits.
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.
❑ A class with public access can be seen by all classes from all packages.
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
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
equals() method:
EX:
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
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.
Int a=10,b=10;
[Link](s1==s3);//reference
check
getClass() method :
Output:
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.
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:
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.
[Link](employee1);
[Link](employee2);
[Link](employee3);
[Link](employee4);
[Link](employee5);
[Link](listEmployees);
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
[Link](getMinValue(4,10));
[Link](getAbsoluteValue(-10));
[Link](invertBoolean(true));
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");
}
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]
[Link]
is equivalent to:
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.
In this example MyString is an immutable class. MyString's state cannot be changed once it is
created.
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";
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.
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.
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.
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
Author:[Link]
5 String substring(int beginIndex) returns substring for given
begin index.
Author:[Link]
16 String[] split(String regex) returns a split string matching
regex.
Author:[Link]
27 String trim() removes beginning and ending
spaces of this string.
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
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);
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
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";
}
}
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);
}
}
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".
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.
[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)
Author:[Link]
StringBuffer append(int n)
test123
insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String 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.
<
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
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
Questions:
String-immtability StringBufer-mutablilty
[Link] immutability and mutability Is any other diff betweeh string & stringbuffer?
In SB reference comparision.
8. why scp concept like avail only for string but not for SB?
Author:[Link]
[Link] means non-changble where as final means also [Link] what is
different between final and immutable?
EX:
Super();
[Link]=empId; …
Author:[Link]
}
P v s main(){
E1. COMPANY_NAME;
Ex2:
Public Counter(){
counter++;
P s v main(_{
New Counter();
Sop([Link]);
New Counter();
Sop([Link]);
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]
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.
Ex:
Author:[Link]
It should not associate any indivial object ,it common for all classes.
Retrun parseDate;
Main(){
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.
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;
}
A static nested class is same as any other top-level class and is nested for only
packaging convenience.
Let’s see all the static keyword in java usage in a sample program.
package [Link];
//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);
}
Author:[Link]
private static int count; //kept private to control its value through setter
public static String str;
Let’s see how to use static variable, method and static class in a test program.
package [Link];
Author:[Link]
[Link] myStaticClass1 = new
[Link]();
[Link]=20;
[Link]([Link]);
[Link]([Link]);
}
public class A {
package [Link];
public class B {
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
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”);
}
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) {
..
[Link](monthString);
int monthNumber = 0;
switch ([Link]()) {
Author:[Link]
..
default:
monthNumber = 0;
break;
return monthNumber;
“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.
//print integers 5 to 10
for (int i=5; i<=10; i++) {
[Link]("Java for loop example - " + i);
}
}
import [Link];
import [Link];
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.
Example 2:
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = [Link]();
int numPs = 0;
// process p's
numPs++;
}
[Link]("Found " + numPs + " p's in the string.");
Author:[Link]
Java while loop example
Here is a simple java while loop example to print numbers from 5 to 10.
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.
Iterator<String> it = [Link]();
while([Link]()) {
[Link]([Link]());
}
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];
}
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.
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];
int i = 5;
do {
[Link](i);
i++;
} while (i <= 10);
}
}
Java break
There are two forms of break statement – unlabeled and labeled.
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
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.
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.
Author:[Link]
Initializing an array in java – object type
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.
Here are some other variations of declaring arrays in java but they are strongly
discouraged to avoid confusion.
Author:[Link]
Example 1:
Example 3:
class B{
public static void main(String args[]){
//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];
Output:
[1,2]
[3,4,5]
Author:[Link]
public class JavaArrayListOfStringArray {
[Link](arr1);
[Link](arr2);
[Link]([Link](strArr));
package [Link];
import [Link];
import [Link];
Author:[Link]
/**
* @param args
*/
[Link]([Link](words));
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.
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.
Author:[Link]
[Link](strArr);
[Link]([Link](intArr));
[Link]([Link](strArr));
[Link]("1");
[Link]("2");
[Link]("3");
[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.
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 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.
boolean Boolean
char Character
byte Byte
Author:[Link]
short Short
int Integer
long Long
float Float
double Double
[Link]
import [Link];
import [Link];
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.
Author:[Link]
String a=”10”;
float aa=[Link](a);
String a1=[Link]();
String
parseXXX()
toString()
toString
valueOf()
Primitive
Wrapper object
xxxValue()
valueOf()
int i=10;
Wrapper-Object To Primitive:
Int a=[Link]();
Wrapper-Object To String:
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.
Unboxing:
Wrapper type into Primitive data type. It is the reverse process of autoboxing.
import [Link];
import [Link];
Author:[Link]
public class AutoboxingUnboxing {
// passed the int, will get converted to Integer object at Runtime using
// autoboxing in java
doSomething(i);
}
}
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.
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.
Parameterized Constructor
Constructor with arguments is called parameterized constructor. Let’s look at the
example of parameterized constructor in java.
public Data(String n) {
[Link]("Parameterized Constructor");
[Link] = n;
}
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.
//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;
}
@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);
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.
// private constructor
private Data() {
//empty constructor for singleton pattern implementation
//can have code to be used inside the getInstance() method of class
}
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.
Author:[Link]
public String getName() {
return 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");
}
}
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.
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.
package [Link];
public Person() {
[Link]("Person Created");
}
public Person(int i) {
[Link] = i;
[Link]("Person Created with Age = " + i);
}
package [Link];
Author:[Link]
public Student() {
[Link]("Student Created");
}
}
Now if we create a Student object like below;
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:
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];
package [Link];
import [Link];
import [Link];
[Link]([Link]());
Author:[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.
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
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.
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.
}
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.
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 {
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;
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();
}
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:
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
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.
Author:[Link]
5) Object is created many times as per requirement. Class is declared once.
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:
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.
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.
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.
Encapsulation
Hiding and security the details
Advanced OOPS:
Coupling
This is advanced concept of OOPS [Link] it can be used structs,spring,webservices.
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.
Low Cohesion:
TotalServlet
High Cohesion:
Enhancement very easy bec everything separate compontes so maintaince also very easy.
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).
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.
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.
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.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface & abstract class
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.
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).
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.
Author:[Link]
Animal a = d;
Cat c1 = (Cat) a; //ClassCastException at runtime
Examples: Object
Base 2
Base 1
[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,
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
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.
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:
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).
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 {
public Animal(){}
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{
Let’s write a simple test class to create Cat object and use some of its methods.
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.
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.
Author:[Link]
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
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.
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:
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...
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...
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
Author:[Link]
Sysout(super.a+super.b+a);//super
}
[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:
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:
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)
[Link]();
Maruti class uses Engine object’s start() method via composition. We can say
that Maruti class HAS-A Engine.
package relationships;
[Link]("Engine Started:");
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;
[Link]("RED");
[Link](180);
[Link]();
[Link]();
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.
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.
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.
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.
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.
[Link]
[Link]
int id;
String name;
Address address; //aggregation
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");
[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.
Author:[Link]
How does Polymorphism make working so easy?
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.
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.
OverLoading:
When a class has multiple methods that have the same name but different parameters, it is referred to
as Method Overloading.
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) {}
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
In java, Method Overloading is not possible by changing the return type of the method only.
Author:[Link]
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}
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));
}}
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.
Methods of child and parent class must have the same parameter.
Author:[Link]
One cannot override private methods of a parent class.
class Parents {
[Link]("I am Parent");
@Override
[Link]("I am Children");
Author:[Link]
multilevel inheritance:(Over Riding)
class OperatingSytem{
void feature() {
}}
void feature(){
[Link]("This is DOS");
}}
void feature(){
[Link]("This is Windows");
} }
void feature(){
[Link]();
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:
Author:[Link]
The second class, a subclass of Animal, is called Cat:
//over riding
[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.
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.
Ex:
Class P{
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);
Author:[Link]
P1.m1(10); //parent
Class c extends P {
Static method is class level method but non-static method Object level method so class level method
how is allowed override ? so not possible.
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:
Result:
Author:[Link]
Before we defined in superclass color,size,eat …
Author:[Link]
But that new species what color,size,eat how to handled ?
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.
Author:[Link]
Abstract Class:
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.
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 {
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.
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
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.
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
An abstract class can have both The interface can have only abstract
abstract and non-abstract methods. methods.
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.
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
Note: implementation must be all methods in abstract class otherwise error occurred.
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:
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.
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:
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.
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.
"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.
[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.
Interface Moveable {}
Interface 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]());
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. }
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));
}}
Points to Note:
Author:[Link]
Difference between abstract class and interface in Java
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.
Ex:
Author:[Link]
Person {
Student{
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)
While implementing interace we can extend any other class and hence we won’t miss any
inheritance benefit.
Author:[Link]
Test t=new Test(); -> 2 min
Hence if evetthing is abstract highly recommended to use interface but not abstract class.
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.
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;
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.
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.
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.
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.
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.
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;
}
}
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) {
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]
File: [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".
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.
Annotation:
Java 1.5 introduced annotations and now it’s heavily used in Java EE frameworks like Hibernate, Jersey,
and Spring.
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.
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
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");
}
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:
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.
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.
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.
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.
CloneNotSupportedException Attempt to clone an object that does not implement theCloneable interface.
IllegalAccessException Access to a class is denied.
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{
}
}
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.
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.
doStuff();
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.
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
1. try
2. catch
3. throw
4. throws
5. finally
Author:[Link]
// need of try-catch clause
class GFG {
// array of size 4.
int i = arr[4];
}
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.
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.
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
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.
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
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
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
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.
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.
Example:
Class DemoThrow_Throws{
//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);
}
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.
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.
Rules:
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
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.
[Link]:
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
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])
1. Checked Exception
Author:[Link]
2. Unchecked Exception
3. Error
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.
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
Author:[Link]
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as
follows:
1. int a=50/0;//ArithmeticException
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
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
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
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{
class ExceptionHandling2{
try{
[Link](9);
}catch(InvalidAgeException ex){
[Link]("Exception occured: "+[Link]());
Author:[Link]
}
Author:[Link]
[Link](); //closing BufferedReader stream
}catch(IOException ie)
{ [Link]("exception"); }
}
}
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.
Author:[Link]
import [Link].*;
class Super
{
void show(){ [Link]("parent class"); }
}
child class
Author:[Link]
void show() throws Exception
{ [Link]("parent class"); }
}
child class
Author:[Link]
Super s=new Sub();
[Link]();
}
catch(Exception e){}
}
}
child class
Author:[Link]
[Link] Exception
[Link] developmer
Jvm Exception:
Example:
Sop(10/0) ;AE
Programmetic Exception:
API developemer:
Who wrote the AE exception? Api developer write inside [Link] file.
Ex:
Class Thread {
setPriority(int newPriority)
[Link]: (unchecked)
Author:[Link]
[Link]:
String s=null;
Sop([Link]());
[Link]: (unchecked)
Object 0=(Object)s;
String s=(String) o;
[Link]();
Jvm immediately try to run [Link] when no found when this error
occurred.
Class Test{
Author:[Link]
[Link]:
Refer above.
[Link]:
Int i=[Link](“10”);
[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
[Link]();
[Link]();
10.
Multi-catch-blocks
Resources means,
Connection con=null;
Try{..
Author:[Link]
}finally{ if(con != null ) [Link](); }
What ever resource we will initiazed inside try cat block ,it will automatically
closed.
Try(resource1;resource2;resource2)
Ex:
III)
2)MultiCatch handling:
3)ReThrowingException:
We can used this approach to convert one exception type to another exception
type.
Ex:
Try { sop(10/0); }
Catch(AE e) {
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.
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
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
[Link]
[Link]
[Link] or unbounded wildcards
Author:[Link]
List<Integer> ints = new ArrayList<>();
[Link](3);[Link](5); [Link](10);
double sum = sum(ints);
[Link]("Sum of ints="+sum);
[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](3); [Link](5);
[Link](3.12); [Link](55.123);
printData(ints1);
printData(ints2);
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:
Saved to a File
Object bytes
Serialization
Stored in DB
Author:[Link]
Transmitted
another Jvm
Introduction to Multithreading
[Link]
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?
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.
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.
[Link]
Java – Alive:
Author:[Link]
Java – Yield Method
[Link]
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.
From Java 1.5 onwards, The Sun Microsystem added some more new concepts
called Generics.
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.
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.
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.
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.
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".
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:
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.
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:
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:
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:
Author:[Link]
EventListener NavigableMap SortedSet
Formattable NavigableSet
Iterator Observer
The list of important classes present in [Link] package is shown in the below
table:
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.
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.
2. Your code is easier to maintain because it provides useful data structure and
interfaces which reduce programming efforts.
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.
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.
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.
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.
Author:[Link]
true if the elements are added otherwise returns false.
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.
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.
Adding object
Author:[Link]
Counting object
Searching object
Retrieving object
Removing object
Replacing object
Inserting object
[Link]
[Link] objects > same class objcts (take 2 employee class or take 2 Integer class)
[Link] obj> 2 objs same class with different ref and diff. data
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 )
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.
[Link](al);
Author:[Link]
14) static Boolean disjoint() It returns true if the two
specified collections have
no elements in common.
Author:[Link]
36) static void reverse() It is used to reverse the
order of the elements in
the specified list.
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]());
1. It is at the top of collection heirarchy and must be implemented by any class that defines a
collection. Its general declaration is,
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 retainAll(Collection c) Deletes all the elements of invoking collection except the
specified 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.
1. It extends the Collection Interface, and defines storage as sequence of elements. Following is its
general declaration,
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:
Author:[Link]
11. Converting between Lists and arrays
12. List to Stream
13. Concurrent lists
[Link]
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
AL vs CopyonWriteArrayList:
ArrayList CopyonWriteArrayList
Author:[Link]
Null not permitted Null permitted
ArrayList Vector
Non-synchronized Synchronized
Enumeration Iterator
You can’t any modification while traversing Remove element only traversing
hasMoreElements(),nextElement() hasNext(),next(),remove()
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,
2. Set Implementations
Author:[Link]
The Queue Interface
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,
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 peek() returns the element at the head of the queue without removing it.
Returns null if queue is empty
Author:[Link]
The Dequeue Interface
1. It extends Queue interface and implements behaviour of a double-ended queue. Its general
declaration is,
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:
WeakHashMap
EnumMap
HashTable -ThreadSafe
TreeMap
ArrayList:
If element removal of the AL,that space will be accomediate shift process this
drawback of array.
Author:[Link]
Ex: Constructor:
LikedList:
Linkedlist connects with other nodes through next and previous ref. so it is called
doubled linked list.
[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.
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
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
Disadvantage
Author:[Link]
Advantage
Disadvantage
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
Disadvantage
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
Author:[Link]
[Link] package
This package is also known as JDBC extension API. It provides classes and interface to access
server-side data.
classes/interface Description
Author:[Link]
1. Go to control panel
Author:[Link]
2. Go to Administrative tools
Author:[Link]
5. Select Access driver from the list, click on finish
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
Author:[Link]
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}
}
catch(Exception e)
{
[Link]();
}
}
}
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
Example
Create a table in Oracle Database
create table Student(sid number(10),sname varchar2(20));
Author:[Link]
try{
//Loading driver
[Link]("[Link]");
//creating connection
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:XE","username","password");
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}
101 adam
102 abhi
Author:[Link]
//creating connection...
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:XE","username","password");
[Link](1,104);
[Link](2,"Alex");
[Link]();
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
Example
Create a table in MySQL Database
create table Student(sid int(10),name varchar(20));
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");
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}
102 adam
103 abhi
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");
[Link](1,104);
[Link](2,"Alex");
[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?
-persistence framework ,your obj with fileds in the database table at runtime.
Drawback:
-against oops
-secuirty restriction
-slow performance
[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 .
Syntax 2 types;
@Entity(name=”STUDENT”)
2. Utilitilation syntax
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)
Second, every time we should check xml syntax properly.(using dom parser)
=======
[Link] analysis(buffering) :
it removed comments only purely take code [Link] we will open .class file we can’t
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)
Second, every time we should check xml syntax properly.(using dom parser)
[Link] analysis
[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]