Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Module 1 Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

BALASORE COLLEGE OF ENGINEERING

AND TECHNOLOGY

CLASS NOTES
ON

OBJECT ORIENTED PROGRAMMING


USING JAVA

Prepared
By
Surendra Nath Bhagat
Department Of
Information Technology
MODULE-I

CHAPTER-1
Programming is giving a set of instructions to a computer to execute.
 Programming is the mental process of thinking up instructions to give to a machine (like a
computer).
 Coding is the process of transforming those ideas into a written language that a computer can
understand.
There are basically two types of computer programming languages given below:
1. Low level language
2. High level language

1. Low Level Languages


The programming languages that are very close to machine code (0s and 1s) are called low-level
programming languages.
The program instructions written in these languages are in binary form.
The examples of low-level languages are:
 machine language
 assembly language

Machine Language
The instructions in binary form, which can be directly understood by the computer (CPU) without
translating them, is called a machine language or machine code.
Machine language is also known as first generation of programming language. Machine language is the
fundamental language of the computer and the program instructions in this language is in the binary form
(that is 0's and 1's).
This language is different for different computers.
It is not easy to learn the machine language.

Advantage of Machine Language


The only advantage of machine language is that the program of machine language runs very fast because no
translation program is required for the CPU.

Disadvantage of Machine Language


Here are some of the main disadvantages of machine languages:
 Machine Dependent - the internal design of every computer is different from every other type of
computer, machine language also differs from one computer to another. Hence, after becoming
proficient in the machine language of one type of computer, if a company decides to change to
another type, then its programmer will have to learn a new machine language and would have to
rewrite all existing program.
 Difficult to Modify - it is difficult to correct or modify this language. Checking machine instructions
to locate errors is very difficult and time consuming.
 Difficult to Program - a computer executes machine language program directly and efficiently, it is
difficult to program in machine language. A machine language programming must be knowledgeable
about the hardware structure of the computer.
Assembly Language
It is another low-level programming language because the program instructions written in this language are
close to machine language.
Assembly language is also known as second generation of programming language.
With assembly language, a programmer writes instructions using symbolic instruction code instead of binary
codes.
Symbolic codes are meaningful abbreviations such as SUB is used for substation operation, MUL for
multiply operation and so on. Therefore this language is also called the low-level symbolic language.
The set of program instructions written in assembly language are also called as mnemonic code.
Assembly language provides facilities for controlling the hardware.

Advantage of Assembly Language


Here are some of the main advantages of using assembly language:
 Easy to understand and use - due to the use of mnemonic instead of numeric op-codes and
symbolic names for data location instead of numeric addresses, it is much easier to understand and
use in contrast with machine language.
 Easier to locate and correct errors - the programmers need not to keep track of storage location of
the data and instruction, fewer errors are made while writing programs in assembly language and
those that are made, are easier to find and correct.
 Easy to modify - assembly language are easier to understand, it is easier to locate, correct and
modify instruction of an assembly language program.
 Efficiency of machine language - an assembly language program will be just as long as the
resulting machine language program. Hence, leaving out the translation time required by the
assembler, the actual execution time for an assembly language program and its equivalent machine
language program.

Disadvantage of Assembly Languages


And here are some of the main disadvantages of using assembly language:
 Machine dependent - each instructions of assembly language program is translated into exactly one
machine language instruction, an assembly language programs are dependent on machine language.
 Knowledge of hardware required - assembly languages are machine dependent, an assembly
language programmer must have a good knowledge of characteristics and logical structure of his/her
computer to write a good assembly language computer code.
 Machine level coding - assembly language instruction is substituted for one machine language
instruction. Hence like machine language programs, write assembly language program is also time
consuming and difficult.

2. High Level Languages


The programming languages that are close to human languages (example like English languages) are called
the high-level languages.
The examples of high-level languages are:Fortran, COBOL, Basic, Pascal, C, C++
The high level languages are similar to English language. The program instructions are written using English
words, for example print, input etc. But each high level language has its own rule and grammar for writing
program instructions. These rules are called syntax of the language.
The program written in high level language must be translated to machine code before to run it. Each high
level language has its own translator program.
The high level programming languages are further divided into:
 Procedural languages
 Non procedural languages
 Object oriented programming languages.

Advantages of High Level Languages


There are several advantages of high level programming languages. The most important advantages are:
 Easy to learn - the high level languages are very easy to learn than low level languages. The
statements written for the program are similar to English-like statements.
 Easy to understand - the program written in high level language by one programmer can easily be
understood by another because the program instructions are similar to the English language.
 Easy to write program - in high level language, a new program can easily be written in a very short
time. The larger and complicated software can be developed in few days or months.
 Easy to detect and remove errors - the errors in a program can be easily detected and removed.
mostly the errors are occurred during the compilation of new program.
 Built-in library functions - Each high level language provides a large number of built-in functions
or procedures that can be used to perform specific task during designing of new programs. In this
way, a large amount of time of programmer is saved.
 Machine Independence - program written in high level language is machine independent. It means
that a program written in one type of computer can be executed on another type of computer.

Limitation of High Level Language


There are two main limitation of high level languages are:
 Low efficiency - a program written in high level languages has lower efficiency than one written in a
machine/assembly language to do the same job. That is, program written in high level languages
result in multiple machine language instruction that may not be optimize, taking more time to
execute and requiring more memory space.
 Less flexibility - high level languages are less flexible than assembly languages because they do not
normally have instructions or mechanism to control a computer's CPU, memory and register.

Procedural Language
Procedural languages are also known as third generation languages (3GLs). In a procedural language, a
program is designed using procedures.
A procedure is a sequence of instructions having a unique name. The instructions of the procedure are
executed with the reference of its name.
In procedural programming languages, the program instructions are written in a sequence or in a specific
order in which they must be executed to solve a specific problem. It means that the order of program
instructions is very important.

Some popular procedural languages are described below:

 FORTRAN it stands for formula translation. It was developed in 1957 for IBM computers. It was
