0% found this document useful (0 votes)
35 views

Java Mid-1 Notes

This document provides an overview of key concepts in the Java programming language. It discusses Java basics like data types, variables, control statements, classes, objects and methods. It also covers Java platforms/editions, requirements for a Hello World program, and how Java programs are compiled and executed. Textbooks on Java programming referenced include publications by Herbert Schildt, H.M. Dietel and P.J. Dietel, and Y. Daniel Liang.

Uploaded by

nehatabassum4237
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Java Mid-1 Notes

This document provides an overview of key concepts in the Java programming language. It discusses Java basics like data types, variables, control statements, classes, objects and methods. It also covers Java platforms/editions, requirements for a Hello World program, and how Java programs are compiled and executed. Textbooks on Java programming referenced include publications by Herbert Schildt, H.M. Dietel and P.J. Dietel, and Y. Daniel Liang.

Uploaded by

nehatabassum4237
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 252

Unit-1

Java Basics:-
1. Introduction
2. History of Java
3. Java buzzwords
4. Data types
5. Variables
6. Scope and Life time of variables
7. Arrays
8. Operators
9. Expressions
10. Control statements
11. Type conversion and casting
12. Simple Java programs
13. Concepts of classes
14. Objects
15. Constructors
16. Methods
17. Access control
18. This keyword
19. Garbage collection
20. Overloading methods
21. Parameter passing
22. Recursion
23. Exploring String Class
TEXT BOOKS

 The complete Reference Java, 8th edition, Herbert Schildt, TMH.


 Java How to Program, H.M. Dietel and P.J.Dietel, 6th Edition, Pearson Education/PHI
 Introduction to java programming, 7th edition by Y Daniel Liang, Pearson.
1.Introduction:-
1. What is Java?
2. Application
3. Java Platforms / Editions
4. The requirement for Java Hello World Example
5. Creating Hello World Example
6. Parameters used in First Java Program
7. how many ways we can write a Java program?
8. How to set path in Java?

1.What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java
has a runtime environment (JRE) and API, it is called a platform.

2.Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of them
are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Types of Java Applications


There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application

Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications
in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an enterprise application.
It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used for creating
enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application. Currently, Android and Java
ME are used for creating mobile applications.

3.Java Platforms / Editions


There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net,
java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of the
Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB(Enterprise Java Bean), JPA(Java
Persistence API (Application Programming Interface)), etc.
3) Java ME (Java Micro Edition)

It is a micro platform that is dedicated to mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user interface API.

4.The requirement for Java Hello World Example


For executing any Java program, the following software or application must be properly installed.

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program

5.Creating Hello World Example


Let's create the hello java program:

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }

Save the above file as Simple.java.

To compile: javac Simple.java

To execute: java Simple

Output:

Hello Java

Execution Process of Java Program


The following three steps are used to create and execute a java program.
 Create a source code (.java file).

 Compile the source code using javac command.

 Run or execute .class file uisng java command.


What is Byte code:-
Byte Code can be defined as an intermediate code generated by the compiler after
the compilation of source code(JAVA Program). This intermediate code makes Java a
platform-independent language.

Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into byte code.

Can you save a Java source file by another name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
Compile time:
Javac Hard.java
Runtime:
Java FirstProgram
What happens at runtime?
At runtime, the following steps are performed:

Classloader: It is the subsystem of JVM that is used to load class files.


Bytecode Verifier: Checks the code fragments for illegal code that can violate access rights to
objects.
Interpreter: Read bytecode stream then execute the instructions.

Can you have multiple classes in a java source file?


Yes, like the figure given below illustrates:
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which Java
bytecode can be executed. It can also run those programs which are written in other languages
and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the JVM: specification,
implementation, and instance.
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM. It
physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.

6.Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the
static method is that there is no need to create an object to invoke the static method. The main() method is executed
by the JVM, so it doesn't require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it in coming section.
o System.out.println() is used to print statement. Here, System is a class, out is an object of the PrintStream class,
println() is a method of the PrintStream class. We will discuss the internal working
of System.out.println() statement in the coming section.

To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories
-> Notepad and write a simple program as we have shownbelow:
As displayed in the above diagram, write the simple program of Java in notepad and saved it as
Simple.java. In order to compile and run the above program, you need to open the command prompt
by start menu -> All Programs -> Accessories -> command prompt. When we have done with all the
steps properly, it shows the following output:

7.how many ways we can write a Java program?


Valid Java main() method signature
1. public static void main(String[] args)
2. public static void main(String []args)
3. public static void main(String args[])
4. public static void main(String... args)
5. static public void main(String[] args)
6. public static final void main(String[] args)
7. final public static void main(String[] args)
Invalid Java main() method signature
1. public void main(String[] args)
2. static void main(String[] args)
3. public void static main(String[] args)
4. abstract public static void main(String[] args)
Resolving an error "javac is not recognized as an internal or external
command"?
If there occurs a problem like displayed in the below figure, you need to set a path. Since DOS doesn't recognize
javac and java as internal or external command. To overcome this problem, we need to set a path. The path is not
required in a case where you save your program inside the JDK/bin directory. However, it is an excellent approach
to set the path. Click here for How to set path in java.

8.How to set path in Java


The path is required to be set for using tools such as javac, java, etc.

If you are saving the Java source file inside the JDK/bin directory, the path is not required to be set because all
the tools will be available in the current directory.

However, if you have your Java file outside the JDK/bin folder, it is necessary to set the path of JDK.

There are two ways to set the path in Java:

1. Temporary
2. Permanent

1) How to set the Temporary Path of JDK in Windows


To set the temporary path of JDK, you need to follow the following steps:
o Open the command prompt
o Copy the path of the JDK/bin directory
o Write in command prompt: set path=copied_path

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

Let's see it in the figure given below:

2) How to set Permanent Path of JDK in Windows


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

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

For Example:
1) Go to MyComputer properties
2) Click on the advanced tab
3) Click on environment variables

4) Click on the new tab of user variables


5) Write the path in the variable name

6) Copy the path of bin folder


7) Paste path of bin folder in the variable value

8) Click on ok button
9) Click on ok button

Now your permanent path is set. You can now execute any program of java from any drive.
Difference between Pop(Procedure Oriented Programming)
and OOP(Object Oriented Programming)

Sr.No. On the basis of POP OOP


1 Definition In procedure programming, we Object-oriented programming
break down a task into a set of is a programming paradigm in
variables and routines after that, it which every program is follows
is carried out every step one by one. the concept of object.
2 Problem solving approach

The focus is on breaking the bigger The focus is on identifying and


problem into smaller one and then resolving smallest problems
repeat the process with each and then integrating them
problem. together to solve the bigger
problem.
3 Subdivision The POP program is divided into OOP program are divided into
small functions. objects.
Ex:- #include<stdio.h> Ex:-class Add{
Void add() …..
{ }
….. Add a=new Add();//object
}
int main(){
…..
add();
}
4 Access Specifiers No concept of access specifiers Make use of access specifiers
such as public, private,
protected etc.,
5 Security Very less security is available More Security because using
garbage collection.
6 Orientation Procedural programming is It is object-oriented.
structure/procedure-oriented.
7 Code Reusability No code reusability in procedural Due to inheritance, concept of
programming. code reusability exists in
object-oriented.
8 Virtual Class In Procedural programming, There There exists a concept of
is no concept of virtual class. virtual classes in object-
oriented programming.
9 Overloading In procedural programming There is a concept of function
overloading is not possible. overloading and operator
overloading in object oriented
programming.
10 Examples Examples of procedural Examples of OOP are java,
programming are fortran, algol, c++, c#, python, JavaScript,
cobol, basic, pascal and c. etc.,

Table.1.Difference between Pop and OOP


Difference Between c , c++ and java?
C definition:- C is a general-purpose, structured, procedural, and high-level programming
language developed by Dennis Ritchie in 1972 at Bell Laboratories.

C++ definition: - C++ is an object-oriented, general-purpose, programming language developed


Bjarne Stroustrup at Bell Labs in 1979.

Java definition: - Java is also an object-oriented, class-based, static, strong, robust, safe,
and high-level programming language. It was developed by James Gosling in 1995.

S.N. Basis C C++ Java

1 Origin The C language The C++ The Java programming language


is based on language is is based on both C and C++.
BCPL. based on the C
language.

2 Programming It is a procedural It is an object- It is a pure object-oriented


Pattern language. oriented programming language.
programming
language.

3 Approach It uses the top- It uses the It also uses the bottom-up approach.
down approach. bottom-up
approach.

4 Dynamic or It is a static It is also a static It is a dynamic programming language.


Static programming programming
language. language.

5 Code The code is The code is The code is executed by the JVM.
Execution executed executed
directly. directly.

6 Platform It is platform It is platform It is platform-independent because


Dependency dependent. dependent. of byte code.

7 Translator It uses a It also uses a Java uses both compiler and


compiler only to compiler only to interpreter and it is also known as
translate the translate the an interpreted language.
code into code into
machine machine
language. language.

8 File It generates the It generates .exe It generates .class file.


Generation .exe, files. file.
9 Number of There There There are 52 keywords in the
Keyword are 32 keywords are 60 keywords Java language.
in the C in the C++
language. language.

10 Source File The source file The source file The source file has a .java extension.
Extension has a .c has a .cpp
extension. extension.

11 Pointer It supports It also supports Java does not support the pointer
Concept pointer. pointer. concept because of security.

12 Union and It supports It also supports It does not support union and
Structure union and union and structure data types.
Datatype structure data structure data
types. types.

13 Pre-processor It uses pre- It uses pre- It does not use directives but uses
Directives processor processor packages.
directives such directives such
as #include, as #include,
#define, etc. #define,
#header, etc.

14 Constructor/ It does not It supports both It supports constructors only.


Destructor support constructor and
constructor and destructor.
destructor.

15 Exception It does not It supports It also supports


Handling support exception exception handling.
exception handling.
handling.

16 Memory It uses the It uses new and It uses a garbage collector to manage
Management calloc(), delete operator the memory.
malloc(), free(), to manage the
and realloc() memory.
methods to
manage the
memory.

17 Overloading It does not Method and Only method overloading


support the operator can be achieved.
overloading overloading can
concept. be achieved.

18 goto It supports the It also supports It does not support the


Statement goto statement. the goto goto statements.
statement.
19 Used for It is widely used It is widely used It is used to develop web
to develop for operating applications, mobile applications, and
drivers and system, windows applications.
operating developing
systems. browsers.

20 Array Size An array should An array should An array can be declared without
be declared with be declared with declaring the size. For example, int num[].
size. For size.
example, int
num[10].

8. OOPS Concepts(Object Oriented Programming System)


OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every program is

follows the concept of object. In other words, OOP is a way of writing programs based on the object concept.

(or)

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.

OOPS concepts are as follows:


1. Class
2. Object
3. Abstraction
4. Encapsulation Pillars of oops
5. Inheritance
6. Polymorphism
1.Class:-
Definition: - A class is a template or blueprint from which you can create an individual
object. Class doesn’t consume any space. It is logical entity.
Ex:-Car

A class in java can contain:


i. Fields or variables
ii. Methods
iii. Constructors
iv. Blocks
v. Nested class and interface
Syntax to declare a class:-
access_modifier class<class_name>
{
//data member;
//method;
//constructor;
//nested class;
//interface;
}
A class is a user-defined blueprint or prototype from which objects are created. It represents the set
of properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:

1. Modifiers: A class can be public or has default access.


2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
6. Body: The class body is surrounded by braces, { }.

Example Program:-

public class Car


{
String color;
int weight;
int speed;
String model;
void startCar()
{
System.out.println("car Started");
}
void changeGear()
{
System.out.println("Gear Changed");
}
void slowDown()
{
System.out.println("Going slowly");
}
void brake()
{
System.out.println("Sudden Brake");
}
}
2.Object: -
Definition: - Object is a real world entity that we can touch physically is
referred as object such as a pen, chair, table, computer, watch, etc., Object
is an instance of a class. Each entity will be having its own state and
behaviour and it is referring as an object. An object contains an address
and takes up some space in memory.
Example:-
Objects of the class car can be BMW, Mercedes, Ferrari, etc.
New:-
The new keyword is used to allocate memory at runtime. All objects get memory in heap memory area.

Syntax:-
<class_name> <object_name>=new <class_name>();
(Or)
<class_name> <object_name>;
<object_name>=new <class_name>();

Example Creating Object for Car:-


Car BMW=new BMW();
Car Ferrari=new Ferrari();
(or)
Car BMW; //creating BMW reference variable for class Car stored in stack memory
BMW=new BMW(); //now BMW object is created in heap memory

Example Program creating Objects and Class:-

1. class Car
2. {
3. String color="red";
4. int weight=50;
5. int speed=100;
6. String model="1";
7. void startCar()
8. {
9. System.out.println("car Started");
10. }
11. void changeGear()
12. {
13. System.out.println("Gear Changed");
14. }
15. void slowDown()
16. {
17. System.out.println("Going slowly");
18. }
19. void brake()
20. {
21. System.out.println("Sudden Brake");
22. }
23. public static void main(String args[])// objects are always create in main method because
JVM is executed main method directly
24. {
25. Car bmw=new Car();
26. Car ferrari;
27. ferrari=new Car();
28. System.out.println(bmw.color);//calling variable
29. ferrari.color="block";//initializing a value through object
30. System.out.println(ferrari.color);
31. bmw.startCar();//calling method
32. ferrari.startCar();
33. }
34. }
35. Output:-
36. red
37. block
38. car Started
39. car Started

3.Abstraction:-
Definition:-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.

Example 2:-
In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using
interfaces.
The abstract method contains only method declaration but not implementation.
Example program:-
1. abstract class Simple{//abstract class
2. abstract public void withdraw();//abstract method
3. }
4. class Test extends Simple{
5. //if you extend abstract class definitely give the
6. //implementation of abstract method or put this Test class abstract class
7. public void withdraw()
8. {
9. System.out.println("Withdraw amount successfully");
10. }
11. public static void main(String args[])
12. {
13. Test t=new Test();
14. t.withdraw();
15. }
16. }
O/P:- Withdraw amount successfully

9. Encapsulation

Definition:- Binding (or Wrapping) code and data together into a single unit are known as encapsulation.
(or)
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds together the code
and the data it manipulates. Another way to think about encapsulation is that it is a protective shield that
prevents the data from being accessed by the code outside this shield.
 Technically, in encapsulation, the variables or the data in a class is hidden from any other class and can be
accessed only through any member function of the class in which they are declared.
 In encapsulation, the data in a class is hidden from other classes, which is similar to what data-
hiding does. So, the terms “encapsulation” and “data-hiding” are used interchangeably.
 Encapsulation can be achieved by declaring all the variables in a class as private and writing public
methods in the class to set and get the values of the variables.
Real world Example:-

Example Program:-
10. class EncapsulationEx{
11. private int a;
12. public int get()//Accessor Method
13. {
14. return a;
15. }
16. public void set(int a) //mutator method
17. {
18. this.a=a;
19. }
20. }
21. class Test{
22. public static void main(String args[]){
23. EncapsulationEx e=new EncapsulationEx();
24. e.set(10);
25. System.out.println(e.get());
26. }
27. }
O/p:-10

3. Inheritance

Definition:- When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance.
(or)
It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another
class. We are achieving inheritance by using extends keyword. Inheritance is also known as “is-a” relationship.
Let us discuss some frequently used important terminologies:
 Superclass: The class whose features are inherited is known as superclass (also known as base or parent
class).
 Subclass: The class that inherits the other class is known as subclass (also known as derived or extended
or child class). The subclass can add its own fields and methods in addition to the superclass fields and
methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and
there is already a class that includes some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the existing class.
 Real world Example:-


Example Program:-
1. class Mother
2. {
3. public void walk()
4. {
5. System.out.println("Walking Slowly");
6. }
7. }
8. class Daughter extends Mother //walk method inherited directly
9. {
10. public void eat()

11. {
12. System.out.println("Eating Slowly");
13. }
14. public static void main(String args[])
15. {
16. Daughter d=new Daughter();
17. d.walk();
18. d.eat();
19. }
20. }
Output:-
Walking Slowly
Eating Slowly

4.Polymorphism

Definition:- Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms.
So polymorphism means many forms.

