KEMBAR78
Arrays and Strings | PDF | Class (Computer Programming) | String (Computer Science)
0% found this document useful (0 votes)
51 views20 pages

Arrays and Strings

The document provides an overview of arrays and strings in Java, detailing their creation, initialization, and key characteristics. It explains the concept of immutable strings, the string constant pool, and various methods associated with string manipulation. Additionally, it covers wrapper classes, their significance, and the processes of autoboxing and unboxing in Java.

Uploaded by

batraaryan03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views20 pages

Arrays and Strings

The document provides an overview of arrays and strings in Java, detailing their creation, initialization, and key characteristics. It explains the concept of immutable strings, the string constant pool, and various methods associated with string manipulation. Additionally, it covers wrapper classes, their significance, and the processes of autoboxing and unboxing in Java.

Uploaded by

batraaryan03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT II

ARRAYS AND STRINGS

Arrays, One-Dimensional arrays, Creating an Array,


declaration of arrays, initialization of arrays, Two-Dimensional
arrays, String arrays, String methods, String Buffer class,
Vectors, Wrapper classes.
Arrays In Java
Arrays in Java are homogeneous data structures implemented in Java as objects. Arrays store one or more
values of a specific data type and provide indexed access to store the same. A specific element in an array
is accessed by its index. Arrays offer a convenient means of grouping related information.

Obtaining an array is a two-step process. First, you must declare a variable of the desired array type.
Second, you must allocate the memory that holds the array, using new, and assign it to the array variable.

Arrays can be initialized when they are declared. The array will automatically be created large enough to
hold the number of elements you specify in the array initializer. There is no need to use a new operator.

Multidimensional arrays are arrays of arrays.


To declare it, we specify each additional index using another set of square brackets.
Strings In Java
In Java, String is an object of the String class that represents a string of characters. For example, “Pencil”
is a string of 6 characters. String class is used to create a string object. It is a predefined immutable class
that is present in the java.lang package. In Java, all classes are also considered as a data type. So, you can
also consider a string as a data type. Immutable means it cannot be changed.

When we create a String object, we are creating a string that cannot be changed. In other words, once a
String object has been created, we cannot change any characters in the string. Therefore, string objects are
immutable in Java.

Basically, memory in Java is divided into three parts such as heap, stack, and String Pool. The string is so
important in Java that it has a dedicated memory location. What string pool does is whenever a string gets
repeated it does not allocate the new memory for that string. It uses the same string by pointing a
reference to it for saving memory.

The String type is known as reference data type. It is not a primitive data type. In Java language, any class
can be used as a reference type for a variable. A variable that is declared by a reference type is called a
reference variable. It references an object.

String Class Declaration in Java

public final class String

extends Object

implements Serializable, Comparable<String>, CharSequence

The above syntax says that string is a final class and object class is its superclass. The class implements
three interfaces Serializable, Comparable, and CharSequence. The CharSequence is an interface that is
used to represent the sequence of characters. String, StringBuffer, and StringBuilder classes implement it.

Creating String Object in Java


To handle string data in Java, we need an object of string class.
Basically, there are three ways to create a string object in Java.

1.​ By string literal.


2.​ By new keyword.
3.​ By converting character arrays into strings
1. String Literal in Java

A string literal is created by using double quotes.


Each time you create a string literal, the JVM
checks the string pool first. If the string already
exists in the pool, a reference to the pooled
instance is returned. If the string doesn’t exist in
the pool, a new string instance is created and
placed in the pool.

In this example, only one object will be created.


The JVM will first create a new object with the
value “Student”, and then it will find the string
with the same value in the pool and return the
reference to the same instance instead of creating a
new one.

The string literal is always created in the string constant


pool, a special area that is used for storing string objects.
It reduces memory overhead and increases performance
by reducing the number of String objects created in the
JVM. Internally, String class uses a string constant pool
(SCP). This SCP area is part of the method area
(Permgen) until Java 1.6 version. From Java 1.7
onwards, SCP area is moved in the heap memory
because SCP is fixed size in the method area but in the
heap memory, SCP can be expandable. Therefore, the
string constant pool has been moved to the heap area for
memory utilization only.

Whenever we create a string literal in Java, JVM checks the string constant pool first. If the string already
exists in the string constant pool, no new string object will be created in the string pool by JVM. JVM
uses the same string object by pointing a reference to it to save memory. But if string does not exist in the
string pool, JVM creates a new string object and places it in the pool.

For example,

String s1 = "Hello";

String s2 = "Hello";
Look at the figure where we have represented string objects with contents in the memory.

In the above example, when JVM will execute the first statement, it will not find any string with value
“Hello” in the string constant pool. So, it will create an object in the string pool and store the string
“Hello” in that object as shown in the above figure.

This object is referenced by the reference variable s1. In other words, if literal is not available in the pool,
a new object will be created in the pool and the address of that object will be assigned to a reference
variable s1.

When the JVM executes the second statement, it will first check the string constant pool to know whether
a string object with the same content is already available there or not. Since string with value “Hello” is
already available in the string pool.

So, JVM will not create a new string object in the pool, and the address of the available object will be
assigned to reference variable s2. That is, it will point a reference variable s2 to the old existing object as
shown in the above figure.

➢​ Remember that creating an object means allocating memory for storing data.
➢​ A string object is created for every string literal.

2. Creating String Object by new Keyword

The second way of creating an object to string class is by using a new operator.

It is just like creating an object of any class. When you use the “new” keyword, a new instance of the
string is created in the heap, regardless of whether it already exists in the string pool.

For example, String s = new String("Hello");

Whenever we create an object of a string class using the new operator, JVM will create two objects. First,
it will create an object in the heap area and store the string “Hello” into the object.

After storing data into memory, JVM will point a reference variable s to that object in the heap.
Allocating memory for string objects is shown in the below figure.
Now JVM will create the second object as a copy
for literal “Hello” in string constant pool for future
purposes. There is no explicit reference variable
pointing to the copy object in the pool but
internally, JVM maintains the reference variable
implicitly.

Remember that the object created in the SCP area


is not eligible for garbage collection because
implicitly, the reference variable will be
maintained by JVM itself.

➢​ For every string literal, one copy will be


created in the SCP area.

3. By Converting Character Arrays into String

The third way to create strings is by converting the character arrays into string.

Let’s take a character type array: arr[ ] with some characters,

char arr[ ] = {'j','a','v','a'};

Now create a string object by passing array name to string constructor like this,

String s = new String(arr);

Now the string object ‘s’ contains the string “java”, all the characters of the array are copied into string. If
all the characters of the array are not needed then we can mention which character you need,

String s = new String(arr, 1,3);

From the above statement, a total of three characters will be copied into string s. Since the original
characters are j-a-v-a. So, the counting will start from 0, i.e. the 0th character in the array is ‘j’ and the
first character is ‘a’. Starting from ‘a’, a total of three characters ‘ava’ will copy into string s.
Total objects created in memory for following string objects,
String s1 = new String("Scientech");
String s2 = new String("Scientech");
String s3 = "Scientech";
String s4 = "Scientech";

In the preceding code, we are creating four string objects using two new operators and 2 string literals.

How many objects will be created in the heap and SCP area?

1. During the execution of the first statement using the new operator, JVM will create two objects, one
with content in the heap area and another as a copy for literal “Scientech” in the SCP area for future
purposes as shown in the figure. The reference variable s1 is pointing to the first object in the heap area.

2. When the second statement is executed, for every new operation, JVM will create again one new object
with content “Scientech” in the heap area. But in the SCP area, no new object literal will be created by
JVM because it is already available in the SCP area. The s2 is pointing to the object in the heap area as
shown in the figure.

