Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
74 views

Java Arrays String StringBuilder SringBuffer Vector

The document discusses manipulating arrays in Java. It describes that an array is a collection of elements of the same data type stored in adjacent memory locations. Arrays can be one-dimensional or multi-dimensional. One-dimensional arrays have a single index while multi-dimensional arrays like two-dimensional arrays have multiple rows and columns. The document shows how to declare, initialize, access, and iterate through elements of one-dimensional and two-dimensional arrays in Java using for loops and for-each loops. It also discusses creating dynamic arrays in Java where the size of the array increases automatically as elements are added.

Uploaded by

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

Java Arrays String StringBuilder SringBuffer Vector

The document discusses manipulating arrays in Java. It describes that an array is a collection of elements of the same data type stored in adjacent memory locations. Arrays can be one-dimensional or multi-dimensional. One-dimensional arrays have a single index while multi-dimensional arrays like two-dimensional arrays have multiple rows and columns. The document shows how to declare, initialize, access, and iterate through elements of one-dimensional and two-dimensional arrays in Java using for loops and for-each loops. It also discusses creating dynamic arrays in Java where the size of the array increases automatically as elements are added.

Uploaded by

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

Manipulating Arrays in java

An array is a collection of elements of a single


data type stored in adjacent memory locations.
You can access an array element by specifying the
name and the subscript number of the array.

The subscript number specifies the position of an


element within the array. It is also called the
index of the element.
The first element of an array has an index, 0, and
the last element has an index one less than the
size (number of elements in an array) of the array.

The following figure shows the array of employeeID.


Creating Arrays in Java
You can create the following types of arrays:

One-dimensional array
Multidimensional array

One-dimensional Array

A one-dimensional array is a collection of elements


with a single index value. A one-dimensional array
can have multiple columns but only one row.

The creation of a one-dimensional array involves


two steps:

1. Declare an array.
2. Assign values to the array.
Declaring an Array
An array needs to be declared before it can be used in
a program. You can declare a one-dimensional array by
using the following syntax:

arraytype arrayname[] = new arraytype[size];

In the preceding syntax, arraytype specifies the type


of element to be stored in array, arrayname specifies
the name of the array, using which the elements of the
array will be initialized and manipulated, and [size]
specifies the size of the array.

The following code snippet declares an array to store


three string values:

String jumbledWords[] = new String[3];

The preceding code snippet creates an array of String,


jumbledWords, which can store three elements with
the index of elements ranging from 0 to 2.
Assigning Values to the Array
You can assign values to each element of the array by
using the index number of the element.

For example, to assign the value, alpep, to the first


element of the array, you can use the following code
snippet:
jumbledWords[0] = “alpep”;

You can also assign values to the array at the time of


declaration. For this, you are not required to specify
the size of the array, as shown in the following code
snippet:

String jumbledWords[] = {“alpep”,”argneo”,”rgaeps”};

In the preceding code snippet, jumbledWords is a one-


dimensional array. The values, alpep, argneo, and
rgaeps, are stored in the array, as shown in the
following figure.
Multidimensional Array
Multidimensional arrays are arrays of arrays.
An array having more than one dimension is
called a multidimensional array. The
commonly used multidimensional array is a
two-dimensional array where you can have
multiple rows and columns. For example, to
store an employee name against each
employee id, you need to create a two-
dimensional array.
The following figure shows a two-dimensional array.

The creation of a two-dimensional array involves two


steps:
1. Declare an array.
2. Assign values to the array.

Declaring an Array
You can declare a two-dimensional array by using the following
syntax:

arraytype arrayname[][] = new arraytype[rowsize][columnsize];


In the preceding syntax, arraytype specifies the type
of element to be stored in array, arrayname specifies
the name of the array, using which the elements of the
array will be initialized and manipulated,
rowsize specifies the number of rows, and columnsize
specifies the number of columns.

The following code snippet declares a two-dimensional


array:
String[][] words = new String[4][2];

The preceding code snippet creates an array of String,


