Unit-02 - Array and String - With - Notes
Unit-02 - Array and String - With - Notes
2
3
Java Arrays:
Normally, an array is a collection of similar type of elements which have a contiguous
memory location.
Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member.
In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We can
store primitive values or objects in an array in Java.
we can also create single dimentional or multidimentional arrays in Java.
Advantages:
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
• Random access: We can get any data located at an index position.
Disadvantages:
• Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java
which grows automatically.
Types of Array in java: 1) Single Dimensional Array 2) Multidimensional Array
Single Dimensional Array in Java:
• Syntax to Declare an Array in Java - int a[ ] ; or int [ ] c ;
• Instantiation of an Array in Java - a = new int [ 10 ] ;
• Declaration and Initialization of Java Array - int a[ ] = { 33 , 3 , 4 , 5 } ;
4
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays with each element of the
array holding the reference of other array. These are also known as Jagged Arrays. A
multidimensional array is created by appending one set of square brackets ( [ ] ) per
dimension.
5
String:
String is a sequence of characters. But in Java, a string is an object that
represents a sequence of characters. The java.lang.String class is used to create string
object.
Java String Pool: Java String pool refers to collection of Strings which are stored in
heap memory. In this, whenever a new object is created, String pool first checks
whether the object is already present in the pool or not. If it is present, then same
reference is returned to the variable else new object will be created in the String pool
and the respective reference will be returned.
In the above image, String object str2 is created. Now, when String object str4 is
created with the value “java5”, instead of creating a new object, the already present
object reference in String Constant Pool is returned.
Strings are immutable. By immutable, we mean that Strings are constant, their values
cannot be changed after they are created.
6
String Methods:
• Int length ( ) : The Java String length() method tells the length of the string. It
returns count of total number of characters present in the String.
• String concat ( String s2 ) : The Java String concat() method combines a specific
string at the end of another string and ultimately returns a combined string. It is
like appending another string.
• char charAt ( int index ) : It returns the character at the specified index. Specified
index value should be between 0 to length() -1 both inclusive. It throws
IndexOutOfBoundsException if index is Invalid / Out of range.
• int compareTo ( String string ) : This method compares the two strings based on
the Unicode value of each character in the strings.
7
String Methods:
• boolean endsWith ( String str ) : The Java String endsWith( ) method checks if this
string ends with the given suffix. If it returns with the given suffix, it will return true
else returns false.
• boolean equals ( Object obj ) : Compares the string with the specified string and
returns true if both matches else false.
• int indexOf ( int ch ) : Returns the index of first occurrence of the specified
character ch in the string.
• int indexOf ( int ch, int fromIndex ) : Same as indexOf method however it starts
searching in the string from the specified fromIndex.
• int indexOf ( String str ) : This method returns the index of first occurrence of
specified substring str.
• int indexOf ( String str , int fromIndex ) : This method returns the index of first
occurrence of specified substring str but it starts searching in the string from the
specified fromIndex.
8
String Methods:
• int lastIndexOf ( int ch ) : It returns the last occurrence of the character ch in the
string.
• int lastindexOf ( String str ) : Returns the index of last occurrence of string str.
• int lastindexOf ( String str , int fromIndex ) : Returns the index of last occurrence
of string str, it starts search from fromIndex.
• String replace ( char oldChar , char newChar ) : It returns the new updated string
after changing all the occurrences of oldChar with the newChar.
9
String Methods:
• String [ ] split ( String regex , int limit ) : It splits the string and returns the array of
substrings that matches the given regular expression. limit is a result threshold
here.
• String [ ] split ( String regex ) : Same as split(String regex, int limit) method
however it does not have any threshold limit.
• boolean startsWith ( String prefix , int offset ) : Checks whether the String is
having the specified prefix or not – starting from the specified offset index, if yes
then it returns true else false.
• String substring ( int beginIndex ) : Returns the substring. The substring starts with
character at beginIndex and ends with the last character of string.
• String substring ( int beginIndex , int endIndex ) : Returns the substring. The
substring starts with character at beginIndex and ends with the character at
endIndex.
10
String Methods:
• String trim( ): Returns the substring after omitting leading and trailing white
spaces from the original string.
• String toString( ): The toString() method returns the string representation of the
object.
11
StringBuffer class:
StringBuffer is a peer class of String that provides much of the
functionality of strings. String represents fixed-length, immutable character
sequences while StringBuffer represents growable and writable character sequences.
StringBuffer may have characters and substrings inserted in the middle
or appended to the end. It will automatically grow to make room for such additions
and often has more characters preallocated than are actually needed, to allow room
for growth.
StringBuffer Constructors:
• StringBuffer( ): Creates a StringBuffer with empty content and 16 reserved
characters by default.
StringBuffer sb = new StringBuffer();
• StringBuffer(int sizeOfBuffer): Creates a StringBuffer with the passed argument
as the size of the empty buffer.
StringBuffer sb = new StringBuffer(20);
• StringBuffer(String string): Creates a StringBuffer with the passed String as the
initial content of the buffer. 16 contingent memory characters are pre-allocated,
not including the buffer, for modification purposes.
StringBuffer sb = new StringBuffer("Hello World!");
12
Methods:
Many methods are similar to String class, Some of the most used methods are:
• append( ): It is used to add text at the end of the existence text. Here are a few of
its forms:
• StringBuffer append(String str)
• StringBuffer append(int num)
• reverse( ): It can reverse the characters within a StringBuffer object using reverse(
).This method returns the reversed object on which it was called.
13
• insert( ): It is used to insert text at the specified index position. These are a few of
its forms:
• StringBuffer insert(int index, String str)
• StringBuffer insert(int index, char ch)
Here, index specifies the index at which point the string will be inserted into
the invoking StringBuffer object.
• replace( ): It can replace one set of characters with another set inside a
StringBuffer object by calling replace( ). The substring being replaced is specified
by the indexes start Index and endIndex. Thus, the substring at start Index through
endIndex–1 is replaced. The replacement string is passed in str. The resulting
StringBuffer object is returned. Its signature is shown here:
• StringBuffer replace(int startIndex, int endIndex, String str)
• length( ) and capacity( ): The length of a StringBuffer can be found by the length( )
method, while the total allocated capacity can be found by the capacity( ) method.
• void setCharAt ( int index , char ch ) : In this method, the character at the
specified index is set to ch.
• public void setCharAt(int index, char ch)
• void setLength ( int newLength ) : This method sets the length of the character
sequence.
• public void setLength(int newLength)
• void trimToSize( ) : This method attempts to reduce storage used for the character
sequence.
• public void trimToSize()
13
String vs StringBuffer:
1) Storage Area:
String objects are stored in a constant pool whereas, StringBuffer objects are stored
on heap memory.
String object consumes more memory whereas, StringBuffer objects consumes less
memory when we perform a string manipulation operation like concat, substring.
Since String is immutable in Java, whenever we do String manipulation like
concatenation, substring etc, it generates a new String and discards the older String
for garbage collection. These are heavy operations and generate a lot of garbage in
heap.
String is immutable:
String str = "Hello World";
str = "Hi World!";
By seeing this code you would say that the value of str has changed so how can it be
immutable?
Let me explain this:
In first statement an object is created using string literal “Hello World”, in second
statement when we assigned the new string literal “Hi World!” to str, the object itself
didn’t change instead a new object got created in memory using string literal “Hi
World!” and the reference to it is assigned to str. So basically both the objects “Hello
World” and “Hi World!” exists in memory having different references(locations).
14
StringBuffer is mutable:
Lets see StringBuffer mutability
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
In the first statement StringBuffer object got created using string literal “Hello” and in
second statement the value of the object got changed to “Hello World” from “Hello”.
Unlike Strings here the object got modified instead of creating the new object.
3) Thread Safe:
String & StringBuffer(Thread-safe)
• String & StringBuffer is thread-safe meaning that they have synchronized methods
to control access so that only one thread can access String or StringBuffer object's
synchronized code at a time.
• String & StringBuffer objects are generally safe to use in a multi-threaded
environment where multiple threads may be trying to access the same String or
StringBuffer object at the same time.
StringBuilder(Non-thread-safe)
• StringBuilder is not synchronized so that it is not thread-safe. By not being
synchronized, the performance of StringBuilder can be better than StringBuffer.
• If we are working in a single-threaded environment, using StringBuilder instead of
StringBuffer may result in increased performance. This is also true of other
situations such as a StringBuilder local variable where only one thread will be
accessing a StringBuilder object.
4) Performance:
While performing concatenations you should prefer StringBuffer over String because
it is faster. The reason is: When you concatenate strings using String, you are actually
creating new object every time since String is immutable.
• Strings are easy to type, easy to use, and are thread-safe. On the other hand they
are immutable (which means more memory consumption) and very slow when
doing string manipulation.
• StringBuffers are mutable, memory efficient, and thread-safe. Their downfall is the
speed when compared to much faster StringBuilders.
• As for StringBuilders, they are also mutable and memory efficient, they are the
fastest in string manipulation, but unfortunately they are not thread-safe.
14
Command Line Argument:
Command Line Argument is information passed to the program when you run the
program. The passed information is stored as a string array in the main method. Later,
you can use the command line arguments in your program.
Important Points:
• Command Line Arguments can be used to specify configuration information while
launching your application.
• There is no restriction on the number of java command line arguments. You can
specify any number of arguments.
• Information is passed as Strings.
• They are captured into the String args of your main method.
Example:
class Demo {
public static void main ( String args [ ] ) {
System.out.println ( "Argument one = “ + args [ 0 ] ) ;
System.out.println ( "Argument two = “ + args [ 1 ] ) ;
}
}
Compile:
javac Demo.java
Run:
java Demo Hello World
15
Wrapper Classes:
A Wrapper class is a class whose object wraps or contains a primitive data types.
When we create an object to a wrapper class, it contains a field and in this field, we
can store a primitive data types. In other words, we can wrap a primitive value into a
wrapper class object.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and
objects into primitives automatically. The automatic conversion of primitive into an
object is known as autoboxing and vice-versa unboxing.
Autoboxing:
The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char to Character,
int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and
short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
16
Unboxing:
The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of autoboxing. Since
Java 5, we do not need to use the intValue() method of wrapper classes to convert
the wrapper type into primitives.
Example: Converting Integer to int
Integer a=new Integer(3);
16
Use of Wrapper classes:
Java is an object-oriented programming language, so we need to deal with objects
many times like in Collections, Serialization, Synchronization, etc. Let us see the
different scenarios, where we need to use the wrapper classes.
• Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the
primitive value in an object, it will change the original value.
• Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through the
wrapper classes.
• Synchronization: Java synchronization works with objects in Multithreading.
• java.util package: The java.util package provides the utility classes to deal with
objects.
• Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector etc.) deal with
objects only.
17
18
19
20