0% found this document useful (0 votes)
9 views25 pages

Unit-III, P1

This document provides an overview of arrays and strings in Java, covering topics such as array declaration, initialization, processing, and methods for passing and returning arrays. It also explains the concept of arrays of objects, 2D arrays, and multidimensional arrays, including their syntax and examples. Key features of arrays, such as fixed size and index-based access, are highlighted throughout the document.

Uploaded by

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

Unit-III, P1

This document provides an overview of arrays and strings in Java, covering topics such as array declaration, initialization, processing, and methods for passing and returning arrays. It also explains the concept of arrays of objects, 2D arrays, and multidimensional arrays, including their syntax and examples. Key features of arrays, such as fixed size and index-based access, are highlighted throughout the document.

Uploaded by

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

JAVA(UGCA-1932)

UNIT-III, PART-I

Course Code: UGCA1932 (PTU)


Course Name: Programming in Java
Course: BCA, Semester: 5th
UNIT-III, PART-I
Arrays and Strings: Introduction to the array, Processing Array Contents, passing array as
argument, Returning array from methods, Array of objects, 2D arrays, Array with three or more
dimensions. String class, string concatenation, Comparing strings, Substring, Difference
between String and String Buffer class, String Tokenizer class.

Introduction to Array:
Array is a structures of data in Java, that allow us to store multiple values of the
same type in a single variable. They are useful for managing collections of same
types data i.e., int, float, string etc. We can store only a fixed set of elements in a
Java array.
In a single line array can be defined as, Array is a collection of similar types of
data in a single variable. Each value of an array is known as element of the array.
Each element of the array is identified by its index value. Index value is unique
value that is started from 0 (zero).
JAVA(UGCA-1932)
UNIT-III, PART-I

Key Features of Java Arrays:


 Fixed size: Once an array is created, its size cannot be changed.
 Homogeneous elements: All elements in the array must be of the same data type.
 Index-based access: Array elements are accessed via their index, starting from 0.

Declaring an Array:
To declare an array in JAVA, we write the data type of elements that array will stored, followed
by square brackets [ ], and then name of the array. Name of the Array can be written before or
after the square bracket i.e. int my_aaray[]; or int[] my_array;

Initializing an Array:
We can initialize an array either at the time of declaring it or later.
Example:
// Declaration without initialization
int[] numbers;

// Declaration and initialization in one line


int[] numbers = new int[5]; // Array of 5 integers

1. Using new keyword:


int[] numbers = new int[5];
// Creates an array of size 5 with default values (0)
2. Direct Initialization:
int[] numbers = {1, 2, 3, 4, 5};
// Array with values

Processing Array Contents:


An array is a collection of the same types of values and various processing can be applied using
array elements such as accessing array elements, modifying elements, finding the length of an
array, and looping/iterating an array using a loop statement.

Accessing and Modifying Array Elements:


Array elements can be accessed or modified using their index.
int[] numbers = {1, 2, 3, 4, 5};

// Access the first element


int firstElement = numbers[0]; // Output: 1

// Modify the second element


numbers[1] = 10; // Now the array is {1, 10, 3, 4, 5}
JAVA(UGCA-1932)
UNIT-III, PART-I

Finding the length of an Array:


An array length can be found using the length property in JAVA.

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


int length = numbers.length; // Output: 5

Looping an Array:
We can loop or iterate an array using a for loop or enhanced for loop (also called for-each loop)
provided by JAVA.
1.for loop:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

2.Enhanced for loop:


for (int number : numbers) {
System.out.println(number);
}

An Example of Array Program:

public class ArrayExample {


public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = {1, 2, 3, 4, 5};

// Access an element
System.out.println("First element: " + numbers[0]);

// Modify an element
numbers[2] = 10;
System.out.println("Modified array ");
// Iterate over the array
System.out.print("Array elements: ");
for (int number : numbers) {
System.out.print(number + " ");
}
}
}
JAVA(UGCA-1932)
UNIT-III, PART-I

OUTPUT

Passing array as an argument:


In Java, you can pass an array as an argument to a method. This allows you to process or manipulate
the array inside the method. When you pass an array to a method, you are actually passing a
reference to the array, which means changes made to the array inside the method will affect the
original array.

The syntax for Passing an Array as an Argument:

1. Method that accepts an array:


The method should declare a parameter of the array type.

public static void processArray(int[] array) {


// Code to process the array
}

