0% found this document useful (0 votes)
2K views8 pages

Java String Methods and Concatenation

Java notes

Uploaded by

Madhu Sudhan
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)
2K views8 pages

Java String Methods and Concatenation

Java notes

Uploaded by

Madhu Sudhan
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

String

String in JAVA
duBridge
String is a sequence of charactersenclosed within double quotes ("") is known as String. It is an
immutable object.
When we create a string in java, it actually creates an object of type String.
Java String class provides a lot of methods to perform operations on string such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

Create String in JAVA


There are two ways to create a String in Java
1. String literal
2. Using new keyword

1. String literal:
Java String literal is created by using double-quotes.
Example:

String s = "king";
All rights reserved.
No part of this document may be reproduced in any material forn (including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBidge Learming Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Lid.

EduBridge

String objects are stored in a special memory area known as the "string constant pool".
This is the most common way of creating the string.

2. Using new keyword:

String object can be created using new operator like java class.
Example:

String s = new String("king");


It creates two objects in String pool and in heap
Also one reference variable 's' is created that will refer to the object in the heap.

Java String Pool: Java String pool refers to collection of Strings which are stored in heap memory. So whenever a new
object is created. It will check whether the new object is already present in the pool or not. f it is present, then same
reference is returned to the variable else new object will be created in the String pool and the respective reference
will be returned.

String concatenation in JAVA


String concatenation means joining of two or more strings.
We have two strings
str1 = "Core" and str2 = "JAVA"
If we add these two strings, we should have a result as str3= "CoreJAVA".
There are two methods to perform string concatenation.
First is by using arithmetic "+" operator and second is using "concat" method of String class.
Both method will results in the same output.

Example
How to perform string concatenation in java
First example is by using arithmetic "+" operator and second is using "concat" method of String class.
string concatenation by operator (+) method:

Example1:
String concatenation in JAVA
String concatenation means joining of two or more strings.
We have two strings
str1 = "Core" and str2 = "JAVA"
If we add these two strings, we should have a result as str3= "CoreJAVA".
There are two methods to perform string concatenation.
First is by using arithmetic "4" operator and second is using "concat" method of String class.
Both method will results in the same output.

Example
" How to perform string concatenation in java
First example is by using arithmetic "+" operator and second is using "concat" method of String class.
string concatenation by operator (+) method:

Examplel:

All ights reserved.


No part of this document may be reproduced in any material form (including printing and photocopying or storing it in any medium by electronie or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Leaming Pvt. Ltd. Application for writen permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.

EduBridge

String str3="Core"+ "JAVA";


String concatenation by concat() method :
Example2:
String str3 = [Link](str2);

Lab Activity:

Following is the web link which is used as a web terminal to try and test Java through JSHELL.
So you can use this link to check the string method examples as shown below:
htlps://[Link]/

" Participant will write &observe the simple hello word program, with the help of trainer

String Method
List of the some important methods available in the Java String are as follows:
Length() :
It returns the length of the string object.
Example:
String s = "Core JAVA";
[Link]()
Output :9

getChars() and toCharArray() :


It is used to populate a character array from the string object as source.
syntax :

getChars(int srcBegin, int srcEnd, char dst[]l, int dstBegin)


Where:
srcBegin -index of the first character in the string to copy.

All rights reserved.


No part of this document muy be repruduced in uny mnaterial lorn (including printing nd photocupying ur storing it in any medium by electrunic or other meunx or not tranxiently or
incidentally to some other use of this document) without the prior written permission of EduBrndge Leaming Pvt. Lid. Application for written permission to reproduce any part of this
document should he addressed to the (EO of FduRidge leaming Pvt l d.

EduBridge
String Method
List of the some important methods available in the Java String are as follows:
Length() :
" It returns the length of the string object.
Example:
String s = "Core JAVA":

[Link]()
Output:9

getChars() and toCharArray() :


It is used to populate a character array from the string object as source.
syntax :

getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)


Where:
srcBegin - index of the first character in the string to copy.

All rights reserved.


No part of this document may be reproduced in any material formm (including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Leaning Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.

EduBridge

srcEnd - index after the last character in the string to copy.


dst - the destination array.
dstBegin - the start offset in the destination array.

Example :

The Java String class getChars(0 method copies the content of this string into a specified char array. There are
four arguments passed in the getChars() method.

Example:
String s1="JAVA";
char[] dest=new char[4];
[Link](0,4,dest,0)
[Link]([Link](dest));
Output: !, A, V, A]
dge
toCharArray():
This method returns a new character array created from the string characters.
The java string toCharArray() method converts this string into character array. It returns a newly
created character array, its length is similar to this string and its contents are initialized with the
characters of this string.

All rights reserved.


No part of this document may be reproduced in any material form (including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Leaming Pvt. Lid. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pv Lid.

EduBridge
String s =
"loT";
[Link]
v)
Output: char[3] {"1, o', T})

EdBridae
compareTo() method is used to compare two strings lexicographicaly.
The compareTolgnoreCase() method is similar to compareTo() method also
performs the lexicographical comparison only it ignore case.
Example :

"Java".

compareTo("
Java")
Output :0

"Java".compareTol
gnoreCase("JAVA")
Output:0

isEmpty(), isBlank():
isEmpty() method returns true if the string is empty.

All rights reserved.


No part of this document may be reproduced in any material form (including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Leaming Pvt. Ltd. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.

EduBridge

isBlank() method returns true if the string is empty or contains only whitespace characters like spaces
and tabs.
Example :
String emptyStr =" ";
emptyStr. isEmpty() I/ Output:
false [Link]()
Output: true

charAt(int index):
This method returns the character at the given index.

Example :

duBridge
String s = "Java";
[Link](3)
Output: 'a'

startsWith) and endsWith():


These methods are used to check if the string has given prefix or suffix strings or not.
Example:
"Coking".startsWith("king")
Output: false

"Coking".endsWith("king")
Output :true

toLowerCase() and toUpperCase():


" These methods are used to create lowercase and uppercase strings.
Example:
"Java".toUpperCase()
Output: "JAVA"

"jAVa".toLowerCase()
Output: "java"

trim(), strip(), stripleading(), and stripTrailing():


trim() : It trim all the leading and trailing whitespaces from a string.
strip(): This method uses [Link]()
method to remove leading and trailing whitespaces from a string.
The stripLeading) and stripTrailingl) methods also remove leading and trailing whitespaces.

UBridge
"Example: String s=" Java "
[Link]()

Output:"Java"

repeat() :
This method returns a new string whose value is the concatenation of this string given number of times.
Example:
String s = "Java"

[Link](2)
Output: JavaJava"

contentEquals():
This String method compares the content of the string.
Example:
String s1 = "Skillking"

All rights reserved.


No part of this document may be reproduced in any mnaterial forn (including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to some other use of this document) without the prior written permission of EduBridge Learning Pvt. Lid. Application for written permission to reproduce any part of this
document should be addressed to the CEO of EduBridge Learning Pvt Lid.

EduBridge

StringBuffer s2 = new StringBuffer()

[Link]("Skillking")
[Link](s2)
Output ::true

Lab Activity:

Trainer will ask the participants to refer to the participant's guide and complete the given exercise.

Exercise 8:

package [Link];

duBridge
EduBridge

public class Hello_World{

public static void main(String[] args) {

I/ String declaration without using new operator


String a ="Cooking":
[Link]("String a=" +a);
|/ String declaration using new operator
String b = new String"loT");
[Link]("String b=" +b);
//There are many string methods available some String Methods are as follows
[Link]("The length of the string:" + [Link]());

Bridge
[Link]([Link]():
[Link]([Link]():
[Link](a + b);
[Link]([Link](b);
[Link]("Character at position 5:" + [Link](5):
[Link]([Link](b)):
[Link]([Link](b)):
[Link]([Link](b):
[Link]([Link]("x");

Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.

String Method
" We can perform operations on string such as trimming, concatenating, converting, comparing, replacing
strings etc. with the help of these methods.
" Like this way there are many more important string method such as

getBytes(), equals(), hash Code() and equalslgnoreCase(), indexOf() and lastindexOf(), substring() and
subSequence() ,matches(), replace(), replaceFirst(), and replaceAll(), split(), lines(), indent(), transform(), format(),

All rights reserved.


No part of this document n be naterialier
incidentally to some other use of this doeument) witboutshe fom k(including nedium by ot transicntly
ent) of EduBridge rmission Dreproduce any part of this
Tor written permissic
document should be addressed to the CEO of EduBridge Learning Pyt Ltd.

EduBridge

intern(), valueOf() and copyValueOf(), repeat(), describeConstable() and resolveConstantDesc(), formatted(),


stripindent), and translateEscapes(), etc.

Java String Buffer class


Java StringBuffer class is used to create mutable string.
StringBuffer represents growable and writable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended to the end.
StringBuffer( ): It reserves space for sixteen characters without reallocation.
Example : StringBuffer s=new StringBuffer();
StringBuffer( int size): It accepts a whole number argument that explicitly sets the scale of the buffer.
Example: StringBuffer s=new StringBuffer(30);
StringBuffer(String str): It reserves area for sixteen characters while not reallocation and accepts a String
argument that sets the initial contents of StringBuffer object.
Example: StringBuffer s=new StringBuffer("loT");

Lab Activity:

Trainer will ask the participants to refer to the participant's guide and complete the given exercise.

Exercise 9:
Java String Buffer class
Java StringBuffer class is used to create mutable string.
StringBuffer represents growable and writable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended to the end.
StringBuffer ): It reserves space for sixteen characters without reallocation.
Example : StringBuffer s=new StringBuffer();
StringBuffer( int size): It accepts a whole number argument that explicitly sets the scale of the buffer.
" Example: StringBuffer s=new StringBuffer(30);
StringBuffer(String str): It reserves area for sixteen characters while not reallocation and accepts a String
argument that sets the initial contents of StringBuffer object.
Example: StringBuffer s=new StringBuffer("loT");

Lab Activity:
Trainer will ask the participants to refer to the participant's guide and complete the given exercise.

Exercise 9:

package [Link];

publicclass Hello_WNorld{

public static void main(Stringl] args) {

StringBuffer str = new StringBuffer("Cooking ");


[Link]("Emerging ");
[Link](str);

All rights reserved.


No part of this document may be reproduced in any material form (including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
c E L d . Apphcation or written pernmission to reproduce any part of this
incidentally to some other use of this document) witho t the prior hould bereedeh
document ridge Learning

EduBridge

[Link](17, "Technology "):


[Link](str):
[Link]( 8, 16, "loT");
[Link](str);

[Link]():
[Link](str);

[Link]( [Link](0 ):

Post completion of the activity trainer will share the feedback/ suggestions on the work done by the participants.

Enum TTOg
Enum is a one of the special data types to declare the list of constants that enable for a variable, which have
similar meaning. For example, we create enum to manage the list of months, name of days, and other similar
kind of values.

We declare enum with the help of enum keyword and since this holds the constant value, the constraint is to
write the value in capital letters.
In a common real-life scenario, we can understand enum such as a short form of code word, which has a
meaning.
In programming, when we want to hide the actual data from the end users, we prefer to use enums.

For example, in our program we want the user to enter a number so that O represents Sunday and 7
represents Saturday. But when we are setting the enum for those numbers, we will set with the name of the
day instead of sequence Oor 1, that will be Sunday, Monday, and so on and we further use the same in our
program for evaluation.

This way, we also mislead the hackers to identify what value is being used in the program and they cannot
easily hack the program written using enum.
We may also use the enum contact with values for mathematical formulas or assign a unique value for that
constant.
of compiling, the compiler implicitly adds some additional features to that call.
An enum class can have methods and fields.

Example (Enum constant):


Public class Enumimpl {
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY, SUNDAY

public static void main(String[] args) {


[Link]([Link]);
Bridge
Output:

MONDAY

Here, we have declared a enum Day, which holds name of the days and printed the first constant MONDAY as
follows

Example (The Enum class type example with contacts with values):

All rights reserved.


No part of this document may be reproduced in any material forn (including printing and photocopying or storing it in any medium by electronic or other means or not transiently or
incidentally to sone other use of this document) without the prior written permission of EduBridge Learning Pvt. Ltd. Application for written permission to reproduce any paurt of this
document should be addressed to the CEO of EduBridge Learning Pvt Ltd.

EduBridge

public enum Day {


SUNDAY(0), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5),
SATURDAY(6);
private int daylndex;
Day(int name){
[Link] = name:

public static void main(String[] args) {


[Link](Day. [Link] Daylndex():
[Link]([Link]);

public int getDaylndex() {


return dayindex;

uBridae

Output:

1
TUESDAY

" In the preceding example, Day(int name) is the constructor, which is assigning the constant value to a private
variable

After this, we have created a getDaylndex method, which helps us to get the value of the constant.
In the main method, we have written the following statements to get the constant and its values:
[Link]([Link](); I/ this line of code will print the value from constant
MONDAY that is 1.
[Link]([Link]): // this line of code will simply print constant TUESDAY.
.
NOTE: AIl enums implicitly extend [Link] because a class can only extend one parent class in Java.

Common questions

Powered by AI

In Java, a String can be created either by using a String literal or the 'new' keyword. A String literal directly creates a String in the String constant pool, providing potential memory efficiency by reusing instances. For example, using `String s = "king";` will check if "king" is already in the pool, and if so, the reference is reused. Conversely, using the 'new' keyword, as in `String s = new String("king");`, explicitly creates a new object in heap memory even if the same content exists in the pool .

Java's String Pool is a special storage area in heap memory where Strings created using literals are stored. When a new String is created using a literal, Java checks if an identical String already exists in the pool. If it does, the same reference is returned to the new variable, thereby saving memory by avoiding the creation of duplicate objects. This mechanism is beneficial for performance and memory efficiency, especially when dealing with a large number of repetitive Strings .

While both compareTo() and compareToIgnoreCase() are used to perform lexicographical comparisons between two strings, compareToIgnoreCase() ignores case sensitivity during comparison. This means 'apple' and 'Apple' would be considered equal by compareToIgnoreCase() but not by compareTo(), where lowercase and uppercase characters would affect the lexical ordering result .

Enums in Java are special data types that enable variable definitions with a set of predefined constants, improving code clarity and safety by restricting the possible values. They are useful for representing fixed sets of constants such as days of the week, direction, or states. For example, an enum for days could simplify managing calendar operations by restricting inputs to only valid days (e.g., SUNDAY, MONDAY). The use of enums also enhances the readability of code and can hide underlying implementation details from users .

StringBuffer should be used when there is a need for mutable sequences of characters, such as when constructing strings piece by piece or making frequent modifications. Unlike Strings, which are immutable, StringBuffers can be appended, inserted, or deleted without creating new objects, which makes operations on them more memory-efficient and faster in scenarios involving extensive modifications. For example, continuously appending strings in a loop would perform better with StringBuffer .

The substring method in Java allows for the creation of new strings by extracting a portion from an existing string, defined by a starting and optional ending index. This capability is particularly useful for parsing; extracting specific segments of data from text, such as dates within strings, or performing custom formatting operations. Using substring, developers can efficiently manage and manipulate strings without additional object creation unless required by the context .

Both the 'concat' method and '+' operator are used for String concatenation in Java and provide similar end results. However, the 'concat' method can only concatenate strings, and using it with non-String operands results in a compile-time error. In contrast, the '+' operator can be used with a wider range of operands due to Java's implicit casting and can convert non-String operands to String when necessary. While '+' operator offers more convenient syntax, both methods eventually compile to similar bytecode when used on Strings .

Using Java's String class offers simplicity and immutability, ensuring that Strings are thread-safe and constant once created, which prevents inadvertent data alteration. However, this immutability can lead to performance issues in scenarios with frequent modifications, as each change results in the creation of a new String object. On the other hand, StringBuffer, which is mutable, allows for direct modifications, improving performance in such scenarios. The trade-off is that StringBuffer is not thread-safe like Strings, though the newer StringBuilder provides similar benefits with less overhead when thread safety is not a concern .

The trim() method removes whitespace from both ends of a string but does so using a less comprehensive definition of whitespace than the newer strip() method, introduced in Java 11. The strip() method uses Character.isWhitespace() to identify whitespace, making it more Unicode-friendly. stripLeading() and stripTrailing() are more specialized variants that remove leading or trailing whitespace, respectively, but not both. These methods provide developers with greater control over whitespace handling in strings .

toCharArray() converts the entire string into a new character array, making it a straightforward method to retrieve characters from a string. In contrast, getChars() copies a defined range from the string into an existing array, offering more flexibility in selective character extraction. Four arguments are required for getChars(): the starting index in the string, the ending index, the destination array, and the starting position in the destination array .

You might also like