SlideShare a Scribd company logo
Page 1 of 19
Class Notes on Arrays and Strings (Week - 4)
Contents:-1 D Array,Creating an Array, Initialization, Array Length, 2-D Array, Variable Size Arrays, Strings, String Arrays,
String Methods, StringBuffer Class, Manipulation of Strings, basic string handling concepts, -String (char(), compare(),
equals(), equalsIgnorecase(), indexOf(), length(), substring(), toCharArray(),toLowercCase(),tostring(), methods), concept
of mutable and immutable string.
Arrays
An array is a very common type of data structure where in all elements must be of the same data type. Once
defined , the size of an array is fixed and cannot increase to accommodate more elements. The first element
of an array starts with zero.
An array is a container object that holds a fixed number of values of a single type. The length of an array is
established when the array is created. After creation, its length is fixed.
Characteristics of an Array:-
 An array is a group of contiguous or related data items that share a common name.
 Used when programs have to handle large amount of data.
 Each value is stored at a specific position.
 Position is called a index or superscript. Base index = 0.
 The ability to use a single name to represent a collection of items and refer to an item by specifying the
item number enables us to develop concise and efficient programs. For example, a loop with index as
the control variable can be used to read the entire array, perform calculations, and print out the
results.
An array of ten elements
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in
the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed
at index 8.
Using and array in your program is a 3 step process -
1) Declaring your Array
2) Constructing your Array
3) Initializing your Array
Page 2 of 19
Syntax for Declaring Array Variables is
Form 1:
Type arrayname[];
Form 2:
Type[] arrayname;
Examples:
int[] students;
int students[];
Note: we don’t specify the size of arrays in the declaration.
Constructing an Array
After declaring arrays, we need to allocate memory for storage array items.In Java, this is carried out by using
“new” operator, as follows:
Arrayname = new type[size];
Examples:
students = new int[7];
Initialisation of Arrays
Once arrays are created, they need to be initialised with some values before access their content. A general
form of initialisation is:
Arrayname [index/subscript] = value;
Example:
students[0] = 50;
students[1] = 40;
Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified.Unlike
C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will
generate an error message.
Arrays – Length
Arrays are fixed length. Length is specified at create time. In java, all arrays store the allocated size in a
variable named “length”. We can access the length of arrays as arrayName.length:
e.g. int x = students.length; // x = 7
The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to
standard output.
Page 3 of 19
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// etc.
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
System.out.println("Element at index 0: "
+ anArray[0]);
System.out.println("Element at index 1: "
+ anArray[1]);
System.out.println("Element at index 2: "
+ anArray[2]);
System.out.println("Element at index 3: "
+ anArray[3]);
System.out.println("Element at index 4: "
+ anArray[4]);
System.out.println("Element at index 5: "
+ anArray[5]);
System.out.println("Element at index 6: "
+ anArray[6]);
System.out.println("Element at index 7: "
+ anArray[7]);
System.out.println("Element at index 8: "
+ anArray[8]);
System.out.println("Element at index 9: "
+ anArray[9]);
}
}
The output from this program is:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Page 4 of 19
In a real-world programming situation, you'd probably use one of the supported looping constructs to iterate
through each element of the array, rather than write each line individually as shown above. However, this
example clearly illustrates the array syntax.
Arrays – Another Example
// StudentArray.java: store integers in arrays and access
class StudentArray{
public static void main(String[] args) {
int[] students;
students = new int[7];
System.out.println("Array Length = " + students.length);
for ( int i=0; i < students.length; i++)
students[i] = 2*i;
System.out.println("Values Stored in Array:");
for ( int i=0; i < students.length; i++)
System.out.println(students[i]);
}
}
Arrays – Initializing at Declaration
Arrays can also be initialised like standard variables at the time of their declaration.
Type arrayname[] = {list of values};
Example:
int[] students = {55, 69, 70, 30, 80};
 Creates and initializes the array of integers of length 5.
 In this case it is not necessary to use the new operator.