the first earliest high level programming language used to introduce the concept of modular
programming. It has been revised many times. Its commonly used version is FORTRAN 77
 COBOL - it stands for common business oriented language. It was developed in 1959. this high-
level language was specially developed for business and commercial applications. It was suitable for
handling large amount of data such as:
o To prepare payroll
o To process credit and debit account
o To control inventory system and many other business applications
 Pascal - this programming language is named in the honour of Blaise Pascal, a mathematician and
scientist who invented the first mechanical calculator. Structured programming language and is
popular in computer science development in 1971. It is suitable for scientific field.
 ADA - it is developed in 1980 and is named in the honour of Lady Augusta ADA. She was the first
computer programmer. The high level structure language Pascal was used as a model for the
development of ADA language. This language is mainly used for defence purposes such as for
controlling military weapons like missiles etc.
 C language - Dennis Ritchie and Brian Karnighan developed it in 1972 at Bell Laboratories. It is a
high level language but it can also support assembly language codes (low level codes). It is because,
C language is also referred to as middle level language. The program written in C can be compiled
and run on any type of computer. In other words programs written in C language are portable. C
language is a structured programming language. The main feature of C language is that, it uses a
large number of built-in functions to perform various tasks. The user can also creates its own
functions.

Non Procedural Languages


Non procedural programming languages are also known as fourth generation languages. In non procedural
programming languages, the order of program instructions is not important. Ihe importance is given only to,
what is to be done.
With a non procedural language, the user/programmer writes English like instructions to retrieve data from
databases. These languages are easier to use than procedural languages. These languages provide the user-
friendly program development tools to write instructions. The programmers have not to spend much time for
coding the program.
The most important non procedural languages and tools are discussed below:
 SQL - it stands for structured query language. it is very popular database access language and is
specially used to access and to manipulate the data of databases. The word query represents that this
language is used to make queries (or enquiries) to perform various operations on data of database.
However, SQL can also be used to create tables, add data, delete data, update data of database tables
etc.
 RPG - it stands for report program generator. This language was introduced by IBM to generate
business reports. Typically, RPG is used for application development on IBM midrange computers,
such as AS/400.

Object Oriented Programming Languages

The object oriented programming concept was introduced in the late 1960s, but now it has become the most
popular approach to develop software.
In object oriented programming, the software is developed by using a set of interfacing object. An object is a
component of program that has a set of modules and data structure. The modules are also called methods
and are used to access the data from the object. The modern technique to design the program is object
oriented approach. It is a very easy approach, in which program designed by using objects. Once an object
for any program designed, it can be re-used in any other program.
Now-a-days, most popular and commonly used object oriented programming (OOPs) languages are C++
and Java.

 Description of Compiler and Interpreter


We mostly write a computer program in high-level languages, which humans understand. High-level
languages are that which contains words and phrases from human languages - for example, English. The
high-level programming language is also known as source code in a computer program. However, computer
machine does not understand these high-level programming languages. It only understood its machine code,
i.e., a program in 0's and 1's in binary form to perform the task accordingly.

To perform an instruction written in high-level language via computer, we need to convert it into machine
language. To do this, either a compiler or an interpreter, or both are used to convert a source code
programming language into machine code. Compiler and interpreter are software programs that convert a
high-level language into a machine language (0's and 1's binary form) that a computer can understand and
perform tasks as per the program's instructions. But there are variations in the working process and steps of a
compiler and interpreter. Before diving into the difference between a compiler and an interpreter, let's see a
brief introduction about both of them.

Compiler
A compileris a software program that follows the syntax rule of programming language to convert a source
code to machine code. It cannot fix any error if present in a program; it generates an error message, and you
have to correct it yourself in the program's syntax. If your written program is correct (contains no error),
then the compiler will convert your entire source code into machine code. A compiler converts complete
source code into machine code at once. And finally, your program get executes.
The entire compilation steps of source code are operated into two phases: Analysis Phase and Synthesis
Phase.
o Analysis Phase: This compiler phase is also known as the front end phase in which a source code is
divided into fundamental parts to check grammar, syntax, and semantic of code; after that,
the intermediate code is generated. The analysis phase of the compilation process includes a lexical
analyzer, semantic analyzer, and syntax analyzer.
o Synthesis Phase: The Synthesis phase is also known as the back end phase in which
the intermediate code (which was generated in Analysis Phase) is optimized and generated
into target machine code. The synthesis phase of the compilation process includes code optimizer
and code generator tasks.

Interpreter
An interpreteris also a software program that translates a source code into a machine language. However, an
interpreter converts high-level programming language into machine language line-by-line while interpreting
and running the program.
Difference between Compiler and Interpreter

Difference Compiler Interpreter


Types

Programming o Write a program in source code. o Write a program in source code.


Steps o Compile will analyze your program o No linking of files happens, or no
statements and check their machine code will generate
correctness. If an error is found in a separately.
program, it throws an error message. o The source code programming
o If the program contains no error, then statements are executed line-by-line
the compiler will convert the source during their execution. If an error is
code program into machine code. found at any specific statement
o The compiler links all the code files interpreter, it stops further execution
into a single runnable program, which until the error gets removed.
is known as the exe file.
o Finally, it runs the program and
generates output.

Translation A compiler translates complete high-level An interpreter translates one statement of


type programming code into machine code at once. programming code at a time into machine
code.

Advantage As the source code is already converted into As the source code is interpreted line-by-
machine code, the code execution time line, error detection and correction become
becomes short. easy.

Disadvantage If you want to change your program for any Interpreted programs can run on only those
reason, either by error or logical changes, you computers which have the same interpreter.
can do it only by going back to your source
code.

Machine code It stores the converted machine code from It never stores the machine code at all on
your source code program on the disk. the disk.

Running time A compiler takes an enormous time to An interpreter takes less time to analyze
analyze source code. However, overall source code as compared to a compiler.
compiled programming code runs faster as However, overall interpreted programming
compression to an interpreter. code runs slower as compression to the
compiler.

Program The compiler generates an output of a The interpreter doesn't generate a separate
generation program (in the form of an exe file) that can machine code as an output program. So it
run separately from the source code program. checks the source code every time during
the execution.

