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

Java String PDF Notes

Java notes

Uploaded by

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

Java String PDF Notes

Java notes

Uploaded by

Madhu Sudhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

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 = str1.concat(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://trvishell.org/

" 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";
s.length()
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":

s.length()
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];
s1.getChars(0,4,dest,0)
System.out.printin(Arrays.toString(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";
s.toCharArra
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 emptyStr.isBlank()
Output: true

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

Example :

duBridge
String s = "Java";
s.charAt(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 Character.isWhitespace()
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 "
s.trim()

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"

s.repeat(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()

s2.append("Skillking")
s1.contentEquals(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 Hello.World;

duBridge
EduBridge

public class Hello_World{

public static void main(String[] args) {

I/ String declaration without using new operator


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

Bridge
System.out.println(a.toUpperCase():
System.out.println(a.toLowerCase():
System.out.println(a + b);
System.out.printin(a.concat(b);
System.out.printin("Character at position 5:" + a.charAt(5):
System.out.printin(a.equals(b)):
System.out.printin(a.equalslgnoreCase(b)):
System.out.printin(a.compareTo(b):
System.out.printin(a.contains("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 Hello.World;

publicclass Hello_WNorld{

public static void main(Stringl] args) {

StringBuffer str = new StringBuffer("Cooking ");


str.append("Emerging ");
System.out.printin(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

str.insert(17, "Technology "):


System.out.printin(str):
str.replace( 8, 16, "loT");
System.out.printin(str);

str.reverse():
System.out.printin(str);

System.out.printin( str.capacity(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) {


System.out.println(Day.MONDAY);
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){
this.daylndex = name:

public static void main(String[] args) {


System.out.printin(Day. MONDA.get Daylndex():
System.out.printin(Day.TUESDAY);

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:
System.out.println(Day.MONDAY.getDaylndex(); I/ this line of code will print the value from constant
MONDAY that is 1.
System.out.printin(Day.TUESDAY): // this line of code will simply print constant TUESDAY.
.
NOTE: AIl enums implicitly extend java.lang.Enum because a class can only extend one parent class in Java.

You might also like