There are two main types of polymorphism i.e. runtime polymorphism and compile-time polymorphism. Runtime
polymorphism (or) dynamic binding is achieved through method overriding , and compile-time polymorphism
(or) static binding is achieved through method overloading. Java doesn't support operator overloading.
Real Time Example:-
Example Program:-
Method Overloading :- If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
It is used to achieve Compile time polymorphism (or) static binding.
1. class MethodOverloadingEx
2. {
3. public void display()
4. {
5. int a=10;
6. System.out.println(a);
7. }
8. public void display(int a)
9. {
10. System.out.println(a);
11. }
12. public static void main(String args[])
13. {
14. MethodOverloadingEx m=new MethodOverloadingEx();
15. m.display();
16. m.display(20);
17. }
18. }
O/p:-
10
20
Method Overriding :- If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
It is used to achieve Run time polymorphism (or) dynamic binding.
1. class Mother{
2. public void walk()
3. {
4. System.out.println("Mother is Walking");
5. }
6. }
7. class Daughter extends Mother
8. {
9. public void walk()
10. {
11. System.out.println("Daughter is Walking");
12. }
13. public static void main(String args[])
14. {
15. Mother m=new Daughter();
16. m.walk();
17. }
18. }
O/p:- Daughter is Walking
2.History of Java
The history of Java is very interesting. Java was originally designed for interactive television, but it was too advanced
technology for the digital cable television industry at the time. The history of Java starts with the Green Team. Java team
members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top
boxes, televisions, etc. However, it was best suited for internet programming. Later, Java technology was incorporated by
Netscape.
he principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by
James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in
the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The
small team of sun engineers called Green Team.

2) 2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) 3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) 4) After that, it was called Oak and was developed as a part of the Green project.

Why Java was named as "Oak"?

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France,
Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java Programming named "Java"?


7) Why had they chose the name Java for Java language? The team gathered to choose a new name. The suggested
words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the
essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say.

According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most
of the team members preferred Java than other names.

8) Java is an island in Indonesia where the first coffee was produced (called Javacoffee). It is a kind of espresso
bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.

9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation)
and released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional
features added to the language. Now Java is being used in Windows applications, Web applications, enterprise
applications, mobile applications, cards, etc. Each new version adds new features in Java.

Java Version History


1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 ( March 2022)
21. Java SE 19 (September 2022)
22. Java SE 20 (to be released by March 2023)

Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version is release in March
month and an odd version released in September month.

3.Java buzzwords

A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. High Performance
9. Distributed
10. Multithreaded
11. Dynamic
12. Interpreted

1)Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem,
Java language is a simple programming language because:

o Java syntax is based on C and C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in
Java.

2)Object-oriented
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every program is
follows the concept of object. In other words, OOP is a way of writing programs based on the object concept.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

3)Platform Independent
Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime
environment (JRE) and API, it is called a platform.
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is
compiled by the compiler and converted into byte code. This byte code is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
4)Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java
classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.
o Security Manager: It determines what resources a class can access such as reading and writing to the local disk.

Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL(Secure socket layer), JAAS(java Authentication and authorization service),
Cryptography, etc.

5)Robust
The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are
not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points make Java robust.

6)Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of
primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for
64-bit architecture. Java occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
7)Portable
Java is portable because it facilitates you to carry the Java byte code to any platform. It doesn't require any
implementation.

8)High-performance
Java is faster than other traditional interpreted programming languages because Java byte code is "close" to native
code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why
it is slower than compiled languages, e.g., C, C++, etc.

9)Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI(remote method
invocation) and EJB(Enterprise java bean) are used for creating distributed applications. This feature of Java
makes us able to access files by calling the methods from any machine on the internet.

10)Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many
tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy
memory for each thread. It shares a common memory area. Threads are important for multi-media, Web
applications, etc.

11)Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand.
It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

12)Interpreted:-

Java is a interpreter language. It is convert byte code to executable code in jvm. It is design to
read the input source code and then translate the executable code instruction by instruction.

4.Data types
Data types specify the different sizes and values that can be stored in the variable.In java, data types are classified
into two types and they are as follows.

 Primitive Data Types


 Non-primitive Data Types
Primitive Data Types
The primitive data types are built-in data types and they specify the type of value stored in a variable and the
memory size. The primitive data types do not have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.

The following table provides more description of each primitive data type.

Data Memory Default


type Meaning size Range Value

byte Integer numbers 1 byte -128 to +127 0

short Integer numbers 2 bytes -32768 to +32767 0

int Integer numbers 4 bytes -2,147,483,648 to +2,147,483,647 0

long Integer numbers 8 bytes -9,223,372,036,854,775,808 to 0L


+9,223,372,036,854,775,807

float Fractional 4 bytes - 0.0f


numbers
double Fractional 8 bytes - 0.0d
numbers

char Single character 2 bytes 0 to 65535 \u0000

boolean unsigned char 1 bit 0 or 1 0 (false)

Let's look at the following example java program to illustrate primitive data types in java and their default values.

Example
public class PrimitiveDataTypes {

bytei;
shor j;
in k;
lon l;
float m;
double n;
charch;
boolean p;

public static void main(String[] args) {

PrimitiveDataTypes obj = new PrimitiveDataTypes();

System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l = " + obj.l);

System.out.println("m = " + obj.m + ", n = " + obj.n);


System.out.println("ch = " + obj.ch);

System.out.println("p = " + obj.p);

}
}

When we run the above example code, it produces the following output.

Non-primitive Data Types


In java, non-primitive data types are the reference data types or user-created data types. All non-primitive data
types are implemented using object concepts. Every variable of the non-primitive data type is an object. The non-
primitive data types may use additional methods to perform certain operations. The default value of non-primitive
data type variable is null.
In java, examples of non-primitive data types are String, Array, List, Queue, Stack, Class, Interface, etc.

Example
public class NonPrimitiveDataTypes {

String str;
public static void main(String[] args) {

String name = "BTech Smart Class!";

String wish = "Hello, ";

NonPrimitiveDataTypes obj = new NonPrimitiveDataTypes();

System.out.println("str = " + obj.str);

//using addition method


System.out.println(wish.concat(name));
}
}

When we run the above example code, it produces the following output.

Primitive Vs Non-primitive Data Types


Primitive Data Type Non-primitive Data Type
These are built-in data types These are created by the users

Does not support additional methods Support additional methods

Always has a value It can be null

Starts with lower-case letter Starts with upper-case letter

Size depends on the data type Same size for all

5.Variables
Defination:-A variable is a named memory location used to store a data value. A
variable can be defined as a container that holds a data value.A variable is assigned
with a data type.
In java, we use the following syntax to create variables.
Syntax
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;

Variable Naming Rules


A variable can have a short name (like x and y) or a more descriptive name
(age, price, carname, etc.).
Go variable naming rules:
 A variable name must start with a letter or an underscore character (_)
 A variable name cannot start with a digit
 A variable name can only contain alpha-numeric characters and
underscores (a-z, A-Z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three
different variables)
 There is no limit on the length of the variable name
 A variable name cannot contain spaces
 The variable name cannot be any Go keywords
 Beginning with a letter, the dollar sign " $ ", or the underscore character " _ ".
The convention, however, is to always begin your variable names with a letter,
not " $ " or " _ ".

Multi-Word Variable Names


Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
In java programming language variables are classified as follows.
 Local variables
 Instance variables or Member variables or Global variables
 Static variables or Class variables
 Final variables
Local variables
The variables declared inside a method or a block are known as local variables. A
local variable is visible within the method in which it is declared. The local variable is
created when execution control enters into the method or block and destroyed after
the method or block execution completed.
Let's look at the following example java program to illustrate local variable in java.
Scope:-With in block or method the variables are visible and access
Life Time:-
The variable life time is ended if method body execution is completed.
Ex:-
public class LocalVariables {public void show() {
int a = 10;
//static int x = 100;
System.out.println("Inside show method, a = " + a);
}
public void display() { //method scope
int b = 20;
System.out.println("Inside display method, b = " + b);
// trying to access variable 'a' - generates an ERROR
//System.out.println("Inside display method, a = " + a);
}
public static void main(String args[]) {
LocalVariables obj = new LocalVariables();
obj.show();
obj.display();
}
}
Output:-
Inside show method, a = 10
Inside display method, b = 20
Instance variables or member variables or global variables
The variables declared inside a class and outside any method, constructor or block
are known as instance variables or member variables. These variables are visible to
all the methods of the class. The changes made to these variables by method affects
all the methods in the class. These variables are created separate copy for every
object of that class.
Scope:-With in class the variables are visible and access
Life Time:-
The variable life time is ended if class body execution is completed.

Let's look at the following example java program to illustrate instance variable in java.
public class InstanceVariables { //class Scope
int x = 100;// instance variable
public void show() {
System.out.println("Inside show method, x = " + x);
x = x + 100;
}
public void display() {
System.out.println("Inside display method, x = " + x);
}
public static void main(String[] args) {
InstanceVariables obj = new InstanceVariables();
obj.show();
obj.display();
}
}
OutPut:-
Inside show method, x = 100
Inside display method, x = 200
Static variables or Class variables
A static variable is a variable that declared using static keyword. The instance
variables can be static variables but local variables can not. Static variables are
initialized only once, at the start of the program execution. The static variable only has
one copy per class irrespective of how many objects we create.
The static variable is access by using class name.
Let's look at the following example java program to illustrate static variable in java.

Ex:-
public class StaticVariablesExample {int x=10, y=20; // Instance variables
static int z=30; // Static variable
public void show() {
int a; // Local variables
System.out.println("Inside show method,");
System.out.println("x = " + x + ", y = " + y + ", z = " + z);
}
public static void main(String[] args) {
StaticVariablesExample obj = new
StaticVariablesExample();
System.out.println(obj.x);
System.out.println(obj.y);
System.out.println(StaticVariablesExample.z);
obj.show();
}
}
Output:-10
20
30
Inside show method,
x = 10, y = 20, z = 30
Final variables
A final variable is a variable that declared using final keyword. The final variable is
initialized only once, and does not allow any method to change it's value again. The
variable created using final keyword acts as constant. All variables like local, instance,
and static variables can be final variables.
Let's look at the following example java program to illustrate final variable in java.
Ex:-
public class Student
{
final int id=10;
void show()
{
System.out.println(id);
id=20;//final variable can’t modify
}
public static void main(String args[]){
Student s1=new Student();
s1.show();
//System.out.println(s1.id);//printing members with a white space }
}
Output:-10

6.Scope and Life time of variables

Scope of a Variable
A variable can be declared and defined inside a class, method, or block. It defines the
scope of the variable where a variable is available to use. i.e. the visibility or
accessibility of a variable. Variable declared inside a block or method are not visible to
outside. If we try to do so, we will get a compilation error.
Example:-
class DemoScope
{ //class scope
public static void main(String args[])
{ //main method scope
int x;
x=10;
if(x==10)
{ //condition scope
int y=20;
System.out.println("X and Y:"+x+" "+y);
x=y*2;
}
//y=100;//get compilation error
System.out.println("X is:"+x);}
}
Life Time of a Variable:
The lifetime of a variable is the time during which the variable stays in memory
and is therefore accessible during program execution. The variables that are
local to a method are created the moment the method is activated and are
destroyed when the activation of the method terminates.
Ex:-
class DemoLifeTime
{
public static void main(String args[])
{
int x;
for(x=0;x<3;x++)
{
int y=-1;
System.out.println("Y is"+y);
y=20;
System.out.println("Y is "+y);
}// After loop completion y is destroyed no longer can use
}
}

7.Arrays
Java Arrays
Defination:-Array is a collection of similar type of elements which has contiguous memory location.
 An array is a collection of similar data values with a single name. An array can also be defined
as, a special type of variable that holds multiple values of the same data type at a time.
 In java, arrays are objects and they are created dynamically using new operator.
 Every array in java is organized using index values. The index value of an array starts with '0' and ends
with 'size-1'. We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
1. One Dimensional Array (or) Single Dimensional Array
2. Multi Dimensional Array

Creating an array

1.One Dimensional Array:-


In the java programming language, an array must be created using new operator and with a specific size. The
size must be an integer value but not a byte, short, or long. We use the following syntax to create an array.
Syntax to Declare an Array in Java
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in Java (Initialization)
1. arr[]=new datatype[size];

Syntax
data_type array_name[ ] = new data_type[size];(or)
data_type[ ] array_name = new data_type[size];
Let's look at the following example program.

Example
public class ArrayExample {
public static void main(String[] args) {
int list[] = new int[5];
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
}
}

Output:-

When we run the above example code, it produces the following output. In java, an array can also be initialized
at the time of its declaration. When an array is initialized at the time of its declaration, it need not specify the
size of the array and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.

Syntax:-
Datatype arrayname[]={value1, value2, value3,…..etc.,);

Example
int list[ ] = {10, 20, 30, 40, 50};

NullPointerException with Arrays


In java, an array created without size and initialized to null remains null only. It does not allow us to assign a
value. When we try to assign a value it generates a NullPointerException.
Look at the following example program.

Example
public class ArrayExample {
public static void main(String[] args) {
short list[] = null;list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
When we run the above example code, it produces the following output.

ArrayIndexOutOfBoundsException with Arrays


In java, the JVM (Java Virtual Machine) throws ArrayIndexOutOfBoundsException when an array is trying
to access with an index value of negative value, value equal to array size, or value more than the array size.
Look at the following example program.

Example
public class ArrayExample {public static void main(String[] args) {
short list[] = {10, 20, 30};
list[4] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
When we run the above example code, it produces the following output.
Looping through an array
An entire array is accessed using either simple for statement or for-each statement. Look at the following
example program to display sum of all the elements in a list.

Example
import java.util.Scanner;
public class ArrayExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int size, sum = 0;
System.out.print("Enter the size of the list: ");
size = read.nextInt();
short list[] = new short[size];
System.out.println("Enter any " + size + " numbers: ");
for(int i = 0; i < size; i++) // Simple for statement
list[i] = read.nextShort();
for(int i : list) // for-each statement
sum = sum + i;
System.out.println("Sum of all elements: " + sum);
}
}
When we run the above example code, it produces the following output.

2. Multidimensional Array
2.1 Two Dimensional Array:-
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3- dimensional, or any
dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array variable, specify each
additional index using another set of square brackets. We use the following syntax to create two-dimensional
array.
Syntax to Declare Multidimensional Array in Java
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java

Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When we create a two-dimensional array, it created with a separate index for rows and columns.
The individual element is accessed using the respective row index followed by the column index. A
multidimensional array can be initialized while it has created using the following syntax.
Syntax
data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};
When an array is initialized at the time of declaration, it need not specify the size of the array and use of the
new operator. Here, the size is automatically decided based on the number of values that are initialized.

Example
int[][] arr=new int[3][3];//3 row and 3 column
int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};
The above statement creates a two-dimensional array of three rows and two columns.

Example Program:-
public class Multidimensional {
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}Out Put:-
123
245
445

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In
other words, it is an array of arrays with different number of columns.

Syntax:-
Data_type array_name[][]=new data_type[n][];\\ n means number
of rows
array_name[]=new datatype[n1];\\n1 means number of columns
(or)
Int arr_name[][]={{value1,value2},{value1,value2,value3}};
Ex:-
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];

Example Program:-
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
//printing the data of a jagged array
for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" "); }
System.out.println();//new line
}
}
}

Out Put:-
012
3456
78
Addition of 2 Matrices in Java
Let's see a simple example that adds two matrices.
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}

Output:
268
6 8 10

Multiplication of 2 Matrices in Java


In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of the
second matrix which can be understood by the image given below.
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
//Java Program to multiply two matrices
public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){ for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}

Output:
6 6 6
12 12 12
18 18 18

Three Dimensional Array(3D Array):-


An array with three indexes (subscripts) is called three dimensional array in java.
In other words, a three-dimensional array is a collection of one or more two-dimensional arrays, all
of which share a common name.
The general syntax to declare 3D array in java is as follows:
data-type[ ][ ][ ] variableName;
variableName = new data-type[size1][size2][size3];
Or,
data-type[ ][ ][ ] variableName = new data-type[size1][size2][size3];

Example:-
int[ ][ ][ ] x = new int[2][3][4];
For example:
x[0][0][0] refers to the data in the first table, first row, and first column.
x[1][0][0] refers to the data in the second table, first row, and first column.
x[1][2][3] refers to the data in the second table, thrid row, and fourth
column.
Example program:-
package arraysProgram;
public class ThreeDArray {
public static void main(String[] args)
{
int[ ][ ][ ] x;
x = new int[3][3][3];
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
for(int k = 0; k < 3; k++)
x[i][j][k] = i + 1;
}
for(int i = 0; i < 3; i++)
{
System.out.println("Table-" +(i + 1));
for(int j = 0; j < 3; j++)
{
for(int k = 0; k < 3; k++)
System.out.print(x[i][j][k] +" ");System.out.println();
}
System.out.println();
}
}
}

