0% found this document useful (0 votes)
8 views

Chapter 4

Ashok IT java Chapter-4

Uploaded by

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

Chapter 4

Ashok IT java Chapter-4

Uploaded by

Rahul Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Core Java Mr.

Ashok

Chapter – 4
• Arrays
• String
• StringBuffer
• StringBuffer
• Command Line Args

47
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

Arrays
-> Array is an object which contains elements of similar data type
-> Array is a container object that hold values of homogeneous type.
-> Array is also known as static data structure because size of an array must be specified at
the time of its declaration.
-> Array starts from zero index and goes to n-1 where n is length of the 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.
-> In Java, array is treated as an object and stores into heap memory. It allows to store
primitive values or reference values.

Types of Arrays in java


There are two types of arrays in java
1) Single Dimensional Array
2) Multidimensional Array
Single Dimensional Array in Java

48
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

-> Instantiation is a process of allocating memory to an array. At the time of instantiation,


we specify the size of array to reserve memory area.

-> In the above example, we created an array arr of int type and can store 5 elements. We
iterate the array to access its elements and it prints five times zero to the console. It prints
zero because we did not set values to array, so all the elements of the array initialized to 0
by default.

Set Array Elements


We can set array elements either at the time of initialization or by assigning direct to its
index.

-> Here, we are assigning values at the time of array creation. It is useful when we want to
store static data into the array.
-> We can set value based on index position also

49
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

Accessing array element


We can access array elements by its index value. Either by using loop or direct index value.
We can use loop like: for, for-each or while to traverse the array elements.

Length Of Array In Java


The length of an array indicates the number of elements present in the array. Unlike C/C++,
where we use ‘sizeof’ operator to get the length of the array, Java array has ‘length’
property. We will explore more on this property later.

50
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

Multi-Dimensional Array
A multi-dimensional array is very much similar to a single dimensional array. It can have
multiple rows and multiple columns unlike single dimensional array, which can have only
one row index.
It represents data into tabular form in which data is stored into row and columns.

Logical Programs On Arrays


1) Write a java program to print array elements
2) Write a java program to calculate sum of array
3) Write a java program to reverse array elements
4) Write a java program to print min and max elements in array
5) Write a java program to print second min and second max elements in array

51
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

Strings
-> String is an object that represents sequence of characters.
Ex: "hello”, "ashokit"
-> In Java, String is represented by String class which is available java.lang package
-> One important thing to notice about string object is that string objects are immutable
that means once a string object is created it cannot be changed.
How to create 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
Working with String literal
-> String literal in Java is created by using double quotes.
String str = "hello";
-> The string literal is always created in the string constant pool.

-> In Java, String constant pool is a special area that is used for storing string objects.
-> Whenever we create a string literal in Java, JVM checks string constant pool first. If the
string already exists in 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 placed it in the pool.

52
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

For example:
String s1 = "Hello";
String s2 = "Hello";

Creating String Object by using new Keyword


-> The second way of creating an object to string class is by using new operator.
-> It is just like creating an object of any class. It can be declared as follows:
String s = new String("Hello");
-> Whenever we will create an object of string class using the new operator, JVM will create
two objects. First, it will create an object in the heap area and store 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.

53
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

-> 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.
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 as given below:
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 string object ‘s’ contains string “java”. It means that all the characters of the array
are copied into string.
-> If you do not want all the characters of the array into string then you can also mention
which character you need, like this:
String s = new String(arr, 1,3);
-> From the above statement, 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 0th character in the array
is ‘j’ and the first character is ‘a’. Starting from ‘a’, total of three characters ‘aja’ will copy
into string s.

How many total objects will be created in memory for following string objects?
String s1 = new String("ashokit");
String s2 = new String("ashokit");
String s3 = "ashokit";
String s4 = "ashokit";

54
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

1. During the execution of first statement using new operator, JVM will create two objects,
one with content in heap area and another as a copy for literal “ashokit” 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 will be executed, for every new operation, JVM will create
again one new object with content “ashokit” in the heap area.
But in the SCP area, no new object for 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 “ashokit” in the SCP area because it is already available in string constant pool.
It simply points the reference variables s3 and s4 to the same object in the SCP. They are
shown in the above figure.
Thus, three objects are created, two in the heap area and one in string constant pool.

Why String Objects are given as immutable objects


An object can be referred by multiple reference variables in this case if string objects are
mutable objects, then we change the content of object automatically other references get
also modified so that string objects are given as immutable objects it means whenever any
operation is done on strings it will create new object.

String Manipulations
String class provided several methods to perform operations on Strings
#1) Length
The length is the number of characters that a given string contains. String class has a
length() method that gives the number of characters in a String.

55
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

#2) concatenation
Although Java uses a ‘+’ operator for concatenating two or more strings. A concat() is an
inbuilt method for String concatenation in Java.

#3) String to CharArray()


This method is used to convert all the characters of a string into a Character Array. This is
widely used in the String manipulation programs.

#4) String charAt()


