JAVA_UNIT I&II

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 83

II BCA

ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

UNIT I
Introduction to OOPS: Paradigms of Programming Languages – Basic concepts of Object
Oriented Programming – Differences between Procedure Oriented Programming and Object
Oriented programming - Benefits of OOPs – Application of OOPs. Java: History – Java
features – Java Environment – JDK – API. Introduction to Java: Types of java program –
Creating and Executing a Java program – Java Tokens- Java Virtual Machine (JVM) –
Command Line Arguments –Comments in Java program.

INTRODUCTION TO OOPS

PARADIGMS OF PROGRAMMING LANGUAGES

Imperative programming paradigm:


It is one of the oldest programming paradigm.

 It features close relation to machine architecture.


 It is based on Von Neumann architecture.
 It works by changing the program state through assignment statements.
 It performs step by step task by changing state.
 The main focus is on how to achieve the goal.
 The paradigm consist of several statements and after execution of all the result is
stored.

Imperative programming is divided into three broad categories: Procedural, OOP and
parallel processing. These paradigms are as follows:
Procedural programming paradigm –
This paradigm emphasizes on procedure in terms of under lying machine model.
 There is no difference in between procedural and imperative approach.
 It has the ability to reuse the code and it was boon at that time when it was in use
because of its reusability.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Object oriented programming –


The program is written as a collection of classes and object which are meant for
communication.
 The smallest and basic entity is object and all kind of computation is performed
on the objects only.
 More emphasis is on data rather procedure.
 It can handle almost all kind of real life problems which are today in scenario.
Advantages:
 Data security
 Inheritance
 Code reusability
 Flexible and abstraction is also present
Parallel processing approach –
Parallel processing is the processing of program instructions by dividing them among
multiple processors.
 A parallel processing system posses many numbers of processor with the objective
of running a program in less time by dividing them.
 This approach seems to be like divide and conquer.
 Examples are NESL (one of the oldest one) and C/C++ also supports because of
some library function.
Declarative programming paradigm:
It is divided as Logic, Functional, Database.
 In computer science the declarative programming is a style of building programs
that expresses logic of computation without talking about its control flow. It often
considers programs as theories of some logic.
 It may simplify writing parallel programs.
 The focus is on what needs to be done rather how it should be done basically
emphasize on what code is actually doing.
 It just declares the result we want rather how it has be produced.
 This is the only difference between imperative (how to do) and declarative (what to
do) programming paradigms.
 Getting into deeper we would see logic, functional and database.
Logic programming paradigms –
It can be termed as abstract model of computation.
 It would solve logical problems like puzzles, series etc.
 In logic programming we have a knowledge base which we know before and along
with the question and knowledge base which is given to machine, it produces result.
 In normal programming languages, such concept of knowledge base is not available
but while using the concept of artificial intelligence, machine learning we have
some models like Perception model which is using the same mechanism.
In logical programming the main emphasize is on knowledge base and the problem.
The execution of the program is very much like proof of mathematical statement,
e.g., Prolog
sum of two number in prolog:

predicates
sumoftwonumber(integer, integer)
clauses
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

sum(0, 0).
sum(n, r):-
n1=n-1,
sum(n1, r1),
r=r1+n
Functional programming paradigms –
The functional programming paradigms has its roots in mathematics and it is language
independent.
 The key principle of this paradigms is the execution of series of mathematical
functions.
 The central model for the abstraction is the function which are meant for some
specific computation and not the data structure.
 Data are loosely coupled to functions.
 The function hide their implementation. Function can be replaced with their values
without changing the meaning of the program.
 Some of the languages like perl, javascript mostly uses this paradigm.
Examples of Functional programming paradigm:

JavaScript : developed by Brendan Eich


Haskell : developed by Lennart Augustsson, Dave Barton
Scala : developed by Martin Odersky
Erlang : developed by Joe Armstrong, Robert Virding
Lisp : developed by John Mccarthy
ML : developed by Robin Milner
Clojure : developed by Rich Hickey
The next kind of approach is of Database.
 Database/Data driven programming approach –
This programming methodology is based on data and its movement. Program statements
are defined by data rather than hard-coding a series of steps.
 A database program is the heart of a business information system and provides file
creation, data entry, update, query and reporting functions. There are several
programming languages that are developed mostly for database application.
 For example SQL. It is applied to streams of structured data, for filtering,
transforming, aggregating (such as computing statistics), or calling other programs. So
it has its own wide application.
CREATE DATABASE databaseAddress;
CREATE TABLE Addr (
PersonID int,
LastName varchar(200),
FirstName varchar(200),
Address varchar(200),
City varchar(200),
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

State varchar(200)
);

BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING

OOPs (Object-Oriented Programming System)

 Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.

It simplifies software development and maintenance by providing some concepts:

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

Object
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 Any entity that has state and behavior is known as an object.


 For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.

 An Object can be defined as an instance of a class. An object contains an address and


takes up some space in memory.

 Objects can communicate without knowing the details of each other's data or code.

 The only necessary thing is the type of message accepted and the type of response
returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

Class

 Collection of objects is called class.


 It is a logical entity.

 A class can also be defined as a blueprint from which you can create an individual
object.

 Class doesn't consume any space.

Inheritance

 When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance.
 It provides code reusability.

 It is used to achieve runtime polymorphism.


II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Polymorphism

 If one task is performed in different ways, it is known as polymorphism.


 For example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.

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

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

Abstraction

 Hiding internal details and showing functionality is known as abstraction.


 For example phone call, we don't know the internal processing.

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

Encapsulation

 Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
 For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

DIFFERENCES BETWEEN PROCEDURE ORIENTED PROGRAMMING AND OBJECT


ORIENTED PROGRAMMING
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

S.no On the Procedural Programming Object-oriented


. basis of programming

1. Definition It is a programming language that is Object-oriented programming is


derived from structure programming and a computer programming
based upon the concept of calling design philosophy or
procedures. It follows a step-by-step methodology that organizes/
approach in order to break down a task models software design around
into a set of variables and routines via a data or objects rather than
sequence of instructions. functions and logic.

2. Security It is less secure than OOPs. Data hiding is possible in


object-oriented programming
due to abstraction. So, it is more
secure than procedural
programming.

3. Approach It follows a top-down approach. It follows a bottom-up


approach.

4. Data In procedural programming, data moves In OOP, objects can move and
movement freely within the system from one communicate with each other
function to another. via member functions.

