JAVA_UNIT I&II
JAVA_UNIT I&II
JAVA_UNIT I&II
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
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
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:
State varchar(200)
);
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.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN
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
A class can also be defined as a blueprint from which you can create an individual
object.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance.
It provides code reusability.
Polymorphism
Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.
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.
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.
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.
13. Data hiding There is not any proper way for data There is a possibility of data
hiding. hiding.
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
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
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.
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.
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 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.
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
Many java versions have been released till now. The current stable release of Java is Java
SE 10.
FEATURES OF JAVA
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
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 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
Java language provides these securities by default. Some security can also be provided by
an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Architecture-neutral
Portable
Java is portable because it facilitates you to carry the Java bytecode to any
platform.
It doesn't require any implementation.
High-performance
Distributed
This feature of Java makes us able to access files by calling the methods from
any machine on the internet.
Multi-threaded
Dynamic
It means classes are loaded on demand. It also supports functions from its
native languages, i.e., C and C++.
JDK
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
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.
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.
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
Moving ahead, we will learn the steps to install Java into your local computer system.
The architecture of JDK in Java includes the following modules as described in the image
below.
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.
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.
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 Java is easy. We have to follow the steps mentioned below.
System Requirements:
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.
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.
Java application programming interfaces (APIs) are predefined software tools that easily
enable interactivity between multiple applications.
JDK
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
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.
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.
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.
B2B
B2C
A2A
B2E
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
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
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 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 are developed to offer organizations services specific to that
organization. These services include only complex data operations and internal processes.
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 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.
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.
Stateless
Uniform interface
Client-server
Cache
Layered
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.
Let us look at a simple code first that will print the words Hello World.
Example
}
}
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
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.
The Java compiler breaks the line of code into text (words) is called Java
tokens.
These are the smallest element of the Java program.
Remember that the delimiters are not part of the Java tokens.
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
Keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
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
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.
Literals:
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
"javatpoint" String
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.
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
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:
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.
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
JVM Architecture
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.
//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
Heap
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.
PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.
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.
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.
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
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
Java Comments
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
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.
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:
CommentExample1.java
Output:
10
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
CommentExample2.java
Output:
10
Note: Usually // is used for short co
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);
Create Document
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN
*********UNIT I COMPLETED*********
UNIT II
ELEMENTS:
JAVA CONSTANT
In this section, we will learn about Java constant and how to declare a
constant in Java.
What is constant?
There is an alternative way to define the constants in Java by using the non-
access modifiers static and final.
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
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.
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
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.
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.
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
3) Static variable
Memory allocation for static variables happens only once when the class is
loaded in the memory.
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.
In Java language, primitive data types are the building blocks of data
manipulation.
These are the most basic data types available in Java language.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
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
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 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
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.
Example:
float f1 = 234.5f
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
Example:
OPERATORS IN JAVA
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.
additive +-
equality == !=
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Output:
10
12
12
10
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output:
15
5
50
2a
0
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.
Output:
40
80
80
240
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.
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.
Output:
false
false
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.
Output:
true
true
true
10
true
11
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.
Output:2
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.
Output:
14
16
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN
EXPRESSION
DECISION-MAKING
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
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
if (x < y)
{
console.log("y is greater");
}
else
{
console.log("x is greater");
}
Output
x is greater
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
Output
c is greater
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
Output
It is mainly used when all branches depend upon the value of a single variable.
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN
The switch statement uses the break or default keywords, but both of them are
optional. Let us define these two keywords:
break:
When it is used, then it will stop the execution within the block.
default:
If the condition passed to switch doesn't match with any value in cases, then
the statement under the default will get executed.
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
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
TernaryOperatorExample.java
{
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.
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
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.
Syntax:
while (condition){
//code to be executed
I ncrement / decrement statement
}
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN
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++;
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
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
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.
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);
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.
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
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.
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.
Consider the following example in which we have used the break statement with the
for loop.
BreakExample.java
Output:
0
1
2
3
4
5
6
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.
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
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.
o for loop
o while 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
}
LabeledForLoop.java
}
}
}
Output:
123456789
123456789
123456789
123456789
123456789
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
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.
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
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
In such case, data is stored in row and column based index (also known as matrix form).
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.
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.
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections
framework.
SN Constructor Description
3) vector(int initialCapacity, int It constructs an empty vector with the specified initial
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN
4) Vector( Collection<? extends E> It constructs a vector that contains the elements of a
c) collection c.
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:
ARRAYLIST IN JAVA
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 {
// Size of the
// ArrayList
int n = 5;
// initial size n
ArrayList<Integer> arrli
= new ArrayList<Integer>(n);
arrli.add(i);
// Printing elements
System.out.println(arrli);
arrli.remove(3);
// after deletion
System.out.println(arrli);
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
II BCA
ADVANCED JAVA PROGRAMMING R.DHAMOTHARAN
1235
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
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***********