Out Put:-
Table-1
111
111
111
Table-2
222
222
222
Table-3
333
333
333

8.Operators
An Operator is a symbol that performs an operation. An operator acts on some variables, called operands to
get the desired result, For example: +, -, *, / etc.
There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Bitwise Operator,
o Assignment Operator,
o Relational Operator,
o Logical Operator,
o Ternary Operator and
o Special Operator.

1.Unary Operator: -
The Java unary operators require only one operand. Unary operators are used to perform various operations.

Operator Type Category Meaning Operator

Unary postfix Post-Increment Operator ( expr++ )

Post-Decrement Operator ( expr--)

prefix Pre-Increment Operator (++expr)

Pre-Decrement Operator (--expr)

Unary Plus +expr

Unary Minus -expr


Negating an expression ~
Bitwise Not complement

Logical or boolean !

Example:-
class UnaryOperator
{
public static void main(String args[])
{
int a=10,b=-5,d=10;
boolean c=true;
System.out.println(a);//10
System.out.println(a++);//10(11)
System.out.println(++a);//12
System.out.println(a--);//12(11)
System.out.println(--a);//10
System.out.println(~d);//-11
System.out.println(~b);//4
System.out.println(!c);//false
System.out.println(!c);//false
}
}
2.Arithmetic Operators:
In java, arithmetic operators are used to performing basic mathematical operations like addition, subtraction,
multiplication, division, modulus, increment, decrement, etc.,

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2

% Modulus - Remainder of the Division 5%2=1

Example:-

public class ArithmeticOperator{


public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
System.out.println(10*10/5+3-1*4/2); //21
System.out.println(10*10/5+(3-1)*4/2); //24
}}
3.Bitwise Operator:- The bitwise operators are used to perform bit-level operations in the
java programming language. When we use the bitwise operators, the operations are performed
based on binary values.

Operator Type Operator meaning Operator


Bitwise Bitwise complement ~
Bitwise And &
Bitwise Inclusive OR |
Bitwise Exclusive or(xor) ^
Bitwise Left Shift <<
Bitwise Right Shift >>
Bitwise Zero Fill Right Shift >>>
Operator

Ex:-
public class BitwiseOperator{
public static void main(String args[]){
int a=5;
int b=6;
int c=2;
int d=-2;
System.out.println(a&b);//4
System.out.println(a|b);//7
System.out.println(a^b);//3
System.out.println(a<<c);//20 5*2^2=5*4=20
System.out.println(a>>c);//1 5/2^2=5/4=1
System.out.println(d>>c);-1
System.out.println(a>>>c);//1
System.out.println(d>>>c);//1073741823
}
}

Assignment Operator:-
The operator is used to store some value into a variable .
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable (Lvalue).
The assignment operator is used in different variants along with arithmetic operators. The following table
describes all the assignment operators in the java programming language.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

Assignment operator

+= Add both left and right-hand side values and store the result into left-hand side variable A += 10

Addition assignment operator

-= Subtract right-hand side value from left-hand side variable value and store the result into left- A -= B
hand side variable

Subtraction assignment operator


*= Multiply right-hand side value with left-hand side variable value and store the result into left- A *= B
hand side variable

Multiplication assignment operator

/= Divide left-hand side variable value with right-hand side variable value and store the result A /= B
into the left-hand side variable

division

%= Divide left-hand side variable value with right-hand side variable value and store the A %= B
remainder into the left-hand side variable

modulus

&= Logical AND assignment -

|= Logical OR assignment -

^= Logical XOR assignment -

Ex:-
public class UnaryOperator{
public static void main(String args[]){
int a=10,b=10;
System.out.println(a+=b);//20
System.out.println(a-=b);//10
System.out.println(a*=b);//100
System.out.println(a/=b);//10
System.out.println(a%=b);//0
System.out.println(a&=b);//0
System.out.println(a|=b);10
System.out.println(a^=b);0
}
}

Relational Operators (<, >, <=, >=, ==, !=)


The relational operators are the symbols that are used to compare two values. That means the relational operators
are used to check the relationship between two values. Every relational operator has two posible results either
TRUE or FALSE. In simple words, the relational operators are used to define conditions in a program. The following
table provides information about relational operators.

Operator Meaning Example

< Returns TRUE if the first value is smaller than second value otherwise returns FALSE 10 < 5 is FALSE

Greater than operator

> Returns TRUE if the first value is larger than second value otherwise returns FALSE 10 > 5 is TRUE

Less than operator

<= Returns TRUE if the first value is smaller than or equal to second value otherwise 10 <= 5 is
returns FALSE FALSE

Less than or equal to

>= Returns TRUE if the first value is larger than or equal to second value otherwise 10 >= 5 is TRUE
returns FALSE

Greater than or equal to

== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is


FALSE
Equal to operator

!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE

Not equal to operator

Ex:- public class UnaryOperator{


public static void main(String args[]){
int a=10,b=10;
System.out.println(a>b);//false
System.out.println(a<b);//false
System.out.println(a>=b);//true
System.out.println(a<=b);//true
System.out.println(a==b);//true
System.out.println(a!=b);//false
}
}

Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one condition. The
following table provides information about logical operators.

Operator Meaning Example

& Logical AND - Returns TRUE if all conditions are TRUE otherwise returns FALSE false & true =>
false

| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns TRUE false | true =>
true

^ Logical XOR - Returns FALSE if all conditions are same otherwise returns TRUE true ^ true =>
false

! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is !false => true
TRUE

&& short-circuit AND - Similar to Logical AND (&), but once a decision is finalized it false & true =>
does not evaluate remianing. false

|| short-circuit OR - Similar to Logical OR (|), but once a decision is finalized it does not false | true =>
evaluate remianing. true

��� The operators &, |, and ^ can be used with both boolean and integer data type values. When they are used
with integers, performs bitwise operations and with boolean, performs logical operations.

��� Logical operators and Short-circuit operators both are similar, but in case of short-circuit operators once
the decision is finalized it does not evaluate remaining expressions.

Ex:-
class Test4
{
public static void main(String args[])
{
int a=10,b=20;
System.out.println(a>b & a<b);//false
System.out.println(a>b && a<b);//false
System.out.println(a>b | a<b);//true
System.out.println(a>b || a<b);//true
System.out.println(a>b ^ a<b);//true
System.out.println(!(a>b));//true
}
}
Conditional or Ternary Operator:-
The Ternary operator is a conditional operator that decreases the length of code while performing comparisons and
conditionals. This method is an alternative for using if-else and nested if-else statements. The order of execution for this
operator is from left to right.

Syntax:(Condition) ? (Statement1) : (Statement2);

Ex:-
class Test4
{
public static void main(String args[])
{
int a=10,b=20;
int max=a>b?a:b;
System.out.println(max);
}
}
Special Operators:-
1.instanceof operator
2.Member or Dot Operator
3.Cast Operator

1.Instanceof: This operator allows us to determine that the object belongs to a particular class or
not.Ex: Person instanceof Student (Object instanceof Class)2. . (Dot) Operator: This operator
is used to access the instance variables and the methods of class objectsEx: Person.age;
Person.getdata();
3.Cast Operator:- Cast operator is used to convert one data type to other.
class Test4
{
double b=20;
int a=(int)b;
public static void main(String args[])
{
Test4 t=new Test4();
System.out.println(t instanceof Test4);
System.out.println(t.b);
System.out.println(t.a);
}
}
9. Expressions

In any programming language, if we want to perform any calculation or to frame any condition etc., we use a set
of symbols to perform the task. These set of symbols makes an expression.In the java programming language, an
expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value or
variable or address of memory location.

Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
Infix Expression

Postfix Expression

Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.

Example

Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.

Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.

Example

10.Control statements
Java Control Statements
In java, the default execution flow of a program is a sequential order. But the sequential order of execution flow
may not be suitable for all situations. Sometimes, we may want to jump from line to another line, we may want
to skip a part of the program, or sometimes we may want to execute a part of the program again and again. To
solve this problem, java provides control statements.

In java, the control statements are the statements which will tell us that in which order the instructions are getting
executed. The control statements are used to control the order of execution according to our requirements. Java
provides several control statements, and they are classified as follows.

Types of Control Statements


In java, the control statements are classified as follows.

 Selection Control Statements ( Decision Making Statements )


 Iterative Control Statements ( Looping Statements )
 Jump Statements

Let's look at each type of control statements in java.

Selection Control Statements


In java, the selection statements are also known as decision making statements or branching statements. The
selection statements are used to select a part of the program to be executed based on a condition. Java provides
the following selection statements.
 if statement
 if-else statement
 if-else-if statement
 nested if statement
 switch statement

if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements based on that
condition result. The if statement checks, the given condition then decides the execution of a block of statements.
If the condition is True, then the block of statements is executed and if it is False, then the block of statements is
ignored. The syntax and execution flow of if the statement is as follows.

Let's look at the following example java code.

Java Program
import java.util.Scanner;

public class IfStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();

if((num % 5) == 0) {
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}
System.out.println("We are outside the if-block!!!");

When we run this code, it produce the following output.

In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the condition
is evaluated to False. Then the if statement ignores the execution of its block of statements.
When we enter a number which is divisible by 5, then it produces the output as follows.
if-else statement in java
In java, we use the if-else statement to test a condition and pick the execution of a block of statements out
of two blocks based on that condition result. The if-else statement checks the given condition then decides
which block of statements to be executed based on the condition result. If the condition is True, then the
true block of statements is executed and if it is False, then the false block of statements is executed. The
syntax and execution flow of if-else statement is as follows.

Let's look at the following example java code.

Java Program
import java.util.Scanner;

public class IfElseStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();

if((num % 2) == 0) {
System.out.println("We are inside the true-block!");
System.out.println("Given number is EVEN number!!");
}
else {
System.out.println("We are inside the false-block!");
System.out.println("Given number is ODD number!!");
}

System.out.println("We are outside the if-block!!!");

When we run this code, it produce the following output.

Nested if statement in java


Writing an if statement inside another if-statement is called nested if statement. The general syntax of the
nested if-statement is as follows.
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}

Let's look at the following example java code.

Java Program
import java.util.Scanner;

public class NestedIfStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();

if (num < 100) {


System.out.println("\nGiven number is below 100");
if (num % 2 == 0)
System.out.println("And it is EVEN");
else
System.out.println("And it is ODD");
} else
System.out.println("Given number is not below 100");

System.out.println("\nWe are outside the if-block!!!");

}
When we run this code, it produce the following output.

if-else if statement in java


Writing an if-statement inside else of an if statement is called if-else-if statement. The general syntax of the
an if-else-if statement is as follows.

Syntax
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}

Let's look at the following example java code.

Java Program
import java.util.Scanner;
public class IfElseIfStatementTest {

public static void main(String[] args) {

int num1, num2, num3;


Scanner read = new Scanner(System.in);
System.out.print("Enter any three numbers: ");
num1 = read.nextInt();//10
num2 = read.nextInt();//20
num3 = read.nextInt();//30

if( num1>=num2 && num1>=num3)


System.out.println("\nThe largest number is " + num1) ;

else if (num2>=num1 && num2>=num3)


System.out.println("\nThe largest number is " + num2) ;

else

System.out.println("\nThe largest number is " + num3) ;

System.out.println("\nWe are outside the if-block!!!");

When we run this code, it produce the following output.


switch statement in java
Using the switch statement, one can select only one option from more number of options very easily. In the
switch statement, we provide a value that is to be compared with a value associated with each option.
Whenever the given value matches the value associated with an option, the execution starts from that option.
In the switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.

The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable
which is being switched.

Let's look at the following example java code.


Java Program
import java.util.Scanner;

public class SwitchStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Press any digit: ");

int value = read.nextInt();

switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}

When we run this code, it produce the following output.


��� In java, the case value of a switch statement can be a String value.

Iterative Control Statements


In java, the iterative statements are also known as looping statements or repetitive statements. The iterative
statements are used to execute a part of the program repeatedly as long as the given condition is True. Using
iterative statements reduces the size of the code, reduces the code complexity, makes it more efficient, and
increases the execution speed. Java provides the following iterative statements.