Execution The process of program execution takes place The process of program execution is a part
separately from its compilation process. of interpretation steps, so it is done line-by-
Program execution only takes place after the line simultaneously.
complete program is compiled.

Memory A compiled program is generated into an An interpreted program does not generate
requirement intermediate object code, and it further an intermediate code. So there is no
required linking. So there is a requirement for requirement for extra memory.
more memory.

Best suited for The compiled program is bounded to the In web environments, compiling takes place
specific target machine. It requires the same relatively more time to run even small code,
compiler on the machine to execute; C and which may not run multiple times. As load
C++ are the most popular programming time is essential in the web environment,
language based on the compilation model. interpreters are better. JavaScript, Python,
Ruby are based on the interpreter model.

Error The compiler shows the complete errors and An interpreter reads the program line-by-
execution warning messages at program compilation line; it shows the error if present at that
time. So it is not possible to run the program specific line. You must have to correct the
without fixing program errors. Doing error first to interpret the next line of the
debugging of the program is comparatively program. Debugging is comparatively easy
complex while working with a compiler. while working with an Interpreter.

Advantage and disadvantage of compiler:-


While using a compiler to translate a source code into machine code, the program codes are translated into
different object codes. Hence the time of code execution is significantly less. The drawback of using a
compiler is that you can only make changes in the program by going back to your source code.

Advantage and disadvantage of an interpreter:-


The interpreter makes it easier to work with source code. So it is highly preferred, especially for beginners.
Interpreted programs can run on only those computers which have the same interpreter.

Advantages of object oriented programming

1. Troubleshooting is easier with the OOP language


Suppose the user has no idea where the bug lies if there is an error within the code. Also, the user has no
idea where to look into the code to fix the error. This is quite difficult for standard programming languages.
However, when Object-Oriented Programming is applied, the user knows exactly where to look into the
code whenever there is an error. There is no need to check other code sections as the error will show where
the trouble lies.It is mainly through encapsulation that makes the objects self-contained. This further helps in
troubleshooting and easier collaborative development.
2. Code Reusability
One of two important concepts that are provided by Object-Oriented Programming is the concept of
inheritance. Through inheritance, the same attributes of a class are not required to be written repeatedly.
This avoids the issues where the same code has still to be written multiple times in a code. With the
introduction of the concept of classes, the code section can be used as many times as required in the
program. Through the inheritance approach, a child class is created that inherits the fields and methods of
the parent class. The methods and values that are present in the parent class can be easily overridden.
Through inheritance, the features of one class can be inherited by another class by extending the class.
Therefore, inheritance is vital for providing code reusability and also multilevel inheritance.
Thus, Object-Oriented Programming offers the feature of class reusability where the class that is once
created can be used again. In doing so, time is saved, and the need for extra coding is eliminated as similar
features can be inherited.
3. Productivity
The productivity of two codes increases through the use of Object-Oriented Programming. This is because
the OOP has provided so many libraries that new programs have become more accessible. Also, as it
provides the facility of code reusability, the length of a code is decreased, further enhancing the faster
development of newer codes and programs.
4. Data Redundancy
By the term data redundancy, it means that the data is repeated twice. This means that the same data is
present more than one time. In Object-Oriented Deprogramming the data redundancy is considered to be an
advantage. For example, the user wants to have a functionality that is similar to almost all the classes. In
such cases, the user can create classes with similar functionaries and inherit them wherever required.
5. Code Flexibility
The flexibility is offered through the concept of Polymorphism. A scenario can be considered for a better
understanding of the concept. A person can behave differently whenever the surroundings change. For
example, if the person is in a market, the person will behave like a customer, or the behavior might get
changed to a student when the person is in a school or any institution.
In this example, it can be observed that different behaviors are shown by the same person whenever the
surroundings around the person get changed. This could explain the concept of Polymorphism and its
flexibility. The developers benefit through Polymorphism in the following ways: simplicity and
extensibility.
6. Solving problems
Problems can be efficiently solved by breaking down the problem into smaller pieces. If a complex problem
is broken down into smaller pieces or components, it becomes a good programming practice. Considering
this fact, OOPS utilizes this feature where it breaks down the code of the software into smaller pieces of the
object into bite-size pieces that are created one at a time. Once the problem is broken down, these broken
pieces can be used again to solve other problems. Also, the more minor codes can get replaced through the
modules with the same interface having the implementation details.
7. Security
Because of the concept of data abstraction in OOPS, only a limited amount of data is shown to the user. The
rest data is not exposed while exposing only the required amount of data. Therefore, it allows the
maintenance of security. The concept of abstraction is used to hide the complexity from other users and
demonstrate the element’s information as per the requirements. It also helps in avoiding repetitive code.
Another concept provided in OOPS is the feature of encapsulation that allows the protection of the data in
the classes from getting accessed by the system. All the internal contents in the class can be safeguarded. In
Java, encapsulation is mainly used for restricting access to the class fields directly while setting all the fields
of the class to private.

 Features of object oriented programming


1. Class:-The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-
defined data type, which holds its own data members and member functions, which can be accessed and
used by creating an instance of that class. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but all
of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage
range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
2. Object: An Object is an identifiable entity with some characteristics and behaviour. An Object is an
instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.
Each object contains data and code to manipulate the data. Objects can interact without having to know
details of each other’s data or code, it is sufficient to know the type of message accepted and type of
response returned by the objects.
3. Encapsulation: Encapsulation is defined as wrapping up of data and information under a single unit. In
Object-Oriented Programming, Encapsulation is defined as binding together the data and the functions
that manipulate them.
Consider a real-life example of encapsulation, in a company, there are different sections like the accounts
section, finance section, sales section etc. The finance section handles all the financial transactions and
keeps records of all the data related to finance. Similarly, the sales section handles all the sales -related
activities and keeps records of all the sales. Now there may arise a situation when for some reason an
official from the finance section needs all the data about sales in a particular month. In this case, he is not
allowed to directly access the data of the sales section. He will first have to contact some other officer in
the sales section and then request him to give the particular data. This is what encapsulation is. Here the
data of the sales section and the employees that can manipulate them are wrapped under a single name
“sales section”.
4. Abstraction:Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding the details.
Data abstraction refers to providing only essential information about the data to the outside world, hiding
the background details or implementation.
 Abstraction using Classes: We can implement Abstraction in C++ using classes. The class helps us to
group data members and member functions using available access specifiers. A Class can decide
which data member will be visible to the outside world and which is not.
 Abstraction in Header files: One more type of abstraction in C++ can be header files. For example,
consider the pow() method present in math.h header file. Whenever we need to calculate the power of
a number, we simply call the function pow() present in the math.h header file and pass the numbers as
arguments without knowing the underlying algorithm according to which the function is actually
calculating the power of numbers.
5. Polymorphism: The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
A person at the same time can have different characteristic. Like a man at the same time is a father, a
husband, an employee. So the same person posses different behaviour in different situations. This is called
polymorphism.
An operation may exhibit different behaviours in different instances. The behaviour depends upon the
types of data used in the operation.
Example: Suppose we have to write a function to add some integers, some times there are 2 integers,
some times there are 3 integers. We can write the Addition Method with the same name having different
parameters, the concerned method will be called according to parameters.

6. Inheritance: The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.
 Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
 Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.
 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.
7. Dynamic Binding: In dynamic binding, the code to be executed in response to function call is decided
at runtime.
8. Message Passing: Objects communicate with one another by sending and receiving information to each
other. A message for an object is a request for execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired results. Message passing involves specifying the
name of the object, the name of the function and the information to be sent.
CHAPTER-II

Introduction to java:-JAVA was developed by James and Patrick Naughton. at Sun Microsystems Inc in
the year 1991, later acquired by Oracle Corporation. It is a simple programming language. Java makes
writing, compiling, and debugging programming easy. It helps to create reusable code and modular
programs.

What is java:- Java is a class-based, object-oriented programming language and is designed to have as
few implementation dependencies as possible. A general-purpose programming language made for
developers to write once run anywhere that is compiled Java code can run on all platforms that support
Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of
Java is similar to c/c++.

Why java:-
 Java is easy to learn:-Java was designed to be easy to use and is therefore easy to write, compile,
debug, and learn than other programming languages.
 Java is object-oriented:-This allows you to create modular programs and reusable code.
 Java is platform-independent:-One of the most significant advantages of Java is its ability to move