3. During the execution of third and fourth statements, JVM will not create a new object with content
“Scientech” in the SCP area because it is already available in the string constant pool. It simply points the
reference variables s3 and s4 to the same object in the SCP.

Thus, three objects are created, two in the heap area and one in the string constant pool.
String Methods

1. length() Method

The length() method returns the length of a String str = "Hello World";​
string. It is a simple method that is frequently int len = str.length();​
used in Java programming. Below is an System.out.println("Length of the string is: " + len);​
// Length of the string us: 11
example.

2. charAt() Method

The charAt() method returns the character at a String str = "Hello World";​
specified index of a string. It is used to access char ch = str.charAt(6);​
System.out.println("Character at index 6 is: " + ch);
individual characters in a string. Below is an
// Character at index 6 is: W
example.

3. substring() Method

The substring() method returns a substring of a String str = "Hello World";​


given string. It is used to extract a portion of a String subStr = str.substring(0, 5);​
System.out.println("Substring is: " + subStr);
string. Here is an example:
// Substring is: Hello

4. equals() Method

The equals() method compares two strings String str1 = "Hello World";​
and returns true if they are equal. It is used to String str2 = "Hello World";​
check if two strings are the same. Here is an boolean result = str1.equals(str2);​
System.out.println("Strings are equal: " + result);
example: // Strings are equal: true

5. contains() Method

The contains() method checks if a string String str = "Hello World";​


contains a specified character sequence. boolean result = str.contains("Hello");​
System.out.println("String contains 'Hello': " + result);
It is used to check if a string contains a
// String contains 'Hello': true
particular substring.

6. replace() Method

The replace() method replaces a character String str = "Hello World";​


or a sequence of characters in a string with String replacedStr = str.replace("World", "Java");​
System.out.println("Replaced string is: " + replacedStr);
another character or sequence. It is used to
// Replaced string is: Hello Java
replace a character or a substring with
another string.
7. toUpperCase() Method

The toUpperCase() method converts all the String str = "hello world";​
characters in a string to uppercase. It is String upperStr = str.toUpperCase();​
System.out.println("Uppercase string is: " + upperStr);
used to convert a string to uppercase.
// Uppercase string is: HELLO WORLD

8. toLowerCase() Method The

toLowerCase() method converts all the String str = "HELLO WORLD";​


characters in a string to lowercase. It is String lowerStr = str.toLowerCase();​
System.out.println("Lowercase string is: " + lowerStr);
used to convert a string to lowercase.
// Lowercase string is: hello world

9. trim() Method

The trim() method removes whitespace String str = " Hello World ";​
from the beginning and end of a string. It is String trimmedStr = str.trim();​
System.out.println("Trimmed string is: " + trimmedStr);
used to remove leading and trailing
// Trimmed string is: Hello World
whitespace from a string. Here is an
example:

10. valueOf() Method

The valueOf() method converts a given data type to int num = 10;​
its corresponding string representation. It is used to String str = String.valueOf(num);​
System.out.println("String value is: " + str);
convert other data types to a string.
// String value is: 10
Wrapper Classes in Java
Java defines a wrapper class for each of its primitive data types. A Wrapper class in Java is one whose
object wraps or contains primitive data types. Wrapper classes help you write cleaner code, which is easy
to read.

Need of Wrapper Class

1.​ Collection Framework : Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, HashSet, etc.) deal with objects only.

2.​ Pass By Reference : If we pass a primitive value as a method parameter, it will not change the
original value. But, if we convert the primitive value into an object, we can change its original
value.

3.​ Serialization : Serialization can be achieved via Wrapper classes. Serialization is converting the
objects into streams. If we have a primitive value, we can convert it into objects through the
wrapper classes.

4.​ Synchronization : Synchronization can be achieved via Wrapper classes as synchronization


works with objects in Multithreading.

5.​ Generics : Generics allow only wrapper classes. Primitive data types cannot be used.

6.​ Predefined Methods : The java.util package provides the utility classes to deal with objects.

