Sunteți pe pagina 1din 18

Java Strings

Java Heap Memory


Heap memory is used by java runtime to allocate memory to
Objects and JRE classes. Whenever we create any object, its
always created in the Heap space. Garbage Collection runs on the
heap memory to free the memory used by objects that doesnt have
any reference. Any object created in the heap space has global
access and can be referenced from anywhere of the application.
Java Stack Memory
Java Stack memory is used for execution of a thread. They contain
method specific values that are short-lived and references to other
objects in the heap that are getting referred from the method. Stack
memory is always referenced in LIFO (Last-In-First-Out) order.
Whenever a method is invoked, a new block is created in the stack
memory for the method to hold local primitive values and reference
to other objects in the method. As soon as method ends, the block
becomes unused and become available for next method.
Stack memory size is very less compared to Heap memory.

Java String
Java Stringprovidesalotofconceptsthatcanbe
performed on a string such as compare, concat,
equals, split, length, replace, compareTo, intern,
substringetc.
Injava,stringisbasicallyanobjectthatrepresents
sequenceofcharvalues.
Anarrayofcharactersworkssameasjavastring.
char[]ch={T',h',a',p',a',r',U',n',i'};
Strings=newString(ch);
Strings=ThaparUni";

The java String is immutable i.e. it cannot be


changedbutanewinstanceiscreated.Formutable
class,useStringBuffer.
TherearetwowaystocreateStringobject:
1.Bystringliteral

2.Bynewkeyword

Strings="welcome";
Eachtimeyoucreateastringliteral,theJVMchecks
the string constant pool first. If the string already
exists in the pool, a reference to the pooled
instance is returned. If string doesn't exist in the
pool,anewstringinstanceiscreatedandplacedin
thepool.
String objects are stored in a
special memory area known
as string constant pool.

Strings1="Welcome";
Strings2="Welcome";
//willnotcreatenewinstance
Oncestringobjectiscreateditsdata
orstatecan'tbechangedbutanew
stringobjectiscreated.

Strings=newString("Welcome");

Insuchcase,JVMwillcreateanewstringobjectin
normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant
pool. The variable s will refer to the object in
heap(nonpool).

Java String compare


Wecancomparestringinjavaonthebasisof
contentandreference.
Itisusedinauthentication(byequals()
method),sorting(bycompareTo()
method),reference matching(by==operator)
etc.
Therearethreewaystocomparestringinjava:
1.Byequals()method
2.By==operator
3.BycompareTo()method

String compare by equals() method


TheStringequals()methodcomparestheoriginal
contentofthestring.Itcomparesvaluesofstring
forequality.
Stringclassprovidestwomethods:
public boolean equals(Object another)
comparesthisstringtothespecifiedobject.
public boolean equalsIgnoreCase(String another)
comparesthisStringtoanotherstring,ignoringcase.

String compare by == operator


The==operatorcomparesreferencesnotvalues.
String compare by compareTo() method
The String compareTo() method compares values
lexicographically and returns an integer value that
describes if first string is less than, equal to or
greaterthansecondstring.
Supposes1ands2aretwostringvariables.If:
s1 == s2:0
s1 > s2 :positivevalue
s1 < s2 :negativevalue

String Concatenation in Java


In java, string concatenation forms a new
stringthat isthecombinationofmultiplestrings.
Therearetwowaystoconcatenatestringsinjava:
1.By+(stringconcatenation)operator
2.Byconcat()method
String Concatenation by concat() method
TheStringconcat()methodconcatenatesthe
specifiedstringtotheendofcurrentstring.
publicStringconcat(Stringanother)

Substring in Java
Apartofstringiscalledsubstring.Inother
words,substringisasubsetofanotherstring.In
caseofsubstringstartIndexisinclusiveand
endIndexisexclusive.
public String substring(int startIndex):This
methodreturnsnewStringobjectcontainingthe
substringofthegivenstringfromspecified
startIndex(inclusive).
public String substring(int startIndex, int
endIndex): ThismethodreturnsnewString
objectcontainingthesubstringofthegivenstring
fromspecifiedstartIndextoendIndex.

Java String toUpperCase() and toLowerCase()


method
ThejavastringtoUpperCase()methodconvertsthis
string into uppercase letter and string
toLowerCase()methodintolowercaseletter.
Java String trim() method
Thestringtrim()methodeliminateswhitespaces
beforeandafterstring.
Java String startsWith() and endsWith()
method
Java String charAt() method
ThestringcharAt()methodreturnsacharacterat
specifiedindex.

Java String length() method


Thestringlength()methodreturnslengthofthe
string.
Java String valueOf() method
ThestringvalueOf()methodcovertsgiventype
suchasint,long,float,double,boolean,charand
chararrayintostring.
inta=10;
Strings=String.valueOf(a);
System.out.println(s+10);

Java String replace() method


Thestringreplace()methodreplacesall
occurrenceoffirstsequenceofcharacterwith
secondsequenceofcharacter.
Strings1="Javaisaprogramminglanguage.Java
isaplatform.JavaisanIsland.";
StringreplaceString=s1.replace("Java","Kava);
System.out.println(replaceString);

Java StringBuffer class


JavaStringBufferclassisusedtocreatedmutable
(modifiable)string.TheStringBufferclassinjavais
sameasStringclassexceptitismutablei.e.itcan
bechanged.
Java StringBuffer class is
thread-safe i.e. multiple
threads cannot access it
simultaneously.
StringBuffer():createsanemptystringbuffer
withtheinitialcapacityof16.
StringBuffer(String str):createsastringbuffer
withthespecifiedstring.
StringBuffer(int capacity):createsanempty
stringbufferwiththespecifiedcapacityaslength.

classA{
publicstaticvoidmain(Stringargs[]){
StringBuffersb=newStringBuffer("Hello");
sb.append("Java");//noworiginalstringischanged
System.out.println(sb);//printsHelloJava
}
}
classA{
publicstaticvoidmain(Stringargs[]){
StringBuffersb=newStringBuffer("Hello");
sb.insert(1,"Java");//noworiginalstringischanged
System.out.println(sb);//printsHJavaello
}
}

Difference between String and


StringBuffer
No.

String

StringBuffer

1)

Stringclassisimmutable.

StringBufferclassismutable.

2)

Stringisslowandconsumesmore StringBufferisfastandconsumesless
memorywhenyouconcattoomany memorywhenyoucancatstrings.
stringsbecauseeverytimeit
createsnewinstance.

3)

Stringclassoverridestheequals() StringBufferclassdoesn'toverridethe
methodofObjectclass.Soyoucan equals()methodofObjectclass.
comparethecontentsoftwostrings
byequals()method.

S-ar putea să vă placă și