easily from one computer system to another. The ability to run the same program on many different
systems is crucial to World Wide Web software, and Java succeeds at this by being platform-
independent at both the source and binary levels.

 History behind 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.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent,
Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and
Dynamic". Javawas 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. Following
are given significant points that describe the history of Java.
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) Initially it was designed for small, embedded systemsin electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
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 Java coffee). 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
Many java versions have been released till now. The current stable release of Java is Java SE 10.
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 (to be released by March 2022

 Features of Java
The primary objective of Java programminglanguage creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role
in the popularity of this language. The features of Java are also known as Java buzzwords.

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++ (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:- Java is an object-orientedprogramming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
3. Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language. A platform is
the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based
platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform that
runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
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 bytecode. This bytecode 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, JAAS, Cryptography, etc.

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


o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
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:-
o Java is architecture neutral because there are no implementation dependent features, for example, the
size of primitive types is fixed.
o In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
Portable
o Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.

7. High-performance
o Java is faster than other traditional interpreted programming languages because Java bytecode 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.
8. Distributed
o Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB
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.
9. Multi-threaded
o 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.
Dynamic
o 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).

 Difference between C/C++ and JAVA

The languages are based on each other but still, they are different in design and philosophy. The following
table describes the major differences between C, C++, and Java. It will help you to select which language
you have to learn.

S.N. Basis C C++ Java

1 Origin The C language is based The C++ language is The Java programming
on BCPL. based on the C language. language is based on both
C and C++.

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


Pattern language. programming language. programming language.

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

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


Static language. programming language. programming language.

5 Code Execution The code is executed The code is executed The code is executed by
directly. directly. the JVM.
6 Platform It is platform dependent. It is platform dependent. It is platform-independent
Dependency because of byte code.

7 Translator It uses a compiler only to It also uses a compiler Java uses both compiler
translate the code into only to translate the and interpreter and it is
machine language. code into machine also known as an
language. interpreted language.

8 File Generation It generates the .exe, and It generates .exe file. It generates .class file.
.bak, files.

9 Number of There are 32 keywords in There are 60 keywords There are 52 keywords in
Keyword the C language. in the C++ language. the Java language.

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

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

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

13 Pre-processor It uses pre-processor It uses pre-processor It does not use directives


Directives directives such as directives such as but uses packages.
#include, #define, etc. #include, #define,
#header, etc.

14 Constructor/ It does not support It supports both It supports constructors


Destructor constructor and constructor and only.
destructor. destructor.

15 Exception It does not support It supports exception It also supports exception


Handling exception handling. handling. handling.

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

17 Overloading It does not support the Method and operator Only method overloading
overloading concept. overloading can be can be achieved.
achieved.

18 goto Statement It supports the goto It also supports the goto It does not support the
statement. statement. goto statements.
19 Used for It is widely used to It is widely used for It is used to develop web
develop drivers and system programming. applications, mobile
operating systems. applications, and windows
applications.

20 Array Size An array should be An array should be An array can be declared


declared with size. For declared with size. without declaring the size.
example, intnum[10]. For example, intnum[].

 First Java Program

o class Simple{
o public static void main(String args[]){
o System.out.println("Hello Java");
o }
o }
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[ ]This represents an array whose type is String and name is args. We
will discuss more about array in Java Array 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.

 Prerequisite before writing a java program

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, and install it.
o Set path of the jdk/bin directory.
o Create the Java program
o Compile and run the Java program

 How to compile and run a java program

Compiling and running a java program is very easy after JDK installation. Following are the steps −
 Open a command prompt window and go to the directory where you saved the java program
(MyFirstJavaProgram.java). Assume it's C:\.
 Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in
your code, the command prompt will take you to the next line (Assumption: The path variable is set).
 Now, type ' java MyFirstJavaProgram ' to run your program.
 You will be able to see the result printed on the window.
The class files generated by the compiler are independent of the machine or the OS, which allows
them to be run on any system. To run, the main class file (the class that contains the method main)
is passed to the JVM and then goes through three main stages before the final machine code is
executed. These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
3. Just-In-Time Compiler
Let us discuss all 3 stages.
Stage 1: Class Loader
The main class is loaded into the memory bypassing its ‘.class’ file to the JVM, through invoking the
latter. All the other classes referenced in the program are loaded through the class loader.
A class loader, itself an object, creates a flat namespace of class bodies that are referenced by a string
name. The method definition is provided below illustration as follows:
Illustration:
// loadClass function prototype
Class r = loadClass(String className, booleanresolveIt);
// className: name of the class to be loaded
// resolveIt: flag to decide whether any referenced class should be loaded or not.
There are two types of class loaders
 primordial
 non-primordial
The primordial class loader is embedded into all the JVMs and is the default class loader. A non-
primordial class loader is a user-defined class loader, which can be coded in order to customize the class-
loading process. Non-primordial class loader, if defined, is preferred over the default one, to load classes.
Stage 2: Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode verifier,
whose job is to check that the instructions don’t perform damaging actions. The following are some of the
checks carried out:
 Variables are initialized before they are used.
 Method calls match the types of object references.
 Rules for accessing private data and methods are not violated.
 Local variable accesses fall within the runtime stack.
 The run-time stack does not overflow.
 If any of the above checks fail, the verifier doesn’t allow the class to be loaded.
Stage 3: Just-In-Time Compiler
This is the final stage encountered by the java program, and its job is to convert the loaded bytecode into
machine code. When using a JIT compiler, the hardware can execute the native code, as opposed to
having the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a
relatively lengthy translation process. This can lead to performance gains in the execution speed unless
methods are executed less frequently.
The process can be well-illustrated by the following diagram as given above as follows from which we
landed up to the conclusion.
Conclusion: Due to the two-step execution process described above, a java program is independent of the
target operating system. However, because of the same, the execution time is way more than a similar
program written in a compiled platform-dependent program.

 What Is the JVM?

A Virtual Machine is a software implementation of a physical machine. Java was developed with the
concept of WORA (Write Once Run Anywhere), which runs on a VM. The compiler compiles the Java
file into a Java .class file, then that .class file is input into the JVM, which loads and executes the class
file. Below is a diagram of the Architecture of the JVM.
 JVM Architecture Diagram

How Does the JVM Work?


As shown in the above architecture diagram, the JVM is divided into three main subsystems:
ClassLoader Subsystem
Runtime Data Area
Execution Engine
1. ClassLoader Subsystem
Java's dynamic class loading functionality is handled by the ClassLoader subsystem. It loads, links. and
initializes the class file when it refers to a class for the first time at runtime, not compile time.
1.1 Loading
Classes will be loaded by this component. BootStrapClassLoader, Extension ClassLoader, and
Application ClassLoader are the three ClassLoaders that will help in achieving it.
BootStrap ClassLoader – Responsible for loading classes from the bootstrap classpath, nothing
but rt.jar. Highest priority will be given to this loader.
Extension ClassLoader – Responsible for loading classes which are inside the ext folder (jre\lib).
Application ClassLoader –Responsible for loading Application Level Classpath, path mentioned
Environment Variable, etc.
The above ClassLoaders will follow Delegation Hierarchy Algorithm while loading the class files.
1.2 Linking
Verify – Bytecode verifier will verify whether the generated bytecode is proper or not if verification fails
we will get the verification error.
Prepare – For all static variables memory will be allocated and assigned with default values.
Resolve – All symbolic memory references are replaced with the original references from Method Area.
1.3 Initialization
This is the final phase of ClassLoading; here, all static variables will be assigned with the original values,
and the static block will be executed.
2. Runtime Data Area
The Runtime Data Area is divided into five major components:
Method Area – All the class-level data will be stored here, including static variables. There is only one
method area per JVM, and it is a shared resource.
Heap Area – All the Objects and their corresponding instance variables and arrays will be stored here.
There is also one Heap Area per JVM. Since the Method and Heap areas share memory for multiple
threads, the data stored is not thread-safe.
Stack Area – For every thread, a separate runtime stack will be created. For every method call, one entry
will be made in the stack memory which is called Stack Frame. All local variables will be created in the
stack memory. The stack area is thread-safe since it is not a shared resource. The Stack Frame is divided
into three subentities:
Local Variable Array – Related to the method how many local variables are involved and the
corresponding values will be stored here.
Operand stack – If any intermediate operation is required to perform, operand stack acts as runtime
workspace to perform the operation.
Frame data – All symbols corresponding to the method is stored here. In the case of any exception, the
catch block information will be maintained in the frame data.
PC Registers – Each thread will have separate PC Registers, to hold the address of current executing
instruction once the instruction is executed the PC register will be updated with the next instruction.
Native Method stacks – Native Method Stack holds native method information. For every thread, a
separate native method stack will be created.
3. Execution Engine
The bytecode, which is assigned to the Runtime Data Area, will be executed by the Execution Engine.
The Execution Engine reads the bytecode and executes it piece by piece.
Interpreter – The interpreter interprets the bytecode faster but executes slowly. The disadvantage of the
interpreter is that when one method is called multiple times, every time a new interpretation is required.
JIT Compiler – The JIT Compiler neutralizes the disadvantage of the interpreter. The Execution Engine
will be using the help of the interpreter in converting byte code, but when it finds repeated code it uses the
JIT compiler, which compiles the entire bytecode and changes it to native code. This native code will be
used directly for repeated method calls, which improve the performance of the system.
Intermediate Code Generator – Produces intermediate code
Code Optimizer – Responsible for optimizing the intermediate code generated above
Target Code Generator – Responsible for Generating Machine Code or Native Code
Profiler – A special component, responsible for finding hotspots, i.e. whether the method is called
multiple times or not.
Garbage Collector: Collects and removes unreferenced objects. Garbage Collection can be triggered by
calling System.gc(), but the execution is not guaranteed. Garbage collection of the JVM collects the
objects that are created.
Java Native Interface (JNI): JNI will be interacting with the Native Method Libraries and provides the
Native Libraries required for the Execution Engine.
Native Method Libraries: This is a collection of the Native Libraries, which is required for the Execution
Engine.
CHAPTER-III
 Java Tokens:-
In Java, the program contains classes and methods. Further, the methods contain the expressions and
statements required to perform a specific operation. These statements and expressions are made up
of tokens. In other words, we can say that the expression and statement is a set of tokens. The tokens are the
small building blocks of a Java program that are meaningful to the Java compiler. Further, these two
components contain variables, constants, and operators.
What is token in Java?
The Java compiler breaks the line of code into text (words) is called Java tokens. These are the smallest
element of the Java program. The Java compiler identified these words as tokens. These tokens are separated
by the delimiters. It is useful for compilers to detect errors. Remember that the delimiters are not part of the
Java tokens,For example, consider the following code.
public class Demo
{
public static void main(String args[])
{
System.out.println("javatpoint");
}
}
In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [, ], ), System, ., out,
println, javatpoint, etc. are the Java tokens. The Java compiler translates these tokens into Java bytecode
. Further, these bytecodes are executed inside the interpreted Java environment.
Types of Tokens
Java token includes the following:
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords: These are the pre-defined reserved words of any programming language. Each keyword
has a special meaning. It is always written in lower case. Java provides the following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class