 while statement
 do-while statement
 for statement
 for-each statement

while statement in java


The while statement is used to execute a single statement or block of statements repeatedly as long as the given
condition is TRUE. The while statement is also known as Entry control looping statement. The syntax and
execution flow of while statement is as follows.
Let's look at the following example java code.

Java Program
ipublic class WhileTest {

public static void main(String[] args) {

int num = 1;

while(num <= 10) {


System.out.println(num);
num++;
}

System.out.println("Statement after while!");

When we run this code, it produce the following output.


do-while statement in java
The do-while statement is used to execute a single statement or block of statements repeatedly as long as given
the condition is TRUE. The do-while statement is also known as the Exit control looping statement. The do-
while statement has the following syntax.

Let's look at the following example java code.

Java Program
public class DoWhileTest {

public static void main(String[] args) {


int num = 1;

do {
System.out.println(num);
num++;
}while(num <= 10);

System.out.println("Statement after do-while!");

When we run this code, it produce the following output.

for statement in java


The for statement is used to execute a single statement or a block of statements repeatedly as long as the given
condition is TRUE. The for statement has the following syntax and execution flow diagram.
In for-statement, the execution begins with the initialization statement. After the initialization statement, it
executes Condition. If the condition is evaluated to true, then the block of statements executed otherwise it
terminates the for-statement. After the block of statements execution, the modification statement gets executed,
followed by condition again.
Let's look at the following example java code.

Java Program
public class ForTest {

public static void main(String[] args) {

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


System.out.println("i = " + i);
}

System.out.println("Statement after for!");


}

When we run this code, it produce the following output.


for-each statement in java
The Java for-each statement was introduced since Java 5.0 version. It provides an approach to traverse through
an array or collection in Java. The for-each statement also known as enhanced for statement. The for-each
statement executes the block of statements for each element of the given array or collection.
��� In for-each statement, we can not skip any element of given array or collection.

The for-each statement has the following syntax and execution flow diagram.
Let's look at the following example java code.

Java Program
public class ForEachTest {

public static void main(String[] args) {

int[] arrayList = {10, 20, 30, 40, 50};

for(int i : arrayList) {
System.out.println("i = " + i);
}

System.out.println("Statement after for-each!");


}

When we run this code, it produce the following output.


Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the next iteration. Java
provides the following jump statements.

 break
 continue
 return

break statement in java


The break statement in java is used to terminate a switch or looping statement. That means the break statement
is used to come out of a switch statement and a looping statement like while, do-while, for, and for-each.
��� Using the break statement outside the switch or loop statement is not allowed.

The floowing picture depictes the execution flow of the break statement.
Let's look at the following example java code.

Java Program
public class JavaBreakStatement {

public static void main(String[] args) {

int list[] = {10, 20, 30, 40, 50};

for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}

When we run this code, it produce the following output.


continue statement in java
The continue statement is used to move the execution control to the beginning of the looping statement. When
the continue statement is encountered in a looping statement, the execution control skips the rest of the statements
in the looping block and directly jumps to the beginning of the loop. The continue statement can be used with
looping statements like while, do-while, for, and for-each.
When we use continue statement with while and do-while statements, the execution control directly jumps to the
condition. When we use continue statement with for statement the execution control directly jumps to the
modification portion (increment/decrement/any modification) of the for loop. The continue statement flow of
execution is as shown in the following figure.

Let's look at the following example java code.

Java Program
public class JavaContinueStatement {

public static void main(String[] args) {

int list[] = {10, 20, 30, 40, 50};

for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
}

When we run this code, it produce the following output.

Labelled break and continue statement in java


The java programming langauge does not support goto statement, alternatively, the break and continue statements
can be used with label.
The labelled break statement terminates the block with specified label. The labbeled continue statement takes the
execution control to the beginning of a loop with specified label.
Let's look at the following example java code.

Java Program
import java.util.Scanner;

public class JavaLabelledStatement {


public static void main(String args[]) {

Scanner read = new Scanner(System.in);

reading: for (int i = 1; i <= 3; i++) {


System.out.print("Enter a even number: ");
int value = read.nextInt();

verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + (4-i)*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more options...");

continue reading;
}
}
}
}

When we run this code, it produce the following output.


return statement in java
In java, the return statement used to terminate a method with or without a value. The return statement takes the
execution control to the calling function. That means the return statement transfer the execution control from
called function to the calling function by carrying a value.
��� Java allows the use of return-statement with both, with and without return type methods.

In java, the return statement used with both methods with and without return type. In the case of a method with
the return type, the return statement is mandatory, and it is optional for a method without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is used without a
return type, it does not carry any value. Instead, simply transfers the execution control.
Let's look at the following example java code.

Java Program
import java.util.Scanner;
public class JavaReturnStatementExample {

int value;
int readValue() {
Scanner read = new Scanner(System.in);

System.out.print("Enter any number: ");


return value=read.nextInt();
}

void showValue(int value) {


for(int i = 0; i <= value; i++) {
if(i == 5)
return;
System.out.println(i);
}
}

public static void main(String[] args) {

JavaReturnStatementExample obj = new JavaReturnStatementExample();

obj.showValue(obj.readValue());

}
}

When we run this code, it produce the following output.


11.Type conversion and casting
The two terms type casting and the type conversion are used in a program to convert one data type to another
data type. The conversion of data type is possible only by the compiler when they are compatible with each other.
Let's discuss the difference between type casting and type conversion in any programming language.

What is a type casting?(or) Narrowing conversion


When a data type is converted into another data type by a programmer or user while writing a program code of
any programming language, the mechanism is known as type casting. The programmer manually uses it to
convert one data type into another. It is used if we want to change the target data type to another data type.
Remember that the destination data type must be smaller than the source data type. Hence it is also called a
narrowing conversion.

Double->float->long->int->char->short->byte

Syntax:

1. Destination_datatype = (target_datatype) variable;


2. (data_type) it is known as casting operator

Target_datatype: It is the data type in which we want to convert the destination data type. The variable defines
a value that is to be converted in the target_data type. Let's understand the concept of type casting with an
example.

Suppose, we want to convert the float data type into int data type. Here, the target data type is smaller than the
source data because the size of int is 4 bytes, and the size of the float data type is 8 bytes. And when we change
it, the value of the float variable is truncated and convert into an integer variable. Casting can be done with a
compatible and non-compatible data type.

1. float b = 3.0;
2. int a = (int) b; // converting a float value into integer

Let's understand the type casting through a java program.

AreaOfRectangle.java

() is Cast operator
Datatype variable=(target-type)variable;
Java Variable example:Narrowing (typecasting)
Class Simple
{
Public static void main(String args[])
{
float f=10.5f;
Int a=(int)f;
System.out.println(a);
System.out.println(f);
}
}
o/p:-
10.5
10

What is type conversion?(or) widening conversion


If a data type is automatically converted into another data type at compile time is known as type conversion. The
conversion is performed by the compiler if both data types are compatible with each other. Remember that the
destination data type should not be smaller than the source type. It is also known as widening conversion of the
data type.

Byte->short->char->int->long->float->double

Let's understand the type conversion with an example.

Suppose, we have an int data type and want to convert it into a float data type. These are data types compatible
with each other because their types are numeric, and the size of int is 4 bytes which is smaller than float data
type. Hence, the compiler automatically converts the data types without losing or truncating the values.

1. int a = 20;
2. Float b;
3. b = a; // Now the value of variable b is 20.000 /* It defines the conversion of int data type to float data type without losin
g the information. */

In the above example, the int data type is converted into the float, which has a larger size than int, and hence it
widens the source data type.

Let's understand type conversion through a java program.

Class Simple
{
Public static void main(String args[])
{
Int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
o/p:
10
10.0
Note:
1.For widening conversions,the numeric types,including integer and floating-point types are compatible with each other.
2.No automatic conversions from the numeric types to char or Boolean. also, char and Boolean are not compatible with
each other.

Difference Between Type Casting and Type Conversion


S.N. Type Casting Type Conversion

1 Type casting is a mechanism in which one data Type conversion allows a compiler to convert one data type
type is converted to another data type using a to another data type at the compile time of a program or code.
casting () operator by a programmer.

2 It can be used both compatible data type and Type conversion is only used with compatible data types, and
incompatible data type. hence it does not require any casting operator.

3 It requires a programmer to manually casting one It does not require any programmer intervention to convert
data into another type. one data type to another because the compiler automatically
compiles it at the run time of a program.
4 It is used while designing a program by the It is used or take place at the compile time of a program.
programmer.

5 When casting one data type to another, the When converting one data type to another, the destination
destination data type must be smaller than the type should be greater than the source data type.
source data.

6 It is also known as narrowing conversion because It is also known as widening conversion because one smaller
one larger data type converts to a smaller data data type converts to a larger data type.
type.

7 It is more reliable and efficient. It is less efficient and less reliable.

8 There is a possibility of data or information being In type conversion, data is unlikely to be lost when
lost in type casting. converting from a small to a large data type.

8 float b = 3.0; int x = 5, y = 2, c;


int a = (int) b float q = 12.5, p;
p = q/x;

12.Simple Java programs


1.Fibonacci series in Java
In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
etc. The first two numbers of fibonacci series are 0 and 1.

Example:-
1. class FibonacciExample1{
2. public static void main(String args[])
3. {
4. int n1=0,n2=1,n3,i,count=10;
5. System.out.print(n1+" "+n2);//printing 0 and 1
6.
7. for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
8. {
9. n3=n1+n2;
10. System.out.print(" "+n3);
11. n1=n2;
12. n2=n3;
13. }
14.
15. }}
Output:-

0 1 1 2 3 5 8 13 21 34

2.Right Triangle Star Pattern

1. public class RightTrianglePattern


2. {
3. public static void main(String args[])
4. {
5. //i for rows and j for columns
6. //row denotes the number of rows you want to print
7. int i, j, row=6;
8. //outer loop for rows
9. for(i=0; i<row; i++)
10. {
11. //inner loop for columns
12. for(j=0; j<=i; j++)
13. {
14. //prints stars
15. System.out.print("* ");
16. }
17. //throws the cursor in a new line after printing each line
18. System.out.println();
19. }
20. }
21. }
Output:-
3.Program to print the duplicate elements of an array
In this program, we need to print the duplicate elements present in the array. This can be done through two loops.
The first loop will select an element and the second loop will iteration through the array by comparing the selected
element with other elements. If a match is found, print the duplicate element.

In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2) present
at index 1. So, duplicate elements in the above array are 2, 3 and 8.

Output:-

1. public class DuplicateElement {


2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
5. System.out.println("Duplicate elements in given array: ");
6. //Searches for duplicate element
7. for(int i = 0; i < arr.length; i++) {
8. for(int j = i + 1; j < arr.length; j++) {
9. if(arr[i] == arr[j])
10. System.out.println(arr[j]);
11. }
12. }
13. }
14. }

Output:-
Duplicate elements in given array:
2
3
8

4.Java Program to count the total number of vowels and consonants in


a string
In this program, our task is to count the total number of vowels and consonants present in the given string.
As we know that, the characters a, e, i, o, u are known as vowels in the English alphabet. Any character other
than that is known as the consonant.

To solve this problem, First of all, we need to convert every upper-case character in the string to lower-case so
that the comparisons can be done with the lower-case vowels only not upper-case vowels, i.e.(A, E, I, O, U).
Then, we have to traverse the string using a for or while loop and match each character with all the vowels, i.e.,
a, e, i, o, u. If the match is found, increase the value of count by 1 otherwise continue with the normal flow of the
program.

Example:-
1. public class CountVowelConsonant {
2. public static void main(String[] args) {
3.
4. //Counter variable to store the count of vowels and consonant
5. int vCount = 0, cCount = 0;
6.
7. //Declare a string
8. String str = "This is a really simple sentence";
9.
10. //Converting entire string to lower case to reduce the comparisons
11. str = str.toLowerCase();
12.
13. for(int i = 0; i < str.length(); i++) {
14. //Checks whether a character is a vowel
15. if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')
{
16. //Increments the vowel counter
17. vCount++;
18. }
19. //Checks whether a character is a consonant
20. else if(str.charAt(i) >= 'a' && str.charAt(i)<='z') {
21. //Increments the consonant counter
22. cCount++;
23. }
24. }
25. System.out.println("Number of vowels: " + vCount);
26. System.out.println("Number of consonants: " + cCount);
27. }
28. }
Output:-
Number of vowels: 10
Number of consonants: 17
13.Concepts of Classes:-
Definition: - A class is a template or blueprint from which you can create an individual
object. Class doesn’t consume any space. It is logical entity.
Ex:-Car

A class in java can contain:


vi. Fields or variables
vii. Methods
viii. Constructors
ix. Blocks
x. Nested class and interface
Syntax to declare a class:-
access_modifier class<class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
A class is a user-defined blueprint or prototype from which objects are created. It represents the set
of properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:

7. Modifiers: A class can be public or has default access.


8. Class keyword: class keyword is used to create a class.
9. Class name: The name should begin with an initial letter (capitalized by convention).
10. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
11. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
12. Body: The class body is surrounded by braces, { }.

Example Program:-

public class Car


{
String color;
int weight;
int speed;
String model;
void startCar()
{
System.out.println("car Started");
}
void changeGear()
{
System.out.println("Gear Changed");
}
void slowDown()
{
System.out.println("Going slowly");
}
void brake()
{
System.out.println("Sudden Brake");
}
}
14.Object: -
Definition: - Object is a real world entity that we can touch physically is
referred as object such as a pen, chair, table, computer, watch, etc., Object
is an instance of a class. Each entity will be having its own state and
behavior and it is referring as an object. An object contains an address and
takes up some space in memory.
Example:-
Objects of the class car can be BMW, Mercedes, Ferrari, etc.

New:-
The new keyword is used to allocate memory at runtime. All objects get memory in heap memory area.

Syntax:-
<class_name> <object_name>=new <class_name>();
(Or)
<class_name> <object_name>;
<object_name>=new <class_name>();

Example Creating Object for Car:-


Car BMW=new BMW();
Car Ferrari=new Ferrari();
(or)
Car BMW; //creating BMW reference variable for class Car in stack memory
BMW=new BMW(); //now BMW object is created in heap memory

Example Program creating Objects and Class:-

class Car
{
String color="red";
int weight=50;
int speed=100;
String model="1";
void startCar()
{
System.out.println("car Started");
}
void changeGear()
{
System.out.println("Gear Changed");
}
void slowDown()
{
System.out.println("Going slowly");
}
void brake()
{
System.out.println("Sudden Brake");
}
public static void main(String args[])// objects are always create in main method because JVM is
executed main method directly
{
Car bmw=new Car();
Car ferrari;
ferrari=new Car();
System.out.println(bmw.color);//calling variable
ferrari.color="block";//initializing a value through object
System.out.println(ferrari.color);
bmw.startCar();//calling method
ferrari.startCar();
}
}
Output:-
red
block
car Started
car Started
15.Constructors
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides
a default constructor by default.

Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have
any.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other words, we
can have private, protected, public or default constructor in Java.

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor
3. Copy Constructor

Java Default Constructor


A constructor that has no parameters is known as default the constructor. A default constructor is invisible.
And if we write a constructor with no arguments, the compiler does not create a default constructor. It is taken
out. It is being overloaded and called a parameterized constructor. The default constructor changed into the
parameterized constructor. But Parameterized constructor can’t change the default constructor.

Syntax of default constructor:


1. Access modifier <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.

1. //Java Program to create and call a default constructor


2. class Bike1{
3. //creating a default constructor
4. Bike1(){
5. System.out.println("Bike is created");
6. }
7. //main method
8. public static void main(String args[]){
9. //calling a default constructor
10. Bike1 b=new Bike1();
11. }
12. }
Test it Now

Output:

Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.

Example of default constructor that displays the default values


1. //Let us see another example of default constructor
2. //which displays the default values
3. class Student3{
4. int id;
5. String name;
6. //method to display the value of id and name
7. void display(){System.out.println(id+" "+name);}
8.
9. public static void main(String args[]){
10. //creating objects
11. Student3 s1=new Student3();
12. Student3 s2=new Student3();
13. //displaying values of the object
14. s1.display();
15. s2.display();
16. }
17. }
Test it Now

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor. Here 0 and null values are provided by default constructor.
Java Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the
class with our own values, then use a parameterized constructor.
Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you can provide
the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We can have any
number of parameters in the constructor.

1. //Java Program to demonstrate the use of the parameterized constructor.


2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. s1.display();
19. s2.display();
20. }
21. }
Test it Now

Output:

111 Karan
222 Aryan

3.Copy Constructor

Unlike other constructors copy constructor is passed with another object which copies the data available from
the passed object to the newly created object.
1. import java.io.*;

2. class Geek {
3. // data members of the class.
4. String name;
5. int id;

6. // Parameterized Constructor
7. Geek(String name, int id)
8. {
9. this.name = name;
10. this.id = id;
11. }

12. // Copy Constructor


13. Geek(Geek obj2)
14. {
15. this.name = obj2.name;
16. this.id = obj2.id;
17. }
18. }
19. class GFG {
20. public static void main(String[] args)
21. {
22. // This would invoke the parameterized constructor.
23. System.out.println("First Object");
24. Geek geek1 = new Geek("avinash", 68);
25. System.out.println("GeekName :" + geek1.name + " and GeekId :" + geek1.id);

26. System.out.println();

27. // This would invoke the copy constructor.


28. Geek geek2 = new Geek(geek1);
29. System.out.println("Copy Constructor used Second Object");
30. System.out.println("GeekName :" + geek2.name + " and GeekId :" + geek2.id);
31. }
32. }
OutPut:-

First Object
GeekName :avinash and GeekId :68

Copy Constructor used Second Object


GeekName :avinash and GeekId :68

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one constructor with different parameter lists.
They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler
by the number of parameters in the list and their types.
Example of Constructor Overloading
1. //Java program to overload constructors
2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }
Test it Now

Output:

111 Karan 0
222 Aryan 25

Difference between constructor and method in Java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the behavior of an
object.
A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you don't have The method is not provided by the compiler
any constructor in a class. in any case.

The constructor name must be same as the class name. The method name may or may not be same as
the class name.

Q) Does constructor return any value?


Yes, it is the current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?


Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the constructor
as you perform in the method.

Is there Constructor class in Java?


Yes.

What is the purpose of Constructor class?


Java provides a Constructor class which can be used to get the internal information of a constructor in the class.
It is found in the java.lang.reflect package.

16.Methods
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to perform a certain
task or operation. It is used to achieve the reusability of code. We write a method once and use it many times.
We do not require to write code again and again. It also provides the easy modification and readability of code,
just by adding or removing a chunk of code. The method is executed only when we call or invoke it.

The most important method in Java is the main() method.


Method Declaration
The method declaration provides information about method attributes, such as visibility, return-type, name, and
arguments. It has six components that are known as method header, as we have shown in the following figure.

Method Signature: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the
method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same package or subclasses
in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by
default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method
name must be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed
within the pair of curly braces.

Naming a Method
While defining a method, remember that the method name must be a verb and start with a lowercase letter. If
the method name has more than two words, the first name must be a verb followed by adjective or noun. In the
multi-word method name, the first letter of each word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

It is also possible that a method has the same name as another method name in the same class, it is known
as method overloading.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method

 Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related
to the corresponding method runs in the background that is already stored in the library.

Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }

Output:

The maximum number is: 9

In the above example, we have used three predefined methods main(), print(), and max(). We have used these
methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class that
returns the greater of two numbers.
In the above method signature, we see that the method signature has access specifier public, non-access
modifier static, return type int, method name max(), parameter list (int a, int b). In the above example, instead
of defining the method, we have just invoked the method. This is the advantage of a predefined method. It makes
programming less complicated.

Similarly, we can also see the method signature of the print() method.

 User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are modified
according to the requirement.

How to Create a User-defined Method

You can create methods in 3 ways


1. Instance Method
2. Static Method
3. Abstract Method

The method of the class is known as an instance method. It is a non-static method defined in the class. Before
calling or invoking the instance method, it is necessary to create an object of its class. Let's see an example of an
instance method.

Let's create a user defined method that checks the number is even or odd. First, we will define the method.

1. //user defined method


2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }

We have defined the above method named findevenodd(). It has a parameter num of type int. The method does
not return any value that's why we have used void. The method body contains the steps to check the number is
even or odd. If the number is even, it prints the number is even, else prints the number is odd.

How to Call or Invoke a User-defined Method

Once we have defined a method, it should be called. The calling of a method in a program is simple. When we
call or invoke a user-defined method, the program control transfer to the called method.

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from the user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }

In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control transfer to the
method and gives the output accordingly.

Let's combine both snippets of codes in a single program and execute it.