7.​ Null Values : Wrapper classes allow Nullability of objects.

Hierarchy of wrapper classes

1.​ Classes Boolean and


Character directly extend
the class Object.

2.​ All the wrapper classes


implement the interfaces
java.io.Serializable and
java.lang.Comparable.

3.​ All the numeric wrapper


classes extend the class
java.lang.Number
Autoboxing
Autoboxing is the automatic conversion of a
primitive data type to an object of the
corresponding wrapper class.

Unboxing
Unboxing is just the reverse process of autoboxing.
It is the automatic conversion of a wrapper class
object to the corresponding primitive data type.

Ways To Create An Object Of Wrapper Class

1.​ Autoboxing

2.​ Constructor​

All the wrapper classes define constructors to


create an object using a corresponding
primitive value and also accept a String
argument representing the primitive value that
needs to be wrapped.

3.​ Static Method ( valueOf() )



All wrapper classes (except Character) also
define a static method that accepts a String
argument representing the primitive value that
needs to be wrapped.
Creating An Object Of Wrapper Class
public class MyClass{​
public static void main(String[] args){​

// Three ways to create Wrapper Class​
// 1. Constructor 2. Static Method 3. Autoboxing​

Integer i = new Integer(50); // Deprecated since it forces JVM to always create a new instance​
Integer i2 = Integer.valueOf(100); // Preferred since it returns cached objects (Managed by JVM)​
Integer c = 12; // Autoboxing ( Automatically calls valueOf() method )​
Integer d = i.valueOf(40); // Can also use an instance of Integer Class​

int a = i; // Unboxing ( Automatically calls intValue() method )​
int b = i.intValue();​

System.out.println(a + b + c + d); // 152​

}​
}

Parsing A String Value To A Primitive Type


import java.util.*;​

public class Main {​

​ public static void main(String[] args) {​

​ ​ Scanner s = new Scanner(System.in);​
​ ​ String str = s.nextLine();​

​ ​ int i = Integer.parseInt(str); // 52​
​ ​ int i2 = Integer.parseInt("50");​

​ ​ System.out.println( i + i2 ); // 102​


​ }​
}
Retrieving Primitive Value From The Wrapper Object
public class MyClass{​
public static void main(String[] args){​

// int a = Integer.intValue(); non-static method cannot be referenced from static
context​

Integer i = 50;​

int a = i;​
float b = i.intValue();​

// Float c = 10; int cannot be converted to float​
// Float d = i.intValue(); int cannot be converted to float​

// typecasting​
Float f = (float) 10;​
Float g = (float) i.intValue();​



Character h = (char) 65;​
Character k = (char) ( f + g );​

// System.out.println( (h + k).charValue() ); // int cannot be dereferenced​
// System.out.println( Character.valueOf(( a + f + h + k)) ); // possible lossy
conversion from float to char​

Character z = Character.valueOf( (char) ( a + f + h ) );​

System.out.println( z ); // Output: }​
System.out.println( z + z.charValue() ); // Output: 250​



}​
}
String Buffer In Java
StringBuffers provide a mutable alternative, rather than regular strings, which are immutable (cannot be
changed once created), They are designed to minimize memory overhead and improve performance
when frequent modifications are needed. StringBuffers are commonly used in scenarios where frequent
string modifications or concatenations are required, such as in text processing, building dynamic SQL
queries, or constructing large strings from smaller pieces.

Characteristics of StringBuffers :

1. Mutable : StringBuffers can be modified, allowing characters to be appended, inserted, or replaced


within the sequence. This is particularly useful when building or modifying strings dynamically.

2. Efficient Concatenation : StringBuffers provide a more efficient way to concatenate strings compared
to using the ‘+’ operator repeatedly. This is because StringBuffers internally manage a resizable character
array, minimizing the need for repeated memory allocation and copying.

3. Thread-Safe Operations : In some programming languages, such as Java, StringBuffer