2. Calling the method with an array:


You call the method by passing the array as an argument.

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


processArray(numbers);

Example: Passing an Array to a Method:

public class ArrayExample {


// Method that processes an array
public static void modifyArray(int[] array) {
// Modifying the first element
array[0] = 10;

// Printing all elements of the array


System.out.print("Modified array inside method: ");
for (int num : array) {
JAVA(UGCA-1932)
UNIT-III, PART-I

System.out.print(num + " ");


}
System.out.println();
}

public static void main(String[] args) {


// Creating an array
int[] numbers = {1, 2, 3, 4, 5};

// Passing the array to the method


modifyArray(numbers);

// Printing the array after modification


System.out.print("Array after method call: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}

OUTPUT

Returning array from methods:


In Java, a method can return an array just like any other type of data. Returning an array allows
you to return multiple values from a method in an organized manner.

Example 1: Returning a New Array from a Method

public class ArrayReturnExample {


// Method that returns an array of integers
public static int[] createArray() {
// Create an array of 5 integers
int[] numbers = {1, 2, 3, 4, 5};
return numbers; // Return the array
}

public static void main(String[] args) {


// Call the method and store the returned array
int[] resultArray = createArray();
JAVA(UGCA-1932)
UNIT-III, PART-I

// Print the returned array


System.out.print("Returned array: ");
for (int num : resultArray) {
System.out.print(num + " ");
}
}
}
OUTPUT

Explanation:
 The method createArray() creates an array numbers and returns it.
 In the main method, the returned array is stored in the variable resultArray, and its
elements are printed.

Example 2: Returning a Modified Array


You can also modify an array inside a method and return the modified array.

public class ModifyArrayExample {


// Method that modifies and returns an array
public static int[] modifyArray(int[] array) {
// Modify the first element
array[0] = 100;
return array; // Return the modified array
}

public static void main(String[] args) {


// Create an array
int[] numbers = {1, 2, 3, 4, 5};

// Call the method with the array and get the modified array
int[] modifiedArray = modifyArray(numbers);

// Print the modified array


System.out.print("Modified array: ");
for (int num : modifiedArray) {
System.out.print(num + " ");
JAVA(UGCA-1932)
UNIT-III, PART-I

}
}
}
OUTPUT

Array of Objects:
The array of Objects, the name itself suggests that it stores multiple objects in an array. Just like
the other array stores values like String, integer, etc. An array of Object stores objects it means
objects are stored as elements of an array.
When we require a single object to perform specified method in the program, we do it with an
object variable. But When we deal with numerous objects, then it is preferred to use an array of
objects.

Syntax for Creating an Array of Objects

1. Declare an array of objects: The syntax for declaring an array of objects is similar to
declaring an array of primitives.

ClassName[] arrayName = new ClassName[size];


2. Instantiate objects for each array element: you need to instantiate the objects and
assign them to each index of the array.

Example1: Array of Objects

class Person {
String name;
int age;

// Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
JAVA(UGCA-1932)
UNIT-III, PART-I

// Method to display the person's details


void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class ArrayOfObjectsExample {


public static void main(String[] args) {
// Create an array of 3 Person objects
Person[] persons = new Person[3];

// Instantiate each Person object and assign it to the array


persons[0] = new Person("John", 25);
persons[1] = new Person("Alice", 30);
persons[2] = new Person("Bob", 22);

// Access and display each person's details


for (int i = 0; i < persons.length; i++) {
persons[i].display();
}
}
}
OUTPUT

Explanation:

1. We create a class Person with attributes name and age and a method display() to print
the details.
2. We declare an array of Person objects: Person[] persons = new Person[3];.
JAVA(UGCA-1932)
UNIT-III, PART-I

3. For each element in the array, we instantiate a Person object and assign it to the
respective array index.
4. Finally, we use a loop to access and display each Person object's details.

Example2: Array of Objects

class Car {
String model;
int year;

// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}

void display() {
System.out.println("Model: " + model + ", Year: " + year);
}
}

public class CarArrayExample {


public static void main(String[] args) {
// Creating an array of Car objects and initializing them at the same time
Car[] cars = {
new Car("Tesla Model S", 2020),
new Car("Ford Mustang", 2019),
new Car("BMW X5", 2021)
};

// Display the details of each car


for (Car car : cars) {
car.display();
}
}
}
OUTPUT
JAVA(UGCA-1932)
UNIT-III, PART-I

2D Arrays:
In Java, a 2D array is an array of arrays, which means each element of a 2D array is another. A 2D
array is commonly used to represent data in a table or matrix form, where each row of the array is
similar to a row in the matrix and each column is similar to a column in the matrix.
The syntax for declaring a 2D array is as follows:
dataType[][] arrayName;

Initializing a 2D Array:

A 2D array can be initialized in several ways:

1. Using new keyword: You can create a 2D array by specifying the number of rows and
columns.

int[][] matrix = new int[3][4];

// 3 rows, 4 columns

2. Directly initializing with values: You can initialize a 2D array by specifying the values
for each row.

int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

Accessing Elements in a 2D Array:


You can access the elements of a 2D array using row and column indexes. Indexing in Java
arrays starts at 0, so the first element is at index [0][0].

int value = matrix[1][2];


// Accesses the element at row 1, column 2 (value is 7)

Modifying Elements in a 2D Array:


You can modify elements in a 2D array by assigning a new value to a specific index.

matrix[0][1] = 20;
// Modifies the element at row 0, column 1
JAVA(UGCA-1932)
UNIT-III, PART-I

Example:

public class TwoDArrayExample {


public static void main(String[] args) {
// Declare and initialize a 2D array
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

// Accessing an element
// System.out.println("Element at row 1, column 2: " + matrix[1][2]);
// Output: 7

// Modifying an element
// matrix[0][0] = 100;
// System.out.println("Modified element at row 0, column 0: " + matrix[0][0]);
// Output: 100

// Printing the entire 2D array


System.out.println("2D array:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
// Move to the next line after printing each row
}
}
}
OUTPUT
JAVA(UGCA-1932)
UNIT-III, PART-I

Array with three or more dimensions:


In Java, arrays can have more than two dimensions. A multidimensional array (like 3D,4D, or
higher) is an array of arrays of arrays. Each additional dimension adds a new level of indexing,
that allow you to represent a more complex data structure.
An array with three indexes is called a three-dimensional array in Java. In other words, a three-
dimensional array is a collection of one or more two-dimensional arrays.
Similarly, a four-dimensional array is an array of three-dimensional arrays. Generally, an n-
dimensional array is an array of (n-1) dimensional arrays.
Declaring Multidimensional Arrays:
dataType[][][] arrayName; // For a 3D array
dataType[][][][] arrayName; // For a 4D array, and so on
Initializing a Multidimensional Array:

 Using new keyword: You can initialize a multidimensional array by specifying the size of
each dimension.

int[][][] array3D = new int[3][4][5];


// 3x4x5 array (3 layers, each with a 4x5 matrix)

 Direct initialization with values: You can directly initialize a multidimensional array with
values.

int[][][] array3D = {
{
{1, 2, 3}, {4, 5, 6}
},
{
{7, 8, 9}, {10, 11, 12}
},
{
{13, 14, 15}, {16, 17, 18}
}
};
Accessing and Modifying Elements in a Multidimensional Array:
Each additional dimension requires an extra index to access specific elements (like; for 2D 2
indexes, for 3D 3 indexes and so on) . For a 3D array, you need three indices: one for the "layer",
one for the "row", and one for the "column".
JAVA(UGCA-1932)
UNIT-III, PART-I

int value = array3D[1][0][2];


// Accesses the element at layer 1, row 0, column 2

You can also modify elements by assigning a new value using the same index notation.

array3D[2][1][0] = 100;
// Modifies the element at layer 2, row 1, column 0

Example: 3D Array in Java

Here's a simple example of a 3D array that represents a collection of 2D matrices (layers).

public class ThreeDArrayExample {


public static void main(String[] args) {
// Declare and initialize a 3D array
int[][][] array3D = {
{
{1, 2, 3}, {4, 5, 6}
},
{
{7, 8, 9}, {0, 1, 2}
},

};

// Print the entire 3D array


for (int i = 0; i < array3D.length; i++) {
System.out.println("Layer " + i + ":");
for (int j = 0; j < array3D[i].length; j++) {
for (int k = 0; k < array3D[i][j].length; k++) {
System.out.print(array3D[i][j][k] + " ");
}
System.out.println(); // New line after each row
}
}
}
}
JAVA(UGCA-1932)
UNIT-III, PART-I

OUTPUT

Example: 4D Array in Java

If you need more dimensions, you can declare arrays with 4, 5, or more dimensions. Here's an
example of a 4D array:

public class FourDArrayExample {


public static void main(String[] args) {

// variable declaration used for indexes


int i, j, k, l;

int a[][][][] = new int[2][2][2][2];

// elements input
a[0][0][0][0] = 1;
a[0][0][0][1] = 2;
a[0][0][1][0] = 3;
a[0][1][0][0] = 4;
a[1][0][0][0] = 5;

// Print the entire 3D array


System.out.println("a[0][0][0][0] = "+a[0][0][0][0]);
System.out.println("a[0][0][0][1] = "+a[0][0][0][1]);
System.out.println("a[0][0][1][0] = "+a[0][0][1][0]);
System.out.println("a[0][1][0][0] = "+a[0][1][0][0]);
System.out.println("a[1][0][0][0] = "+a[1][0][0][0]);

}
}
JAVA(UGCA-1932)
UNIT-III, PART-I

OUTPUT

String Class:
String:
Generally, a String is a sequence of characters. But in Java, a string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.

In Java, the String class is used to represent and manipulate sequences of characters. Strings are
one of the most commonly used classes in Java, and they are immutable, meaning that once String
object is created, its value cannot be changed.

Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

Key Points about String in Java:


 Immutable: Once a String object is created, it cannot be changed. Any operation that is
applied to modify the string, creates a new String object.
 Stored in a String Pool: Strings in Java are stored in a special memory area called the
"string pool." This helps save memory and improve performance by reusing string literals

Creating a String
There are two main ways to create a string in Java:
1. Using string literals: When a string is created using double quotes, it is automatically
stored in the string pool.
String str1 = "Hello"; // String literal
JAVA(UGCA-1932)
UNIT-III, PART-I

2. Using the new keyword: When a string is created using the new keyword, it creates a new
String object in the heap, even if the same string already exists in the pool.

String str2 = new String("Hello");


// Creates a new String object

Commonly Used String Methods:


The String class provides a wide range of methods to manipulate and work with strings. Some of
the commonly used methods are:

1. length(): Returns the number of characters in the string.

String str = "Hello";


int length = str.length(); // 5

2. charAt(int index): Returns the character at the specified index.

char ch = str.charAt(1); // 'e'

3. substring(int beginIndex): Returns a substring starting from the given index.

String substr = str.substring(2); // "llo"

4. substring(int beginIndex, int endIndex): Returns a substring between


the given indices (start inclusive, end exclusive).

String substr = str.substring(1, 4); // "ell"

5. toUpperCase() / toLowerCase(): Converts the string to uppercase or


lowercase.

String upper = str.toUpperCase(); // "HELLO"


String lower = str.toLowerCase(); // "hello"

6. concat(String str): Concatenates the specified string to the end of the current
string.

String newStr = str.concat(" World"); // "Hello World"

7. contains(CharSequence s): Checks if the string contains the specified sequence


of characters.

boolean contains = str.contains("ell"); // true


JAVA(UGCA-1932)
UNIT-III, PART-I

8. equals(Object obj): Compares two strings for content equality.

boolean isEqual = str.equals("Hello"); // true

9. equalsIgnoreCase(String anotherString): Compares two strings,


ignoring case differences.

boolean isEqualIgnoreCase = str.equalsIgnoreCase("hello");


// true

10. startsWith(String prefix) / endsWith(String suffix): Checks if


the string starts or ends with the specified prefix or suffix.

boolean starts = str.startsWith("He"); // true


boolean ends = str.endsWith("lo"); // true

11. indexOf(String str): Returns the index of the first occurrence of the specified
substring. Returns -1 if the substring is not found.

int index = str.indexOf("l"); // 2

12. replace(char oldChar, char newChar): Replaces all occurrences of a


specified character with a new character.

String replacedStr = str.replace('l', 'p'); // "Heppo"

13. trim(): Removes any leading and trailing whitespace from the string.

String trimmedStr = " Hello ".trim(); // "Hello"

14. split(String regex): Splits the string into an array of substrings based on a
regular expression (regex).

String[] parts = str.split("l"); // {"He", "", "o"}

15. toCharArray(): Converts the string to an array of characters.

char[] chars = str.toCharArray();


// {'H', 'e', 'l', 'l', 'o'}
JAVA(UGCA-1932)
UNIT-III, PART-I

String Immutability Example:

public class StringExample {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = str1;

// Modify str1
str1 = str1.concat(" World");

// Check if str1 and str2 are still equal


System.out.println("str1: " + str1); // "Hello World"
System.out.println("str2: " + str2);
// "Hello" (unchanged)
}
}
Output:
str1: Hello World
str2: Hello

In this example, you can see that str1 was modified to "Hello World", but str2 (which was
initially pointing to the same string as str1) still holds "Hello". This demonstrates that strings
are immutable.

Summary:

 The String class in Java is immutable, meaning any modification results in a new string
being created.
 Strings are stored in a special memory area called the string pool for optimization
purposes.
 The String class provides many methods for string manipulation such as length(),
substring(), toUpperCase(), concat(), and replace().
 String objects are compared using either the == operator (reference comparison) or the
equals() method (content comparison).

Comparing Strings:
1. == operator: Compares the references (memory addresses) of the two string objects. It
checks if both strings point to the same memory location.

2. equals() method: Compares the contents of two strings for equality.


JAVA(UGCA-1932)
UNIT-III, PART-I

3. String.equalsIgnoreCase():It compares two string ignoring their case (lower or


upper). This method returns true if the argument is not null and the contents of both the
Strings are same ignoring case, else false.

Syntax:
Str2.equalsIgnoreCase(str1);

4. compareTo(String anotherString): Compares two strings and Returns:


 A negative number if the current string is smaller than the other string.
 Zero if both strings are equal.
 A positive number if the current string is lexicographically greater than the other
string.

int result = "apple".compareTo("banana"); // Negative value

String Concatenation:
String concatenation in Java refers to combining two or more strings into a single string. Java
provides several ways to concatenate strings, including using the + operator, the concat()
method, and the StringBuilder or StringBuffer classes for more efficient concatenation
in loops or complex operations.

1. Using the + Operator

The most common and simplest way to concatenate strings in Java is by using the + operator.

String str1 = "Hello";


String str2 = "World";
String result = str1 + " " + str2; // "Hello World"
System.out.println(result);

2. Using the concat() Method

The concat() method is another way to join two strings. It is part of the String class and
can only concatenate one string to another.

String str1 = "Hello";


String str2 = "World";
String result = str1.concat(" ").concat(str2); // "Hello World"
System.out.println(result);
JAVA(UGCA-1932)
UNIT-III, PART-I

 Note: The concat() method doesn't add spaces between strings, so you need to manually
include them where necessary.

3. Using StringBuilder (Recommended for Performance in Loops)

The StringBuilder class is used to concatenate strings more efficiently, especially in


scenarios where you need to append strings inside loops or where performance is critical. Unlike
String, StringBuilder is mutable, which means it can change its value without creating
new objects.

StringBuilder sb = new StringBuilder();


sb.append("Hello");
sb.append(" ");
sb.append("World");

String result = sb.toString(); // "Hello World"


System.out.println(result);

 StringBuilder is faster than + and concat() when performing many concatenations because
it does not create new objects for every concatenation.
 After concatenation, you can use the toString() method to convert the StringBuilder to a
String.

4. Using StringBuffer (Thread-Safe Alternative to StringBuilder)

StringBuffer is similar to StringBuilder, but it is thread-safe, meaning it is synchronized


and safe to use in multi-threaded environments. However, it is generally slower than
StringBuilder.

StringBuffer sbf = new StringBuffer();


sbf.append("Hello");
sbf.append(" ");
sbf.append("World");

String result = sbf.toString(); // "Hello World"


System.out.println(result);

Summary of Methods

1. + Operator:
o Simple and commonly used.
o Suitable for small concatenations.
JAVA(UGCA-1932)
UNIT-III, PART-I

o Creates multiple intermediate String objects, which can be slow in large-scale


operations.
2. concat() Method:
o Part of the String class.
o Used for simple concatenation without spaces.
o Less flexible than the + operator because it can only concatenate one string at a
time.
3. StringBuilder:
o Efficient for concatenating strings, especially in loops.
o Mutable, meaning no new objects are created.
o Not thread-safe but faster than StringBuffer.
4. StringBuffer:
o Thread-safe, meaning it can be used safely in multi-threaded environments.
o Slower than StringBuilder due to synchronization overhead.

Substring in Java:
In Java, the substring() method is part of the String class and is used to extract a portion of a string.
There are two different way of the substring() method, each allowing you to specify either a
starting index or both starting and ending indices.

1. substring(int beginIndex):

This method extracts a substring starting from the specified index to the end of the string.

String str = "Hello World";


String substr = str.substring(6); // "World"
System.out.println(substr);
o beginIndex: The starting index (inclusive) of the substring.
o The substring extends to the end of the string.

2. substring(int beginIndex, int endIndex):

This method extracts a substring between the specified beginIndex and endIndex.

String str = "Hello World";


String substr = str.substring(0, 5); // "Hello"
System.out.println(substr);

 beginIndex: The starting index (inclusive) of the substring.


 endIndex: The ending index (exclusive). The character at endIndex is not included
in the substring.
JAVA(UGCA-1932)
UNIT-III, PART-I

Key Points:
 Indexing in Java strings is zero-based, meaning the first character is at index 0.
 The beginIndex is inclusive, meaning the character at beginIndex is included in the
substring.
 The endIndex is exclusive, meaning the character at endIndex is not included in the
substring.
 If beginIndex is equal to endIndex, the result is an empty string ("").
 If beginIndex is negative or greater than the string's length, or if beginIndex is greater
than endIndex, the method throws a StringIndexOutOfBoundsException.

Difference between String and String Buffer class:


What is String?
When it comes to Java, a string is considered as an object that defines a sequence of char values.
In Java, strings are unchangeable. In any case, if a modification happens in a string, a completely
new string is constructed.

What is StringBuffer?
StringBuffer is the equivalent class of the class string. The class StringBuffer provides more
functionality than the other class strings. We can make changes here because the StringBuffer is
mutable.
S. No. String StringBuffer

1 String is immutable. It is mutable.

2 It is slow in terms of executing the It is fast in terms of executing the


concatenation task. concatenation task.

3 Here the length of the string class Here the length can be modified whenever
is static. required, as it is dynamic in behavior.

4 It is less efficient. It is more efficient in nature as compared to the


string class.

5 String consumes more memory as StringBuffer uses less memory as compared to


compared to the StringBuffer. the string.

6 It utilizes a pool ( part of the It prefers heap memory to store the objects.
memory) to store the values.
JAVA(UGCA-1932)
UNIT-III, PART-I

String Tokenizer class:


The StringTokenizer class in Java is used to break a string into tokens. It is part of the java.util
package. The StringTokenizer class is often used to split strings into smaller pieces (tokens) based
on a specified delimiter.
Delimiters are the characters that separate tokens. Default delimiters are whitespaces, new lines,
spaces, and tabs.

It's generally recommended to use the split() method of the String class or Scanner class, as they
are more flexible and easier to use.

Various Constructors of StringTokenizer:

1. StringTokenizer(String str): Uses whitespace as the default delimiter to break the


string into tokens.

StringTokenizer st = new StringTokenizer("Hello World");

2. StringTokenizer(String str, String delim):Breaks the string using the


provided delimiter.

StringTokenizer st = new StringTokenizer("Hello,World", ",");


true);

Commonly Used Methods:

1. hasMoreTokens(): Returns true if there are more tokens available.

StringTokenizer st = new StringTokenizer("Hello World");


while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

2. nextToken(): Returns the next token from the string.

StringTokenizer st = new StringTokenizer("Hello World");


String token = st.nextToken(); // "Hello"

3. nextToken(String delim): Returns the next token using the specified delimiter
instead of the default one.

StringTokenizer st = new StringTokenizer("Hello,World");


String token = st.nextToken(","); // "Hello"
JAVA(UGCA-1932)
UNIT-III, PART-I

4. countTokens(): Returns the number of tokens remaining.

StringTokenizer st = new StringTokenizer("Hello World");


int tokens = st.countTokens(); // 2

Example: Basic Usage of StringTokenizer

import java.util.StringTokenizer;

public class StringTokenizerExample {


public static void main(String[] args) {
String str = "Shahid is learning JAVA in the BCA 5th sem.";

// Create a StringTokenizer with default delimiter (whitespace)


StringTokenizer st = new StringTokenizer(str);

// Count tokens
System.out.println("NumberOfToken:" + st.countTokens());

// Print each token


while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}

OUTPUT
JAVA(UGCA-1932)
UNIT-III, PART-I

Conclusion:

 Use Case: StringTokenizer is useful for quick tokenization when no regular


expression is required and when backward compatibility with older Java code is necessary.
 Legacy Class: In most cases, prefer the split() method or Scanner for tokenizing
strings in modern Java development.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy