0% found this document useful (0 votes)
15 views6 pages

Java String Methods Overview

The document discusses various methods and operations that can be performed on strings in Java. It covers declaring and initializing strings, taking string input, concatenating strings, finding string length, accessing characters in a string, comparing strings, substrings, parsing integers from strings using parseInt, converting integers to strings using toString, and homework problems involving strings.

Uploaded by

Preeti Kumari
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)
15 views6 pages

Java String Methods Overview

The document discusses various methods and operations that can be performed on strings in Java. It covers declaring and initializing strings, taking string input, concatenating strings, finding string length, accessing characters in a string, comparing strings, substrings, parsing integers from strings using parseInt, converting integers to strings using toString, and homework problems involving strings.

Uploaded by

Preeti Kumari
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

Java - Introduction to Programming

Lecture 12

Strings

Declaration
String name = "Tony";

Taking Input
Scanner sc = new Scanner([Link]);
String name = [Link]();

Concatenation (Joining 2 strings)


String firstName = "Tony";
String secondName = "Stark";

String fullName = firstName + " " + secondName;


[Link](fullName);

Print length of a String


String firstName = "Tony";
String secondName = "Stark";

String fullName = firstName + " " + secondName;


[Link]([Link]());

Access characters of a string


String firstName = "Tony";
String secondName = "Stark";

String fullName = firstName + " " + secondName;

for(int i=0; i<[Link](); i++) {


[Link]([Link](i));
}

Apna College
Compare 2 strings
import [Link].*;

public class Strings {


public static void main(String args[]) {
String name1 = "Tony";
String name2 = "Tony";

if([Link](name2)) {
[Link]("They are the same string");
} else {
[Link]("They are different strings");
}

//DO NOT USE == to check for string equality


//Gives correct answer here
if(name1 == name2) {
[Link]("They are the same string");
} else {
[Link]("They are different strings");
}

//Gives incorrect answer here


if(new String("Tony") == new String("Tony")) {
[Link]("They are the same string");
} else {
[Link]("They are different strings");
}

}
}

Substring
The substring of a string is a subpart of it.
public class Strings {
public static void main(String args[]) {
String name = "TonyStark";

[Link]([Link](0, 4));

Apna College
}
}

ParseInt Method of Integer class


public class Strings {
public static void main(String args[]) {
String str = "123";
int number = [Link](str);
[Link](number);

}
}

ToString Method of String class


public class Strings {
public static void main(String args[]) {
int number = 123;
String str = [Link](number);
[Link]([Link]());

}
}

ALWAYS REMEMBER : Java Strings are Immutable.

Apna College
Homework Problems
1. Take an array of Strings input from the user & find the cumulative (combined)
length of all those strings.
import [Link].*;