06. case 07. catch 08. char 09. continue 10. default

11. do 12. double 13. else 14. extends 15. final

16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. int 24. interface 25. long

26. native 27. new 28. package 29. private 30. protected

31. public 32. return 33. short 34. static 35. super

36. switch 37. synchronized 38. this 39. thro 40. throws

41. transient 42. try 43. void 44. volatile 45. while

46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier: Identifiers are used to name a variable, constant, function, class, and array. It usually defined by
the user. It uses letters, underscores, or a dollar sign as the first character. The label is also known as a
special kind of identifier that is used in the goto statement. Remember that the identifier name must be
different from the reserved keywords. There are some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with digits
but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.

Literals: In programming literal is a notation that represents a fixed value (constant) in the source code. It
can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the programmer.
Once it has been defined cannot be changed. Java provides five types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean

Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"javatpoint" String

null any reference type

Operators: In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the functionality they
provide. There are eight types of operators in Java , are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

perator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||
Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>

Separators: The separators in Java is also known as punctuators. There are nine separators in Java, are as
follows:
separator <= ; | , | . | ( | ) | { | } | [ | ]
o Square Brackets []: It is used to define array elements. A pair of square brackets represents the
single-dimensional array, two pairs of square brackets represent the two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two
statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.
o
Comments: Comments allow us to specify information about the program inside our Java code. Java
compiler recognizes these comments as tokens but excludes it form further processing. The Java compiler
treats comments as whitespaces. Java provides the following two types of comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.

 Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are the most basic
data types available in Java language.
There are 8 types of primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its
value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-
2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is
- 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The
long data type is used when you need a range of values more than those provided by int.

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating point
numbers. The float data type should never be used for precise values, such as currency. Its default value is
0.0F.

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. The double data type also should never
be used for precise values, such as currency. Its default value is 0.0d.

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff'
(or 65,535 inclusive).The char data type is used to store characters.

Why char uses 2 byte in java and what is \u0000 ?


It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode
system. To get detail explanation about Unicode visit next page.

Unicode System
Unicode is a universal international standard character encoding that is capable of representing most of the w
languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:

ASCII (American Standard Code for Information Interchange) for the United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.

Problem
This caused two problems:
1. A particular code value corresponds to different letters in the various language standards.
2. The encodings for languages with large character sets have variable length. Some common
characters are encoded as single bytes, other require two or more byte.
Solution
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
 Operators in Java
Operators are the constructs which can manipulate the values of the operands. Consider the expression 2 + 3
= 5, here 2 and 3 are operands and + is called operator. In this article on Java operators, the goal is to get
you the expertise required to get started and work with operators in Java.
Java supports the following types of operators:
 Arithmetic Operators
 Assignment Operators
 Logical Operators
 Relational Operators
 Unary Operators
 Bitwise Operators
 Ternary Operators
 Shift Operators
Arithmetic Operators in Java:-Arithmetic Operators are used to perform mathematical operations like
addition, subtraction, etc. Assume that A = 10 and B = 20 for the below table.
Operator Description Example
Adds values on either side of the
+ Addition A+B=30
operator
Subtracts the right-hand operator
– Subtraction A-B=-10
with left-hand operator
Multiplies values on either side of
* Multiplication A*B=200
the operator
Divides left hand operand with
/ Division A/B=0
right hand operator
Divides left hand operand by right
% Modulus hand operand and returns A%B=0
remainder

Assignment Operators in Java:-An Assignment Operator is an operator used to assign a new value to a
variable. Assume A = 10 and B = 20 for the below table.
Operator Description Example
= Assigns values from right side operands to left side operand c=a+b
It adds right operand to the left operand and assigns the result to
+= c += a
left operand
It subtracts right operand from the left operand and assigns the
-= c -= a
result to left operand
It multiplies right operand with the left operand and assigns the
*= c *= a
result to left operand
It divides left operand with the right operand and assigns the
/= c /= a
result to left operand
It takes modulus using two operands and assigns the result to
%= c %= a
left operand
Performs exponential (power) calculation on operators and
^= c ^= a
assign value to the left operand

Relational Operators in Java:-These operators compare the values on either side of them and decide the
relation among them. Assume A = 10 and B = 20.

Operator Description Example