implementations are designed to be thread-safe. This means that multiple threads can safely perform
operations on a shared StringBuffer object without conflicts or data corruption.

4. Efficient Memory Management : StringBuffers are designed to optimize memory usage. They
allocate an initial buffer size, which can be increased dynamically as needed. This avoids excessive
memory allocations and improves performance when building or modifying long strings.

5. String Conversion : StringBuffers provide methods to convert the mutable sequence of characters into
an immutable String object when needed. This allows for compatibility with methods or APIs that require
immutable strings.
StringBuffer Methods

1) StringBuffer append() Method

The append() method concatenates the given


argument with this String.

Output :

2) StringBuffer insert() Method

The insert() method inserts the given String


with this string at the given position.

Output :

3) StringBuffer replace() Method

The replace() method replaces the given String from


the specified beginIndex and endIndex.

Output :

4) StringBuffer delete() Method

The delete() method of the StringBuffer class deletes


the String from the specified beginIndex to endIndex.

Output:
5) StringBuffer reverse() Method

The reverse() method of the StringBuilder class


reverses the current String

Output :

6) StringBuffer capacity() Method

The capacity() method of the StringBuffer


class returns the current capacity of the
buffer. The default capacity of the buffer is
16. If the number of character increases
from its current capacity, it increases the
capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it
will be (16*2)+2=34.
Output :

7) StringBuffer ensureCapacity() method

The ensureCapacity() method of the


StringBuffer class ensures that the given
capacity is the minimum to the current
capacity. If it is greater than the current
capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your
current capacity is 16, it will be
(16*2)+2=34.

Output:
Vector Class
The Vector class in Java (package java.util.Vector) since Java 1.0 implements a growable array of objects,
Like an array, it contains components that can be accessed using an integer called “Index”. The size of
Vector automatically grows or shrinks required to accommodate adding or removing items after the
instantiation of Vector. It implements all operational list operations and permits all elements, including
null.

Vector is a synchronized data structure. It was introduced with Java Development Kit 1.0. Later, the
vector is rectified by extending it with AbstractList, which was introduced in JDK 1.2 as part of the Java
collection framework. Besides that, the vector also implements List, RandomAccess, Cloneable and
Serializable interfaces.

All of the operations in the vector are thread-safe and actually allow one thread at a time to enter. As a
result, a vector is slower than other similar data structures, such as an array list. If a thread-safe
implementation is not required, java.util.ArrayList is recommended.

Characteristics of Vector

1.​ Dynamic size : Vectors can grow or shrink in size as elements are added or removed.

2.​ Synchronized : Vectors are thread-safe, meaning they can be safely accessed and modified by
multiple threads concurrently.

3.​ Legacy : The Vector class has been around since Java 1.0 and is now largely replaced by the
ArrayList class, which is more efficient and flexible.

Vector Methods

1.​ add(E element) : Adds an element to the end of the vector.

2.​ remove(int index) : Removes an element at a specific index.

3.​ get(int index) : Retrieves an element to a particular index.

4.​ capacity(): It is used to get the current capacity of a vector.

5.​ size() : Returns the number of elements in the vector.


Some drawbacks of Vector

1.​ Synchronization overhead : Vectors are synchronized, which means they have built-in
thread-safety features. It can lead to performance issues in single-threaded environments, as the
synchronization mechanisms can introduce unnecessary overhead.

2.​ Legacy : The Vector class has been around since Java 1.0 and hasn’t seen significant updates in a
long time. As a result, it lacks many of the features and improvements introduced in newer
collection classes like ArrayList.

3.​ Performance : Vectors are generally slower than ArrayLists due to their synchronization
overhead and legacy implementation.

4.​ Limited functionality : Vectors don’t provide many of the convenience methods available in
ArrayList, such as forEach(), removeIf(), or stream().

5.​ Memory usage : Vectors use more than ArrayLists, especially for large datasets.

Dynamic Growth of Vector