Example of Arrays using initialization at declaration
// StudentArray.java: store integers in arrays and access
class StudentArray{
public static void main(String[] args) {
int[] students = {55, 69, 70, 30, 80};
System.out.println("Array Length = " + students.length);
System.out.println("Values Stored in Array:");
for ( int i=0; i < students.length; i++)
System.out.println(students[i]);
}
}
Page 5 of 19
Two-Dimensional Arrays
An array keeps track of multiple pieces of information in linear order, a one-dimensional list. However, the
data associated with certain systems (a digital image, a board game, etc.) lives in two dimensions. To visualize
this data, we need a multi-dimensional data structure, that is, a multi-dimensional array.
A two-dimensional array is really nothing more than an array of arrays (a three-dimensional array is an array of
arrays of arrays). Think of your dinner. You could have a one-dimensional list of everything you eat:
(lettuce, tomatoes, salad dressing, steak, mashed potatoes, string beans, cake, ice cream, coffee)
Or you could have a two-dimensional list of three courses, each containing three things you eat:
(lettuce, tomatoes, salad dressing) and (steak, mashed potatoes, string beans) and (cake, ice cream, coffee)
In the case of an array, our old-fashioned one-dimensional array looks like this:
int[] myArray = {0,1,2,3};
And a two-dimensional array looks like this:
int[][] myArray = { {0,1,2,3}, {3,2,1,0}, {3,5,6,1}, {3,8,3,4} };
For our purposes, it is better to think of the two-dimensional array as a matrix. A matrix can be thought of as a
grid of numbers, arranged in rows and columns, kind of like a bingo board. We might write the two-
dimensional array out as follows to illustrate this point:
int[][] myArray = { {0, 1, 2, 3},
{3, 2, 1, 0},
{3, 5, 6, 1},
{3, 8, 3, 4} };
We can use this type of data structure to encode information about an image. For example, the following
grayscale image could be represented by the following array:
int[][] myArray = { {236, 189, 189, 0},
{236, 80, 189, 189},
{236, 0, 189, 80},
{236, 189, 189, 80} };
Page 6 of 19
2D arrays manipulations
Declaration:
int myArray [][];
Creation:
myArray = new int[4][3]; // OR
int myArray [][] = new int[4][3];
Initialisation:
Single Value:
myArray[0][0] = 10;
Multiple values:
int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}};
int tableA[][] = {{10, 15, 30}, {14, 30, 33}};
Variable Size Arrays
Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows:
Arrays of Objects
Arrays can be used to store objects
Circle[] circleArray;
circleArray = new Circle[25];
The above statement creates an array that can store references to 25 Circle objects. Circle objects are not
created.
Create the Circle objects and stores them in the array.
//declare an array for Circle
Circle circleArray[] = new Circle[25];
int r = 0;
// create circle objects and store in array
for (r=0; r <25; r++)
circleArray[r] = new Circle(r);
Page 7 of 19
Strings in Java
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming
language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this
case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a constructor. The String
class has eleven constructors that allow you to provide the initial value of the string using different sources,
such as an array of characters:
public class StringDemo{
public static void main(String args[]){
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This would produce following result:
Hello.
Following are some useful classes that Java provides for String operations.
 String Class
 StringBuffer Class
 StringTokenizer Class
Although character arrays have the advantage of being able to query their length, they themselves are too
primitive and don’t support a range of common string operations. For example, copying a string, searching for
specific pattern etc.
Recognising the importance and common usage of String manipulation in large software projects, Java
supports String as one of the fundamental data type at the language level. Strings related book keeping
operations (e.g., end of string) are handled automatically.
Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a
necessity to make a lot of modifications to Strings of characters then you should use String Buffer Classes.
Page 8 of 19
String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor method
that you can use with strings is the length() method, which returns the number of characters contained in the
string object.
After the following two lines of code have been executed, len equals 17:
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This would produce following result:
String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat()
method with string literals, as in:
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in:
"Hello," + " world" + "!"
which results in:
"Hello, world!"
Let us look at the following example:
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
Page 9 of 19
This would produce following result:
Dot saw I was Tod
Creating Format Strings:
You have printf() and format() methods to print output with formatted numbers. The String class has an
equivalent class method, format(), that returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to
a one-time print statement. For example, instead of:
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
you can write:
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
String Array In Java
In this section, you will learn how to use string array in Java. Here, you will see how to declare a string array
and the syntax for using in the program. This section provides you a simple java program which illustrates
about the string array in very efficient manner.
Program Description:
Following code of the program declares a string array and store some strings like "chandan", "tapan", "Amar",
"santosh", and "deepak" to it. And in the main method these string are displayed one by one by retrieving
from the specified string array named names. In this program all the string values are stored in the names
string array at the declaration time.
Here is the code of this program:
class StringCharacter
{
static String[] names={"chanan","tapan","Amar","santosh","deepak"};
public static void main(String args[]){
for(int i=0;i<5;i++){
System.out.println(names[i]);
}
}
}
Page 10 of 19
Output of program:
C:>javac StringCharacter.java
C:>java StringCharacter
chanan
tapan
Amar
santosh
deepak
C:>
You can also initialize Strings Arrays by using new operator as shown below
String city[] = new String[5];
city[0] = new String(“Melbourne”);
city[1] = new String(“Sydney”);
String class – Constructors
The String class supports several constructors. To create an empty String, you call the default constructor. For
example,
String s = new String();
will create an instance of String with no characters in it. Frequently, you will want to create strings that have
initial values. The String class provides a variety of constructors to handle this. To create a String initialized by
an array of characters, use the constructor shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string "abc".
You can specify a subrange of a character array as an initializer using the following constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of
characters to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
Page 11 of 19
This initializes s with the characters cde.
You can construct a String object that contains the same character sequence as another String object using
this constructor:
String(String strObj)
Here, strObj is a String object. Consider this example:
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
As you can see, s1 and s2 contain the same string.
Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings
on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings
are common, the String class provides constructors that initialize a string when given a byte array. Their forms
are shown here:
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Here, asciiChars specifies the array of bytes. The second form allows you to specify a subrange. In each of
these constructors, the byte-to-character conversion is done by using the default character encoding of the
platform. The following program illustrates these constructors:
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
Page 12 of 19
This program generates the following output:
ABCDEF
CDE
Extended versions of the byte-to-string constructors are also defined in which you can specify the character
encoding that determines how bytes are converted to characters. However, most of the time, you will want to
use the default encoding provided by the platform.
Note: The contents of the array are copied whenever you create a String object from an array. If you modify
the contents of the array after you have created the string, theString will be unchanged.
String Methods:
Here is the list methods supported by String class (go to link for details):
SN Methods with Description
1 char charAt(int index)
Returns the character at the specified index.
2 int compareTo(Object o)
Compares this String to another Object.
3 int compareTo(String anotherString)
Compares two strings lexicographically.
4 int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
5 String concat(String str)
Concatenates the specified string to the end of this string.
6 boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
7 boolean equals(Object anObject)
Compares this string to the specified object.
8 boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
9 byte getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte
array.
10 byte[] getBytes(String charsetName
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
11 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
12 int hashCode()
Returns a hash code for this string.
13 int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
14 int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the
specified index.
15 int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
16 int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
Page 13 of 19
17 String intern()
Returns a canonical representation for the string object.
18 int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
19 int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at
the specified index.
20 int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
21 int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at
the specified index.
22 int length()
Returns the length of this string.
23 boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
24 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
25 boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
26 String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
27 String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
28 String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
29 String[] split(String regex)
Splits this string around matches of the given regular expression.
30 String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
31 boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
32 boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
33 CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
34 String substring(int beginIndex)
Returns a new string that is a substring of this string.
35 String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
36 char[] toCharArray()
Converts this string to a new character array.
37 String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
38 String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
39 String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
40 String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
41 String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
Page 14 of 19
toString() Method
toString() method is a special method that can be defined in any class. This method should return a String
argument. When an object is used in a String concatenation operation or when specified in print statement,
this method gets invoked automatically.
toString() Method –Example
class Circle {
double x,y,r;
public Circle(double centreX, double centreY, double radius ) {
x = centreX ; y = centreY; r = radius;
}
public String toString()
{
String s = “I am a Circle with centre [“ + x + “,” + y + “] and
radius [“+ r + “]”;
return s;
}
}
class CircleTest {
Circle c = new Circle(10,20, 30);
System.out.println( c );
// I am a circle with centre [10.0,20.0] and radius [30.0]
}
StringBufferClass
Unlike the String class, StringBuffer class is mutable (changeable).Use StringBufferClass class in operations
where the string has to be modified.
Page 15 of 19
StringBuffer class – Constructors
public StringBuffer() Constructs a StringBuffer with an empty string.
public StringBuffer(String str) Constructs a StringBuffer with initial value of str.
StringBuffer class – Some operations
public int length() Returns the length of the buffer
public void setCharAt(int index, char ch) Replaces the character at the specified position
s1.setLength(int n)
Truncates or extends the buffer.
If(n<s1.length(), s1 is truncated; else zeros are added to s1.
public StringBuffer append(String str) Appends the string to this string buffer.
public StringBuffer append(int i)
Append of other data items (float, char, etc.)
is supported.
Appends the string representation of the int argument to this
string buffer.
Java StringBuffer Examples
StringBuffer is a mutable sequence of characters. It is like a String but the contents of the StringBuffer can be
modified after creation.
StringBuffer Capacity
Every StringBuffer object has a capacity associated with it. The capacity of the StringBuffer is the number of
characters it can hold. It increases automatically as more contents added to it.
StringBuffer’s current capacity can be obtained using following method.
int capacity()
This method returns the current capacity of the StringBuffer object.
For example,
StringBuffer stringBuffer = new StringBuffer(“Hello World”);
System.out.println(stringBuffer.capacity());
Page 16 of 19
This will print 27 (11 + 16) on console when executed.
The actual number of characters in StringBuffer can be obtained by following method.
int length()
Returns the actual number of characters contained in the StringBuffer object.
For example,
StringBuffer stringBuffer = new StringBuffer(“Hello World”);
System.out.println(stringBuffer.length());
System.out.println(stringBuffer.capacity());
This will print,
11
27
on console when run.
Specifying initial capacity of StringBuffer
Initial capacity of the StringBuffer object can be specified using following method.
void ensureCapacity(int initialCapacity)
Ensures that the StringBuffer’s initial capacity would be grater than or equal to the specified initial capacity.
The new capacity of the StringBuffer is the maximum of,
1) The initialCapacity argument passed and
2) ( Old capacity * 2 ) + 2
StringBuffer Constructors
StringBuffer object can be created using following StringBuffer constructors.
1) StringBuffer()
Creates empty StringBuffer object having initial capacity of 16.
For example,
StringBuffer stringBuffer = new StringBuffer();
Here, capacity of stringBuffer object would be 16.
Page 17 of 19
2) StringBuffer(int capacity)
Creates empty StringBuffer object having initial capacity specified.
For example,
StringBuffer stringBuffer = new StringBuffer(50);
Here, capacity of stringBuffer object would be 50.
This constructor may throw NegativeArraySizeException if the passed argument is less than 0.
3) StringBuffer(String content)
Creates new StringBuffer object having contents same as the argument string object. The initial capacity of the
newly created StringBuffer object will be the length of the argument string object + 16.
For example,
String str = “Hello”;
StringBuffer stringBuffer = new StringBuffer(str);
Here, capacity of stringBuffer object would be 5 + 16 = 21.
String concatenation and StringBuffer
In Java, String concatenation operator (+) is internally implemented using StringBuffer.
For Example,
String str = “Hello” + “World”;
Would be executed as,
String str = new
StringBuffer().append(“Hello”).append(“World”).toString();
First an empty StringBuffer will be created and then operands of the + operator would be appended using
append method of the StringBuffer. Finally toString() method of the StringBuffer would be called to convert it
to string object and the same will be returned.
String concatenation using this approach is very expensive in nature, because it involves creation of temporary
StringBuffer object. Then that temporary object’s append method gets called and the resulting StringBuffer
would be converted back to String using toString() method.
When to use String and when StringBuffer?
If there is a need to change the contents frequently, StringBuffer should be used instead of String because
StringBuffer concatenation is significantly faster than String concatenation.
Page 18 of 19
Inserting a String in Middle of Existing StringBuffer
StringBuffer str = new StringBuffer(“Object Language”);
String aString = new String(str.toString());
Int pos = aString.indexOf(“ Language”);
str.insert(pos, “ Oriented “);
What will output of at this point?
System.out.println(“Modified String:”+str);
What will be string after executing (modifying character)?
str.setChar(6,’-’);
For more example on StringBuffer visit:
http://www.java-examples.com/java-stringbuffer-examples
StringTokenizer
 Breaks string into parts, using delimiters.
 The sequence of broken parts are the tokens of the string.
 More than one delimiter can be specified.
 The tokens can be extracted with or without the delimiters.
StringTokenizer – Functionality
 Consider the following String
CREATE_USER:1234567;John;Smith
 Separate the tokens(Here Delimiters are: “:;”)
CREATE_USER
1234567
John
Smith
StringTokenizer – Constructors
public StringTokenizer(String str, String delim,
boolean returnTokens)
Creates a SringTokenizer with the specified delimiter. If
returnTokens is true the delimiters are also returned.
public StringTokenizer(String str, String delim) Delimiters are not returned
public StringTokenizer(String str) Delimiters are (“ tnrf”)
public boolen hasMoreTokens() Returns true if more tokens are found.
Page 19 of 19
public String nextToken() Returns the next token of the String.
public String nextToken(String delim) Switches the delimiter set to characters in delim and returns
the next token.
public int countTokens() Returns the count of remaining tokens.
StringTokenizer – example
import java.util.StringTokenizer;
class TokenizerExample {
public static void main(string[] args)
{
String str = “CREATE_USER:123456;John;Smith”;
StringTokenizer tokens = new StringTokenizer(str, “:;”);
while ( tokens.hasMoreTokens() )
System.out.println(tokens.nextToken());
}
}
 Output of the program
CREATE_USER
123456
John
Smith

More Related Content

What's hot

An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Array in Java
Array in JavaArray in Java
Array in Java
Shehrevar Davierwala
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentationNeveen Reda
 
