Unit 1 Introduction To Java-1
Unit 1 Introduction To Java-1
of Computer Application
Unit 1:
Introduction to java:
Java programming language was originally developed by Sun
Microsystems which was initiated by James Gosling and released in 1995 as
core component of Sun Microsystems. Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the
advancement of Java and its widespread popularity, multiple configurations were
built to suit various types of platforms.
For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME
respectively. Java is guaranteed to be Write Once, Run Anywhere.
Object-Oriented Programming
Object-oriented programming (OOP) is a programming paradigm based
on the concept of “objects”, which may contain data in the form of fields,
often known as attributes and code in the form of procedures, often known as
methods.
Platform independent:
Unlike many other programming languages including C and C++, when
Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and
interpreted by virtual Machine (JVM) on whichever platform it is being run.
Features of Java
1. Simple: Java is designed to be easy to learn. If you understand the basic
concept of OOP.
2. Secure:
Java program cannot harm other system thus making it secure.
Java provides a secure means of creating Internet applications.
Java provides secure way to access web applications.
1
Divya S R , Assistant Professor, Dept. of Computer Application
3. Portable:
Java programs can execute in any environment for which there is a
Java run-time system.
Java programs can run on any platform (Linux, Window, Mac OS)
Java programs can be transferred over world wide web (e.g: applets).
4. Object-oriented:
Java programming is object-oriented programming language.
Like C++, java provides most of the object oriented features.
Java is pure OOP Language. (while C++ is semi object oriented)
5. Robust:
Java encourages error-free programming by being strictly typed and
performing run- time checks.
6. Multithreaded:
Java provides integrated support for multithreaded programming.
7. Interpreted :
Java supports cross-platform code through the use of Java bytecode.
Bytecode can be interpreted on any platform by JVM (Java Virtual
Machine).
8. High performance:
Bytecodes are highly optimized.
JVM can execute bytecodes much faster.
9. Distributed:
Java is designed with the distributed environment.
Java can be transmitted over internet.
10. Platform Independent
2
Divya S R , Assistant Professor, Dept. of Computer Application
1. Documentation Section
The documentation section is an important section but optional for a Java
program. It includes basic information about a Java program. The information
includes the author's name, date of creation, version, program name,
company name, and description of the program. It improves the readability
of the program
Ex: //First Java Program
2. Package Declaration
The package declaration is optional. It is placed just after the documentation
section. In this section, we declare the package name in which the class is
placed. Note that there can be only one package statement in a Java program.
It must be defined before any class and interface declaration.
Example: package javatpoint; //where javatpoint is the package name
3. Import Statements
import keyword is used to import built-in and user-defined packages into java
source file. So that the class can refer to a class that is in another package by
directly using its name.
The keyword is import. The general syntax is
import package1 [.package2].[classname].*;
3
Divya S R , Assistant Professor, Dept. of Computer Application
Example
import [Link]; //it imports the Scanner class only
import [Link].*; //it imports all the class of the [Link] package
4. Interface Section
It is an optional section. We can create an interface in this section if required.
We use the interface keyword to create an interface. An interface is a slightly
different from the class. It contains only constants and method declarations.
Example:
interface car
void start();
void stop();
}
5. Class Definition
In this section, we define the class Without the class, we cannot create any Java
program. A Java program may conation more than one class definition. We use
the class keyword to define the class. It contains information about user-defined
methods, variables, and constants. Every Java program has at least one class
that contains the main() method. For
Example:
class Student //class definition
{
}
In this section, we define the main() method. It is essential for all Java
programs. Because the execution of all Java programs starts from the main()
method. In other words, it is an entry point of the class. It must be inside the
class. Inside the main method, we create objects and call the methods.
Example:
public static void main(String args[])
{
}
4
Divya S R , Assistant Professor, Dept. of Computer Application
Example:
5
Divya S R , Assistant Professor, Dept. of Computer Application
Graphical representation
10100011
11111011
1
Bytecode:
Bytecode is the intermediate representation of a Java program, allowing
a JVM to translate a program into machine-level assembly instructions.
When a Java program is compiled, bytecode is generated in the form of a(
.class) file. This (.class) file contains non-runnable instructions and relies on a
JVM to be interpreted.
6
Divya S R , Assistant Professor, Dept. of Computer Application
Java comments
The java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation
about the variable, method, class or any statement. It can also be used to hide
program code for specific time.
A single-line comment begins with a // and ends at the end of the line.
Syntax example
//Comment
//This is single line comment
Java tokens
Each individual characters or units used in a java program are termed as
tokens. Java program are written using these tokens and the syntax of the
language. The java has various types of tokens as follows as
Identifier
Keywords
Separators
Punctuators
Constants
Variables
Operators
Java Identifiers:
All Java components require names. Names used for classes, variables and
methods are called identifiers. In Java, there are several points to remember
about identifiers.
They are as follows:
All identifiers should begin with a letter (A to Z or a to z), or an underscore (_).
After the first character, identifiers can have any combination of characters. A
keyword cannot be used as an identifier.
“Most importantly identifiers are case sensitive”.
7
Divya S R , Assistant Professor, Dept. of Computer Application
Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using
modifiers.
There are two categories of modifiers:
Access Modifiers:
default, public, protected, private
Non-access Modifiers:
final, abstract
Keywords
8
Divya S R , Assistant Professor, Dept. of Computer Application
Constants
Any fixed value that does not change during the execution of a program is
known as constant.
The general syntax is
a) Integer constant
The numbers which represents without decimal part is known as integer
constants.
There are three types of constants
Decimal integer constants
Octal integer constants
Hexadecimal integer constants
Decimal integer constants
It is a combination of digits from 0 through 9, preceded by an optional
minus signs. The following table shows some valid and in-valid example.
Valid In-valid
-125 +250 500 1,500 20.22 20*10
9
Divya S R , Assistant Professor, Dept. of Computer Application
b) Real constants
A Real Constant must have at Least one Digit.
• it must have a Decimal value.
• it could be either positive or Negative.
• if no sign is Specified then it should be treated as Positive.
• No Spaces and Commas are allowed in Name.
Like 251, 234.890 etc are Real Constants.
In The Exponential Form of Representation the Real Constant is Represented in
the two [Link] part before appearing e is called mantissa where as the part
appearing after e is called Exponent.
0.65 e 4
Mantissa Exponent
Example: 0.65e4
10
Divya S R , Assistant Professor, Dept. of Computer Application
e) Boolean constants:
It is a special type of constant represents as true or false.
Valid In-valid
true false “True” TRUE FALSE
11
Divya S R , Assistant Professor, Dept. of Computer Application
Data types
In Java, each type of data (such as integer, character, etc. ) is predefined as
part of the programming language and all constants or variables defined within a
given program must be described with one of the data types.
Data types represent the different values to be stored in the variable. In java,
there are two categories of data types:
a) Primitive data types
b) Non-primitive data types
Primitive types
Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean. The primitive types are also commonly referred to as
simple types and they are grouped into the following four groups:
1) Integers - This group includes byte, short, int, and long. All of these are
signed, positive and negative values. The width and ranges of these
integer types vary widely, as shown in the following table:
12
Divya S R , Assistant Professor, Dept. of Computer Application
4) Boolean - This group includes boolean. It can have only one of two
possible values, true or false.
Class
A class in Java is a user defined data type i.e. it is created by the user. It
acts a template to the data which consists of member variables and
methods.
Objects
An object is the variable of the class, which can access the elements of
class i.e. methods and variables.
13
Divya S R , Assistant Professor, Dept. of Computer Application
Interface:
An interface is similar to a class however the only difference is that its methods
are abstract by default i.e. they do not have body. An interface has only the final
variables and method declarations. It is also called a fully abstract class.
String:
A string represents a sequence of characters for example "Javatpoint", "Hello
world", etc. String is the class of Java.
One of the ways to create a string and store a value in it is shown below:
Example: String str = "You're the best";
Array:
An array is a data type which can store multiple homogenous variables i.e.,
variables of same type in a sequence. They are stored in an indexed manner
starting with index 0. The variables can be either primitive or non-primitive data
types.
The general format is
data_type int:
Example: int [ ] marks;
Variables
A variable is the holder that can hold the value while the java program is
executed. A variable is assigned with a data type. It is name of reserved area
allocated in memory. In other words, it is a name of memory location. There are
three types of variables in java: local, instance and static.
Datatype variable=value;
Example
int a, b, c; // Declaration of variables a, b, and c.
int a = 20, b = 30; // initialization
byte B = 22; // Declaration initializes a byte type variable B.
14
Divya S R , Assistant Professor, Dept. of Computer Application
15
Divya S R , Assistant Professor, Dept. of Computer Application
Initializing variable
When a variable gets initialized during declaration is termed as static
initialization. Under this situation a variable is assigned directly with assignment
operator.
There are of two types of initialization
1. Static initialization
2. Dynamic initialization
1. Static initialization
When a variable gets initialized during declaration is termed as static
initialization. Under this situation a variable is assigned directly with
assignment operator.
Example:
Data Type Declaration Static Initialization
int int x; x=10;
float float y; y=5.5f;
double double z; z=25;
char char ch ch=’A’
2. Dynamic Initialization
When a variable gets initialized runtime is termed as dynamic
initialization. Under this situation, a variable is assigned with the outcome
of any arithmetic or logical operations.
Example:
Data Type Declaration Static Initialization
int int x,y,z; x=x+y;
float float a,b,c; c=a+b;
double double z; z=25+10;
char char ch ch=”computer”.charAt(0);
16
Divya S R , Assistant Professor, Dept. of Computer Application
Example: a = 10;
a = b;
17
Divya S R , Assistant Professor, Dept. of Computer Application
Scope of Variables
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.
Example
class First
{
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable
18
Divya S R , Assistant Professor, Dept. of Computer Application
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
It is called an instance variable because its value is instance-specific and is not
shared among instances.
Example
class GFG
{
public String geek; // Declared Instance Variable
// Object Creation
GFG name = new GFG();
// Displaying O/P
[Link]("Geek name is: " + [Link]);
}
}
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
class GFG
{
public static String geek = "Shubham Jain"; //Declared static variabl
public static void main (String[] args)
{
//geek variable can be accessed without object creation
[Link]("Geek Name is : "+[Link]);
}
}
19
Divya S R , Assistant Professor, Dept. of Computer Application
Each object will have its own copy of Whereas we can only have one copy
an instance variable. of a static variable per class,
irrespective of how many objects we
create.
// Instance variable
int b;
}
20
Divya S R , Assistant Professor, Dept. of Computer Application
21
Divya S R , Assistant Professor, Dept. of Computer Application
Operators
Operators in Java can be classified into 6 types:
Arithmetic Operators.
Assignment Operators.
Relational Operators.
Logical Operators.
Unary Operators.
Bitwise Operators
22
Divya S R , Assistant Professor, Dept. of Computer Application
23
Divya S R , Assistant Professor, Dept. of Computer Application
&& (and) True if both the operands is true a<10 && a<20
24
Divya S R , Assistant Professor, Dept. of Computer Application
Unary operators are the one that needs a single operand and are used to
increment a value, decrement or negate a value.
~
returns the one’s complement. (all bits reversed) ~a
(Complement)
25
Divya S R , Assistant Professor, Dept. of Computer Application
Control Structures
Java Control statements control the flow of execution in a java program, based
on data values and conditional logic used.
There are two main categories of control flow statements;
Selection statements:
a) if statement
b) if-else statement
c) Switch statement.
Loop statements:
a) while loop
b) do-while loop
c) for loop.
Selection statements:
The selection statements checks the condition only once for the program
execution.
a) If Statement:
The if statement executes a block of code only if the specified
expression is true. If the value is false, then the if block is skipped and
execution continues with the rest of the program.
The simple if statement has the following syntax
if (Condition)
{
statement(s);
}
26
Divya S R , Assistant Professor, Dept. of Computer Application
Example
public class programif
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
[Link](“a > b”);
if (a < b)
[Link](“b < a”);
}
}
b) If-else Statement
The if-else statement is an extension of the if statement. If the condition in
the if statement fails, the statements in the else block are executed.
Example:
public class ProgramIfElse
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
{
[Link](“a > b”);
27
Divya S R , Assistant Professor, Dept. of Computer Application
}
else
{
[Link](“b < a”);
}
}
}
c) Switch statement
The Java switch statement executes one statement from multiple
conditions. It is like if-else-if ladder statement.
The case value must be of switch expression type only. The case value
must be literal or constant. It doesn't allow variables.
The case values must be unique. In case of duplicate value, it renders
compile-time error.
Each case statement can have a break statement which is optional. When
control reaches to the break statement, it jumps the control after the
switch expression. If a break statement is not found, it executes the next
case.
The case value can have a default label which is optional.
28
Divya S R , Assistant Professor, Dept. of Computer Application
Example
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: [Link]("10");
break;
case 20: [Link]("20");
break;
case 30: [Link]("30");
break;
//Default case statement
default:
[Link]("Not in 10, 20 or 30");
}
}
}
The break and continue statements are the jump statements that are used to skip
some statements inside the loop or terminate the loop immediately without
checking the test expression. These statements can be used inside any loops such
as for, while, do-while loop.
Syntax :
break;
29
Divya S R , Assistant Professor, Dept. of Computer Application
Example:
Class examplebreak
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
[Link](i);
if(i==5)
break;
}
}
}
Output:
1
2
3
4
5
Continue: It is used to skip the rest of the statements in the body of the loop and
execution continuous until the condition is satisfied.
Syntax:
continue;
Example:
Class examplebreak
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
[Link](i);
if(i==5)
continue;
}
}
}
30
Divya S R , Assistant Professor, Dept. of Computer Application
Output:
1
2
3
4
5
6
7
8
9
10
Break continue
d) Nested if statement
A nested if statement is an if statement placed inside another if statement.
Nested if statements are often used when you must test a combination of
conditions before deciding on the proper action.
if(Condition1)
{
// Executes when the condition 1 is true
if(Condition2)
{
// Executes when the Boolean expression 2 is true
}
}
31
Divya S R , Assistant Professor, Dept. of Computer Application
Example:
public class Test
{
{
int x = 30;
int y = 10;
if( x == 30 )
if( y == 10 )
Looping Structures
Looping in programming languages is a feature which facilitates the execution of
a set of instructions/functions repeatedly while some condition evaluates to true.
a) while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement.
While loop starts with the checking of condition. If it evaluated to true,
then the loop body statements are executed otherwise first statement
following the loop is executed. For this reason it is also called Entry
control loop
Once the condition is evaluated to true, the statements in the loop body
are executed. Normally the statements contain an update value for the
variable being processed for the next iteration.
When the condition becomes false, the loop terminates which marks the
end of its life cycle.
32
Divya S R , Assistant Professor, Dept. of Computer Application
Syntax :
while (condition)
{
loop statements...
}
Example:
public class ProgramWhile
{
public static void main(String[] args)
{
int count = 1;
[Link](“Printing Numbers from 1 to 10”);
while (count <= 10)
{
[Link](count++);
}
}
}
}
b) DO-While loop
The do-while loop is similar to the while loop, except that the test condition is
performed at the end of the loop instead of at the beginning. The do—while loop
executes at least once without checking the condition. It begins with the
keyword do, followed by the statements that making up the body of the loop.
Finally, the keyword while and the test expression completes the do-while loop.
When the loop condition becomes false, the loop is terminated and execution
continues with the statement immediately following the loop.
do
{
statements..
}
while (condition);
33
Divya S R , Assistant Professor, Dept. of Computer Application
Example
public class dowhileloop
{
public static void main(String[] args)
{
int count = 1;
[Link](“Printing Numbers from 1 to 10”);
Do
{
[Link](count++);
}
while (count <= 10);
}
}
C) For loop
For loop provides a concise way of writing the loop structure. Unlike a while loop,
a for statement consumes the initialization, condition and increment/decrement
in one line thereby providing a shorter, easy to debug structure of looping.
Example
public class ProgramFor
{
public static void main(String[] args)
{
[Link](“Printing Numbers from 1 to 10”);
for (int count = 1; count <= 10; count++)
{
[Link](count);
}
34
Divya S R , Assistant Professor, Dept. of Computer Application
}
}
Java Method
A method in Java or Java Method is a collection of statements that perform
some specific task and return the result to the caller. Methods in Java allow us to
reuse the code without retyping the code.
Types of Methods
There are two types of methods
35
Divya S R , Assistant Professor, Dept. of Computer Application
Example 2:
Inside main, call the myMethod() method:
public class Main
{
static void myMethod()
{
[Link]("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
}
}
36
Divya S R , Assistant Professor, Dept. of Computer Application
Method Overloading
If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be
any number of arguments, if you write the method such as “adder(int,int)” for
two parameters, and “bca(int,int,int)” for three parameters then it may be
difficult for you as well as other programmers to understand the behaviour of the
method because its name differs.
So, we perform method overloading to figure out the program quickly.
Example:
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
[Link]([Link](2,3));
[Link]([Link](3,4,5));
}
}
Output:
5
12
37
Divya S R , Assistant Professor, Dept. of Computer Application
Math Class
The Java Math class has many methods that allows you to perform mathematical
tasks on numbers.
[Link];
[Link](x,y)
The [Link](x,y) method can be used to find the highest value of x and y:
Example:
[Link];
public class Main
[Link]([Link](5, 10));
Output: 10
[Link](x,y)
The [Link](x,y) method can be used to find the lowest value of x and y:
Example:
[Link];
public class Main
[Link]([Link](5, 10));
Output: 5
38
Divya S R , Assistant Professor, Dept. of Computer Application
[Link](x)
Example:
public class Main
{
public static void main(String[] args)
{
[Link]([Link](64));
}
}
Output: 8
[Link](x)
Example:
public class Main
{
public static void main(String[] args)
{
[Link]([Link](-4.7));
}
}
Output: 4.7
Floor() :
[Link]()
method returns the floor value of an argument i.e. the closest integer value
which is either less or equal to the passed argument.
Example:
class Main
{
public static void main(String[] args)
{
39
Divya S R , Assistant Professor, Dept. of Computer Application
double a = 3.8;
[Link]([Link](a));
}
}
Output: 3.0
Pow()
The pow() method returns the result of the first argument raised to the power of
the second argument.
Example:
class Main
{
public static void main(String[] args)
{
}
}
Output: 125.0
ceil()
The ceil() method rounds the specified double value upward and returns it. The
rounded value will be equal to the mathematical integer. That is, the value 3.24
will be rounded to 4.0 which is equal to integer 4.
Example:
class Main
{
public static void main(String[] args)
{
double a = 3.24;
[Link]([Link](a));
}
}
Output: 4.0
40
Divya S R , Assistant Professor, Dept. of Computer Application
round()
The round() method rounds the specified value to the closest int or long value
and returns it. That is, 3.87 is rounded to 4 and 3.24 is rounded to 3.
Example:
class Main
{
public static void main(String[] args)
{
double a = 3.87;
[Link]([Link](a));
}
}
Output: 4
41
Divya S R , Assistant Professor, Dept. of Computer Application
Arrays
Normally, an array is a collection of similar type of elements which has
contiguous memory location.
Example:
int arrayInteger[3] = {10,20,30};
This creates an array of size 3 with the name arrayInteger and initializes
arrayInteger[0] as 10, arrayInteger[1] as 20, arrayInteger[2] as 30.
The size of the array has to be specified inside the square brackets [] and the
elements have to be assigned inside the { }, separated by commas.
42
Divya S R , Assistant Professor, Dept. of Computer Application
Example:
int arrayInteger[] = {10,20,30,40};
Types of array
There are two types of an array
a) one Dimentional array
b) Two DImentional array
a) One Dimentional array: The group of logically related data items of same
data type which share a common name it contain one subscript.
a)) Declaring the array:- Arrays in java may be declared in two forms:
Type1:
The general syntax is
Datatype arrayname[size];
Example:
int a[10];
Type2:
The general syntax is
Datatype[size] arrayname;
Example:
int[10] a;
43
Divya S R , Assistant Professor, Dept. of Computer Application
Example:
10
20
30
44
Divya S R , Assistant Professor, Dept. of Computer Application
Example:
int a[ ] = new a[5];
5 memory locations are reserved
Example:
int a[ ] = {10,20,30,40,50};
the array “a” reserve 5 storage locations
Array length
In java, all arrays store the allocated size ina variable named length. We can
obtain the length of the array using length.
int a[ ] = {10,20,30,40,50};
int n= [Link]; //the value of n is 5
45
Divya S R , Assistant Professor, Dept. of Computer Application
Example:
class arraylengthexample
{
public static void main(String[] args)
{
int[] num = new int[10];
int arraylength=[Link];
[Link]("The length of the array is: "+ arraylength);
}
}
Output:
b) Two Dimentional array: The group of logically related data items of same
data type which share a common name it contain two subscript.
46
Divya S R , Assistant Professor, Dept. of Computer Application
a)) Declaring the array:- Arrays in java may be declared in two forms:
Type1:
The general syntax is
Datatype arrayname[row][column];
Example:
int arrayname[3][3];
Type2:
The general syntax is
Datatype[row][column] arrayname;
Example:
int[4][4] arrayname;
data_type arrayname[row][column];
arrayname = new data_type[row][column];
Example:
int a[ ][ ] = new a[3][3];
47
Divya S R , Assistant Professor, Dept. of Computer Application
Example:
int arrayname[3][3] = {10,20,30,40,50,60,70,80,90};
the array “a” reserve 5 storage locations
48
Divya S R , Assistant Professor, Dept. of Computer Application
Example:
class twod
{
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
A jagged array is an array of arrays such that member arrays can be of different
sizes, i.e., we can create a 2-D array but with a variable number of columns in
each row. These types of arrays are also known as Jagged arrays.
49
Divya S R , Assistant Professor, Dept. of Computer Application
Once the array is declared, you can define it as a Jagged array as shown
below:
myarray[1] = new int[2];
myarray[2] = new int[3];
myarray[3] = new int[4];
The first statement above indicates that the first row in the 2D array will
have 2 columns.
The second row will have 3 columns while the
third row will have 4 columns thereby making it a Jagged array.
Once the array is created, you can initialize it with values.
50
Divya S R , Assistant Professor, Dept. of Computer Application
You can also omit all the new operators all together and have a
declaration and initialization statement as shown below.
int[][] arr = {
{ 1, 2, 3 },
{ 4, 5, 6, 7 },
{ 8, 9 }
};
The program below initializes a ragged array by assigning initial values to
each row. Here each row of the array is initialized to the column values.
Example:
import [Link].*;
import [Link].*;
public class Main
{
public static void main(String[] args)
{
// Declaring a 2-D array with 3 rows
51
Divya S R , Assistant Professor, Dept. of Computer Application
99 100 101
199 200
Example:
import [Link];
public class Main
{
public static void main(String[] args)
{
52
Divya S R , Assistant Professor, Dept. of Computer Application
2) add(int index, Object o): It adds the object o to the array list at the given
index.
Example: [Link](2, "bye");
It will add the string bye to the 2nd index (3rd position as the array list starts
with index 0) of array list.
5) set(int index, Object o): Used for updating an element. It replaces the
element present at the specified index with the object o.
Example: [Link](2, "Tom");
53
Divya S R , Assistant Professor, Dept. of Computer Application
It would replace the 3rd element (index =2 is 3rd element) with the value Tom.
6) int indexOf(Object o): Gives the index of the object o. If the element is not
found in the list then this method returns the value -1.
Example: int pos = [Link]("Tom");
This would give the index (position) of the string Tom in the list.
7) int size(): It gives the size of the ArrayList – Number of elements of the list.
Example: int numberofitems = [Link]();
9) clear(): It is used for removing all the elements of the array list in one go.
The below code will remove all the elements of ArrayList whose object is obj.
54