5. Orientation It is structure/procedure-oriented. It is object-oriented.

6. Access There are no access modifiers in The access modifiers in OOP


modifiers procedural programming. are named as private, public,
and protected.

7. Inheritance Procedural programming does not have There is a feature of inheritance


the concept of inheritance. in object-oriented
programming.

8. Code There is no code reusability present in It offers code reusability by


reusability procedural programming. using the feature of inheritance.

9. Overloading Overloading is not possible in procedural In OOP, there is a concept of


programming. function overloading and
operator overloading.

10. Importance It gives importance to functions over data. It gives importance to data over
functions.

11. Virtual class In procedural programming, there are no In OOP, there is an appearance
virtual classes. of virtual classes in inheritance.

12. Complex It is not appropriate for complex It is appropriate for complex


problems problems. problems.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

13. Data hiding There is not any proper way for data There is a possibility of data
hiding. hiding.

14. Program In Procedural programming, a program is In OOP, a program is divided


division divided into small programs that are into small parts that are referred
referred to as functions. to as objects.

15. Examples Examples of Procedural programming The examples of object-oriented


include C, Fortran, Pascal, and VB. programming are -
.NET, C#, Python, Java,
VB.NET, and C++.

BENEFITS OF OOPs:
Code reusability
 New objects can be derived from old objects, allowing for improvement and
refinement of the code at each stage and also preserving parts of the code for other
programs.
 This is used to develop many class libraries using class codes that have already been
written, for example, Microsoft Foundation Classes (MFC).
Code Modularity
 Everything in OOP is an object;
 these objects can be interchanged or removed to meet the users’ needs .
Easier maintenance
 Inheritance usually reduces maintenance because of the ‘domino effect it has on
derived classes when a change is made in a base class.
Design stability
 Once a stable base class has been developed, the new classes that are derived may
have fewer less errors and bugs.
Improved communication
 between developers and users Objects can be broken down into real life entities,
hence it is easier it communicate ideas.
Seamless transition
 from design to implementation This is mainly because communications are improved

APPLICATION OF OOPs

 Object-oriented programming (OOP) is a programming language model that revolves


around objects and not actions.
 Historically, it was viewed as a procedure that takes input, processes the data, and
gives an output.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 Web developers across the world learn object-oriented programming with Python to
achieve many goals.

 If you are new to the game, here are some basic concepts of OOP:

Abstraction
Abstraction is the process of picking out (abstracting) similar characteristics of procedures
and objects.
Class
Class is categorizing objects. A class defines all the common traits of the numerous objects
that fall under it.
Encapsulation
Encapsulation is wrapping the data under a single, consolidated unit. In OOP, it is defined as
binding data with a function that manipulates it.
Inheritance
Inheritance is the ability of one class to derive its characteristics from another class.
Interface
Interface comprises the languages and the codes used by various applications to communicate
with each other.
Object
Object is an entity that is self-contained. It consists of data as well as procedures.
Polymorphism
Polymorphism refers to a programming language’s ability to process objects uniquely
according to their data type and/or class.
Procedure
Procedure is the part of a program performing a specific task.
Message Passing
Message passing is a form of communication used in parallel programming and OOP.

JAVA HISTORY

JAVA EVOLUTION

 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".
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 Java was developed by James Gosling, who is known as the father of Java, in 1995.
James Gosling and his team members started the project in the early '90s.

 Java is used in internet programming, mobile devices, games, e-business solutions,


etc. Following are given significant points that describe the history of Java.

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

 Initially it was designed for small, embedded systems in electronic appliances like set-
top boxes.

 Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

 After that, it was called Oak and was developed as a part of the Green project.

Why Java was named as "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.In 1995, Oak was renamed as "Java" because it was
already a trademark by Oak Technologies.

Why Java Programming named "Java"?

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.

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.

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

Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary


of Oracle Corporation) and released in 1995.

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

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.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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 programming language 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.

A list of the most important features of the Java language

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

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.
Object-oriented
o Java is an object-oriented programming language.
o Everything in Java is an object.
o Object-oriented means we organize our software as a combination of different
types of objects that incorporate both data and behavior.
 Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.

Platform Independent

o 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.
o A platform is the hardware or software environment in which a program runs.

o 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).

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
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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.

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.

Architecture-neutral

 Java is architecture neutral because there are no implementation dependent


features, for example, the size of primitive types is fixed.
 In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture.

 However, it occupies 4 bytes of memory for both 32 and 64-bit architectures


in Java.

Portable

 Java is portable because it facilitates you to carry the Java bytecode to any
platform.
 It doesn't require any implementation.

High-performance

 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.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Distributed

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.

Multi-threaded

 A thread is like a separate program, executing concurrently.


 We can write Java programs that deal with many tasks at once by defining
multiple threads.

 The main advantage of multi-threading is that it doesn't occupy memory for


each thread.

 It shares a common memory area.

 Threads are important for multi-media, Web applications, etc.

Dynamic

 Java is a dynamic language.


 It supports the dynamic loading of classes.

 It means classes are loaded on demand. It also supports functions from its
native languages, i.e., C and C++.

 Java supports dynamic compilation and automatic memory management


(garbage collection).

JDK

 JDK is an acronym for Java Development Kit.


 The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications and applets.

 It physically exists. It contains JRE + development tools.

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

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.

Components of JDK in Java

The fundamental components of JDK in Java are listed below.


 java
It acts as the deployment launcher in the older SUN java. It loads the class files and interprets
the source code compiled by the javac compiler.
 javac
The javac specifies the java compiler to convert the source code into bytecode.
 javadoc
The javadoc generates documentation for the comments added in the source code.
 jar
The jar helps the archives to manage the jar files in the package library.
 jps
The jps stands for Java Virtual Machine Process Status Tool. It manages the active JVMs for
the currently executing program.
 appletviewer
The appletviewer is designed to run and debug Java applets without the help of an internet
browser.
 idlj
An IDL-to-Java compiler generates Java bindings from a given Java IDL file.
 javap
The javap acts as a file disassembler.
 JConsole
JConsole acts as a Java Management and Monitoring unit.
 javah
The javah is a stub-generator, and C-Header is employed to write native methods.
 javaws
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

The javaws acts as the Web Start launcher for JNLP applications.
 jhat
The jhat is a heap analysis tool.
 jmc
The jmc stands as an abbreviation for Java Mission Control.
Now that we know the vital components of JDK, let us move ahead and understand the
various latest JDK versions available currently for Java.

Latest Version of JDK in Java

The oracle corporations own the current Java, and now it is commercially available. Yet,
there is still a free java version available, which is called OpenJDK.

The current Java JDK version from Oracle corporation is the JDK 14. The following are the
features of Oracle JDK 14.

1. Text blocks

2. Pattern Matching for instanceof


3. Helpful NullPointerExceptions
4. Records
5. Packaging Tool
6. NUMA-Aware Memory Allocation for G1

Moving ahead, we will learn the steps to install Java into your local computer system.

The Architecture of JDK in Java

The architecture of JDK in Java includes the following modules as described in the image
below.

The three vital software modules of JDK are:

JVM (Java Virtual Machine)

Java Virtual Machine is a software tool responsible for creating a run-time environment for
the Java source code to run. The very powerful feature of Java, "Write once and run
anywhere," is made possible by JVM.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

The JVM stays right on top of the host operating system and converts the java source code
into ByteCode (machine language), and executes the program.

JDK (Java Development Kit)

We can define the Java Development Kit as a software development environment responsible
for creating a run-time environment for the Java source code to run.

JRE (Java Run-time Environment)

Java Run-time Environment is a software platform where all the Java Source codes are
executed. JRE is responsible for integrating the software plugins, jar files, and support
libraries necessary for the source code to run.

We have explored the architecture of JDK in Java, and now we will move ahead and learn
more about the components of JDK in Java.

Getting started with JDK in Java

Getting Started with Java is easy. We have to follow the steps mentioned below.

System Requirements:

1. Windows Vista, 7, 8, and above or Linux Operating System

2. 128 MB and above Space on the RAM


3. 128 MB and above Space on the ROM
4. Internet Browser

Steps to download and install Java

1. Navigate to the official website of Java

2. Create an Oracle Account


3. Download the latest version of JDK
4. Setup the environment for Java
5. Verify Java Installation

With that, we have come to the end of this article based on the JDK in Java.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

API

Java APIs

Java APIs are integrated pieces of software that come with JDKs. APIs in Java provides the
interface between two different applications and establish communication.

We will learn more about Java APIs in the next section.

What Are Java APIs?

 APIs are important software components bundled with the JDK. APIs in Java include
classes, interfaces, and user Interfaces.

 They enable developers to integrate various applications and websites and offer real-
time information.

The following image depicts the fundamental components of the Java API.

What is Java API, its Advantages and Need for it


Lesson 25 of 34By Ravikiran A S
Last updated on Aug 9, 2022134054

Java application programming interfaces (APIs) are predefined software tools that easily
enable interactivity between multiple applications.

JDK

As previously noted, a Java download consists of two files:

 JDK

 JRE

Installing Java is usually simple. To learn more, please see the Simplilearn article “One-Stop
Solution for Java Installation in Windows.”

The JDK file is key to developing APIs in Java and consists of:
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 The compiler

 The JVM
 The Java API

Compiler

A Java compiler is a predefined program that converts the high-level, user-


written code language to low-level, computer-understandable, byte-code language during the
compile time.

JVM

A JVM processes the byte-code from the compiler and provides an output in a user-readable
format.

Java APIs

Java APIs are integrated pieces of software that come with JDKs. APIs in Java provides the
interface between two different applications and establish communication.

We will learn more about Java APIs in the next section.

What Are Java APIs?

APIs are important software components bundled with the JDK. APIs in Java include classes,
interfaces, and user Interfaces. They enable developers to integrate various applications and
websites and offer real-time information.

Who Uses Java APIs?

Three types of developers use Java APIs based on their job or project:

1. Internal developers

2. Partner developers
3. Open developers
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Internal Developers

Internal developers use internal APIs for a specific organization. Internal APIs are accessible
only by developers within one organization.

Applications that use internal APIs include:

 B2B

 B2C
 A2A
 B2E

Examples include Gmail, Google Cloud VM, and Instagram.

What is Java API, its Advantages and Need for it


Lesson 25 of 34By Ravikiran A S
Last updated on Aug 9, 2022134054

Java application programming interfaces (APIs) are predefined software tools that easily
enable interactivity between multiple applications.

Partner Developers
Organizations that establish communications develop and use partner APIs. These types of
APIs are available to partner developers via API keys.
Applications that use partner APIs include:

 B2B
 B2C

Examples include Finextra and Microsoft (MS Open API Initiative),

Open Developers
Some leading companies provide access to their APIs to developers in the open-source
format. These businesses provide access to APIs via a key so that the company can ensure
that the API is not used illegally.
The application type that uses internal APIs is:

 B2C

Examples include Twitter and Telnyx.


The next section explores the importance of Java APIs.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

The Need for Java APIs


Java developers use APIs to:

Streamline Operating Procedures


Social media applications like Twitter, Facebook, LinkedIn, and Instagram provide users with
multiple options on one screen. Java APIs make this functionality possible.

Improve Business Techniques


Introducing APIs to the public leads many companies to release private data to generate new
ideas, fix existing bugs, and receive new ways to improve operations. The Twitter developer
account is an example of an API that gives programmers private API keys to access Twitter
data and develop applications.

Create Powerful Applications


Online banking has changed the industry forever, and APIs offer customers the ability to
manage their finances digitally with complete simplicity.
Below we discuss the various types of Java APIs.

Types of Java APIs


There are four types of APIs in Java:

 Public
 Private
 Partner
 Composite

Public
Public (or open) APIs are Java APIs that come with the JDK. They do not have strict
restrictions about how developers use them.

Private
Private (or internal) APIs are developed by a specific organization and are accessible to only
employees who work for that organization.

Partner
Partner APIs are considered to be third-party APIs and are developed by organizations for
strategic business operations.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Composite
Composite APIs are microservices, and developers build them by combining several service
APIs.
Now that we’ve covered the types of Java APIs, let’s discuss the categorization of Java APIs
based on the services that different varieties of APIs in Java provide.
What is Java API, its Advantages and Need for it
Lesson 25 of 34By Ravikiran A S
Last updated on Aug 9, 2022134054

Java application programming interfaces (APIs) are predefined software tools that easily
enable interactivity between multiple applications.

Data and API Services