The vector class holds an array of objects to store data. This array is initialised with an initial capacity of
10. The key point to grasp here is the distinction between the capacity and size of the inner array. Size
refers to the number of elements contained within the array, whereas capacity refers to the magnitude of
the array.

When we create a “Vector” object, it creates an internal array with a capacity of 10. This is the vector’s
initial capacity, whereas size is the actual number of elements stored in the vector using the method add.
Once you start adding elements, the size increases and reaches capacity. At that point, when the total
number of elements exceeds its capacity, the vector increases and doubles its size of the internal array.
Vector makes sure to keep all existing values while increasing the current capacity of the array.

The vector array grows twice when the threshold is exceeded. As a result, we see a lot of empty boxes.
Features of Vector
1. Vector class is a resizable array or growable array.
2. Duplicate elements are allowed in the vector class.
3. It always preserves the insertion order of elements.
4. Null elements are allowed in the Java vector class.
5. Heterogeneous elements are allowed in the vector class. It can hold elements of any type.
6. Most of the methods present in the vector class are synchronized. That means it is thread-safe. Two
threads cannot access the same vector object at the same time. Only one thread can access the vector
object at a time.

Ways to Create Vector Class Object in Java


There are four ways to create an object of a vector class in Java. They are as follows :

1. Vector v = new Vector();

2. Vector v = new Vector(int initialCapacity);​



Vector v = new Vector(3);
// It will create an empty vector with initial capacity of 3.​

3. Vector v = new Vector(int initialCapacity, capacityIncrement);​

Vector v = new Vector(3, 5);​

4. Vector v = new Vector(Collection c);​

Vector v = new Vector(list);
// list is an element of the collection.

Vector v = new Vector();

It creates a vector list with a default initial capacity of 10. Inside the vector list, data is stored as an array
of objects according to the initial size that you specify in the constructor. Since default initial capacity is
10. So, we can store only 10 elements.

When the 11th element is inserted into the vector, the capacity of the vector will be exceeded. In this case.
a new internal array will be automatically created that is equal to the size of the old array plus capacity
increment specified in the constructor.

If you do not specify an initial capacity and capacity increment, each time vector will be resized due to
exceeding its capacity. A new internal array will be created which copies all the original elements of the
old array into the new array by using System.arraycopy() method.
Creating a new array and copying elements will take more time. Therefore, it is important to assign the
value of initial capacity and capacity increment for minimizing the number of resizing operations without
wasting too much memory and time.

In this object creation, we did not specify any capacity increment in the constructor. So, its size will be
doubled by default, which will be 20. After resizing, it copies all original elements of the old array into
the new array using System.arraycopy() method, and then it will insert the 11th element.

Generic Vector Class Object


Vector<T> vec = new Vector<T>(); // T is the type of generic.​

Vector<String> vec = new Vector<String>(); // It will store only string type elements.
Vector<Integer> v = new Vector<Integer>(3,6);

Base Non-generic Vector Class Generic Vector Class

Syntax Vector v = new Vector(); Vector<ReferenceType> v = new Vector<ReferenceType>();

Can hold any type of data. Hence


Type-safety Can hold only the defined type of data. Hence type safe.
not type-safe.

Individual type casting needs to be


Typecasting No type casting is needed.
done at every retrieval.

Compile-Time
Checked for type safety at runtime. Checked for type safety at Compile-time.
Checking

ArrayList and Vector are nearly the same and are implemented from the same interfaces AbstractList.
Therefore, In comparison to ArrayList, Vector is thread-safe and Synchronized while ArrayList is not.
That is the reason ArrayList performs faster operations in a single-threaded environment. Whereas, Vector
is much slower in comparison to ArrayList. Vector is a legacy class, whereas ArrayList is not. ArrayList
increases its capacity by 50% of the size when threshold is reached, whereas Vector straightaway doubles
its size, that is 100% of its capacity, thereby showing that Vector may have more empty spaces in memory

You might also like