EvenOdd.java

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. EvenOdd e=new EvenOdd ();
7. //creating Scanner class object
8. Scanner scan=new Scanner(System.in);
9. System.out.print("Enter the number: ");
10. //reading value from user
11. int num=scan.nextInt();
12. //method calling
13. e.findEvenOdd(num);
14. }
15. //user defined method
16. public void findEvenOdd(int num)
17. {
18. //method body
19. if(num%2==0)
20. System.out.println(num+" is even");
21. else
22. System.out.println(num+" is odd");
23. }
24. }

Output 1:

Enter the number: 12


12 is even

Output 2:

Enter the number: 99


99 is odd

Let's see another program that return a value to the calling method.

In the following program, we have defined a method named add() that sum up the two numbers. It has two
parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value of a and b, respectively.
Therefore, the method adds the value of a and b and store it in the variable s and returns the sum.

Addition.java

1. public class Addition


2. {
3. public int add(int n1, int n2) //n1 and n2 are formal parameters
4. {
5. int s;
6. s=n1+n2;
7. return s; //returning the sum
8. }

9. public static void main(String[] args)


10. {
11. Addition s=new Addition();
12. int a = 19;
13. int b = 5;
14. //method calling
15. int c = s.add(a, b); //a and b are actual parameters
16. System.out.println("The sum of a and b is= " + c);
17. }
18. //user defined method
19. }

Output:

The sum of a and b is= 24

There are two types of instance method:

o Accessor Method
o Mutator Method

Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method. We can
easily identify it because the method is prefixed with the word get. It is also known as getters. It returns the value
of the private field. It is used to get the value of the private field.

Example

1. public int getId()


2. {
3. return Id;
4. }

Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can easily identify
it because the method is prefixed with the word set. It is also known as setters or modifiers. It does not return
anything. It accepts a parameter of the same data type that depends on the field. It is used to set the value of the
private field.

Example

1. public void setRoll(int roll)


2. {
3. this.roll = roll;
4. }
Example of accessor and mutator method

Student.java

1. class Student
2. {
3. private int roll;
4. public int getRoll() //accessor method
5. {
6. return roll;
7. }
8. public void setRoll(int roll) //mutator method
9. {
10. this.roll = roll;
11. }
12. public static void main(String args[])
13. {
14. Student s=new Student();
15. s.setRoll(10);
16. System.out.println(s.getRoll());
17. }
18. }
OutPut:-
10

Static Method
A method that has static keyword is known as static method. In other words, a method that belongs to a class
rather than an instance of a class is known as a static method. We can also create a static method by using the
keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object. It can access static data
members and also change the value of it. It is used to create an instance method. It is invoked by using the class
name. The best example of a static method is the main() method.

Example of static method

Display.java

1. public class Display


2. {
3. public static void main(String[] args)
4. {
5. show();
6. }
7. static void show()
8. {
9. System.out.println("It is an example of static method.");
10. }
11. }

Output:

It is an example of a static method.


Abstract Method
The method that does not has method body is known as abstract method. In other words, without an
implementation is known as abstract method. It always declares in the abstract class. It means the class itself
must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract.

Syntax

1. abstract void method_name();


Example of abstract method

Demo.java

1. abstract class Demo //abstract class


2. {
3. //abstract method declaration
4. abstract void display();
5. }
6. public class MyClass extends Demo
7. {
8. //method impelmentation
9. void display()
10. {
11. System.out.println("Abstract method?");
12. }
13. public static void main(String args[])
14. {
15. //creating object of abstract class
16. Demo obj = new MyClass();
17. //invoking abstract method
18. obj.display();
19. }
20. }

Output:

Abstract method...

17.Access control
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:


1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package through child
class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the
class, within the package and outside the package.
5.

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access within within outside package by subclass outside


Modifier class package only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

18.This keyword
‘this’ is a reference variable that refers to the current object, or can be said “this” in Java is a keyword that
refers to the current object instance. It can be used to call current class methods and fields, to pass an instance
of the current class as a parameter, and to differentiate between the local and instance variables. Using “this”
reference can improve code readability and reduce naming conflicts.

Usage of Java this keyword


Here is given the 6 usage of java this keyword.
Proving this keyword
Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the
reference variable and this, output of both variables are same.

1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. System.out.println(obj);//prints the reference ID
8. obj.m();
9. }
10. }
Test it Now

Output:

A5@22b3ea59
A5@22b3ea59

1) this can be used to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance
variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. s1.display();
16. }}
Test it Now

Output:

0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we are using this
keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword(write on exam this example program only)
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10.
11. class TestThis2{
12. public static void main(String args[]){
13. Student s1=new Student(111,"ankit",5000f);
14. s1.display();
15. }}
Test it Now

Output:

111 ankit 5000.0


112 sumit 6000.0

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like
in the following program:

Program where this keyword is not required


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int r,String n,float f){
6. rollno=r;
7. name=n;
8. fee=f;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis3{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now

Output:

111 ankit 5000.0


112 sumit 6000.0
It is better approach to use meaningful names for variables. So we use same name for instance variables and
parameters in real time, and always use this keyword.

2.This can be used to invoke current class method:-


this keyword can be used to invoke the method of the current class. Let’s understand that with the help of an
example.

public class Addition


{
void m()
{
System.out.println("welcome");
}
void m1()
{
this.m();
//m(); this also work
//but this keyword only use instance method
//this keyword not supported static methods
System.out.println("Anusha");
}
public static void main(String args[])
{
Addition a=new Addition();
a.m1();
}
}
Output:-
Welcome
Anusha
3.This can be Passed as an argument in the method call

this keyword can be used inside the method in order to call another method from same class. Below example
demonstrates the same.

1. class Simple{
2. int a=10;
3. void m1(Simple s1)
4. {
5. System.out.println(s1.a);
6. }
7. void m2()
8. {
9.
//Simple s=new Simple();
//m1(Simple s2);
10. m1(this);
11. System.out.println("hello");
12. }
13. public static void main(String args[])
14. {
15. //int a=10;
16. Simple s=new Simple();
17. s.m2();

18. }
19. }

Output:-
10
Hello

4. this keyword can be used to return the current class instance


Here, you can return this keyword as a statement from the method. In this case, return type of the method must be the
class type. Let’s understand this with the help of an example.

class Simple{

int m1()
{
int a=10;
return a;
}
float m2()
{
float b=2.5f;
return b;
}
Simple m3()
{
//Simple s3=new Simple();
//return s3;
return this;
}
public static void main(String args[])
{
//int a=10;
Simple s=new Simple();
System.out.println(s.m1());
System.out.println(s.m2());
System.out.println(s.m3());
}
}

Output:-
10
2.5
practice.Simple@19e0bfd

5.this keyword can be used to invoke a constructor


this() constructor call can be used to call the current class constructor. It can be also used to reuse the constructor. You
can also call this technique as constructor chaining. Let’s take a small example and understand how this() is used.

1. class Test {
2. int a;
3. int b;

4. // Default constructor
5. Test()
6. {
7. this(10, 20);//calling parameterized constructor
8. System.out.println("Inside default constructor \n");
9. }

10. // Parameterized constructor


11. Test(int a, int b)
12. {
13. this.a = a;
14. this.b = b;
15. System.out.println("Inside parameterized constructor");
16. }

17. public static void main(String[] args)


18. {
19. Test object = new Test();
20. }
21. }
Output:-
Inside parameterized constructor
Inside default constructor

6.this keyword is used as an argument in the constructor call


You can pass this keyword in the constructor also. It is useful if you have to use one object in multiple classes.
Now let’s understand the same with the help of an example.

1. class Simple{
2. Simple()
3. {
// Simple s2=new Simple();
// Test t=new Test(s2);
4.
Test t=new Test(this);
System.out.println(this);
5. }
6. public static void main(String args[])
7. {

Simple s=new Simple();

8. }
9. }
10. class Test{
11. Simple obj;
12. Test(Simple s1)
13. {
obj=s1;
System.out.println(obj);
14. }
15. }
Output:-
Simple@19e0bfd
Simple@19e0bfd

Garbage collection
 In java, garbage means unreferenced objects
 Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it
is a way to destroy the unused objects.
To achieve this we can use
 free() function in C language and Delete() in C++
But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

 How to unreferenced object?


There are 3 ways to unreferenced object
1.By nulling the reference
Ex:- Animal a=new Animal();
a=null;
2. By assigning a reference to another
Ex:- Animal a1=new Animal();
Animal a2=new Animal();
a1=a2;
3.By anonymous object
Ex:- new Animal();

 Finalize() method
It is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.
This method is defined in Object class as
Protected void finalize(){}
 gc() method
It is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
It is static method which is used to call finalize before destroying the object.
public static void gc(){}

 Example Program:-
class Animal
{
Animal(){
System.out.println("Object is created");
}
protected void finalize()
{
System.out.println("Object is destroyed");
}
}
class AnimalDemo
{
public static void main(String args[])
{
Animal a=new Animal();
a=null;//1.By assigning a null
Animal a1=new Animal();
Animal a2=new Animal();
a1=a2;//2. By assigning reference to another
new Animal();//By anonymous object
System.gc();
}
}
Output:-
Object is created
Object is created
Object is created
Object is created
Object is destroyed
Object is destroyed
Object is destroyed
20.Overloading methods
Defination:-
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Note:- In Java, Method Overloading is not possible by changing the return type of the method only.
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two numbers and second
add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Test it Now

Output:

22
33
Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method receives two integer
arguments and second add method receives two double arguments.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Test it Now

Output:

22
24.9

21.Parameter passing
There are different ways in which parameter data can be passed into and out of methods and
functions. Let us assume that a function B() is called from another function A(). In this case A is
called the “caller function” and B is called the “called function or callee function”. Also, the
arguments which A sends to B are called actual arguments and the parameters of B are called formal
arguments.
Types of parameters:
Formal Parameter: A variable and its type as they appear in the prototype of the function or
method.
Syntax:
function_name(datatype variable_name)
Actual Parameter: The variable or expression corresponding to a formal parameter that appears in
the function or method call in the calling environment.
Syntax:
func_name(variable name(s));

Two ways passing parameters into java


1.Pass by value
2.Pass by reference

1.Pass by Value (or) call by value: In the pass by value concept, the method is called by passing a value. So, it is called
pass by value. It does not affect the original parameter.
In case of call by value original value is not changed.
Example:-

1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }

Output:
before change 50
after change 50

2.Pass by Reference (or) call by reference: In the pass by reference concept, the method is called using an alias or
reference of the actual parameter. So, it is called pass by reference. It forwards the unique identifier of the object to the
method. If we made changes to the parameter's instance member, it would affect the original value.

In case of call by reference original value is changed if we made changes in the called method. If we pass object
in place of any primitive value, original value will be changed. In this example we are passing object as a value.

Let's take a simple example:

1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7. public static void main(String args[]){
8. Operation2 op=new Operation2();
9.
10. System.out.println("before change "+op.data);
11. op.change(op);//passing object
12. System.out.println("after change "+op.data);
13.
14. }
15. }

Output:
before change 50
after change 150
Why Java does not support pass by reference concept?
Java does not support call by reference because in call by reference we need to pass the address and address are stored in
pointers n java does not support pointers and it is because pointers breaks the security. Java is always pass-by-value.

22.Recursion
a method that calls itself is known as a recursive method. And, this process is known as recursion.
A physical world example would be to place two parallel mirrors facing each other. Any object in
between them would be reflected recursively.

How Recursion works?

In the above example, we have called the recurse() method from inside the main method. (normal
method call). And, inside the recurse() method, we are again calling the same recurse method. This
is a recursive call.
In order to stop the recursive call, we need to provide some conditions inside the method.
Otherwise, the method will be called infinitely.

Hence, we use the if...else statement (or similar approach) to terminate the recursive call inside the
method.
Example: Factorial of a Number Using Recursion
class Factorial {

static int factorial( int n ) {


if (n != 0) // termination condition
return n * factorial(n-1); // recursive call
else
return 1;
}

public static void main(String[] args) {


int number = 4, result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
}
}
Run Co

Output:

4 factorial = 24

In the above example, we have a method named factorial() . The factorial() is called from
the main() method. with the number variable passed as an argument.
Here, notice the statement,

return n * factorial(n-1);

The factorial() method is calling itself. Initially, the value of n is 4 inside factorial() . During the next
recursive call, 3 is passed to the factorial() method. This process continues until n is equal to 0.
When n is equal to 0, the if statement returns false hence 1 is returned. Finally, the accumulated
result is passed to the main() method.
Working of Factorial Program
The image below will give you a better idea of how the factorial program is executed using
recursion.
Factorial Program using Recursion
23.Exploring String Class
Defination:-String is a sequence of characters. In java, objects of String are immutable which means
a constant and cannot be changed once created. String is represented by String class which is
located into java.lang package.
The Java String class implements Serializable, Comparable and CharSequence interface
that we have represented using the below image.

In Java, CharSequence Interface is used for representing a sequence of characters.


CharSequence interface is implemented by String, StringBuffer and StringBuilder
classes. This three classes can be used for creating strings in java.
What is an Immutable object?

An object whose state cannot be changed after it is created is known as an Immutable


object. String, Integer, Byte, Short, Float, Double and all other wrapper classes objects
are immutable.

 Creating a String object

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.

public class Demo{

public static void main(String[] args) {

String s1 = "Hello Java";//String Literal

System.out.println(s1);

Hello Java

2) Using new Keyword

We can create a new string object by using new operator that allocates memory for the
object.

public class Demo{

public static void main(String[] args) {

String s1 = new String("Hello Java");//new keyword

System.out.println(s1);
}

Hello Java

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

 String object and How they are stored

When we create a new string object using string literal, that string literal is added to the
string pool, if it is not present there already.

String str= "Hello";

And, when we create another object with same string, then a reference of the string literal
already present in string pool is returned.

String str2 = str;


But if we change the new string, its reference gets modified.

str2=str2.concat("world");
String Methods:-
String Methods List

Method Description

It returns char value for the particular


char charAt(int index)
index

int length() It returns string length

static String format(String format, Object...


It returns a formatted string.
args)

static String format(Locale l, String format, It returns formatted string with given
Object... args) locale.

It returns substring for given begin


String substring(int beginIndex)
index.

It returns substring for given begin


String substring(int beginIndex, int endIndex)
index and end index.

It returns true or false after matching


boolean contains(CharSequence s)
the sequence of char value.

static String join(CharSequence delimiter,


It returns a joined string.
CharSequence... elements)
static String join(CharSequence delimiter,
It returns a joined string.
Iterable<? extends CharSequence> elements)

It checks the equality of string with the


boolean equals(Object another)
given object.

boolean isEmpty() It checks if string is empty.

String concat(String str) It concatenates the specified string.

It replaces all occurrences of the


String replace(char old, char new)
specified char value.

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


new) specified CharSequence.

It compares another string. It doesn't


static String equalsIgnoreCase(String another)
check case.

String[] split(String regex) It returns a split string matching regex.

It returns a split string matching regex


String[] split(String regex, int limit)
and limit.

String intern() It returns an interned string.


int indexOf(int ch) It returns the specified char value index.

It returns the specified char value index


int indexOf(int ch, int fromIndex)
starting with given index.

int indexOf(String substring) It returns the specified substring index.

It returns the specified substring index


int indexOf(String substring, int fromIndex)
starting with given index.

String toLowerCase() It returns a string in lowercase.

It returns a string in lowercase using


String toLowerCase(Locale l)
specified locale.

String toUpperCase() It returns a string in uppercase.

It returns a string in uppercase using


String toUpperCase(Locale l)
specified locale.

It removes beginning and ending spaces


String trim()
of this string.

It converts given type into string. It is


static String valueOf(int value)
an overloaded method.
 Concatenating String

There are 2 methods to concatenate two or more string.

1. Using concat() method


2. Using + operator

1) Using concat() method

Concat() method is used to add two or more string into a single string object. It is string
class method and returns a string object.