Data and API services are another way to categorize Java APIs other than public, private,
partner, and composite. APIs are also classified based on their data-manipulation capabilities
and the variety of services they offer, including:

 Internal API services

 External API services


 CRUD
 User interface services

Internal API Services

Internal API services are developed to offer organizations services specific to that
organization. These services include only complex data operations and internal processes.

External API Services

External APIs are open-source APIs that developers integrate into an existing application or
website.

CRUD

CRUD APIs provide data manipulation operations over various data storage units such as
software as a service (SaaS) and relational database management systems (RDBMS), using
standard storage-unit connecting tools like Java Database Connectivity (JDBC).
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

User Interface Services

User interface service APIs are open-source APIs that allow developers to build user
interfaces for mobile devices, computers, and other electronics.

Next, let’s examine the rules and protocols that Java APIs follow.

API Service Protocols

The rules and protocols guide the functionality of the Java API. Different APIs have different
service protocols. Let’s consider an example of RESTful API service protocol as an example.

For a typical RESTful API, developers must follow these rules:

 Stateless

 Uniform interface
 Client-server
 Cache
 Layered

Stateless

A RESTful API follows client-server architecture so it must be stateless.

Uniform Interface

The entities in a RESTful API are the server and clients. Applications that run on a global
scale need a uniform client and server interface through the Hypertext Transfer Protocol
(HTTP). Uniform Resource Identifiers (URIs) allocate the required resources.

Client-Server

The client-server model used in the RESTful API should be fault-tolerant. Both the client and
server are expected to operate independently. The changes made at the client end should not
affect the server end and vice versa.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Cache

Including a cache memory allows the application to record intermediate responses and run
faster in real-time. A RESTful API also includes the cache memory.

Layered

A RESTful API is built using layers. Layers in the API are loosely coupled, or independent,
from each other. Each layer contributes to a different level of hierarchy and also supports
encapsulation.

Types of Java Program


Java program has two types. They are:
1. Application Program (Stand-alone application)
2. Applets Program.
1. Stand-alone applications are those java programs that can be developed and executed on
a stand-alone local computer.(which we can execute from the command prompt). The stand-
alone application can be executed without the browsers (Internet connectivity).A java
program is not embedded within HTML or any other language and can Stand on its own. It
is referred to as Application program.
2. Applet Programs are small java programs developed for internet applications. Applets are
embedded in HTML documents. Applet programs can be run using the applet viewer or web
browser. For example, when you use java to enhance a WWW page, the java code is
embedded within HTML code. It is called as Applet.

CREATION AND EXECUTION IN JAVA PROGRAM

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

Example

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

public static void main(String []args) {


System.out.println("Hello World"); // prints Hello World
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

}
}
Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps −
 Open notepad and add the code as above.
 Save the file as: MyFirstJavaProgram.java.
 Open a command prompt window and go to the directory where you saved the class.
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 ' Hello World ' printed on the window.

Output

C:\> javac MyFirstJavaProgram.java


C:\> java MyFirstJavaProgram
Hello World

Basic Syntax

About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity − Java is case sensitive, which means
identifier Hello and hello would have a different meaning in Java.
 Class Names − For all class names, the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example: class MyFirstJavaClass
 Method Names − All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter
should be in Upper Case.
Example: public void myMethodName()
 Program File Name − Name of the program file should exactly match the class
name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be
saved as 'MyFirstJavaProgram.java'
 public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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.

token <= identifier | keyword | separator | operator | literal | comment

For example, consider the following code.


public class Demo
{
public static void main(String args[])
{
System.out.println("javatpoint");
}
}
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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 keywords are also known as reserved words.

 Keywords are particular words that act as a key to a code.

 These are predefined words by Java so they cannot be used as a variable or


object name or class name.

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
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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

46. assert 47. const 48. enum 49. goto 50. strictfp

List of Java Keywords

A list of Java keywords or reserved words are given below:

1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class
can provide the implementation of the interface. It can have abstract and non-abstract
methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can
hold True and False values only.
3. break: Java break keyword is used to break the loop or switch statement. It breaks the
current flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements.
It must be used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit
Unicode characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current
flow of the program and skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch
statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a
part of the program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from another
class or interface.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

16. final: Java final keyword is used to indicate that a variable holds a constant value. It
is used with a variable. It is used to restrict the user from updating the value of the
variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This
block is always executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-
point number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the number of
iteration is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to
the current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance
of the specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.
25. interface: Java interface keyword is used to declare an interface. It can have only
abstract methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native
code using JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything.
It removes the garbage value.
30. package: Java package keyword is used to declare a Java package that includes the
classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a
method or variable may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within
the package and outside the package but through inheritance only. It can't be applied
with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is
accessible anywhere. It has the widest scope among all other modifiers.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

34. return: Java return keyword is used to return from a method when its execution is
complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class
method. The static keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure
portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class
objects. It can be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable against
multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or
methods in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or
constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw
keyword is mainly used to throw custom exceptions. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked
exceptions can be propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the
program several times. If the number of iteration is not fixed, it is recommended to
use the while loop.

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.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 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.

Some valid identifiers are:


PhoneNumber , PRICE, radius,a1, _phonenumbe, $circumference, jagged_array
12radius //invalid

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:
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 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

Operator 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 <= ; | , | . | ( | ) | { | } | [ | ]

Note that the first three separators (; , and .) are tokens that separate other tokens, and the
last six (3 pairs of braces) separators are also known as delimiters. For example, Math.pow(9,
3); contains nine tokens.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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.

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 */.
JVM (JAVA VIRTUAL MACHINE)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides


runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).

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

The JVM performs following operation:


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

JVM provides definitions for the:


II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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

JVM Architecture

It contains classloader, memory area, execution engine etc.

1) Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath" switch. It
is also known as Application classloader.

//Let's see an example to print the classloader name


public class ClassLoaderExample
{
public static void main(String[] args)
{
// Let's print the classloader name of current class.
//Application/System classloader will load this class
Class c=ClassLoaderExample.class;
System.out.println(c.getClassLoader());
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

//If we print the classloader name of String, it will print null because it is an
//in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader
System.out.println(String.class.getClassLoader());
}
}

Output:

sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to create your own
classloader, you need to extend the ClassLoader class.

Class(Method) Area

 Class(Method) Area stores per-class structures such as the runtime constant


pool, field and method data, the code for methods.