L10 array
L10 arrayL10 array
L10 array
teach4uin
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
Gopal Ji Singh
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
Arzath Areeff
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Mesics lecture 8 arrays in 'c'
Mesics lecture 8   arrays in 'c'Mesics lecture 8   arrays in 'c'
Mesics lecture 8 arrays in 'c'
eShikshak
 
Two-dimensional array in java
Two-dimensional array in javaTwo-dimensional array in java
Two-dimensional array in java
Talha mahmood
 
array
array array
Array in c#
Array in c#Array in c#
Array in c#
Prem Kumar Badri
 
Arrays basics
Arrays basicsArrays basics
Arrays basics
sudhirvegad
 
Array in c++
Array in c++Array in c++
Array in c++
Mahesha Mano
 
Array in Java
Array in JavaArray in Java
Array in Java
Ali shah
 
Data structure array
Data structure  arrayData structure  array
Data structure array
MajidHamidAli
 

What's hot (20)

An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentation
 
L10 array
L10 arrayL10 array
L10 array
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Mesics lecture 8 arrays in 'c'
Mesics lecture 8   arrays in 'c'Mesics lecture 8   arrays in 'c'
Mesics lecture 8 arrays in 'c'
 
Two-dimensional array in java
Two-dimensional array in javaTwo-dimensional array in java
Two-dimensional array in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
array
array array
array
 
Arrays
ArraysArrays
Arrays
 
07slide
07slide07slide
07slide
 
Java arrays
Java arraysJava arrays
Java arrays
 
javaarray
javaarrayjavaarray
javaarray
 
Array in c#
Array in c#Array in c#
Array in c#
 
Arrays basics
Arrays basicsArrays basics
Arrays basics
 
Array in c++
Array in c++Array in c++
Array in c++
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 

Similar to Class notes(week 4) on arrays and strings

Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
suchitrapoojari984
 
Array in C
Array in CArray in C
Array in C
adityas29
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
JayanthiM19
 
Arrays
ArraysArrays
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
bhavesh prakash
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Lecture 6
Lecture 6Lecture 6
Arrays In C
Arrays In CArrays In C
Arrays In C
yndaravind
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
ajajkhan16
 
Python array
Python arrayPython array
Python array
Arnab Chakraborty
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
Pamarthi Kumar
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
KristinaBorooah
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
Rakesh Roshan
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
Umar Farooq
 