words in which it contains four rows and two columns.
Assigning Values to the Array
You can assign values to each element of the array by
using the index number of the element. For example, to
assign the value, alpep, to the 0th row and the 0th column
and apple to the 0th row and the 1st column, you can use
the following code snippet:

words[0][0] = “alpep”;
words[0][1] = “apple”;

We, can also assign values to the array at the time of


declaration, as shown in the following code snippet:

String[][] jumbledWords = new String[][] {


{“elapp”,“apple”},{“argneo”,”orange”},{“agrspe”,“grapes”}};
The preceding code snippet stores string values in a
two-dimensional array, jumbledWords, as shown in the
following figure.

The Values Stored in the jumbledWords Array


Accessing Arrays
To perform various manipulations on the array, you
need to access the following types of arrays:
1. One-dimensional array
2. Two-dimensional array

One-dimensional Array
To access a one-dimensional array, the following syntax
is used:

arrayname[index];

In the preceding syntax, arrayname specifies the name


of the array and index specifies the location of the
array element.
Consider the following code snippet:

String jumbledWords[] = {“alpep”,”argneo”,”rgaeps”};


System.out.println(jumbledWords[0]);
if you want to display all the elements stored in the
array, you can use the for loop, as shown in the
following code snippet:

String jumbledWords[] = {“alpep”,”argneo”,”rgaeps”};


for(int i=0;i<3;i++)
System.out.println(jumbledWords[i]);

However, if you do not know the total number of


elements in the array, then traversing through the
entire array will be difficult. This can be simplified by
using the length property of an array. This property
returns the length of an array. The following code
snippet is used to traverse through the array using the
for loop and the length property:

String jumbledWords[] = {“alpep”,”argneo”,”rgaeps”};


for(int i=0;i<jumbledWords.length;i++)
System.out.println(jumbledWords[i]);
In the preceding code snippet, the
jumbledwords.length property returns 3, which is the
length of the array.

While traversing an array using the for loop, you need


to use a variable. This variable undergoes three
operations: initialization, comparison, and increment.
This is an error-prone approach, if any one of the
operations is not handled properly.

Therefore, to avoid the occurrence of errors, Java


provides the for-each loop to iterate through an
array. This loop increases the readability and simplifies
the code as you need not take care of the three
operations, which are handled by the Java language
implicitly.

The syntax of the for-each loop to use in an array is:


for(type var: arrayobject)
The following code snippet is used to display all the
elements stored in the array using the for-each loop:

String[] jumbledWords = {“alpep”,”argneo”,”rgaeps”};


System.out.println(“Elements stored in array are: “);

for (String i : jumbledWords)


{
System.out.println(i);
}
Two-dimensional Array
To access the two-dimensional array, the following
syntax is used:

arrayname[row][column];

In the preceding syntax, arrayname specifies the name


of the array, and row and column specify the location of
the array element. Consider the following code snippet:

String[][] jumbledWords = new String[][] {


{“elapp”,”apple”},{“argneo”,”orange”},{“agrspe”,”grapes”}};

System.out.println(jumbledWords[0][0]);
However, if you want to display all the elements, you can
use the for loop, as shown in the following code snippet:
String[][] jumbledWords = new String[][]{
{“elapp”,”apple”},{“argneo”,”orange”},{“agrspe”,”grapes”}};

System.out.println(“Elements stored in array are: “);


for (int i=0; i<3; i++)
{
for (int j=0; j<2; j++)
{
System.out.print(jumbledWords[i][j]);
}
}

int a[][] = {{1,2},{4,3}};


for(int i=0; i<a.length; i++)
{
for(int j=0; j<a[i].length; j++)
System.out.println(a[i][j]);
}
In the preceding code snippet, a.length is used
to calculate the total number of rows and
a[i].length is used to calculate the total number
of columns in row of the array.
Further, you can use the following code
snippet to display all the elements stored in
the two-dimensional array using the for-each
loop:
String[][] jumbledWords = new
String{“elapp”,”apple”},{ “argneo”,”orange”},{
“agrspe”,”grapes”}};