Heap

 It is the runtime data area in which objects are allocated.

Stack

 Java Stack stores frames. It holds local variables and partial results, and plays
a part in method invocation and return.
 Each thread has a private JVM stack, created at the same time as thread.

 A new frame is created each time a method is invoked. A frame is destroyed


when its method invocation completes.

Program Counter Register

PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.

Native Method Stack

It contains all the native methods used in the application.

Execution Engine
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here, the term "compiler" refers
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.

Java Native Interface

Java Native Interface (JNI) is a framework which provides an interface to


communicate with another application written in another language like C, C++, Assembly
etc. Java uses JNI framework to send output to the Console or interact with OS libraries.

JAVA COMMAND LINE ARGUMENTS

 The java command-line argument is an argument i.e. passed at the time of


running the java program.
 The arguments passed from the console can be received in the java program
and it can be used as an input.

 So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments from
the command prompt.

Simple example of command-line argument in java


we are receiving only one argument and printing it. To run this java program, you must pass
at least one argument from the command prompt.

class CommandLineExample
{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo

Example of command-line argument that prints all the values


we are printing all the arguments passed from the command-line. For this purpose,
we have traversed the array using for loop.
class A{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Output: sonoo
jaiswal
1
3
Abc

COMMENTS IN JAVA PROGRAM

Java Comments

The Java comments are the statements in a program that are not executed by the compiler and
interpreter.

Why do we use comments in a code?

o Comments are used to make the program more readable by adding the details of the
code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the
alternative code.

Types of Java Comments

There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

1) Java Single Line Comment

The single-line comment is used to comment only one line of the code. It is the widely used
and easiest way of commenting the statements.

Single line comments starts with two forward slashes (//). Any text in front of // is not
executed by Java.

Syntax:

1. //This is single line comment

Let's use single line comment in a Java program.

CommentExample1.java

1. public class CommentExample1 {


2. public static void main(String[] args) {
3. int i=10; // i is a variable with value 10
4. System.out.println(i); //printing the variable i
5. }
6. }

Output:

10

2) Java Multi Line Comment

The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to
use single-line comments there).

Multi-line comments are placed between /* and */. Any text between /* and */ is not
executed by Java.

Syntax:

1. /*
2. This
3. is
4. multi line
5. comment
6. */
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Let's use multi-line comment in a Java program.

CommentExample2.java

1. public class CommentExample2 {


2. public static void main(String[] args) {
3. /* Let's declare and
4. print variable in java. */
5. int i=10;
6. System.out.println(i);
7. /* float j = 5.9;
8. float k = 4.4;
9. System.out.println( j + k ); */
10. }
11. }

Output:

10
Note: Usually // is used for short co

3) Java Documentation Comment

Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e.,
which classes, methods, arguments, etc., are used in the code.

To create documentation API, we need to use the javadoc tool. The documentation
comments are placed between /** and */.

Syntax:

/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
import java.io.*;
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

/**
* <h2> Calculation of numbers </h2>
* This program implements an application
* to perform operation such as addition of numbers
* and print the result
* <p>
* <b>Note:</b> Comments make the code readable and
* easy to understand.
*
* @author Anurati
* @version 16.0
* @since 2021-07-06
*/
public class Calculate{
/**
* This method calculates the summation of two integers.
* @param input1 This is the first parameter to sum() method
* @param input2 This is the second parameter to the sum() method.
* @return int This returns the addition of input1 and input2
*/
public int sum(int input1, int input2){
return input1 + input2;
}
/**
* This is the main method uses of sum() method.
* @param args Unused
* @see IOException
*/
public static void main(String[] args) {
Calculate obj = new Calculate();
int result = obj.sum(40, 20);

System.out.println("Addition of numbers: " + result);


} }

Compile it by javac tool:

Create Document
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

*********UNIT I COMPLETED*********

UNIT II

Elements: Constants – Variables – Data types - Scope of variables – Type casting –


Operators: Special operators – Expressions – Evaluation of Expressions. Decision making
and branching statements- Decision making and Looping– break – labeled loop – continue
Statement. Arrays: One Dimensional Array – Creating an array – Array processing –
Multidimensional Array – Vectors – ArrayList – Advantages of Array List over Array
Wrapper classes.

ELEMENTS:
JAVA CONSTANT

 A constant is an entity in programming that is immutable.


 In other words, the value that cannot be changed.

 In this section, we will learn about Java constant and how to declare a
constant in Java.

What is constant?

 Constant is a value that cannot be changed after assigning it.


 Java does not directly support the constants.

 There is an alternative way to define the constants in Java by using the non-
access modifiers static and final.

How to declare constant in Java?

 In Java, to declare any variable as constant, we use static and final modifiers.
 It is also known as non-access modifiers.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 According to the Java naming convention the identifier name must be


in capital letters.

Static and Final Modifiers


 The purpose to use the static modifier is to manage the memory.
 It also allows the variable to be available without loading any instance of the class in
which it is defined.
 The final modifier represents that the value of the variable cannot be changed. It also
makes the primitive data type immutable or unchangeable.

The syntax to declare a constant is as follows:

static final datatype identifier_name=value;

For example, price is a variable that we want to make constant.

static final double PRICE=432.78;

Where static and final are the non-access modifiers. The double is the data type and PRICE is
the identifier name in which the value 432.78 is assigned.

Why we use constants?

 The use of constants in programming makes the program easy and


understandable which can be easily understood by others.
 It also affects the performance because a constant variable is cached by both
JVM and the application.

Points to Remember:
o Write the identifier name in capital letters that we want to declare as constant. For
example, MAX=12.
o If we use the private access-specifier before the constant name, the value of the
constant cannot be changed in that particular class.
o If we use the public access-specifier before the constant name, the value of the
constant can be changed in the program.

ConstantExample1.java
import java.util.Scanner;
public class ConstantExample1
{
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args)
{
int unit;
double total_bill;
System.out.print("Enter the number of units you have used: ");
Scanner sc=new Scanner(System.in);
unit=sc.nextInt();
total_bill=PRICE*unit;
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

System.out.println("The total amount you have to deposit is: "+total_bill);


}
}

Output:

JAVA VARIABLES
 A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.
 Variable is a name of memory location.

 There are three types of variables in java: local, instance and static.

There are two types of data types in Java:


 Primitive
 non-primitive.

A variable is the name of a reserved area allocated in memory.