Similar to Class notes(week 4) on arrays and strings (20)

Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
Array in C
Array in CArray in C
Array in C
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 
Arrays
ArraysArrays
Arrays
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Arrays
ArraysArrays
Arrays
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
Arrays In C
Arrays In CArrays In C
Arrays In C
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Python array
Python arrayPython array
Python array
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
2 arrays
2   arrays2   arrays
2 arrays
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 

More from Kuntal Bhowmick

Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsMultiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Kuntal Bhowmick
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Kuntal Bhowmick
 
1. introduction to E-commerce
1. introduction to E-commerce1. introduction to E-commerce
1. introduction to E-commerce
Kuntal Bhowmick
 
Computer graphics question for exam solved
Computer graphics question for exam solvedComputer graphics question for exam solved
Computer graphics question for exam solved
Kuntal Bhowmick
 
DBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsDBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental concepts
Kuntal Bhowmick
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
Kuntal Bhowmick
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
Kuntal Bhowmick
 
Operating system Interview Questions
Operating system Interview QuestionsOperating system Interview Questions
Operating system Interview Questions
Kuntal Bhowmick
 
Computer Network Interview Questions
Computer Network Interview QuestionsComputer Network Interview Questions
Computer Network Interview Questions
Kuntal Bhowmick
 
C interview questions
C interview  questionsC interview  questions
C interview questions
Kuntal Bhowmick
 
C question
C questionC question
C question
Kuntal Bhowmick
 
Distributed operating systems cs704 a class test
Distributed operating systems cs704 a class testDistributed operating systems cs704 a class test
Distributed operating systems cs704 a class test
Kuntal Bhowmick
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
Kuntal Bhowmick
 

More from Kuntal Bhowmick (20)

Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsMultiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
 
1. introduction to E-commerce
1. introduction to E-commerce1. introduction to E-commerce
1. introduction to E-commerce
 
Computer graphics question for exam solved
Computer graphics question for exam solvedComputer graphics question for exam solved
Computer graphics question for exam solved
 
DBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsDBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental concepts
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
Operating system Interview Questions
Operating system Interview QuestionsOperating system Interview Questions
Operating system Interview Questions
 
Computer Network Interview Questions
Computer Network Interview QuestionsComputer Network Interview Questions
Computer Network Interview Questions
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
C question
C questionC question
C question
 
Distributed operating systems cs704 a class test
Distributed operating systems cs704 a class testDistributed operating systems cs704 a class test
Distributed operating systems cs704 a class test
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 

Recently uploaded

MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 

Recently uploaded (20)

MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 