public class Strings {

public static void main(String args[]) {

Scanner sc = new Scanner ([Link]);

int size = [Link]();

String array[] = new String[size];

int totLength = 0;

for(int i=0; i<size; i++) {

array[i] = [Link]();

totLength += array[i].length();

[Link](totLength);

2. Input a string from the user. Create a new string called ‘result’ in which you will
replace the letter ‘e’ in the original string with letter ‘i’.

Example :

original = “eabcdef’ ; result = “iabcdif”

Original = “xyz” ; result = “xyz”

Apna College
import [Link].*;

public class Strings {

public static void main(String args[]) {

Scanner sc = new Scanner ([Link]);

String str = [Link]();

String result = "";

for(int i=0; i<[Link](); i++) {

if([Link](i) == 'e') {

result += 'i';

} else {

result += [Link](i);

[Link](result);

3. Input an email from the user. You have to create a username from the email by
deleting the part that comes after ‘@’. Display that username to the user.

Example :

email = “apnaCollegeJava@[Link]” ; username = “apnaCollegeJava”

email = “helloWorld123@[Link]”; username = “helloWorld123”

Apna College
import [Link].*;

public class Strings {

public static void main(String args[]) {

Scanner sc = new Scanner ([Link]);

String email = [Link]();

String userName = "";

for(int i=0; i<[Link](); i++) {

if([Link](i) == '@') {

break;

} else {

userName += [Link](i);

[Link](userName);

Apna College

Common questions

Powered by AI

To create a username from an email, iterate through the email string until the '@' character is found, then capture the preceding substring as the username. This task involves string parsing techniques. It's crucial to handle edge cases such as emails without '@' or with multiple '@' symbols (though invalid by standard). Implementing validation checks before extraction safeguards against malformed emails, ensuring robustness. Additionally, regular expressions can be used for more complex username extraction requirements .

For efficient string operations in Java, prioritize using mutable classes like StringBuilder or StringBuffer for operations involving multiple modifications, as they allow changes without creating new instance overhead. Prefer bulk operations and reduce concatenation inside loops to minimize object creation. Cache reusable string data, validate inputs, and utilize pre-built functions like 'replace' and 'split' for clarity and performance. Additionally, regularly profiling and optimizing memory management practices will prevent memory leaks and excessive garbage collection .

Methods like 'parseInt' and 'toString' are crucial in applications requiring conversion between numbers and strings, an essential operation in form validation, data exchange, and user interaction. In real-world applications, 'parseInt' can be used to convert user input from a text field into numeric data for processing, such as in calculators or data entry forms. 'toString', conversely, can be useful in formatting numbers as string values for display, such as showing currency or units in a user interface. Using these conversions effectively allows for dynamic interactivity and data management between backend processing and user-facing interfaces .

The 'substring' method is useful when a programmer needs to extract a specific part of a string for further processing, such as parsing input data (e.g., extracting a username from an email). A potential pitfall is the risk of generating a 'StringIndexOutOfBoundsException' if the specified indices are invalid, which can happen if assumptions are made about string length without validation. Additionally, because strings in Java are immutable, excessive use of 'substring' can lead to unnecessary memory usage if not handled efficiently, as each call can create additional string objects .

The 'equals' method in Java compares the actual data within two strings, checking if they are lexically identical, while the '==' operator compares the references, i.e., the memory location of the objects. This distinction is crucial because using '==' for string comparison can lead to incorrect results unless both string variables reference the same string object in memory. On the other hand, 'equals' provides a consistent and accurate method for determining if two strings contain the same sequence of characters, regardless of their memory address .

To replace the character 'e' with 'i' in a string, one can iterate over each character of the string, checking if it matches 'e' and appending 'i' to a new result string; otherwise, append the character itself. This operation requires careful handling to avoid inefficiencies: Instead of using string concatenation inside a loop, which is time-consuming, using a StringBuilder to build the result can optimize this process by reducing the number of temporary string instances created during concatenation .

Using '==' for string equality checks in Java can lead to incorrect results because it compares reference identities instead of actual data. Instances where strings with identical characters have different references will return false if compared with '=='. Ignoring this advice can cause logic errors, such as failing to recognize when two user-input strings are semantically the same, potentially leading to bugs in authentication systems, form validations, or configuration comparisons, thus compromising application correctness and security .

To calculate the cumulative length of an array of strings, iterate through the array and sum the lengths of each string using the 'length()' method. Potential pitfalls include not handling null strings, which could lead to a NullPointerException, and assuming all elements are initialized. Ensuring proper validation and initialization checks can prevent these errors. Also, careful design is necessary to ensure inputs are correctly taken from the user before processing, which includes error handling for input mismatches .

Java strings being immutable means that once a string is created, its value cannot be changed. Any operation that seems to modify a string actually results in a new string being created. This immutability provides several benefits, such as thread safety and reduced error in string handling, as strings can't be altered unexpectedly. However, it can affect performance negatively, especially in scenarios involving extensive string manipulation, as frequent creation of new string objects increases memory overhead and potential garbage collection activity .

String concatenation in Java, especially inside loops, can be inefficient because it creates numerous temporary String objects due to string immutability, which increases memory usage and processing time. In contrast, StringBuilder is designed for efficient string manipulation by allowing a mutable sequence of characters. Using StringBuilder for concatenation tasks, particularly in performance-critical applications, significantly reduces the overhead as it modifies the same object without creating additional instances, leading to better memory and CPU utilization .

You might also like