Strings in Java || Java + DSA course || Blog 6
Strings are defined as an array of characters. "Hello" is a string and "I am a student" is also a string.Strings are used in programming for various purpose.Strings are immutable, meaning it cannot be changed.To change it we use string builder.
Lets learn about strings in a practical way.
Declaration
You can even make them print together like:
Output: Elon Musk
This is contatention/joining two strings.
You can directly print it or save it in another variable as
String fullname = name + lastname;
Length is the total space it has captured. The length of elon musk would be 9.
If you want to print the sentence letter by letter then charAt() function is used with for loop.
compareTo() is used to see whether name1 and name2 strings are same.
The output will be YES.
Lets understand how it works:it works on alphabetical order. Lets take one string as "Bill" and another string as "Jeff". When we compare it b becomes before than j. so string1 is before than string 2. simply: string1 > string2. It returns a positive value like 8,1,4,3,...so it is not equal to 0 and it will not print YES.eg: hello<wello
Same if string1 was "jeff" and string2 was "bill", it would written negative value again not equal to zero.eg: hello>cello
But when elon and elon is seen, it returns zero and YES is printed.eg:hello==hello
Lets take a sentence
Java is a zero index based language. Indexing starts from zero.
What if we want to just print elon from the sentence. For this, we use.substring(index from which to start, index to end)
As i told you strings are immutable, so we use string builder
String Builder
normal string:
stringbuilder
string doesnt take much time rather than string as it keeps changing itself.
Indexing
the output will be e.
SetCharAt()
the output is ulon
.insert()
the output is melon.
.delete()
the output is lon
.append()
the output is elona.
_____________________________________________________________________________________
checkout:https://javaanddsa.blogspot.com/
did you like our blog 6??
tell us in the comment section
Interesting information . Great
ReplyDeleteInformative as always
ReplyDelete