System.out.println(“Fruits are: “);


for (String[] i : jumbledWords)
{
for (String j : i)
{
System.out.println(j);
}
}
Creating a Dynamic Array in Java

Arrays are linear data structures which means


that similar types of elements will be inserted
as known in a continuous manner. Now as we know
there is an issue with arrays that size needs to
be specified at the time of declaration or taken
from the user in java which constructs
ourselves. Hence, there arise dynamic arrays in
java in which entries can be added as the array
increases its size as it is full.

The size of the new array increases to double


the size of the original array. Now all elements
are retained in a new array which is in specified
array domain size and the rest are added after
them in the newly formed array. This array
keeps on growing dynamically.
Implementation: Creating an Array class that declares the int
arr and int count. We just created an array whenever the array is
full the array will be resized.

// Java Program to Create a Dynamic Array

class Array {

// Member variables of this class


// Private access modifier
private int arr[];
private int count;

// Note they can only be called through function

// Method 1
// Inside helper class
// to compute length of an array
public Array(int length)
{
arr = new int[length];
}
// Method 2
// Inside helper class
// To print array
public void printArray()
{

// Iterating over array using for loop


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

// Print the elements of an array


System.out.print(arr[i] + " ");
}
}

// Method 3 Inside Helper class


public void insert(int element)
{

if (arr.length == count) {

// Creating a new array double the size of array declared above


int newArr[] = new int[2 * count];

// Iterating over new array using for loop


for (int i = 0; i < count; i++) {
newArr[i] = arr[i];
}

// Assigning new array to original array


// created above
arr = newArr;
}

arr[count++] = element;
}
}
// Class 2
// Main class
public class DynamicArray {

// Main driver method


public static void main(String[] args)
{

// Creating object of Array(user-defined) class


Array numbers = new Array(3);

// Adding elements more than size specified above


// to the array to illustrate dynamic nature
// using the insert() method

// Custom input elements


numbers.insert(10);
numbers.insert(30);
numbers.insert(40);
numbers.insert(50);

// Calling the printArray() method to print


// new array been dynamically created
numbers.printArray();
}
}
Procedure:
1. First, we declared an array of types int with the
private access specifier .

2. Declare the count variable.

3. Create a constructor that initializes the array of


the given length.

4. Here the magic comes with the method insert.

5. First, before we insert the value it checks for the


length of the array and count variable if both are
of the same size then the array is said to be full.

6. Then we create a new array whose size is twice the


size of the previous array.

7. Just initialized the new array with the previous


array and reinitialized it back to the previous array.
Manipulating Strings
String is a sequence of characters. In java, objects of
String are immutable which means a constant and cannot
be changed once created. However, the reference
variables of the String class are mutable.
Java only supports operator overloading for the String
class. The + operator allows us to combine two strings.
For instance, "a"+"b"="ab."

StringBuilder and StringBuffer are two helpful classes in


Java that can be used to manipulate strings. A string is a
final class in Java that extends java.lang.
Creating a String

There are two ways to create string in Java:


1. String literal
String s1 = “CIMAGE”;
The preceding code snippet creates a new string object
with a value, CIMAGE, in the string constant pool and
assigns it to the reference variable, s1.
For example, consider the following figure

In the preceding figure, s1 is a string reference


variable, which refers to the string object with the
value, Hello.

If you append the string literal, World, to the


string reference variable, s1, then a new string
object, Hello World, is created in the memory and
the variable, s1, will refer to the new string object.
However, the string object, Hello, still exists in the
memory but has no reference, as shown in the
following figure.
The String Reference Variable Referring to the New String Object

Thus, every time you manipulate a string object, a


new string object is created in the memory.
Therefore the String class is called as an
immutable class.
2. Using new keyword
String s1 = new String (“CIMAGE”);
The preceding code snippet creates a new string
object in the heap memory, with a value, CIMAGE, and
assigns it to reference variable, s1.