public class Demo{

public static void main(String[] args) {

String s = "Hello";

String str = "Java";

String str1 = s.concat(str);

System.out.println(str1);

Copy

HelloJava

2) Using + operator

Java uses "+" operator to concatenate two string objects into single one. It can also
concatenate numeric value with string object. See the below example.

public class Demo{


public static void main(String[] args) {

String s = "Hello";

String str = "Java";

String str1 = s+str;

String str2 = "Java"+11;

System.out.println(str1);

System.out.println(str2);

Copy

HelloJava

Java11

 String Comparison

To compare string objects, Java provides methods and operators both. So we can
compare string in following three ways.

1. Using equals() method


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

1.Using equals() method

equals() method compares two strings for equality. Its general syntax is,

boolean equals (Object str)

Copy
Example

It compares the content of the strings. It will return true if string matches, else
returns false.

public class Demo{

public static void main(String[] args) {

String s = "Hell";

String s1 = "Hello";

String s2 = "Hello";

boolean b = s1.equals(s2); //true

System.out.println(b);

b= s.equals(s1) ; //false

System.out.println(b);

Copy

true

false

2.Using == operator

The double equal (==) operator compares two object references to check whether they
refer to same instance. This also, will return true on successful match else returns false.

public class Demo{

public static void main(String[] args) {

String s1 = "Java";
String s2 = "Java";

String s3 = new String ("Java");

boolean b = (s1 == s2); //true

System.out.println(b);

b= (s1 == s3); //false

System.out.println(b);

Copy

true

false

Explanation

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.


3.By compareTo() method

String compareTo() method compares values and returns an integer value 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.

Syntax:

int compareTo(String str)

Example:

public class HelloWorld{

public static void main(String[] args) {

String s1 = "Abhi";

String s2 = "Viraaj";

String s3 = "Abhi";

int a = s1.compareTo(s2); //return -21 because s1 < s2

System.out.println(a);

a = s1.compareTo(s3); //return 0 because s1 == s3

System.out.println(a);

a = s2.compareTo(s1); //return 21 because s2 > s1

System.out.println(a);

-21
0

21

 String class functions


The methods specified below are some of the most commonly used methods of
the String class in Java. We will learn about each method with help of small code
examples for better understanding.

1.charAt() method

String charAt() function returns the character located at the specified index.

public class Demo {

public static void main(String[] args) {

String str = "studytonight";

System.out.println(str.charAt(2));

Output: u

NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of the
String str.

2.equalsIgnoreCase() method

String equalsIgnoreCase() determines the equality of two Strings, ignoring their case (upper
or lower case doesn't matter with this method).

public class Demo {

public static void main(String[] args) {

String str = "java";


System.out.println(str.equalsIgnoreCase("JAVA"));

OutPut:-true

3.indexOf() method

String indexOf() method returns the index of first occurrence of a substring or a character.
indexOf() method has four override methods:

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

public class StudyTonight {

public static void main(String[] args) {

String str="StudyTonight";

System.out.println(str.indexOf('u')); //3rd form

System.out.println(str.indexOf('t', 3)); //2nd form

String subString="Ton";

System.out.println(str.indexOf(subString)); //1st form

System.out.println(str.indexOf(subString,7)); //4th form


}

11

-1

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

4.length() method

String length() function returns the number of characters in a String.

public class Demo {

public static void main(String[] args) {

String str = "Count me";

System.out.println(str.length());

5.replace() method

String replace() method replaces occurances of character with a specified new character.

public class Demo {

public static void main(String[] args) {

String str = "Change me";


System.out.println(str.replace('m','M'));

Change Me

6.substring() method

String substring() method returns a part of the string. substring() method has two override
methods.

1. public String substring(int begin);

2. public String substring(int begin, int end);

The first argument represents the starting point of the subtring. If the substring() method is
called with only one argument, the subtring returns characters from specified starting
point to the end of original string.

If method is called with two arguments, the second argument specify the end point of
substring.

public class Demo {

public static void main(String[] args) {

String str = "0123456789";

System.out.println(str.substring(4));

System.out.println(str.substring(4,7));

}
456789

456

7.toLowerCase() method

String toLowerCase() method returns string with all uppercase characters converted to
lowercase.

public class Demo {

public static void main(String[] args) {

String str = "ABCDEF";

System.out.println(str.toLowerCase());

abcdef

8.toUpperCase() method

This method returns string with all lowercase character changed to uppercase.

public class Demo {

public static void main(String[] args) {

String str = "abcdef";

System.out.println(str.toUpperCase());

}
ABCDEF

9.valueOf() method

String class uses overloaded version of valueOf() method for all primitive data types and
for type Object.

NOTE: valueOf() function is used to convert primitive data types into Strings.

public class Demo {

public static void main(String[] args) {

int num = 35;

String s1 = String.valueOf(num); //converting int to String

System.out.println(s1);

System.out.println("type of num is: "+s1.getClass().getName());

35

type of num is: java.lang.String

10.toString() method

String toString() method returns the string representation of an object. It is declared in the
Object class, hence can be overridden by any java class. (Object class is super class of all
java classes).

public class Car {

public static void main(String args[])

{
Car c = new Car();

System.out.println(c);

public String toString()

return "This is my car object";

This is my car object

Whenever we will try to print any object of class Car, its toString() function will be called.

NOTE: If we don't override the toString() method and directly print the object, then it
would print the object id that contains some hashcode.

11.trim() method

This method returns a string from which any leading and trailing whitespaces has been
removed.

public class Demo {

public static void main(String[] args) {

String str = " hello ";

System.out.println(str.trim());

}
hello

12.contains()Method

String contains() method is used to check the sequence of characters in the given string. It
returns true if a sequence of string is found else it returns false.

public class Demo {

public static void main(String[] args) {

String a = "Hello welcome to studytonight.com";

boolean b = a.contains("studytonight.com");

System.out.println(b);

System.out.println(a.contains("javatpoint"));

true

false

13.endsWith() Method

String endsWith() method is used to check whether the string ends with the given suffix or
not. It returns true when suffix matches the string else it returns false.

public class Demo {


public static void main(String[] args) {

String a="Hello welcome to studytonight.com";

System.out.println(a.endsWith("m"));

System.out.println(a.endsWith("com"));

true

true

14.format() Method

String format() is a string method. It is used to the format of the given string.

Following are the format specifier and their datatype:

Format Specifier Data Type

%a floating point

%b Any type

%c character

%d integer
%e floating point

%f floating point

%g floating point

%h any type

%n none

%o integer

%s any type

%t Date/Time

%x integer

public class Demo {

public static void main(String[] args) {

String a1 = String.format("%d", 125);

String a2 = String.format("%s", "studytonight");

String a3 = String.format("%f", 125.00);


String a4 = String.format("%x", 125);

String a5 = String.format("%c", 'a');

System.out.println("Integer Value: "+a1);

System.out.println("String Value: "+a2);

System.out.println("Float Value: "+a3);

System.out.println("Hexadecimal Value: "+a4);

System.out.println("Char Value: "+a5);

Integer Value: 125

String Value: studytonight

Float Value: 125.000000

Hexadecimal Value: 7d

Char Value: a

15.getBytes() Method

String getBytes() method is used to get byte array of the specified string.

public class Demo {

public static void main(String[] args) {

String a="studytonight";
byte[] b=a.getBytes();

for(int i=0;i<b.length;i++)

System.out.println(b[i]);

16.getChars() Method

String getChars() method is used to copy the content of the string into a char array.

public class Demo {

public static void main(String[] args) {


String a= new String("Hello Welcome to studytonight.com");

char[] ch = new char[16];

try

a.getChars(6, 12, ch, 0);

System.out.println(ch);

catch(Exception ex)

System.out.println(ex);

Welcom

17.isEmpty() Method

String isEmpty() method is used to check whether the string is empty or not. It returns true
when length string is zero else it returns false.

public class IsEmptyDemo1

{
public static void main(String args[])

String a="";

String b="studytonight";

System.out.println(a.isEmpty());

System.out.println(b.isEmpty());

true

false

18.join() Method

String join() method is used to join strings with the given delimiter. The given delimiter is
copied with each element

public class JoinDemo1

public static void main(String[] args)

String s = String.join("*","Welcome to studytonight.com");

System.out.println(s);
String date1 = String.join("/","23","01","2020");

System.out.println("Date: "+date1);

String time1 = String.join(":", "2","39","10");

System.out.println("Time: "+time1);

Welcome to studytonight.com

Date: 23/01/2020

Time: 2:39:10

19.startsWith() Method

String startsWith() is a string method in java. It is used to check whether the given string
starts with given prefix or not. It returns true when prefix matches the string else it
returns false.

public class Demo {

public static void main(String[] args) {

String str = "studytonight";

System.out.println(str.startsWith("s"));

System.out.println(str.startsWith("t"));

System.out.println(str.startsWith("study",1));

}
}

true

false

false

 StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is
the same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and
will result in an order.

Important Constructors of StringBuffer Class


Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.

What is a mutable String?


A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes are
used for creating mutable strings.

1) StringBuffer Class append() Method


The append() method concatenates the given argument with this String.

StringBufferExample.java

1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

Output:

Hello Java

 StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() It creates an empty String Builder with the initial capacity of 16.

StringBuilder(String str) It creates a String Builder with the specified string.

StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.

StringBuilder Examples
.

StringBuilder append() method


The StringBuilder append() method concatenates the given argument with this String.

StringBuilderExample.java

1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

Output:

Hello Java
Difference between String and StringBuffer

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is mutable.

2) String is slow and consumes more memory when we concatenate StringBuffer is fast and consumes less
too many strings because every time it creates new instance. memory when we concatenate t strings.

3) String class overrides the equals() method of Object class. So you StringBuffer class doesn't override the
can compare the contents of two strings by equals() method. equals() method of Object class.

4) String class is slower while performing concatenation operation. StringBuffer class is faster while performing
concatenation operation.

5) String class uses String constant pool. StringBuffer uses Heap memory

Difference between StringBuffer and StringBuilder

No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. thread safe. It StringBuilder is non-synchronized i.e. not thread
means two threads can't call the methods of safe. It means two threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.

2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.

3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
Unit-2
Inheritance and Polymorphism:-
1. Types of inheritance
2. Member access rules
3. Super uses
4. Using final with inheritance
5. The object class and its methods
6. Method Overriding
7. Dynamic Binding
8. Abstract Classes
9. Abstract Methods

Inheritance:-
Defination:- When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

 We can achieve inheritance by using the extends keyword.


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

Terms used in Inheritance


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

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}
 A class whose properties are inherited is known as parent class and a class that inherits the
properties of the parent class is known as child class. Thus, it establishes a relationship
between parent and child class that is known as parent-child or Is-a relationship.
 Suppose, there are two classes named Father and Child and we want to inherit the properties
of the Father class in the Child class. We can achieve this by using the extends keyword.

Inheritance Example

 As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

Example program:-

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:-

Programmer salary is:40000.0


Bonus of programmer is:10000

1.Types of Inheritance:-
o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
o Multiple Inheritance

Note: Multiple inheritance is not supported in Java.

1.Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties
and behavior of a single-parent class. Sometimes it is also known as simple inheritance.

In the above figure, Employee is a parent class and Executive is a child class. The Executive class
inherits all the properties of the Employee class.

Let's implement the single inheritance mechanism in a Java program.

Executive.java
class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}

Output:

Total salary credited: 414408.0


Bonus of six months: 18000.0

2.Multi-level Inheritance
In multi-level inheritance, a class is derived from a class which is also derived from another
class is called multi-level inheritance. In simple words, we can say that a class that has more than
one parent class is called multi-level inheritance. Note that the classes must be at different levels.
Hence, there exists a single base class and single derived class but multiple intermediate base
classes.
In the above figure, the class Marks inherits the members or methods of the class Students. The
class Sports inherits the members of the class Marks. Therefore, the Student class is the parent
class of the class Marks and the class Marks is the parent of the class Sports. Hence, the class
Sports implicitly inherits the properties of the Student along with the class Marks.

Let's implement the multi-level inheritance mechanism in a Java program.

MultilevelInheritanceExample.java

//super class
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}

Output:

registration number= 0987


marks= 78.0
score= 68.7

3.Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called hierarchical inheritance.

In the above figure, the classes Science, Commerce, and Arts inherit a single parent class named
Student.
Let's implement the hierarchical inheritance mechanism in a Java program.

HierarchicalInheritanceExample.java

//parent class
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
}

Output:

The method of the class Student invoked.


The method of the class Student invoked.
The method of the class Student invoked.

4.Hybrid Inheritance
Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more
types of inheritance.

 In the above figure, GrandFather is a super class. The Father class inherits the properties of
the GrandFather class. Since Father and GrandFather represents single inheritance. Further,
the Father class is inherited by the Son and Daughter class. Thus, the Father becomes the
parent class for Son and Daughter. These classes represent the hierarchical inheritance.
Combinedly, it denotes the hybrid inheritance.

Let's implement the hybrid inheritance mechanism in a Java program.

Daughter.java

//parent class
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}

Output:

I am daughter.
5.Multiple Inheritance (not supported)

 Java does not support multiple inheritances due to ambiguity. For example, consider the
following Java program.

Demo.java

class Wishes
{
void message()
{
System.out.println("Best of Luck!!");
}
}
class Birthday
{
void message()
{
System.out.println("Happy Birthday!!");
}
}
public class Demo extends Wishes, Birthday //considering a scenario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
obj.message();
}
}

 The above code gives error because the compiler cannot decide which message() method is to
be invoked. Due to this reason, Java does not support multiple inheritances at the class level
but can be achieved through an interface.

2.Member Access Rules:-


Member Access Rules in Inheritance
The following rules for inherited methods are enforced −
 Methods declared public in a superclass also must be public in all subclasses.
 Methods declared protected in a superclass must either be protected or public in subclasses; they cannot
be private.
 Methods declared private are not inherited at all, so there is no rule for them.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers :


1) Private
The access level of a private modifier is only within the class. It cannot be accessed from outside
the class and sub class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member
and private method. We are accessing these private members from outside the class, so there is a
compile-time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside
the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class.


2) Default

The access level of a default modifier is only within the sub classes,class and package . It cannot
be accessed from outside the sub class,class and package. If you do not specify any keyword, it
will be the default.

If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.

3) Protected
The protected access modifier is accessible within sub class,class and package and outside the
sub class package but through inheritance only.

 Methods declared protected in a superclass must either be protected or public in subclasses; they cannot
be private.
 The protected access modifier can be applied on the data member, method and constructor.
It can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) Public
The public access modifier is accessible everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package. It has the widest scope among all
other modifiers.

 Methods declared public in a superclass also must be public in all subclasses.

Example of public access modifier

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Java Access Modifiers with Method Overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

class A{
protected void msg(){System.out.println("Hello java");} //used protected
}

public class Simple extends A{


void msg(){System.out.println("Hello java");}//C.T.Error //assigned default
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}

The default modifier is more restrictive than protected. That is why, there is a compile-time error.

3.Super Uses:-
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred
by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.


We can use super keyword to access the data member or field of parent class. It is used if parent class and child
class have same fields.

Example program:-

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
Output:-
black
white
In the above example, Animal and Dog both classes have a common property color. If we print color property, it will
print the color of current class by default. To access the parent property, we need to use super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass contains the
same method as parent class. In other words, it is used if method is overridden.

Example Program:-

1. class Animal1{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog1 extends Animal1{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog1 d=new Dog1();
15. d.work();
16. }}

Output:-
eating…
barking…

In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it
will call the eat() method of Dog class by default because priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:

Note: super() is added in each class constructor automatically by compiler if there is no super() or this().
Example program:-

1. class Animal2{
2. Animal2(){System.out.println("animal is created");}
3. }
4. class Dog2 extends Animal2{
5. Dog2(){
6. super();//without use of super keyword java compiler automatically executed
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog2 d=new Dog2();
13. }}

Output:-
animal is created
dog is created
Does a super class reference be used to refer sub class
object?justify
Ans:-
 So difference between referencing using superclass reference and referencing using subclass
reference is use superclass referencing can holds object of subclass and could only access
the methods which are defined/overridden by subclass while use subclass referencing can
not hold object of superclass and could access the methods of both superclass and subclass.
 If you assign an object of the subclass to the reference variable of the superclass then
the subclass object is converted into the type of superclass and this process is termed
as widening (in terms of references).
class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}
Output:-
Dog is eating

4.Using Final With Inheritance:-


Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final
can be:

1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.

Example Program Final Variable:-

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
OutPut:-
Compile time error //can’t modify final variable value
2) Java final method
If you make any method as final, you cannot override it.

Example of final method


1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }

OutPut:-
Compile time error//can’t override method

3) Java final class


If you make any class as final, you cannot extend it.
Example of final class
1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
OutPut:-
Compile time error //can’t inherited

5.Object class in Java


Object Class in Java:-

Object Class in Java is the topmost class among all the classes in Java. We can also say that the
Object class in Java is the parent class for all the classes. It means that all the classes in Java are
derived classes and their base class is the Object class. Object class is present
in java.lang package.

All the classes directly or indirectly inherit from the Object class in Java.
Ex:-public class Object{

//Object class body

/*

1. toString()
2. hashCode()
3. equals(Object o)
4. clone()
5. finalize()
6. getClass()
7. wait()
8. wait(long timeout)
9. wait(long timeout,int nanos)
10.notify()
11.notifyAll()
*/

/*Consider the example-

class Vehicle{
//body of class Vehicle
}

Here we can see that class Vehicle is not inheriting any class, but it inherits the Object class. It
is an example of the direct inheritance of object class.

Now, look at this example-

class Vehicle{
//body of class Vehicle
}
class Car extends Vehicle{
//body of class Car
}

Here we can see that the Car class directly inherits the Vehicle class. The extends keyword is
used to establish inheritance between two classes. But we have seen in the above example that
if we define a class without inheriting it from some other class, it directly inherits the Object
class. Since Car inherits the Vehicle and the Vehicle inherits the Object class, Car indirectly
inherits the Object class. */
Fig.1.Object Class

Methods of Object class

Method Description

public final Class getClass() returns the Class class object of this object. The Class class
can further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long causes the current thread to wait for the specified milliseconds,
timeout)throws InterruptedException until another thread notifies (invokes notify() or notifyAll() method).

public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread notifies
(invokes notify() or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll() method).

protected void finalize()throws is invoked by the garbage collector before object


Throwable is being garbage collected.
Object class provides many methods. They are as follows:

6.Method Overriding:-
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding
in Java.In other words,If a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Fig.1.Method overriding process

Syntax:-class A
{
Void show()
{
// block of code
}
}
Class B extends A
{
Void show()
{
//block of code
}
}

Example of method overriding:-


In this example, we have defined the run method in the subclass as defined in the parent class but it has some
specific implementation. The name and parameter of the method are the same, and there is IS-A relationship
between the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

OutPut:-

Bike is running safely


Example 2:-
A real example of Java Method Overriding
Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate
of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9%
rate of interest.

class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

7.Dynamic Binding:-
Connecting a method call to the method body is known as binding.

There are two types of binding


1. Static Binding (also known as Early Binding).
2. Dynamic Binding (also known as Late Binding).

Dynamic Binding is also known as runtime polymorphism or dynamic method dispatch.

Understanding Type
Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

Ex:- int data=30;

Here data variable is a type of int.

2) References have a type


class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}
3) Objects have a type
An object is an instance of particular java class,but it is also an instance of its superclass.

class Animal{}

class Dog extends Animal{


public static void main(String args[]){
Dog d1=new Dog();
}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.

If there is any private, final or static method in a class, there is static binding.

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}
//In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instan
So compiler doesn't know its type, only its base type.

Output:-
dog is eating…
8.Abstraction:-
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.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class:-
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods.
It needs to be extended and its method implemented. It cannot be instantiated.

Rules For Java Abstract Class:-

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
o To use an abstract class, you have to inherit it from sub classes.
o If a class contain partial implementation, then we should declare a class as abstract.

Syntax:-

abstract class class_name{

//abstract methods and non-abstract methods

Abstract Method
A method which is declared as abstract and does not have implementation is known as an abstract method.

Syntax of abstract method

abstract access modifier return type method_name();//no method body and abstract method

Abstract class Example1:-

In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is
provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Output:-

running safely
Abstract Method Using Real Scenario:-Example 2

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method
s.draw();
}
}
Output:-
Drawing circle
Abstract class having constructor, data member and methods
An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and
even main() method.

Example 3:-

File: TestAbstraction2.java

1. //Example of an abstract class that has abstract and non-abstract methods


2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear changed");}
6. }
7. //Creating a Child class which inherits Abstract class
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. //Creating a Test class which calls abstract and non-abstract methods
12. class TestAbstraction2{
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.changeGear();
17. }
18. }
OutPut:-
Bike is created
Running safely..
Gear changed

Note1:-If there is an abstract method in a class, that class must be abstract.


Note2:If you are extending an abstract class that has an abstract method, you must either provide the implementation
of the method or make this class abstract.

9.Abstract Method
A method declared using the abstract keyword within an abstract class and does not have a definition
(implementation) is called an abstract method.

When we need just the method declaration in a super class, it can be achieved by declaring the methods as
abstracts.

Abstract method is also called subclass responsibility as it doesn't have the implementation in the super class.
Therefore a subclass must override it to provide the method definition.

Syntax for abstract method:


abstract return_type method_name( [ argument-list ] );
Here, the abstract method doesn't have a method body. It may have zero or more arguments.
Steps to Create Abstract Method:-

 It can only be used in abstract class.


 It doesn’t contain any body “{ }” and always ends with semicolon “;”.
 Abstract method must be overridden in sub-classes otherwise it will also become a abstract class.
 Whenever the action is common but implementation are difficult then we should use abstract method.
Ex:-class fruit abstract class fruit
{ {
public void test() public abstract void test();
{ }
}
}
Example Program:-
abstract class Programming {
abstract public void developer();
}
class C extends Programming
{
@Override
public void developer()
{
System.out.println("Dennis Ritchie");
}
}
class Java extends Programming
{
@Override
public void developer()
{
System.out.println("James Gosling");//
}
}
class Main
{
public static void main(String args[])
{
Programming p=new C();
Java j=new Java();
p.developer();
j.developer();
}

}
Output:-
Dennie Ritchie
James Gosling
Difference between abstract class and interface
Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods. Since Java 8, it can have
default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.

6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface
public abstract void draw(); void
} }
Part-B

Packages and Interfaces:-


1. Defining
2. Creating and Accessing a Package
3. Understanding CLASSPATH
4. Importing Packages
Packages:-
Defining:-
It is necessary in software development to create several classes and interfaces. After creating
these classes and interfaces, it is better if they are divided into some groups depending on their
relationship. Thus, the classes and interfaces which handle similar or same task are put into the
same directory. This directory or folder is also called a package.
Defination:- A java package is a group of similar types of classes, interfaces and sub-packages.
There are several following advantages of package concept:
1. Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2. Java package provides access protection.
3. Java package removes naming collision.

/*
 Packages are useful to arrange related classes and interfaces into a group. This makes all
the classes and interfaces performing the same task to put together in the same package.
For example, in Java, all the classes and interfaces which perform input and output
operations are stored in java.io package.
 packages hide the classes and interfaces in a separate sub directory, so that accidental
deletion of classes and interfaces will not take place.
 The classes and interfaces of a package are isolated from the classes and interfaces of
another package. This means that we can use same names for classes of two different
classes. For example, there is a Date class in java.util package and also there is another
Date class available in java.sql package.
 A group of packages is called a library. The classes and interfaces of a package are like
books in a library and can be reused several times. This reusability nature of packages
makes programming easy. Just think, the packages in Java are created by JavaSoft people
only once, and millions of programmers all over the world are daily by using them in
various programs.
*/
Different Types of Packages
There are two different types of packages in Java. They are:
 Built-in packages
 User-defined packages

(or)

Built-in or Pre-defined Packages:-


The Package which are already created by java developer people are called pre-defined package.

Java.lang.* :-This package as primary classes and interfaces essential for Java language. It
consists of Wrapper Classes . Ex: System, String, Integer, Character classes etc..,
Java.util.* :-This Package consist useful classes and interfaces like Stack, LinkedList, Vector,
ArrayList, Date etc.,
java.io.* :-This packages handles Files and input, output related tasks. Ex:- File, FileInputStream,
FilOutputStream, FileReader, FileWriters.
Java.awt.* :-awt means Abstract Window Toolkit. This packages helps to develop GUI. It
consists of two important some packages.
1. Java.awt.*;
2. Java.awt.event.*;
3. Java.awt.image.*;
Javax.swing.* :-This package helps to develop GUI. Java.awt will have additional features than
java.awt.*;
Java.net.* :-Client and Server programming can be done using packages it uses TCP/IP TCP
means Transmission Control Protocol and IP means Internet Protocol.
Java.applet.* : - Applets are small intelligent program which travel from one place to another
place on Internet and executed in client side.
Java.sql.*:-This package helps to connect to the database like Oracle, MsAccess etc..,
Java.beans.*:-Beans are software reusalble components in the network they can be develop this
package.
Java.rmi.*:-rmi stands for Remote Method Invocation. This object which exists one computer
in the network can be invoked from another computer and can be used.
Javax.servlet.* :-Servlets are Server Side Programming which handles clients.

Creating and Accessing a Package:-


User Defined Package:-
Creating a Package:-
the users of the Java language can also create their own packages. They are called user-defined
packages. User defined packages can also be imported into other classes and used exactly in the
same way as the Built-in packages.
Let us see how to create a package of our own and use it in any other class. To create a package
the keyword package used as:

Syntax:-
1. Package packagename; //to create a package
2. Package packagename.subpackagename; //to create a sub package within a package

Simple example of java package:

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example

javac -d . Simple.java

See the output to understand how to compile a Java program that contains a package. The –d
option (switch) tells the Java compiler to create a separate sub directory and place the .class file
there. The dot(.) after –d indicates that the package should be created in the current directory i.e.,
C:\. We have written as:

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

Ex:-java mypack.Simple
To Compile: javac -d . Simple.java
To Run: java mypack.Simple

Output:Welcome to package
Note: Sequence of the program must be package then import then class.

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.

Subpackage in java:-
Package inside the package is called the subpackage. It should be created to categorize the
package further.

Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes
are for networking etc and so on. So, Sun has subcategorized the java package into subpackages
such as lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.

Syntax:-

Package packagename.subpackagename; //to create a sub package within a package

Example of Subpackage
package high.sub;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}

To Compile: javac -d . Simple.java


To Run: java high.sub.Simple
Output:Hello subpackage
Accessing a Package:-
There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to
the current package.

Example of package that import the packagename.*

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B

Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B

Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.

Example of package by import fully qualified name

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B

Output:Hello

Accessing a Packages using Access Modifiers:-


The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers using to access Packages:

1) Private
The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member
and private method. We are accessing these private members from outside the class, so there is a
compile-time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside
the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class.

2) Default

The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.

If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.

3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) Public
The public access modifier is accessible everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package. It has the widest scope among all
other modifiers.

Example of public access modifier

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Understanding CLASSPATH:-
The CLASSPATH is an environment variable that tells the Java compiler where to look for class
files import. CLASSPATH is generally set to a directory or a Jar(Java Archive) file.

To see what is there currently in the CLASSPATH variable in your system, you can type in
Windows
C:\>echo %path% \\used to know the all the classpaths in the particular directory
C:\>echo %classpath% \\used to know the current classpath name
send the class file to another directory or drive?

There is a scenario, I am created one class A.java in a e directory folder source. I want to put the
class file of A.java source file in classes folder of c: drive.

//save as Simple.java
package mypack;
public class A{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:

e:\sources> javac -d c:\classes A.java


To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:

The –classpath or -cp switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:

Output:Welcome to package

e:\sources> java -classpath c:\classes mypack.Simple

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in the
jre/lib/ext folder.

4.Importing Packages
There are three ways to import a package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.

Syntax:-

import Packagename.*;

import packagename.subpackagename.*;

Example of package that import the packagename.*

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B

Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Syntax:-
Import packagename.classname;

import packagename.subpackagename.classname;

Example of package by import package.classname

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B

Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.

Example of package by import fully qualified name

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B

Output:Hello

1.How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one
public class, but keep the package name same.
For example:
//save as A.java
package p1;
public class A{}
//save as B.java
package p2;
public class B{}
2.How to put same class name in a packages?
If you want to put two classes names same so, create two different package names and create
same class names.
save as A.java
package p1;
public class A{}
//save as A.java
package p2;
public class A{}

The JAR Files


A Java Archive file (JAR) is a file that contains compressed version of several .class files, audio
files, image files or directories. JAR file is useful to bundle up several files related to a project
and use them easily.
Let us see how to create a .jar file and related commands which help us to work with .jar files:
 To create .jar file, JavaSoft people have provided jar command, which can be used in the
following way:
jar cf jarfilename inputfiles
 Here, cf represents create file. For example, assuming our package pack is available in
C:\directory, to convert it into a jar file with the name pack.jar, we can given the command as:
C:\> jar cf pack.jar pack
Now, pack.jar file created.
 To view the contents of a .jar fie, we can use the jar command as:
jar tf jarfilename
Here, tf represents table view of file contents. For example, to view the contents f our pack.jar
file, we can give the command:
C:\> jar tf pack.jar
Now, the contents of pack.jar are displayed as:
META-INF
META-INF/MANIFEXT.MF
pack/
pack/Addition.class
pack/Subtraction.class
The first two entries represent that there is a manifest file created and added to pack.jar file. The
third entry represents the sub directory with the name pack and the last two represents the file
names in the directory pack.
When we create a .jar file, it automatically receives the default manifest file. There can be only
one manifest file in an archive, and it always has the pathname
META-INF/MANIFEXT.MF
This manifest file is useful to specify the information about other files which are packaged.
 To extract the files from a .jar file, we can use:
jar xf jarfilename
Here, xf represents extract files from the jar file. For example, to extract the contents of our
pack.jar file, we can write: C:\> jar xf pack.jar
This will create the following directories in C:\
META-INF
Pack // in this directory, we can see Addition.class and Subtraction.class
Now, we know how to create a .jar file, let us see how it can be used. In software development,
any package is converted into a .jar file and stored in a separate sub directory. For example,
convert our package pack into pack.jar file and store it in a sub directory e:\temp
Now set the CLASSPATH permanently to the pack.jar file by following the procedure
shown here:
First, go to start->settings -> Control panel
In Control Panel, select System and double click on it, System properties dialog box appears
In this, select Advanced tab and then click on Environment variables button
Go to User variables and click on New button
Set the CLASSPATH variable to pack.jar and also to the current directory, by typing at:
Variable name: CLASSPATH
Variable value : E:\temp\pack.jar;
Then click on OK button
Then click on OK in the Environment variables window and System Properties windows.
Close the Control Panel.
After setting the CLASSPATH permanently as shown in the preceding steps to the apck.jar file,
it is available any were in that computer system. Our program (Use.java) which uses the package
may present in any directory, it can be compiled and run without any problem.
Interface

An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body.
It is used to achieve abstraction and multiple inheritance in Java.
Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the methods declared in the interface.

Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

Internal addition by the compiler

The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public,
static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.

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.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided in the A6
class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Output: Hello

Java Interface Example: Drawable


In this example, the Drawable interface has only one method. Its implementation is provided by Rectangle
and Circle classes. In a real scenario, an interface is defined by someone else, but its implementation is
provided by different implementation providers. Moreover, it is used by someone else. The
implementation part is hidden by the user who uses the interface.

File: TestInterface1.java

1. //Interface declaration: by first user


2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
16. d.draw();
17. }}

Output:drawing circle

Java Interface Example: Bank

Let's see another example of java interface which provides the implementation of Bank interface.

File: TestInterface2.java

1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
Output:ROI: 9.15

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as
multiple inheritance.

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Test it Now
Output:Hello
Welcome

Q) Multiple inheritance is not supported through class in java, but it is


possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case
of class because of ambiguity. However, it is supported in case of an interface because there is no
ambiguity. It is because its implementation is provided by the implementation class. For example:

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. obj.print();
13. }
14. }

Output:

Hello

As you can see in the above example, Printable and Showable interface have same methods but its
implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance

A class implements an interface, but one interface extends another interface.

1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }
Test it Now

Output:

Hello
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non- Interface has only static and final variables.
static variables.

4) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.

7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword
"implements".

8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction
(100%).
Unit-3
Exception Handling:
1. Concepts of Exception handling
2. Benefits of Exception Handling
3. Exception Hierarchy
4. Usage of try and catch
5. Usage of throw
6. Usage of throws
7. Usage of finally
9.Built in Exceptions
10.Creating own Exceptions Sub Class

1.Concepts of Exception handling:-


Dictionary Meaning: Exception is an abnormal condition.
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
Definition:-
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Run Time Error:-
Run Time errors occur or we can say, are detected during the execution of the program.
Sometimes these are discovered when the user enters an invalid data or data which is not
relevant. Runtime errors occur when a program does not contain any syntax errors but asks the
computer to do something that the computer is unable to reliably do. During compilation, the
compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine)
that detects it while the program is running.
Ex:-
class TestRunTimeError
{
public static void main (String args[])
{
int a=10;
int b=0;
int c;
System.out.println("Dividing of two numbers is:"+a+" "+b);
c=a/b;//raised run time exception
System.out.println(" Program Ending");
}
}
Out Put:-
Compile Time:-
Javac TestRunTimeError.java