== If the values of two operands are (A == B) is not true
equal, then the condition becomes
true.
If the values of two operands are
!= not equal, then condition becomes (A != B) is true
true.
If the value of the left operand is
greater than the value of right
> (a > b) is not true
operand, then condition becomes
true.
If the value of the left operand is
< less than the value of right operand, (a < b) is true
then condition becomes true.
If the value of the left operand is
greater than or equal to the value of
>= (a >= b) is not true
the right operand, then condition
becomes true.
If the value of the left operand is
less than or equal to the value of
<= (a <= b) is true
right operand, then condition
becomes true.

Logical Operators in Java:-The following are the Logical operators present in Java:
Operator Description Example
&& (and) True if both the operands is true a<10 && a<20
|| (or) True if either of the operands is true a<10 || a<20
! (not) True if an operand is false (complements the operand) !(x<10 && a<20)

Unary Operator in Java:- Unary operators are the one that needs a single operand and are used to
increment a value, decrement or negate a value.
Operator Description Example
increments the value by 1. There is post-increment and pre-increment
++ a++ and ++a
operators
decrements the value by 1. There is post decrement and pre decrement
— a– or –a
operators
! invert a boolean value !a
Bitwise Operator in Java:-Bitwise operations directly manipulate bits. In all computers, numbers are represented
with bits, a series of zeros and ones. In fact, pretty much everything in a computer is represented by bits. Assume that
A = 10 and B = 20 for the below table.
Operator Description Example

& (AND) returns bit by bit AND of input a&b

| (OR) returns OR of input values a|b

^ (XOR) returns XOR of input values a^b

~
returns the one’s complement. (all bits reversed) ~a
(Complement)
Ternary Operators in Java:-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);

 Condition: It is the expression to be evaluated which returns a boolean value .


 Statement 1: It is the statement to be executed if the condition results in a true state .
 Statement 2: It is the statement to be executed if the condition results in a false state.

Shift Operators in Java:-Shift operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number. There are three different types of shift operators, namely left shift
operator()<<, signed right operator(>>) and unsigned right shift operator(>>>).

Syntax: number shift_opnumber_of_places_to_shift;

 Typecasting in Java
Programming is playing around with data. In Java, there are many data types. Most of the times while
coding, it is necessary to change the type of data to understand the processing of a variable and this is called
Type Casting.
What is Type Casting?
Type casting is nothing but assigning a value of one primitive data type to another. When you assign the
value of one data type to another, you should be aware of the compatibility of the data type. If they are
compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and
if not, then they need to be casted or converted explicitly.
There are two types of casting in Java as follows:
 Widening Casting
 Narrowing Casting
Widening Casting (automatically) – This involves the conversion of a smaller data type to the larger type
size.
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) – This involves converting a larger data type to a smaller size type.
double -> float -> long -> int -> char -> short -> byte

Widening Casting
This type of casting takes place when two data types are automatically converted. It is also known as
Implicit Conversion. This happens when the two data types are compatible and also when we assign the
value of a smaller data type to a larger data type.
Example:-
public class Conversion{
public static void main(String[] args)
{
int i = 200;
//automatic type conversion
long l = i;
//automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Output:
Int value 200
Long value 200
Float value 200.0
Narrowing Casting
In this case, if you want to assign a value of larger data type to a smaller data type, you can perform Explicit
type casting or narrowing. This is useful for incompatible data types where automatic conversion cannot be
done.
Example:-
program to illustrate explicit type conversion
public class Narrowing
{
public static void main(String[] args)
{
double d = 200.06;
//explicit type casting
long l = (long)d;
//explicit type casting
int i = (int)l;
System.out.println("Double Data type value "+d);
//fractional part lost
System.out.println("Long Data type value "+l);
//fractional part lost
System.out.println("Int Data type value "+i);
}
}
Output:
Double Data type value 200.06
Long Data type value 200
Int Data type value 200

Explicit Type Casting in Expressions


When you are evaluating the expressions, the output is automatically updated to the larger data type of the
operand. But if you store that result in any smaller data type it generates compile time error, due to which we
need to type cast the output.
 Java Control Statements | Control Flow in Java
Java compiler executes the code from top to bottom. The statements in the code are executed according to
the order in which they appear. However, Javaprovides statements that can be used to control the flow of
Java code. Such statements are called control flow statements. It is one of the fundamental features of Java,
which provides a smooth flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when. Decision-
making statements evaluate the Boolean expression and control the program flow depending upon the result
of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and
switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending
upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In
Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression
and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20

2) if-else statement:-
The if-else statementis an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we
can say that it is the chain of if-else statements that create a decision tree where the program may enter in the
block of code where the condition is true. We can also define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.
Student.java
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Output:
Delhi
4. Nested if-statement:
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.

Student.java
public class Student {
public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:
Delhi

Switch Statement:
In Java, Switch statementsare similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.

Points to be noted about switch statement:


o The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same type as
the variable. However, it will also be a constant value.

The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Student.java
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:
2

While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value. The switch permits only int, string, and Enum type
variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates
to true. However, loop statements are used to execute the set of instructions in a repeated order. The
execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax
and condition checking time.
1. for loop
2. while loop
3. do-while loop
Java for loop
In Java, for loopis similar to Cand C++. It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code. We use the for loop only when we exactly know the number of
times, we want to execute the block of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
Calculation.java
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55

For-Each loop
The traversal of elements in an array can be done by the for-each loop. The elements present in the array are
returned one by one. It must be noted that the user does not have to increment the value in the for-each loop.
Example:
public class foreachLoop{
public static void main(String args[]){
ints[] = {18,25,28,29,30};
for (inti : s) {
System.out.println(i);
}
}
}
Output:
18
25
28
29
30
while loop:-
The while loopis also used to iterate over the number of statements multiple times. However, if we don't
know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the
initialization and increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be
executed.
The syntax of the while loop is given below.
while(condition){
//looping statements
}

Example:
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
do-while loop
The do-while loopchecks the condition at the end of the loop after executing the loop statements. When the
number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the
do-while loop is given below.
do
{
//statements
} while (condition)
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10

Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words,
jump statements transfer the execution control to the other part of the program. There are two types of jump
statements in Java, i.e.,

1. Break and
2. Continue.
1. Java break statement
As the name suggests, the break statementis used to break the current flow of the program and transfer the
control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in
the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the
loop or switch statement.
BreakExample.java
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6

2. Java continue statement


Unlike break statement, the continue statementdoesn't break the loop, whereas, it skips the specific part of
the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Example:
public class Main
{
public static void main(String args[])
{
for (int k = 5; k < 15; k++)
{
// Odd numbers are skipped
if (k%2 != 0)
continue;
// Even numbers are printed
System.out.print(k + " ");
Output:
6 8 10 12 14
 Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on
1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
datatype[] arr; (or)
datatype []arr; (or)
datatype arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse
an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop
. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then
executes the body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array){
//body of the loop
}
Example of print the elements of Java array using the for-each loop.
//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5

Passing Array to a Method in Java


We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any array.
Example to get the minimum number of an array using a method.
//Java Program to demonstrate the way of passing an array
//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];

System.out.println(min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Output:
3
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the array while passing an
array to the method.
//Java Program to demonstrate the way of passing an anonymous array to method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}
Output:
10
22
44
66

Returning Array from the Method


We can also return an array from the method in Java.
//Java Program to return an array from the method
class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}
Output:
10
30
50
90
60
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
123
245
445

Copying a Java Array


We can copy an array to another by the arraycopy() method of System class.
Syntax of arraycopy method
public static void arraycopy( Object src, int srcPos,Object dest, int destPos, int length )
Example of Copying an Array in Java
//Java Program to copy a source array into a destination array in Java
class TestArrayCopyDemo {
public static void main(String[] args) {
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
//copying array using System.arraycopy() method
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));
}
}
Output:
caffein
Cloning an Array in Java
Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we create
the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will copy the
actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy of the Java
array which means it copies the references.
//Java Program to clone the array
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
System.out.println("Printing original array:");
for(int i:arr)
System.out.println(i);
System.out.println("Printing clone of the array:");
int carr[]=arr.clone();
for(int i:carr)
System.out.println(i);
System.out.println("Are both equal?");
System.out.println(arr==carr);
}}

Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
False

 Command line argument