In addition, it creates another string object with the

value, CIMAGE, in the string constant pool.


Example :
String s1 = new String(“CIMAGE”);

String s2 = new String(“CIMAGE”);

System.out.println(s1==s2);
System.out.println(s1.equals(s2));
Example :
String s=new String(“CIMAGE”);
String s=“CIMAGE”;

Just a Minute
How memory is allocated in above case. In Heap and
String Constant Pool ?

Example :

String s1=new String(“CIMAGE”);


String s2=new String(“CIMAGE”);
String s3=“CIMAGE”;
String s4=“CIMAGE”;

Just a Minute
How memory is allocated in above case. In Heap and
String Constant Pool ?
The following table lists the some of the most commonly
used methods of the String class
Method Description Example
int length() Returns the length of a String str = “newstring”;
string object.
int len = str.length();
System.out.println(len);

Output:
9
char Returns the character at String str = “Fruit”;
charAt(int index) the specified index, char result = str.charAt(3);
which ranges from 0 to
the length of string object
System.out.println(result);
-1.
Output:
i
void Copies characters from a String Str1 = new String(“Welcome to
java”);
getChars(int source string object into
char[] Str2 = new char[6];
srcBegin,int the destination character Str1.getChars(8, 10, Str2, 0);
srcEnd, array. The first character
to be copied is at index
char[] dst, srcBegin, the last System.out.print(“Value Copied = “);
int dstBegin) character to be copied is
at index srcEnd-1. The System.out.println(Str2);
Output:
character is copied into
Value Copied = to
dst, starting at index,
dstbegin.
boolean Compares the current String str1 = “Fruit”;
string object with the
equals(object other string and returns String str2 = “Fruit”;
obj) a boolean value. boolean result = str1.equals(str2);
System.out.println(result);
Output:
True
Method Description Example
int compareTo( Compares the current String str1 = “fruits”;
string object with String str2 = “fruits are good”;
String str) another string int result = str1.compareTo( str2
);

If the strings are same,


the return value is 0, System.out.println(result);
else the return value
is non-zero. Output:
-9

boolean Tests whether a string starts String Str = new String(“Welcome to


with the specified prefix or Java”);
startsWith( not. If the character System.out.print(“Value returned :”);
sequence represented by the
String prefix) argument is a prefix of the
System.out.println(Str.startsWith(“W
elcome”));
string, the return value is
true.
Output:
Otherwise, it is false.
Value returned :true
boolean Tests if the string object ends String Str = new String(“Welcome to
with the specified suffix. Java”);
endsWith( Returns true if the System.out.print(“Value Returned:”);
character sequence
String suffix) represented by the argument
System.out.println(Str.endsWith(“Jav
a”));
is a suffix of the character
sequence represented by this
object. Otherwise, it is Output:
false.
Value Returned: true

int indexOf( Returns the index of the String Str = new String(“Welcome to
first occurrence of the Java”);
int ch) specified character System.out.print(“Index Found at:”);
within a string. If the System.out.println(Str.indexOf('o'));
character is not found,
the method returns –1.
Output:
Method Description Example
String Str = new String(“Welcome to
int Returns the index of the
Java”);
specified character
lastIndexOf occurring last in the System.out.print(“Last Index Found
at :” );
(int ch) string. If the character
System.out.println(Str.lastIndexOf(
is not found, the 'o' ));
method, indexOf(),
Output:
returns –1.
Last Index Found at :9

String Returns a substring of String Str = new String(“Welcome to


Java”);
subString(int a string. The substring
System.out.print(“Value Returned:”
beginindex) begins with the );
character at the System.out.println(Str.substring(10)
specified index and );
extends to the end of Output:
the main string. Value Returned: Java

String Concatenates the String str1 = “Hello “;