Run Time:-
Java TestRunTimeError
Dividing of two numbers is:10 0
Exception in thread "main" java.lang.ArithmeticException: / by zero

To handle the error during the run time we can use Exception handling to put our error code
inside the try block and catch the error inside the catch block.
Example Program2:-
class TestRunTimeError
{
public static void main (String args[])
{
int a=10;
int b=0;
int c;
try{

System.out.println("Dividing of two numbers is:"+a+" "+b);


c=a/b;
System.out.println(c);
}
catch(Exception e)
{
System.out.println(e);
System.out.println("Number is can't divide by zero");
}
System.out.println("Program Ending");
}
}
Out put:-
Compile Time:-
Javac TestRunTimeError.java
Run Time:-
Java TestRunTimeError

Dividing of two numbers is:10 0


java.lang.ArithmeticException: / by zero
Number is can't divide by zero
Program Ending

2.Benefits of Exception Handling:-


 It is used to handle runtime errors

 It is used to display message to user when an exception occurs

 It can handle any kind of exception

 You can even execute some code when an exception occurs

 Separating Error-Handling code from “regular” business logic code

 Propagating errors up the call stack

 Grouping and differentiating error types


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 need to handle
exceptions. Let's consider 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 a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when
we perform exception handling, the rest of the statements will be executed. That is why we use
exception handling in Java.