Class notes(week 4) on arrays and strings

  • 1. Page 1 of 19 Class Notes on Arrays and Strings (Week - 4) Contents:-1 D Array,Creating an Array, Initialization, Array Length, 2-D Array, Variable Size Arrays, Strings, String Arrays, String Methods, StringBuffer Class, Manipulation of Strings, basic string handling concepts, -String (char(), compare(), equals(), equalsIgnorecase(), indexOf(), length(), substring(), toCharArray(),toLowercCase(),tostring(), methods), concept of mutable and immutable string. Arrays An array is a very common type of data structure where in all elements must be of the same data type. Once defined , the size of an array is fixed and cannot increase to accommodate more elements. The first element of an array starts with zero. An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Characteristics of an Array:-  An array is a group of contiguous or related data items that share a common name.  Used when programs have to handle large amount of data.  Each value is stored at a specific position.  Position is called a index or superscript. Base index = 0.  The ability to use a single name to represent a collection of items and refer to an item by specifying the item number enables us to develop concise and efficient programs. For example, a loop with index as the control variable can be used to read the entire array, perform calculations, and print out the results. An array of ten elements Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. Using and array in your program is a 3 step process - 1) Declaring your Array 2) Constructing your Array 3) Initializing your Array
  • 2. Page 2 of 19 Syntax for Declaring Array Variables is Form 1: Type arrayname[]; Form 2: Type[] arrayname; Examples: int[] students; int students[]; Note: we don’t specify the size of arrays in the declaration. Constructing an Array After declaring arrays, we need to allocate memory for storage array items.In Java, this is carried out by using “new” operator, as follows: Arrayname = new type[size]; Examples: students = new int[7]; Initialisation of Arrays Once arrays are created, they need to be initialised with some values before access their content. A general form of initialisation is: Arrayname [index/subscript] = value; Example: students[0] = 50; students[1] = 40; Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified.Unlike C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will generate an error message. Arrays – Length Arrays are fixed length. Length is specified at create time. In java, all arrays store the allocated size in a variable named “length”. We can access the length of arrays as arrayName.length: e.g. int x = students.length; // x = 7 The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output.
  • 3. Page 3 of 19 class ArrayDemo { public static void main(String[] args) { // declares an array of integers int[] anArray; // allocates memory for 10 integers anArray = new int[10]; // initialize first element anArray[0] = 100; // initialize second element anArray[1] = 200; // etc. anArray[2] = 300; anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000; System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]); System.out.println("Element at index 6: " + anArray[6]); System.out.println("Element at index 7: " + anArray[7]); System.out.println("Element at index 8: " + anArray[8]); System.out.println("Element at index 9: " + anArray[9]); } } The output from this program is: Element at index 0: 100 Element at index 1: 200 Element at index 2: 300 Element at index 3: 400 Element at index 4: 500 Element at index 5: 600 Element at index 6: 700 Element at index 7: 800 Element at index 8: 900 Element at index 9: 1000
  • 4. Page 4 of 19 In a real-world programming situation, you'd probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as shown above. However, this example clearly illustrates the array syntax. Arrays – Another Example // StudentArray.java: store integers in arrays and access class StudentArray{ public static void main(String[] args) { int[] students; students = new int[7]; System.out.println("Array Length = " + students.length); for ( int i=0; i < students.length; i++) students[i] = 2*i; System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); } } Arrays – Initializing at Declaration Arrays can also be initialised like standard variables at the time of their declaration. Type arrayname[] = {list of values}; Example: int[] students = {55, 69, 70, 30, 80};  Creates and initializes the array of integers of length 5.  In this case it is not necessary to use the new operator. Example of Arrays using initialization at declaration // StudentArray.java: store integers in arrays and access class StudentArray{ public static void main(String[] args) { int[] students = {55, 69, 70, 30, 80}; System.out.println("Array Length = " + students.length); System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); } }
  • 5. Page 5 of 19 Two-Dimensional Arrays An array keeps track of multiple pieces of information in linear order, a one-dimensional list. However, the data associated with certain systems (a digital image, a board game, etc.) lives in two dimensions. To visualize this data, we need a multi-dimensional data structure, that is, a multi-dimensional array. A two-dimensional array is really nothing more than an array of arrays (a three-dimensional array is an array of arrays of arrays). Think of your dinner. You could have a one-dimensional list of everything you eat: (lettuce, tomatoes, salad dressing, steak, mashed potatoes, string beans, cake, ice cream, coffee) Or you could have a two-dimensional list of three courses, each containing three things you eat: (lettuce, tomatoes, salad dressing) and (steak, mashed potatoes, string beans) and (cake, ice cream, coffee) In the case of an array, our old-fashioned one-dimensional array looks like this: int[] myArray = {0,1,2,3}; And a two-dimensional array looks like this: int[][] myArray = { {0,1,2,3}, {3,2,1,0}, {3,5,6,1}, {3,8,3,4} }; For our purposes, it is better to think of the two-dimensional array as a matrix. A matrix can be thought of as a grid of numbers, arranged in rows and columns, kind of like a bingo board. We might write the two- dimensional array out as follows to illustrate this point: int[][] myArray = { {0, 1, 2, 3}, {3, 2, 1, 0}, {3, 5, 6, 1}, {3, 8, 3, 4} }; We can use this type of data structure to encode information about an image. For example, the following grayscale image could be represented by the following array: int[][] myArray = { {236, 189, 189, 0}, {236, 80, 189, 189}, {236, 0, 189, 80}, {236, 189, 189, 80} };
  • 6. Page 6 of 19 2D arrays manipulations Declaration: int myArray [][]; Creation: myArray = new int[4][3]; // OR int myArray [][] = new int[4][3]; Initialisation: Single Value: myArray[0][0] = 10; Multiple values: int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}}; int tableA[][] = {{10, 15, 30}, {14, 30, 33}}; Variable Size Arrays Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows: Arrays of Objects Arrays can be used to store objects Circle[] circleArray; circleArray = new Circle[25]; The above statement creates an array that can store references to 25 Circle objects. Circle objects are not created. Create the Circle objects and stores them in the array. //declare an array for Circle Circle circleArray[] = new Circle[25]; int r = 0; // create circle objects and store in array for (r=0; r <25; r++) circleArray[r] = new Circle(r);
  • 7. Page 7 of 19 Strings in Java Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings. Creating Strings: The most direct way to create a string is to write: String greeting = "Hello world!"; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters: public class StringDemo{ public static void main(String args[]){ char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); System.out.println( helloString ); } } This would produce following result: Hello. Following are some useful classes that Java provides for String operations.  String Class  StringBuffer Class  StringTokenizer Class Although character arrays have the advantage of being able to query their length, they themselves are too primitive and don’t support a range of common string operations. For example, copying a string, searching for specific pattern etc. Recognising the importance and common usage of String manipulation in large software projects, Java supports String as one of the fundamental data type at the language level. Strings related book keeping operations (e.g., end of string) are handled automatically. Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters then you should use String Buffer Classes.
  • 8. Page 8 of 19 String Length: Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17: public class StringDemo { public static void main(String args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); } } This would produce following result: String Length is : 17 Concatenating Strings: The String class includes a method for concatenating two strings: string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in: "My name is ".concat("Zara"); Strings are more commonly concatenated with the + operator, as in: "Hello," + " world" + "!" which results in: "Hello, world!" Let us look at the following example: public class StringDemo { public static void main(String args[]) { String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); } }
  • 9. Page 9 of 19 This would produce following result: Dot saw I was Tod Creating Format Strings: You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of: System.out.printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatVar, intVar, stringVar); you can write: String fs; fs = String.format("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatVar, intVar, stringVar); System.out.println(fs); String Array In Java In this section, you will learn how to use string array in Java. Here, you will see how to declare a string array and the syntax for using in the program. This section provides you a simple java program which illustrates about the string array in very efficient manner. Program Description: Following code of the program declares a string array and store some strings like "chandan", "tapan", "Amar", "santosh", and "deepak" to it. And in the main method these string are displayed one by one by retrieving from the specified string array named names. In this program all the string values are stored in the names string array at the declaration time. Here is the code of this program: class StringCharacter { static String[] names={"chanan","tapan","Amar","santosh","deepak"}; public static void main(String args[]){ for(int i=0;i<5;i++){ System.out.println(names[i]); } } }
  • 10. Page 10 of 19 Output of program: C:>javac StringCharacter.java C:>java StringCharacter chanan tapan Amar santosh deepak C:> You can also initialize Strings Arrays by using new operator as shown below String city[] = new String[5]; city[0] = new String(“Melbourne”); city[1] = new String(“Sydney”); String class – Constructors The String class supports several constructors. To create an empty String, you call the default constructor. For example, String s = new String(); will create an instance of String with no characters in it. Frequently, you will want to create strings that have initial values. The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here: String(char chars[ ]) Here is an example: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); This constructor initializes s with the string "abc". You can specify a subrange of a character array as an initializer using the following constructor: String(char chars[ ], int startIndex, int numChars) Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use. Here is an example: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3);
  • 11. Page 11 of 19 This initializes s with the characters cde. You can construct a String object that contains the same character sequence as another String object using this constructor: String(String strObj) Here, strObj is a String object. Consider this example: // Construct one String from another. class MakeString { public static void main(String args[]) { char c[] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); } } The output from this program is as follows: Java Java As you can see, s1 and s2 contain the same string. Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. Their forms are shown here: String(byte asciiChars[ ]) String(byte asciiChars[ ], int startIndex, int numChars) Here, asciiChars specifies the array of bytes. The second form allows you to specify a subrange. In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform. The following program illustrates these constructors: // Construct string from subset of char array. class SubStringCons { public static void main(String args[]) { byte ascii[] = {65, 66, 67, 68, 69, 70 }; String s1 = new String(ascii); System.out.println(s1); String s2 = new String(ascii, 2, 3); System.out.println(s2); } }
  • 12. Page 12 of 19 This program generates the following output: ABCDEF CDE Extended versions of the byte-to-string constructors are also defined in which you can specify the character encoding that determines how bytes are converted to characters. However, most of the time, you will want to use the default encoding provided by the platform. Note: The contents of the array are copied whenever you create a String object from an array. If you modify the contents of the array after you have created the string, theString will be unchanged. String Methods: Here is the list methods supported by String class (go to link for details): SN Methods with Description 1 char charAt(int index) Returns the character at the specified index. 2 int compareTo(Object o) Compares this String to another Object. 3 int compareTo(String anotherString) Compares two strings lexicographically. 4 int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences. 5 String concat(String str) Concatenates the specified string to the end of this string. 6 boolean endsWith(String suffix) Tests if this string ends with the specified suffix. 7 boolean equals(Object anObject) Compares this string to the specified object. 8 boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations. 9 byte getBytes() Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. 10 byte[] getBytes(String charsetName Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. 11 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string into the destination character array. 12 int hashCode() Returns a hash code for this string. 13 int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. 14 int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. 15 int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. 16 int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
  • 13. Page 13 of 19 17 String intern() Returns a canonical representation for the string object. 18 int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character. 19 int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. 20 int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring. 21 int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. 22 int length() Returns the length of this string. 23 boolean matches(String regex) Tells whether or not this string matches the given regular expression. 24 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Tests if two string regions are equal. 25 boolean regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal. 26 String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. 27 String replaceAll(String regex, String replacement Replaces each substring of this string that matches the given regular expression with the given replacement. 28 String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement. 29 String[] split(String regex) Splits this string around matches of the given regular expression. 30 String[] split(String regex, int limit) Splits this string around matches of the given regular expression. 31 boolean startsWith(String prefix) Tests if this string starts with the specified prefix. 32 boolean startsWith(String prefix, int toffset) Tests if this string starts with the specified prefix beginning a specified index. 33 CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence that is a subsequence of this sequence. 34 String substring(int beginIndex) Returns a new string that is a substring of this string. 35 String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. 36 char[] toCharArray() Converts this string to a new character array. 37 String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale. 38 String toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale. 39 String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale. 40 String toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale. 41 String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
  • 14. Page 14 of 19 toString() Method toString() method is a special method that can be defined in any class. This method should return a String argument. When an object is used in a String concatenation operation or when specified in print statement, this method gets invoked automatically. toString() Method –Example class Circle { double x,y,r; public Circle(double centreX, double centreY, double radius ) { x = centreX ; y = centreY; r = radius; } public String toString() { String s = “I am a Circle with centre [“ + x + “,” + y + “] and radius [“+ r + “]”; return s; } } class CircleTest { Circle c = new Circle(10,20, 30); System.out.println( c ); // I am a circle with centre [10.0,20.0] and radius [30.0] } StringBufferClass Unlike the String class, StringBuffer class is mutable (changeable).Use StringBufferClass class in operations where the string has to be modified.
  • 15. Page 15 of 19 StringBuffer class – Constructors public StringBuffer() Constructs a StringBuffer with an empty string. public StringBuffer(String str) Constructs a StringBuffer with initial value of str. StringBuffer class – Some operations public int length() Returns the length of the buffer public void setCharAt(int index, char ch) Replaces the character at the specified position s1.setLength(int n) Truncates or extends the buffer. If(n<s1.length(), s1 is truncated; else zeros are added to s1. public StringBuffer append(String str) Appends the string to this string buffer. public StringBuffer append(int i) Append of other data items (float, char, etc.) is supported. Appends the string representation of the int argument to this string buffer. Java StringBuffer Examples StringBuffer is a mutable sequence of characters. It is like a String but the contents of the StringBuffer can be modified after creation. StringBuffer Capacity Every StringBuffer object has a capacity associated with it. The capacity of the StringBuffer is the number of characters it can hold. It increases automatically as more contents added to it. StringBuffer’s current capacity can be obtained using following method. int capacity() This method returns the current capacity of the StringBuffer object. For example, StringBuffer stringBuffer = new StringBuffer(“Hello World”); System.out.println(stringBuffer.capacity());
  • 16. Page 16 of 19 This will print 27 (11 + 16) on console when executed. The actual number of characters in StringBuffer can be obtained by following method. int length() Returns the actual number of characters contained in the StringBuffer object. For example, StringBuffer stringBuffer = new StringBuffer(“Hello World”); System.out.println(stringBuffer.length()); System.out.println(stringBuffer.capacity()); This will print, 11 27 on console when run. Specifying initial capacity of StringBuffer Initial capacity of the StringBuffer object can be specified using following method. void ensureCapacity(int initialCapacity) Ensures that the StringBuffer’s initial capacity would be grater than or equal to the specified initial capacity. The new capacity of the StringBuffer is the maximum of, 1) The initialCapacity argument passed and 2) ( Old capacity * 2 ) + 2 StringBuffer Constructors StringBuffer object can be created using following StringBuffer constructors. 1) StringBuffer() Creates empty StringBuffer object having initial capacity of 16. For example, StringBuffer stringBuffer = new StringBuffer(); Here, capacity of stringBuffer object would be 16.
  • 17. Page 17 of 19 2) StringBuffer(int capacity) Creates empty StringBuffer object having initial capacity specified. For example, StringBuffer stringBuffer = new StringBuffer(50); Here, capacity of stringBuffer object would be 50. This constructor may throw NegativeArraySizeException if the passed argument is less than 0. 3) StringBuffer(String content) Creates new StringBuffer object having contents same as the argument string object. The initial capacity of the newly created StringBuffer object will be the length of the argument string object + 16. For example, String str = “Hello”; StringBuffer stringBuffer = new StringBuffer(str); Here, capacity of stringBuffer object would be 5 + 16 = 21. String concatenation and StringBuffer In Java, String concatenation operator (+) is internally implemented using StringBuffer. For Example, String str = “Hello” + “World”; Would be executed as, String str = new StringBuffer().append(“Hello”).append(“World”).toString(); First an empty StringBuffer will be created and then operands of the + operator would be appended using append method of the StringBuffer. Finally toString() method of the StringBuffer would be called to convert it to string object and the same will be returned. String concatenation using this approach is very expensive in nature, because it involves creation of temporary StringBuffer object. Then that temporary object’s append method gets called and the resulting StringBuffer would be converted back to String using toString() method. When to use String and when StringBuffer? If there is a need to change the contents frequently, StringBuffer should be used instead of String because StringBuffer concatenation is significantly faster than String concatenation.
  • 18. Page 18 of 19 Inserting a String in Middle of Existing StringBuffer StringBuffer str = new StringBuffer(“Object Language”); String aString = new String(str.toString()); Int pos = aString.indexOf(“ Language”); str.insert(pos, “ Oriented “); What will output of at this point? System.out.println(“Modified String:”+str); What will be string after executing (modifying character)? str.setChar(6,’-’); For more example on StringBuffer visit: http://www.java-examples.com/java-stringbuffer-examples StringTokenizer  Breaks string into parts, using delimiters.  The sequence of broken parts are the tokens of the string.  More than one delimiter can be specified.  The tokens can be extracted with or without the delimiters. StringTokenizer – Functionality  Consider the following String CREATE_USER:1234567;John;Smith  Separate the tokens(Here Delimiters are: “:;”) CREATE_USER 1234567 John Smith StringTokenizer – Constructors public StringTokenizer(String str, String delim, boolean returnTokens) Creates a SringTokenizer with the specified delimiter. If returnTokens is true the delimiters are also returned. public StringTokenizer(String str, String delim) Delimiters are not returned public StringTokenizer(String str) Delimiters are (“ tnrf”) public boolen hasMoreTokens() Returns true if more tokens are found.
  • 19. Page 19 of 19 public String nextToken() Returns the next token of the String. public String nextToken(String delim) Switches the delimiter set to characters in delim and returns the next token. public int countTokens() Returns the count of remaining tokens. StringTokenizer – example import java.util.StringTokenizer; class TokenizerExample { public static void main(string[] args) { String str = “CREATE_USER:123456;John;Smith”; StringTokenizer tokens = new StringTokenizer(str, “:;”); while ( tokens.hasMoreTokens() ) System.out.println(tokens.nextToken()); } }  Output of the program CREATE_USER 123456 John Smith