In other words, it is a name of the memory location. It is a combination of "vary +


able" which means its value can be changed.

int data=50;//Here data is variable


Types of Variables

There are three types of variables in Java:


o local variable
o instance variable
o static variable

1) Local Variable

 A variable declared inside the body of the method is called local variable.
 You can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.

 A local variable cannot be defined with "static" keyword.

2) Instance Variable

 A variable declared inside the class but outside the body of the method, is
called an instance variable.
 It is not declared as static.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 It is called an instance variable because its value is instance-specific and is not


shared among instances.

3) Static variable

 A variable that is declared as static is called a static variable.


 It cannot be local. You can create a single copy of the static variable and share
it among all the instances of the class.

 Memory allocation for static variables happens only once when the class is
loaded in the memory.

Example to understand the types of variables in java


public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

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:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. 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.

 Java is a statically-typed programming language.


 It means, all variables must be declared before its use.
 That is why we need to declare variable's type and name.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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


II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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.

Example:
Boolean one = false
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.

Example:
byte a = 10, byte b = -20

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.

Example:
short s = 10000, short r = -5000
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.

Example:
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

int a = 100000, int b = -200000


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.

Example:
long a = 100000L, long b = -200000L
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.

Example:
float f1 = 234.5f

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.

Example:

double d1 = 12.3

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.


II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Example:

char letterA = 'A'

OPERATORS IN JAVA

Operator in Java is a symbol that is used to perform operations. For example: +, -,


*, / etc.

There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator


11)
System.out.println(--x);//10
}}

Output:
10
12
12
10

Java Arithmetic Operators

 Java arithmetic operators are used to perform addition, subtraction,


multiplication, and division.
 They act as basic mathematical operations.

Java Arithmetic Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

System.out.println(a/b);//2
System.out.println(a%b);//0
}}

Output:
15
5
50
2a
0

Java Left Shift Operator

The Java left shift opertor << is used to shift all of the bits in a value to the left side of
a specified number of times.

Java Left Shift Operator Example


public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

Output:
40
80
80
240

Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right
by the number of bits specified by the right operand.

Java Right Shift Operator Example


public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Output:2 5 2
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true
or false.

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}

Output:
false
false

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is true.
It checks the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is true or
false.

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Output:
true
true
true
10
true
11

Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statement and
used a lot in Java programming. It is the only conditional operator which takes three
operands.

Java Ternary Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}

Output:2

Java Assignment Operator

Java assignment operator is one of the most common operators. It is used to assign the
value on its right to the operand on its left.

Java Assignment Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}

Output:
14
16
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

EXPRESSION

 Expression is an essential building block of any Java program.


 Generally, it is used to generate a new value.

 Sometimes, we can also assign a value to a variable.

 In Java, expression is the combination of values, variables, operators,


and method calls.

There are three types of expressions in Java:

 Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2.


Note that the expression enclosed in the parentheses will be evaluate first, after
that rest of the expression.
 Expressions that assign a value. For example, number = 90, pi = 3.14.
 Expression that neither produces any result nor assigns a value.
 For example, increment or decrement a value by using increment or decrement
operator respectively, method invocation, etc.
 These expressions modify the value of a variable or state (memory) of a program.
 For example, count++, int sum = a + b; The expression changes only the value of
the variable sum. The value of variables a and b do not change, so it is also a side
effect.

DECISION-MAKING

 Conditional statements are used to perform different actions based on various


conditions.
 The conditional statement evaluates a condition before the execution of
instructions.

 To perform different actions for different decisions.

 You can easily perform it by using conditional statements.

Types of Conditional Statements

The conditional statements in JavaScript are listed below:

o if statement
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

o if….else statement
o if….else if….statement
o nested if statement
o switch statement

Let us try to elaborate on these conditional statements.

The if statement

It is one of the simplest decision-making statement which is used to decide whether a block
of JavaScript code will execute if a certain condition is true.

Syntax

if (condition) {
// block of code will execute if the condition is true
}

If the condition evaluates to true, the code within if statement will execute, but if the
condition evaluates to false, then the code after the end of if statement (after the closing of
curly braces) will execute.

Note: The if statement must be written in the lowercase letters. The use of Uppercase letters
(If or IF) will cause a JavaScript error.

Flowchart
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

For example

var x = 78;
if (x>70) {
console.log("x is greater") }

Output

x is greater
The if….else statement

 An if….else statement includes two blocks that are if block and else block.
 It is the next form of the control statement, which allows the execution of
JavaScript in a more controlled way.

 It is used when you require to check two different conditions and execute a
different set of codes.

 The else statement is used for specifying the execution of a block of code if
the condition is false.

Syntax

if (condition)
{
// block of code will execute if the condition is true
}
else
{
// block of code will execute if the condition is false
}

If the condition is true, then the statements inside if block will be executed, but if the
condition is false, then the statements of the else block will be executed.

Flowchart
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

For example

Let us try to understand if….else statement by the following example:

var x = 40, y=20;

if (x < y)
{
console.log("y is greater");
}
else
{
console.log("x is greater");
}

Output

x is greater

The if….else if…..else statement

 It is used to test multiple conditions.


 The if statement can have multiple or zero else if statements and they must be used
before using the else statement.

 You should always be kept in mind that the else statement must come after the else if
statements.

Syntax

if (condition1)
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

{
// block of code will execute if condition1 is true
}
else if (condition2)
{
// block of code will execute if the condition1 is false and condition2 is true
}
else
{
// block of code will execute if the condition1 is false and condition2 is false
}

Example

var a = 10, b = 20, c = 30;


if( a > b && a > c) {
console.log("a is greater");
} else if( b > a && b > c ) {
console.log("b is greater");
} else {
console.log("c is greater");
}

Output

c is greater

The nested if statement

It is an if statement inside an if statement.

Syntax

if (condition1)
{
Statement 1; //It will execute when condition1 is true
if (condition2)
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

{
Statement 2; //It will execute when condition2 is true
}
else
{
Statement 3; //It will execute when condition2 is false
}
}

Example

var num = 20;


if (num > 10)
{
if (num%2==0)
console.log( num+ " is greater than 10 and even number");
else
console.log(num+ " is greater than 10 and odd number");
}
else
{
console.log(num+" is smaller than 10");
}
console.log("After nested if statement");

Output

20 is greater than 10 and even number

After nested if statement

The switch statement

 It is a multi-way branch statement that is also used for decision-making