3.Exception Hierarchy:-
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Fig. Exception Hierarchy

 Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

Built in exception:-

1. Checked Exception//both checked and unchecked exceptions comes under built-in


exceptions
2. Unchecked Exception
3. Error
1.Checked Exception:-
Checked Exceptions are checked by the java Compiler so they are called compile Time
Exceptions. Checked Exceptions occur at compile time. These Types of Exceptions can be
handled at the time of compilation. Must be handled in a try-and-catch block, or be thrown by
the invoking method
Ex:-Raised Compile Time Exception
Import java.io.FileReader;
class TestRunTimeError
{
public static void main (String args[])
{
FileReader file=new FileReader(“somefile.txt”);
//raised compile time exception FileNotFoundException
}
}
These Types of Exceptions can be handled at the time of compilation. Must be handled in a try-
and-catch block, or be thrown by the invoking method
Ex2:-Solved Using Try and Catch Block
import java.io.FileReader;
import java.io.FileNotFoundException;
class TestCheckedException
{
public static void main (String args[]) throws FileNotFoundException
{
try{
FileReader file=new FileReader("somefile.txt");
}
catch(Exception e){
System.out.println(e);
}
}
}
OutPut:-
java.io.FileNotFoundException: somefile.txt (The system cannot find the file specified)

2.Unchecked Exception:-
Unchecked Exceptions are not checked by the compiler.These are called runtime
exceptions.Unchecked exceptions occur at runtime.These types of exceptions cannot be catched
or handled at the time of compilation,because they get generated by the mistakes in the program.
Ex:-
class TestRunTimeError
{
public static void main (String args[])
{
System.out.println(10/0); //raised run time exception
System.out.println(" Program Ending");
}
}
OutPut:-
Compile Time:-
Javac TestRunTimeError.java
Run Time:-//Unchecked by compile time and raised by run time exception is called
unchecked exception
Java TestRunTimeError
Exception in thread "main" java.lang.ArithmeticException: / by zero
 Handle this unchecked exception using Exception handling keyword try and catch block.

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters; converting this
variable into digit will cause NumberFormatException.

String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

3.Error:-

Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or
handled. It indicates a serious problem. It occurs at run time. These are always unchecked. An
example of errors is OutOfMemoryError, LinkageError, AssertionError, etc. are the
subclasses of the Error class.

Example program:-
1. public class ErrorExample
2. {
3. public static void main(String args[])
4. {
5. //method calling
6. recursiveDemo(10);
7. }
8. public static void recursiveDemo(int i)
9. {
10.while(i!=0)
11.{
12.//increments the variable i by 1
13.i=i+1;
14.//recursive called method
15.recursiveDemo(i);
16.}
17.}
18.}

Difference Between Checked and Unchecked Exception

S. Checked Exception Unchecked Exception


No

1. These exceptions are checked at compile time. These exceptions are just opposite to the checked
These exceptions are handled at compile time too. exceptions. These exceptions are not checked and
handled at compile time.

2. These exceptions are direct subclasses of They are the direct subclasses of the RuntimeException
exception but not extended from class.
RuntimeException class.

3. The code gives a compilation error in the case The code compiles without any error because the
when a method throws a checked exception. The exceptions escape the notice of the compiler.
compiler is not able to handle the exception on its These exceptions are the results of user-created
own. errors in programming logic.

4. These exceptions mostly occur when the These exceptions occur mostly due to programming
probability of failure is too high. mistakes.
5. Common checked exceptions include Common unchecked exceptions
IOException, DataAccessException, include ArithmeticException,
InterruptedException, etc. InvalidClassException,
NullPointerException, etc.

6. These exceptions are propagated using the throws These are automatically propagated.
keyword.

7. It is required to provide the try-catch and try- In the case of unchecked exception
finally block to handle the checked exception. it is not mandatory.

Difference Between Exception and Error

In Java, Error, and Exception both are subclasses of the Java Throwable class that belongs to
java.lang package.

Basis of Exception Error


Comparison

Recoverable/ Exception can be recovered by using the


try-catch block. An error cannot be recovered.
Irrecoverable

Type It can be classified into two categories i.e. All errors in Java are unchecked.
checked and unchecked.

Occurrence It occurs at compile time or run time. It occurs at run time.

Package It belongs to java.lang.Exception package. It belongs to java.lang.Error package.

Known or Only checked exceptions are known to the Errors will not be known to the compiler.
unknown compiler.

Causes It is mainly caused by the application It is mostly caused by the environment in which
itself.
the application is running.

Example Checked Exceptions: Java.lang.StackOverFlow,


SQLException,IOException java.lang.OutOfMemoryError
Unchecked Exceptions:
ArrayIndexOutOfBoundException,
NullPointerException,
ArithmaticException
Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes
each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used w
signature.

4.Usage of Try and catch :-


Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.

If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.

Java catch block

Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
Syntax of try-finally block
1. try{
2. //code that may throw an exception
3. }finally{}
Internal Working of Java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.

But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.

Example program:-
public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("try block code");

}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

Output:

java.lang.ArithmeticException: / by zero

rest of the code

 Multiple Catch Block:-


A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block

Example Program for Multiple Catch Block:-


public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Arithmetic Exception occurs
Output:

Arithmetic Exception occurs


rest of the code

 Multiple try Block:-


One program you can write multiple try blocks and You cannot have multiple try blocks with a
single catch block. Each try block must be followed by catch or finally. Still if you try to have
single catch block for multiple try blocks a compile time error is generated.

Example program for Multiple try Block:-


class MultipleTryCatchBlock{
public static void main(String args[]){
try{
int a=10,b=20,c;
c=30/0;
System.out.println(c);
}

catch(ArithmeticException e){System.out.println("task1 is completed");}

try{
int a[]=new int[3];
a[4]=10;
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}

System.out.println("rest of the code...");


}
}
Output:-
task1 is completed
task 2 completed
rest of the code...

 Nested try Block:-


A try block which contain inside another try block called nested try block.
Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e2)
{
//exception message
}
....

Example Program for nested try block:-


class NestedTry {

// main method
public static void main(String args[])
{
// Main try block
try {

// initializing array
int a[] = { 1, 2, 3, 4, 5 };

// trying to print element at index 5


System.out.println(a[5]);

// try-block2 inside another try block


try {
// performing division by zero
int x = a[2] / 0;
}
catch (ArithmeticException e2) {
System.out.println("division by zero is not possible");
}
}
catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Element at such index does not exists");
}
}
// end of main method
}
Output:
ArrayIndexOutOfBoundsException
Element at such index does not exists

Whenever a try block does not have a catch block for a particular exception, then the catch blocks
of parent try block are inspected for that exception, and if a match is found then that catch block
is executed.

 Nested catch Block:-


An catch block which contain inside another catch block is called nested catch block.
Example Program:-
class NestedCatch {

// main method
public static void main(String args[])
{
// Main try block
try {

// initializing array
int a[] = { 1, 2, 3, 4, 5 };

// trying to print element at index 5


System.out.println(a[5]);

// try-block2 inside another try block


}
catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Element at such index does not exists");
try {
int a[] = { 1, 2, 3, 4, 5 };
// performing division by zero
int x = a[2] / 0;
}
catch (ArithmeticException e2) {
System.out.println("division by zero is not possible");
}
}
}
// end of main method
}
Output:-
ArrayIndexOutOfBoundsException
Element at such index does not exists
division by zero is not possible

5.Usage of Finally Block:-


Defination:-Java finally block is a block used to execute important code such as closing the
connection, etc. Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.

The finally block follows the try-catch block.

Syntax:-

try

finally

}
Flowchart of finally block

Note: If you don't handle the exception, before terminating the program, JVM executes
finally block (if any).
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.

Rule: For each try block there can be zero or more catch blocks, but only one finally block.

Finally block executed following cases

Case 1: When an exception does not occur Finally Block Executed


Example program1:-
class TestFinallyBlock {
public static void main(String args[]){
//first final block without error
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(Exception e){
System.out.println(e);
}

//executed regardless of exception occurred or not


finally {
System.out.println("finally block is always executed1");
}
System.out.println("rest of phe code...");
//second final block with error

try {
int data=25/0;
System.out.println(data);
}

catch(ArithmeticException e){
System.out.println(e);
}
finally {
System.out.println("finally block is always executed2");
}
//third final block with error and wrong exception class

try {

System.out.println("Inside the try block");

//below code throws divide by zero exception

int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed3");
}

System.out.println("rest of phe code...");


}
}
Output:-
5
finally block is always executed1
rest of phe code...
java.lang.ArithmeticException: / by zero
finally block is always executed2
Inside the try block
finally block is always executed3
at Exception1.TestFinallyBlock.main(TestClass.java:212)
C:\Users\Admin\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned:
1
BUILD FAILED (total time: 0 seconds)

6.Usage of throw:-
Defination:-Throw keyword is used to throw the user defined or customize exception object to the
JVM explicitly for that purpose we use throw keyword.
In Java, exceptions allows us to write good quality codes where the errors are checked at the compile
time instead of runtime and we can create custom exceptions(user defined exception) making the
code recovery and debugging easier.

The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception.

We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw exception using throw keyword.

The syntax of the Java throw keyword is given below.

 throw new exception_class("error message");


Let's see the example of throw IOException.

 throw new IOException("sorry device error");

Where the Instance must be of type Throwable or subclass of Throwable. For example, Exception
is the sub class of Throwable and the user-defined exceptions usually extend the Exception class.
Example 1: Throwing Unchecked Exception

In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.

TestThrow1.java

public class TestThrow1 {


//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}

Output:

The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the exception or
declare in throws clause.
7.Usage of throws:-
Defination:-throws keyword is used when we doesn’t want to handle the exception and try to send
the exception to the JVM(JVM or other method)

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide the
exception handling code so that the normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.

Syntax of Java throws


return_type method_name() throws exception_class_name{
//method code
}
Q).Which exception should be declared?

Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Example program:-

public class TestClass {

public static void wait1() throws InterruptedException


{
for(int i=0;i<=10;i++)
{
System.out.println(i);
Thread.sleep(1000);
}
}
public static void main(String args[]) throws InterruptedException
{

wait1();
try
{
}
finally{
System.out.println("Successfully Executed");
}
}
}
Output:-
0
1
2
3
4
5
6
7
8
9
10
Finally block

8.Java Exception Propagation


An exception is first thrown from the top of the stack and if it is not caught, it drops down the
call stack to the previous method. If not caught there, the exception again drops down to the
previous method, and so on until they are caught or until they reach the very bottom of the call
stack. This is called exception propagation.

Note: By default Unchecked Exceptions are forwarded in calling chain (propagated).


Exception Propagation Example

TestExceptionPropagation1.java

class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...

In the above example exception occurs in the m() method where it is not handled, so it is
propagated to the previous n() method where it is not handled, again it is propagated to the p()
method where exception is handled.

Exception can be handled in any method in call stack either in the main() method, p() method,
n() method or m() method.

9.Built in Exceptions:-
Built-in Exception

Exceptions that are already available in Java libraries are referred to as built-in exception.
These exceptions are able to define the error situation so that we can understand the reason of
getting this error. It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.
Checked Exception

Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler. The compiler ensures whether the programmer handles the
exception or not. The programmer should have to handle the exception; otherwise, the system
has shown a compilation error.

Example program:-
1. FileNotFoundException : This Exception is raised when a file is not accessible or does not
open.
// Java program to demonstrate
// FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {

public static void main(String args[])


{
try {

// Following file does not exist


File file = new File("E:// file.txt");

FileReader fr = new FileReader(file);


}
catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}

Output:
File does not exist

Unchecked Exceptions

The unchecked exceptions are just opposite to the checked exceptions. The compiler will not
check these exceptions at compile time. In simple words, if a program throws an unchecked
exception, and even if we didn't handle or declare it, the program would not give a compilation
error. Usually, it occurs when the user provides bad data during the interaction with the program.
Example Program:-
1. ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been
accessed with an illegal index. The index is either negative or greater than or equal to the
size of the array.

class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds

10.Creating own Exception sub classes:-


Custom Exception or User Defined Exception:-

In Java, we can create our own exceptions that are derived classes of the Exception class. Creating
our own Exception is known as custom exception or user-defined exception. Basically, Java
custom exceptions are used to customize the exception according to user need.

Consider the example 1 in which InvalidAgeException class extends the Exception class.

Using the custom exception, we can have your own exception and message.

Following are few of the reasons to use custom exceptions:

o To catch and provide specific treatment to a subset of existing Java exceptions.


o Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the exact
problem.

In order to create custom exception, we need to extend Exception class that belongs to java.lang
package.

Consider the following example, where we create a custom exception named


WrongFileNameException:

public class WrongFileNameException extends Exception {


public WrongFileNameException(String errorMessage) {
super(errorMessage);
}
}
Note: We need to write the constructor that takes the String as the error message and it is called
parent class constructor.
Example 1:

Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of parent
class Exception using the super() method. Also the constructor of Exception class can be called
without using a parameter and calling super() method is not mandatory.

TestCustomException1.java

// class representing custom exception


class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class TestCustomException1
{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}

Output:
Difference between throw and throws in Java
Sr. Basis of Differences throw throws
no.

1. Definition Java throw keyword is used Java throws keyword is used in the
throw an exception explicitly method signature to declare an
in the code, inside the exception which might be thrown by the
function or the block of function while the execution of the code.
code.

2. Type of exception Using


throw keyword, we can only Using throws keyword, we can declare
propagate unchecked both checked and unchecked exceptions.
exception i.e., the checked However, the throws keyword can be
exception cannot be used to propagate checked exceptions
propagated using throw only.
only.

3. Syntax The throw keyword is The throws keyword is followed by


followed by an instance of class names of Exceptions to be thrown.
Exception to be thrown.

4. Declaration throw is used within the throws is used with the method
method. signature.

5. Internal implementation We are allowed to throw We can declare multiple exceptions


only one exception at a time using throws keyword that can be
i.e. we cannot throw multiple thrown by the method. For example,
exceptions. main() throws IOException,
SQLException.
Difference between final, finally and finalize
S Key final finally finalize
r
.
n
o
.

1 Definition final is the keyword and finally is the block in finalize is the method in Java
. access modifier which is Java Exception which is used to perform clean
used to apply restrictions on Handling to execute up processing just before
a class, method or variable. the important code object is garbage collected.
whether the
exception occurs or
not.

2 Applicable Final keyword is used with Finally block is finalize() method is used with
. to the classes, methods and always related to the the objects.
variables. try and catch block
in exception
handling.

3 Functionalit (1) Once declared, final (1) finally block runs finalize method performs
. y variable becomes constant the important code the cleaning activities with
and cannot be modified. even if exception respect to the object before its
(2) final method cannot be occurs or not. destruction.
overridden by sub class. (2) finally block
(3) final class cannot be cleans up all the
inherited. resources used in try
block

4 Execution Final method is executed Finally block is finalize method is executed


. only when we call it. executed as soon as just before the object is
the try-catch block is destroyed.
executed.

It's execution is not


dependant on the
exception.

You might also like