The command line argument is the argument that passed to a program during runtime. It is the way to pass
argument to the main method in Java. These arguments store into the String type args parameter which is
main method parameter.
To access these arguments, you can simply traverse the args parameter in the loop or use direct index value
because args is an array of type String.
For example, if we run a HelloWorld class that contains main method and we provide argument to it during
runtime, then the syntax would be like.
java HelloWorld arg1 arg2 ...
We can pass any number of arguments because argument type is an array
Example
In this example, we created a class HelloWorld and during running the program we are providing command-
line argument.
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}
Execute this program as java cmd 10 20 30
Output:-
10
20
30
Example:-Factorial of a number using command-line arguments
class Example1{
publicstaticvoidmain(String[] args){
inta , b = 1;
intn = Integer.parseInt(args[0]);
for(a = 1; a<= n ; a++)
{
b = b*a;
}
System.out.println("factorial is"+b);
}
}
Output:

Example:-Sum of two numbers using command-line arguments


class Example2{
public static void main(String[] args){
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.println("The sum is" +sum);
}
}
Output:

Example:-Fibonacci Series program using command-line arguments


class Example3{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
int t1 = 0;
int t2 = 1;
for(int i = 1; i <=n; i++){
System.out.println(t1);
int sum = t1+t2;
t1 = t2;
t2 = sum;
}
}
}
Output:
 Taking input from keyboard:-

1. Using Scanner Class:-


The Scanner class is used to get user input, and it is found in the java.util package.To use the Scanner class,
create an object of the class and use any of the available methods found in the Scanner class documentation.
In our example, we will use the nextLine() method, which is used to read Strings:
Example
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");.

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output user input
}
}
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read other types,
look at the table below:
Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user


Example
import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
String name = myObj.nextLine(); // String input
int age = myObj.nextInt(); // Numerical input
double salary = myObj.nextDouble();// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}

Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like
"InputMismatchException").

2. Using BufferedReader Class:-

These are the following steps to take character input using BufferedReader:
1. In the first step, we have to create an instance of the BufferedReader class by using
the InputStreamReader The InputStreamReader is a class that act as a bridge in between the byte stream to
character stream. The reason of using InputStreamReaderis to decode bytes to characters.
2. We will use the read() method of the BufferedReader class to read character from the
given BufferedReader and typecast it to char.
3. We will store the return value of the read() method into the character type variable. The read() method
returns the character read by this method. The read() method gives us result -1 in case when the buffered
stream has ended and there is no character to be read.
4. At the end, we will print the character data on the screen which we read using the read() method.

Example:-Simply read the character data using the BufferedReader class and print it to the screen.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReaderExample {
public static void main(String[] args) throws IOException{
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
char data = (char)obj.read();
System.out.println(data);
}
}
Output:-

Example:- String from user using BufferedReader class and perform some operations on the user entered
string..
//Import classes and packages
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//Creating BufferedReaderExample2 class
public class BufferedReaderExample2 {
public static void main(String[] args) throws IOException{ //main() method with IOException
//Creating instance of the BufferedReader class with InputStreamReader
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
System.out.print ( "Enter the height of triangle:" ); //Getting height of triangle
String hightData = obj.readLine();
double height = Double.parseDouble ( hightData );
System.out.print ( "Enter the base of triangle:" ); //Getting base of triangle
String baseData = obj.readLine();
double base = Double.parseDouble ( baseData ); //Calculating area of triangle
double area = (height*base)/2; //Printing the area of the triangle
System.out.println("The area of triangle is:"+area );
}
}
Output

References:-
1. PROGRAMMING WITH JAVA BY E.BALAGURUSAMY
2. JAVA COMPLETE REFERENCE BY HERBALT SCHELIDT
3.CORE JAVA BY RASMI KANTA DAS
4. ONLINE DIFFERENT WEB SITES.

You might also like