Java String PDF Notes
Java String PDF Notes
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.
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.
String object can be created using new operator like java class.
Example:
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.
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:
EduBridge
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
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
EduBridge
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.
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.
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'
"Coking".endsWith("king")
Output :true
"jAVa".toLowerCase()
Output: "java"
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"
EduBridge
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
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(),
EduBridge
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{
EduBridge
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.
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):
EduBridge
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.