purposes.
 In some cases, the switch statement is more convenient than if-else
statements.

 It is mainly used when all branches depend upon the value of a single variable.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 It executes a block of code depending upon the different cases.

The switch statement uses the break or default keywords, but both of them are
optional. Let us define these two keywords:

break:

 It is used within the switch statement for terminating the sequence of a


statement. It is optional to use.
 If it gets omitted, then the execution will continue on each statement.

 When it is used, then it will stop the execution within the block.

default:

 It specifies some code to run when there is no case match.


 There can be only a single default keyword in a switch.

 It is also optional, but it is recommended to use it as it takes care of


unexpected cases.

 If the condition passed to switch doesn't match with any value in cases, then
the statement under the default will get executed.

Some points to remember


o There can be one or multiple case values for a switch expression.
o The use of break and default keywords are optional.
o The case statements can only include constants and literals. It cannot be an expression
or a variable.
o Unless you put a break after the code of every block, the execution will continuously
flow into the next block.
o It is not necessary that the default case has to be placed at last in a switch block.
Syntax
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

code to be executed if all cases are not matched;


}

Flowchart

Example

var num = 5;
switch(num) {
case 0 : {
console.log("Sunday");
break;
}
case 1 : {
console.log("Monday");
break;
}
case 2 : {
console.log("Tuesday");
break;
}
case 3 : {
console.log("Wednesday");
break;
}
case 4 : {
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

console.log("Thursday");
break;
}
case 5 : {
console.log("Friday");
break;
}
case 6 : {
console.log("Saturday");
break;
}
default: {
console.log("Invalid choice");
break;
}
}

Output

Friday

Ternary Operator Java

In Java, the ternary operator is a type of Java conditional operator. In this section, we will
discuss the ternary operator in Java with proper examples.

The meaning of ternary is composed of three parts. The ternary operator (? :) consists of
three operands. It is used to evaluate Boolean expressions. The operator decides which value
will be assigned to the variable. It is the only conditional operator that accepts three operands.
It can be used instead of the if-else statement. It makes the code much more easy, readable,
and shorter.

Note: Every code using an if-else statement cannot be replaced with a ternary operator.

Syntax:
1. variable = (condition) ? expression1 : expression2

The above statement states that if the condition returns true, expression1 gets executed, else
the expression2 gets executed and the final result stored in a variable.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Let's understand the ternary operator through the flowchart.

Example of Ternary Operator

TernaryOperatorExample.java

public class TernaryOperatorExample


{
public static void main(String args[])
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
}
}

Output

Value of y is: 90
Value of y is: 61

LOOPS IN JAVA

 The Java for loop is used to iterate a part of the program several times.
 If the number of iteration is fixed, it is recommended to use for loop.

There are three types of for loops in Java.

o Simple for Loop


o For-each or Enhanced for Loop
o Labeled for Loop
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Java Simple for Loop

A simple for loop is the same as C/C++. We can initialize the variable, check condition
and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return boolean
value either true or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an
optional condition.
4. Statement: The statement of the loop is executed each time until the second condition
is false.

Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}

Flowchart:

Example:

ForExample.java
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

//Java Program to demonstrate the example of for loop


//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}

Output:

1
2
3
4
5
6
7
8
9
10
Java While Loop

The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.

The while loop is considered as a repeating if statement. If the number of iteration is


not fixed, it is recommended to use the while loop.

Syntax:

while (condition){
//code to be executed
I ncrement / decrement statement
}
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

The different parts of do-while loop:

1. Condition: It is an expression which is tested. If the condition is true, the loop body is
executed and control goes to update expression. When the condition becomes false, we exit
the while loop.

Example:

i <=100

2. Update expression: Every time the loop body is executed, this expression increments or
decrements loop variable.

Example:

i++;

Flowchart of Java While Loop

Here, the important thing about while loop is that, sometimes it may not even execute. If the
condition to be tested results into false, the loop body is skipped and first statement after the
while loop will be executed.

Example:

In the below example, we print integer values from 1 to 10. Unlike the for loop, we
separately need to initialize and increment the variable used in the condition (here, i).
Otherwise, the loop will execute infinitely.

WhileExample.java

public class WhileExample {


public static void main(String[] args) {
int i=1;
while(i<=10){
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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

Output:

1
2
3
4
5
6
7
8
9
10

Java do-while Loop

 The Java do-while loop is used to iterate a part of the program repeatedly, until
the specified condition is true.
 If the number of iteration is not fixed and you must have to execute the loop at
least once, it is recommended to use a do-while loop.

 Java do-while loop is called an exit control loop.

 Therefore, unlike while loop and for loop, the do-while check the condition at
the end of loop body.

 The Java do-while loop is executed at least once because condition is checked
after loop body.

Syntax:

do{
//code to be executed / loop body
//update statement
}while (condition);

The different parts of do-while loop:

1. Condition: It is an expression which is tested.


II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

2. If the condition is true, the loop body is executed and control goes to update
expression. As soon as the condition becomes false, loop breaks automatically.

Example:

i <=100

2. Update expression: Every time the loop body is executed, the this expression increments or
decrements loop variable.

Example:

i++;

Note: The do block is executed at least once, even if the condition is false.

Flowchart of do-while loop:

Example:

In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately
need to initialize and increment the variable used in the condition (here, i). Otherwise, the
loop will execute infinitely.

DoWhileExample.java

public class DoWhileExample {


public static void main(String[] args) {
int i=1;
do{
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

System.out.println(i);
i++;
}while(i<=10);
}
}

Output:

1
2
3
4
5
6
7
8
9
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., break and continue.

Java break statement

As the name suggests, the break statement is 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.

The break statement example with for loop

Consider the following example in which we have used the break statement with the
for loop.

BreakExample.java

public class BreakExample {


II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

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

Java continue statement

Unlike break statement, the continue statement doesn'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);
}
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

}
}

Output:

0
1
2
3
5
1
2
3
5
2
3
5

Labeled Loop in Java

In programming, a loop is a sequence of instructions that is continually repeated until


a certain condition is met. In this section, we will discuss the labeled loop in Java with
examples.

What is a labeled loop in Java?

A label is a valid variable name that denotes the name of the loop to where the control
of execution should jump. To label a loop, place the label before the loop with a colon at the
end. Therefore, a loop with the label is called a labeled loop.

we can say that label is nothing but to provide a name to a loop. It is a good habit to
label a loop when using a nested loop. We can also use labels
with continue and break statements.

There are three types of loop in Java:

o for loop
o while loop

Let's discuss the above three loops with labels.

Java Labeled for Loop