This method is used to retrieve a single character from a given String.
The syntax is given as:
char charAt(int i);
The value of ‘i’ should not be negative and it should specify the location of a given String i.e.
if a String length is 5, then the value of ‘i’ should be less than 5.

56
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

#5) Java String compareTo()


This method is used to compare two Strings. The comparison is based on alphabetical order.
In general terms, a String is less than the other if it comes before the other in the dictionary.

#6) String contains()


This method is used to determine whether a substring is a part of the main String or not.
The return type is Boolean.
For E.g. In the below program, we will check whether “it” is a part of “ashokit” or not and
we will also check whether “blog” is a part of “ashokit”.

57
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

#7) Java String split()


As the name suggests, a split() method is used to split or separate the given String into
multiple substrings separated by the delimiters (“”, “ ”, \\, etc).
In the below example, we will split the String (Thexyzwebsitexyzisxyzashokitxyzhelp) using a
chunk of String(xyz) already present in the main String.

#8) Java String indexOf()


This method is used to perform a search operation for a specific character or a substring on
the main String. There is one more method known as lastIndexOf() which is also commonly
used.

58
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

indexOf() is used to search for the first occurrence of the character.


lastIndexOf() is used to search for the last occurrence of the character.

#9) Java String toString()


This method returns the String equivalent of the object that invokes it. This method does
not have any parameters. Given below is the program where we will try to get the String
representation of the object.

#10) String replace ()


The replace() method is used to replace the character with the new characters in a String.

59
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

#12) Substring Method ()


The Substring() method is used to return the substring of the main String by specifying the
starting index and the last index of the substring.
For Example, in the given String “ashokitjavaclasses”, we will try to fetch the substring by
specifying the starting index and the last index.

StringBuffer Class
-> StringBuffer class is used to create a mutable string object. It means, it can be changed
after it is created.
-> It is similar to String class in Java both are used to create string, but stringbuffer object
can be changed.
-> StringBuffer class is used when we have to make lot of modifications to our string.
-> It is also thread safe i.e multiple threads cannot access it simultaneously.
StringBuffer defines 4 constructors.
StringBuffer(): It creates an empty string buffer and reserves space for 16 characters.
StringBuffer(int size): It creates an empty string and takes an integer argument to set
capacity of the buffer.
StringBuffer(String str): It creates a stringbuffer object from the specified string.
StringBuffer(charSequence []ch): It creates a stringbuffer object from the charsequence
array.

60
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

Creating StringBuffer Object

Difference Between String & StringBuffer

Note: In the above program Output is such because String objects are immutable objects.
Hence, if we concatenate on the same String object, it won't be altered But StringBuffer
creates mutable objects. Hence, it can be altered.

StringBuffer class methods


#1) append()
This method will concatenate the string representation of any type of data to the end of the
StringBuffer object

61
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

#2) insert() :
This method inserts one string into another. Here are few forms of insert() method

#3) reverse()
This method reverses the characters within a StringBuffer object.

62
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

#4) replace()
This method replaces the string from specified start index to the end index.

#5) capacity()
This method returns the current capacity of StringBuffer object.

Java StringBuilder class


-> StringBuilder is identical to StringBuffer except for one important difference that it is not
synchronized, which means it is not thread safe.
-> StringBuilder also used for creating string object that is mutable and non synchronized.
-> The StringBuilder class provides no guarantee of synchronization.
-> StringBuffer and StringBuilder both are mutable but if synchronization is not required
then it is recommended to use StringBuilder class.
-> This class is located into java.lang package and signature of the class is as:
StringBuilder Constructors
StringBuilder (): creates an empty StringBuilder and reserves room for 16 characters.
StringBuilder (int size): create an empty string and takes an integer argument to set
capacity of the buffer.

63
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

StringBuilder (String str): create a StringBuilder object and initialize it with string str.
StringBuilder (CharSequence seq): It creates stringbuilder object by using CharSequence
object.

Working with StringBuilder class

-> When we want a mutable String without thread-safety then StringBuilder should be used
-> When we want a mutable String with thread-safety then StringBuffer should be used
-> When we want an Immutable object then String should be used.

Logical Programs on Strings


1) Write a java program to combine two strings
2) Write a java program to reverse a String
3) Write a java program to check given String is a palindrome or not
4) Write a java program remove all occurrences of a given character from String
5) Write a program to count number of words in a String
6) Write a java program to compare two strings
7) Write a java program to check first string present in second string
8) Write a java program to find first non-repeated character in given String

64
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok

Command Line Arguments


-> Command-line arguments in Java are used to pass arguments to the main program.
-> If you look at the Java main method syntax, it accepts String array as an argument.

-> When we pass command-line arguments, they are treated as strings and passed to the
main method in the string array argument.
-> The arguments have to be passed as space-separated values.
-> We can pass strings and primitive data types as command-line arguments.
-> The arguments will be converted to strings and passed into the main method string array
argument.
Java Program with Command Line Arguments

Passing Command Line Arguments to Above Program

65
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com

You might also like