concat(String specified string to String str2 = “Everybody”;
str) the end of the
System.out.println(str1.concat(str2)
string object. );
Output:
Hello Everybody
String Replaces the occurrence String Str = new String(“Welcome to
of a specified character Java”);
replace(char by a new specified System.out.print(“Value Returned:”
oldChar,char character. Returns the );
newChar) string derived from the System.out.println(Str.replace('o',
string by replacing every 'T'));
occurrence of oldChar Output:
with newChar. Value Returned:WelcTme tT Java
Just a Minute
Example :

String s= new String(“CIMAGE”);


s.concat(“ Patna”);
s=s.concat(“ Bihar”);
How memory is allocated in above case. In Heap and
String Constant Pool?
Just A Minute
String s1=new String(“Spring”);

s1.concat(“Fall”);

String s2=s1.concat(“Winter”);

s2.concat(“Summer”);

System.out.println(s1);

System.out.println(s2);
String s1=new String(“We like core Java”);

String s2=new String(“We like core Java”);

System.out.println(s1==s2); //false

String s3=“We like core Java”;

System.out.println(s1==s3); //false

String s4=“We like core Java”;

System.out.println(s3==s4); //true

String s5=“We like ”+”core Java”;

System.out.println(s4==s5); //true

String s6=“We like “;

String s7=s6+“core Java”;


System.out.println(s4==s7); //false

final String s8=“We like “;

String s9=s8+”core Java”;

System.out.println(s4==s9); //true
Method Description Example
String String Str = new String(“Welcome to
Converts the string Java”);
toUpperCase() to uppercase and System.out.print(“Value Returned:”);
System.out.println(Str.toUpperCase()
returns it. );
Output:
Value Returned: WELCOME TO JAVA
String String Str = new String(“WELCOME TO
Converts the string JAVA”);
toLowerCase() into lowercase and System.out.print(“Value Returned:”);
returns it. System.out.println(Str.toLowerCase())
;
Output:
Value Returned: welcome to java

String trim() String Str = new String(“


Removes white WELCOME TO JAVA”);
space from both System.out.print(“Value Returned
ends of a string :”);
object and returns System.out.println(Str.trim());
Output:
the trimmed string.
Value Returned :WELCOME TO JAVA
char[] String Str = new String(“WELCOME TO
Returns a newly JAVA”);
toCharArray() allocated array System.out.print(“Value Returned: “);
whose length is the char ch[] = Str.toCharArray();
length of this string
System.out.println(ch);
and whose content
are initialized to Output:
contain the Value Returned: WELCOME TO JAVA
character sequence
represented by this
string.
Method Description Example

String Returns the string int a = 10; Double b


valueOf( representation of
= 2.00;
the specified char[] arr = {'a', 'b'};
Object obj) argument. Returns System.out.println(“Return
null if the Value : “
argument is null. + String.valueOf(a));
The valueOf() System.out.println(“Return
Value : “+ String.valueOf(b)
method is a static );
method.

Output:
Return Value : 10

Return Value : 2.0

boolean Compares this String Str1 = new


equalsIgnore string with String(“fruits”); String Str2
Case(String another string = new String(“FRUITS”);
anotherString) and ignores System.out.println(“Return
case = “+
Str1.equalsIgnoreCase(Str2)
considerations. );
Output:
Return = true
StringBuilder, and StringBuffer classes

You can also use the StringBuilder and StringBuffer


classes to work with strings. These classes are mutable
classes as they do not create any new string object when
manipulated. Therefore, when you need to do various
manipulations, such as appending, concatenating, and
deleting with string literals, you should use StringBuilder
and StringBuffer.

The following code snippet initializes a string object to a


StringBuilder reference:

StringBuilder s1= new StringBuilder(“Hello”);