 Labeling a for loop is useful when we want to break or continue a specific for
loop according to requirement.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

 If we put a break statement inside an inner for loop, the compiler will jump out
from the inner loop and continue with the outer loop again.

 What if we need to jump out from the outer loop using the break statement
given inside the inner loop? The answer is, we should define the label along
with the colon(:) sign before the loop.

Syntax:

labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}

Let's see an example of labeled for-loop.

LabeledForLoop.java

public class LabeledForLoop


{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

}
}
}

Output:

123456789
123456789
123456789
123456789
123456789

Java Labeled while Loop

Syntax:

labelName:

while ( ... )

{
//statements to execute
}

LabledWhileLoop.java
public class LabledWhileLoop
{
public static void main(String args[])
{
int i = 0;
whilelabel:
while (i < 5)
{
System.out.println("outer value of i= " + i);
i++;
forlabel:
for (int j = 0; j < 5; j++)
{
if (j > 0)
{
//execution transfer to the for loop
continue forlabel;
} //end of if
if (i > 1)
{
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

//execution transfer to the while loop


continue whilelabel;
} //end of if
System.out.println("inner value of i= " + i + ", j= " + j);
} //end of for
} //end of while
} //end of main
}

Output:

outer value of i= 0
inner value of i= 1, j= 0
outer value of i= 1
outer value of i= 2
outer value of i= 3
outer value of i= 4

ARRAYS IN JAVA

 Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type.
 An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
 Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.
 This tutorial introduces how to declare array variables, create arrays, and process
arrays using indexed variables.

Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for declaring an
array variable −
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType
arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate
C/C++ programmers.
Example
The following code snippets are examples of this syntax −
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.

Creating Arrays

You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
 It creates an array using new dataType[arraySize].
 It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to arrayRefVar.length-1.
Example
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList −
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.

Processing Arrays

When processing array elements, we often use either for loop or foreach loop because all of
the elements in an array are of the same type and the size of the array is known.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Example
Here is a complete example showing how to create, initialize, and process arrays −
Live Demo

public class TestArray {

public static void main(String[] args) {


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

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}

// Summing all elements


double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);

// Finding the largest element


double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This will produce the following result −
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

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

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

3. dataType arrayRefVar[][]; (or)


4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Example of Multidimensional Java Array

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

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
Test it Now
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

Output:

123
245
445

Java Vector

Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection
framework since Java 1.2. It is found in the java.util package and implements
the List interface, so we can use all the methods of List interface here.

It is recommended to use the Vector class in the thread-safe implementation only. If you don't
need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will
perform better in such case.

The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it
fails and throws the ConcurrentModificationException.

It is similar to the ArrayList, but with two differences-

o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections
framework.

Java Vector class Declaration

1. public class Vector<E>


2. extends Object<E>
3. implements List<E>, Cloneable, Serializable
4. Java Vector Constructors
5. Vector class supports four types of constructors. These are given below:

SN Constructor Description

1) vector() It constructs an empty vector with the default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the specified initial


capacity and with its capacity increment equal to zero.

3) vector(int initialCapacity, int It constructs an empty vector with the specified initial
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

capacityIncrement) capacity and capacity increment.

4) Vector( Collection<? extends E> It constructs a vector that contains the elements of a
c) collection c.

Java Vector Example

1. import java.util.*;
2. public class VectorExample {
3. public static void main(String args[]) {
4. //Create a vector
5. Vector<String> vec = new Vector<String>();
6. //Adding elements using add() method of List
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Adding elements using addElement() method of Vector
12. vec.addElement("Rat");
13. vec.addElement("Cat");
14. vec.addElement("Deer");
15.
16. System.out.println("Elements are: "+vec);
17. }
18. }
Test it Now

Output:

Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

ARRAYLIST IN JAVA

 ArrayList is a part of the Java collection framework and it is a class of java.util


package.
 It provides us with dynamic arrays in Java.
 Though, it may be slower than standard arrays but can be helpful in programs where
lots of manipulation in the array is needed.
 This class is found in java.util package.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

The main advantages of ArrayList are, if we declare an array then it’s needed to mention
the size but in ArrayList, it is not needed to mention the size of ArrayList if you want to
mention the size then you can do it.

import java.io.*;

import java.util.*;

class ArrayListExample {

public static void main(String[] args)

// Size of the

// ArrayList

int n = 5;

// Declaring the ArrayList with

// initial size n

ArrayList<Integer> arrli

= new ArrayList<Integer>(n);

// Appending new elements at

// the end of the list


II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

for (int i = 1; i <= n; i++)

arrli.add(i);

// Printing elements

System.out.println(arrli);

// Remove element at index 3

arrli.remove(3);

// Displaying the ArrayList

// after deletion

System.out.println(arrli);

// Printing elements one by one

for (int i = 0; i < arrli.size(); i++)

System.out.print(arrli.get(i) + " ");

Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

1235

Advantages Of Using ArrayList Over Arrays


Array and ArrayList are most used data types while developing any java applications.
Both are used to store group of objects.
In this post I have tried to list down the advantages of using ArrayList over Arrays.
Before discussing the advantages of ArrayList, let’s see what are the drawbacks of arrays.
 Arrays are of fixed length. You can not change the size of the arrays once they are
created.
 You can not accommodate an extra element in an array after they are created.
 Memory is allocated to an array during it’s creation only, much before the actual
elements are added to it.
Because of these drawbacks, use of arrays are less preferred. Instead of arrays, you can use
ArrayList class which addresses all these drawbacks.

Here are some advantages of using ArrayList over arrays.

You can define ArrayList as re-sizable array. Size of the ArrayList is not fixed. ArrayList
can grow and shrink dynamically.

class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();

list.add("ONE");

list.add("TWO");

list.add("THREE");

System.out.println(list.size()); //Output : 3

//Inserting some more elements


list.add("FOUR");

list.add("FIVE");

System.out.println(list.size()); //Output : 5

//Removing an element
list.remove("TWO");

System.out.println(list.size()); //Output : 4
}
}
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN

REFERENCE: https://www.javatpoint.com/java-tutorial

**********UNIT II COMPLETED***********

You might also like