Note :-
StringBuffer class has the same methods as that of the
StringBuilder class.
However, the methods in StringBuffer class are
synchronized
The following table lists the some of the most commonly
used methods of the StringBuilder class
Method Description Example
StringBuilder Appends the argument StringBuilder sb = new
append(String to the string builder. StringBuilder(“Fruits “);
obj) sb.append(“are good for health”);
System.out.println(sb);
Output:
Fruits are good for health
StringBuilder Deletes the sequence from StringBuilder str = new
delete(int start to end in the char StringBuilder(“fruits are very
start, int sequence. good”);
end)
str.delete(10, 15);
System.out.println(“After deletion =
“+ str);
Output:
After deletion = fruits are good
StringBuilder Inserts the second StringBuilder str = new
insert(int argument into the string StringBuilder(“fruitsgood”);
offset, String builder. The first argument str.insert(6, “ are “);
obj) indicates the index before
System.out.print(“After insertion =
which the data is to be
“);
inserted.
System.out.println(str.toString());
Output:
After insertion = fruits are good
StringBuilder The sequence of StringBuilder str = new
reverse() characters in the string StringBuilder(“fruits”);
builder is reversed. System.out.println(“reverse = “ +
str.reverse());
Output:
reverse = stiurf
Just A Minute
StringBuffer sb1=new StringBuffer(“CIMAGE”);
StringBuffer sb2=new StringBuffer(“CIMAGE”);

System.out.println(sb1==sb2)
System.out.println(sb1.equals(sb2));

What will be the output? Explain.


Vector Class in Java
The java.util.Vector class implements a growable array of
objects. Like an array, it contains components that can be
accessed using an integer index.

However, the size of a Vector can grow or shrink as needed to


accommodate adding and removing items after the Vector has
been created.

It extends AbstractList and implements List interfaces.


Vector class constructors:
Constructor Description

It creates a default vector, which has an initial size


Vector( )
of 10.

It creates a vector whose initial capacity is specified


by size and whose increment is specified by incr. The
Vector(int size, int incr)
increment specifies the number of elements to
allocate each time that a vector is resized upward.

It creates a vector that contains the elements of


Vector(Collection c)
collection c.
The following table lists the commonly used methods of the Vector class

Method Description
boolean add(E e) Is used to add the specified object at the end of
Vector.
void clear() Is used to remove all the objects from Vector.
E get(int index) Is used to retrieve the object at the specified index from Vector.

E remove(int index) Is used to remove the object at the specified index from Vector.

boolean Is used to remove the first occurrence of the specified object from Vector.
remove(Object o)
int size() Is used to get the number of objects in Vector.
The following table lists the commonly used methods of the Vector class.

Method Description

boolean add(E e) Is used to add the specified object


at the end of
Vector.
void clear() Is used to remove all the objects
from Vector.
E get(int index) Is used to retrieve the object at
the specified index from Vector.

E remove(int index) Is used to remove the object at


the specified index from Vector.

boolean remove(Object o) Is used to remove the first


occurrence of the specified object
from Vector.
int size() Is used to get the number of
objects in Vector.
Consider the following code to add and remove the objects to/ from a Vector collection:

import java.util.ListIterator;
import java.util.Vector;
public class VectorDemo
{
public static void main(String[] args)
{
Vector<Double> obj = new Vector<Double>();
Double dobj1 = new Double(77.5);
Double dobj2 = new Double(68.1);
Double dobj3 = new Double(52.8);
Double dobj4 = new Double(40.2);
System.out.println("Size of Vector is: "
+obj.size());
obj.add(dobj1);
obj.add(dobj2);
obj.add(dobj3);
obj.add(dobj4);
obj.add(dobj1);

System.out.println("\nVector after adding the objects: " +


obj);
System.out.println("Size of Vector after adding objects: "
+obj.size());
obj.remove(dobj1);
obj.remove(dobj3);
System.out.println("\nVector after removing the
objects: " + obj);
System.out.println("Size of Vector after removing
objects: " +obj.size());
System.out.println("\nThe final Vector: ");
ListIterator i = obj.listIterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Once the preceding code is executed, the following output is displayed:

Size of Vector is: 0

Vector after adding the objects: [77.5, 68.1, 52.8, 40.2, 77.5] Size of
Vector after adding objects: 5

Vector after removing the objects: [68.1, 40.2, 77.5] Size of Vector after
removing objects: 3

The final Vector:


68.1
40.2

You might also like