Sei sulla pagina 1di 35

1

Java String Methods


All String Methods
The String class has a set of built-in methods that you can use on strings.

Method Description Return Type

charAt() Returns the character at the specified index (position) char

codePointAt() Returns the Unicode of the character at the specified index int

codePointBefore( Returns the Unicode of the character before the specified index int
)

codePointCount() Returns the Unicode in the specified text range of this String int

compareTo() Compares two strings lexicographically int

compareToIgnore Compares two strings lexicographically, ignoring case differences int


Case()

concat() Appends a string to the end of another string String

contains() Checks whether a string contains a sequence of characters boolean

contentEquals() Checks whether a string contains the exact same sequence of characters boolean
of the specified
CharSequence or StringBuffer

copyValueOf() Returns a String that represents the characters of the character array String

endsWith() Checks whether a string ends with the specified character(s) boolean

equals() Compares two strings. Returns true if the strings are equal, and false if boolean
not

equalsIgnoreCase Compares two strings, ignoring case considerations boolean


()

format() Returns a formatted string using the specified locale, format string, and String
arguments

getBytes() Encodes this String into a sequence of bytes using the named charset, byte[]
storing the result into a
new byte array

getChars() Copies characters from a string to an array of chars void

hashCode() Returns the hash code of a string int


2

indexOf() Returns the position of the first found occurrence of specified characters int
in a string

intern() Returns the index within this string of the first occurrence of the specified String
character, starting
the search at the specified index

isEmpty() Checks whether a string is empty or not boolean

lastIndexOf() Returns the position of the last found occurrence of specified characters int
in a string

length() Returns the length of a specified string int

matches() Searches a string for a match against a regular expression, and returns the boolean
matches

offsetByCodePoi Returns the index within this String that is offset from the given index by int
nts() codePointOffset code points

regionMatches() Tests if two string regions are equal boolean

replace() Searches a string for a specified value, and returns a new string where the String
specified values are replaced

replaceFirst() Replaces the first occurrence of a substring that matches the given regular String
expression with the given replacement

replaceAll() Replaces each substring of this string that matches the given regular String
expression with the given replacement

split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with specified characters boolean

subSequence() Returns a new character sequence that is a subsequence of this sequence CharSequence

substring() Extracts the characters from a string, beginning at a specified start String
position, and through the specified number of character

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a string String

valueOf() Returns the primitive value of a String object String


3

Java String
In Java, string is basically an object that represents sequence of char values. An array of characters works

same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";

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.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and

StringBuilder classes implement it. It means, we can create strings in java by using these three classes.

The Java String is immutable which means it cannot be changed. Whenever we change any string, a new

instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.

We will discuss immutable string later. Let's first understand what is String in Java and how to create the

String object.
4

What is String in java


Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of

characters. The java.lang.String class is used to create a string object.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already

exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool,

a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string object with the

value "Welcome" in string constant pool, that is why it will create a new object. After that it will find the

string with the value "Welcome" in the pool, it will not create a new object but will return the reference to

the same instance.

Note: String objects are stored in a special memory area known as the "string constant pool".

Why Java uses the concept of String literal?


5

To make Java more memory efficient (because no new objects are created if it exists already in the string

constant pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in 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 a heap

(non-pool).

Java String Example


1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
Test it Now

java
strings
example

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of char values.

No. Method Description

1 char charAt(int index) returns char value for the particular index
6

2 int length() returns string length

3 static String returns a formatted string.


format(String format,
Object... args)

4 static String returns formatted string with given locale.


format(Locale l, String
format, Object... args)

5 String substring(int returns substring for given begin index.


beginIndex)

6 String substring(int returns substring for given begin index and end index.
beginIndex, int
endIndex)

7 boolean returns true or false after matching the sequence of char value.
contains(CharSequence
s)

8 static String returns a joined string.


join(CharSequence
delimiter,
CharSequence...
elements)

9 static String returns a joined string.


join(CharSequence
delimiter, Iterable<?
extends CharSequence>
elements)

10 boolean equals(Object checks the equality of string with the given object.
another)

11 boolean isEmpty() checks if string is empty.


7

12 String concat(String str) concatenates the specified string.

13 String replace(char old, replaces all occurrences of the specified char value.
char new)

14 String replaces all occurrences of the specified CharSequence.


replace(CharSequence
old, CharSequence new)

15 static String compares another string. It doesn't check case.


equalsIgnoreCase(String
another)

16 String[] split(String returns a split string matching regex.


regex)

17 String[] split(String returns a split string matching regex and limit.


regex, int limit)

18 String intern() returns an interned string.

19 int indexOf(int ch) returns the specified char value index.

20 int indexOf(int ch, int returns the specified char value index starting with given index.
fromIndex)

21 int indexOf(String returns the specified substring index.


substring)

22 int indexOf(String returns the specified substring index starting with given index.
substring, int
fromIndex)

23 String toLowerCase() returns a string in lowercase.


8

24 String returns a string in lowercase using specified locale.


toLowerCase(Locale l)

25 String toUpperCase() returns a string in uppercase.

26 String returns a string in uppercase using specified locale.


toUpperCase(Locale l)

27 String trim() removes beginning and ending spaces of this string.

28 static String valueOf(int converts given type into string. It is an overloaded method.
value)

Do You Know?

o Why are String objects immutable?


o How to create an immutable class?
o What is string constant pool?
o What code is written by the compiler if you concatenate any string by + (string concatenation
o operator)?
o What is the difference between StringBuffer and StringBuilder class?

What will we learn in String Handling?


o Concept of String
o Immutable String
o String Comparison
o String Concatenation
o Concept of Substring
o String class methods and its usage
o StringBuffer class
o StringBuilder class
o Creating Immutable class
o toString() method
o StringTokenizer class
9

Java String compare


We can compare string in java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo()


method), reference matching (by == operator) etc.

There are three ways to compare string in java:

1. By equals() method
2. By = = operator
3. By compareTo() method

1) String compare by equals() method


The String equals() method compares the original content of the string. It compares values
of string for equality. String class provides two methods:

o public boolean equals(Object another) compares this string to the specified


object.
o public boolean equalsIgnoreCase(String another) compares this String to
another string, ignoring case.

1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }
Output:true
true
false
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
10

6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s2));//true
8. }
9. }

Output:

false
true
Click here for more about equals() method

2) String compare by == operator


The = = operator compares references not values.

1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }
Output:true
false

3) 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 greater than second string.

Suppose s1 and s2 are two string variables. If:

o s1 == s2 :0
o s1 > s2 :positive value
o s1 < s2 :negative value

1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
11

9. }
10. }
Output:0
1
-1

String Concatenation in Java


In java, string concatenation forms a new string that is the combination of multiple
strings. There are two ways to concat string in java:

1. By + (string concatenation) operator


2. By concat() method

1) String Concatenation by + (string concatenation)


operator
Java string concatenation operator (+) is used to add strings. For Example:

1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }
Output:Sachin Tendulkar

The Java compiler transforms above code to this:

1. String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

In java, String concatenation is implemented through the StringBuilder (or


StringBuffer) class and its append method. String concatenation operator produces a
new string by appending the second operand onto the end of the first operand. The
string concatenation operator can concat not only string but primitive values also. For
Example:

1. class TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }
80Sachin4040
12

Note: After a string literal, all the + will be treated as string concatenation operator.

2) String Concatenation by concat() method

The String concat() method concatenates the specified string to the end of current
string. Syntax:

1. public String concat(String another)

Let's see the example of String concat() method.

1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8. }
Sachin Tendulkar

Substring in Java
A part of string is called substring. In other words, substring is a subset of another string.
In case of substring startIndex is inclusive and endIndex is exclusive.

Note: Index starts from 0.

You can get substring from the given string object by one of the two methods:

1. public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex, int endIndex): This method returns
new String object containing the substring of the given string from specified
startIndex to endIndex.

In case of string:

o startIndex: inclusive
o endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

1. String s="hello";
13

2. System.out.println(s.substring(0,2));//he

In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example of java substring


1. public class TestSubstring{
2. public static void main(String args[]){
3. String s="SachinTendulkar";
4. System.out.println(s.substring(6));//Tendulkar
5. System.out.println(s.substring(0,6));//Sachin
6. }
7. }
Tendulkar
Sachin

Java String class methods


The java.lang.String class provides a lot of methods to work on string. By the help of these
methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a string if you submit
any form in window based, web based or mobile application.

Let's see the important methods of String class.

Java String toUpperCase() and toLowerCase() method


The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

1. String s="Sachin";
2. System.out.println(s.toUpperCase());//SACHIN
3. System.out.println(s.toLowerCase());//sachin
4. System.out.println(s);//Sachin(no change in original)
SACHIN
sachin
Sachin

Java String trim() method


The string trim() method eliminates white spaces before and after string.

1. String s=" Sachin ";


2. System.out.println(s);// Sachin
3. System.out.println(s.trim());//Sachin
Sachin
Sachin

Java String startsWith() and endsWith() method


1. String s="Sachin";
14

2. System.out.println(s.startsWith("Sa"));//true
3. System.out.println(s.endsWith("n"));//true
true
true

Java String charAt() method


The string charAt() method returns a character at specified index.

1. String s="Sachin";
2. System.out.println(s.charAt(0));//S
3. System.out.println(s.charAt(3));//h
S
h

Java String length() method


The string length() method returns length of the string.

1. String s="Sachin";
2. System.out.println(s.length());//6
6

Java String intern() method


A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String
object as determined by the equals(Object) method, then the string from the pool is
returned. Otherwise, this String object is added to the pool and a reference to this String
object is returned.

1. String s=new String("Sachin");


2. String s2=s.intern();
3. System.out.println(s2);//Sachin
Sachin

Java String valueOf() method


The string valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into string.

1. int a=10;
2. String s=String.valueOf(a);
3. System.out.println(s+10);

Output:

1010
15

Java String replace() method


The string replace() method replaces all occurrence of first sequence of character with
second sequence of character.

1. String s1="Java is a programming language. Java is a platform. Java is an Island.";


2. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "K
ava"
3. System.out.println(replaceString);

Output:

Kava is a programming language. Kava is a platform. Kava is an Island.

Java StringBuffer class


Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Important Constructors of StringBuffer class


Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.

Important methods of StringBuffer class


Modifier and Method Description
Type

public append(String s) is used to append the specified string with


synchronized
this string. The append() method is
StringBuffer

overloaded like append(char), append(boolean),


16

append(int), append(float), append(double) etc.

public insert(int offset, is used to insert the specified string with this
synchronized String s)
string at the specified position. The insert() method
StringBuffer
is overloaded like insert(int, char), insert(int, boolean)

insert(int, int), insert(int, float), insert(int, double) etc

public replace(int is used to replace the string from specified startIndex


synchronized startIndex, int
and endIndex.
StringBuffer endIndex, String
str)

public delete(int is used to delete the string from specified startIndex


synchronized startIndex, int
and endIndex.
StringBuffer endIndex)

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity(in is used to ensure the capacity at least equal to the
t
given minimum.
minimumCapacity
)

public char charAt(int index) is used to return the character at the specified

position.

public int length() is used to return the length of the string i.e. total

number of characters.

public String substring(int is used to return the substring from the specified
beginIndex)
17

beginIndex.

public String substring(int is used to return the substring from the specified
beginIndex, int
beginIndex and endIndex.
endIndex)

What is mutable string


A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

1) StringBuffer append() method


The append() method concatenates the given argument with this string.

1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

2) StringBuffer insert() method


The insert() method inserts the given string with this string at the given position.

1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }

3) StringBuffer replace() method


The replace() method replaces the given string from the specified beginIndex and
endIndex.

1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
18

6. }
7. }

4) StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified beginIndex
to endIndex.

1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }

5) StringBuffer reverse() method


The reverse() method of StringBuilder class reverses the current string.

1. class StringBufferExample5{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }

6) StringBuffer capacity() method


The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.

1. class StringBufferExample6{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }

7) StringBuffer ensureCapacity() method


The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
19

capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be


(16*2)+2=34.

1. class StringBufferExample7{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }

Java StringBuilder class


Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is
available since JDK 1.5.

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() creates an empty string Builder with the initial capacity of 16.

StringBuilder(String str) creates a string Builder with the specified string.

StringBuilder(int length) creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

Method Description

public StringBuilder append(String s) is used to append the specified string with this string.

The append() method is overloaded like append(char),


20

append(boolean), append(int), append(float), append(do

public StringBuilder insert(int offset, is used to insert the specified string with this string at
String s)
the specified position. The insert() method is

overloaded like insert(int, char), insert(int, boolean),

insert(int, int), insert(int, float), insert(int, double) etc.

public StringBuilder replace(int is used to replace the string from specified startIndex
startIndex, int endIndex, String str)
and endIndex.

public StringBuilder delete(int is used to delete the string from specified startIndex
startIndex, int endIndex)
and endIndex.

public StringBuilder reverse() is used to reverse the string.

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity)
minimum.

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total numbe

public String substring(int is used to return the substring from the specified
beginIndex)
beginIndex.

public String substring(int is used to return the substring from the specified
beginIndex, int endIndex)
beginIndex and endIndex.

Java StringBuilder Examples


Let's see the examples of different methods of StringBuilder class.
21

1) StringBuilder append() method


The StringBuilder append() method concatenates the given argument with this string.

1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

2) StringBuilder insert() method


The StringBuilder insert() method inserts the given string with this string at the given
position.

1. class StringBuilderExample2{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }

3) StringBuilder replace() method


The StringBuilder replace() method replaces the given string from the specified beginIndex
and endIndex.

1. class StringBuilderExample3{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

4) StringBuilder delete() method


The delete() method of StringBuilder class deletes the string from the specified beginIndex
to endIndex.

1. class StringBuilderExample4{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
22

7. }

5) StringBuilder reverse() method


The reverse() method of StringBuilder class reverses the current string.

1. class StringBuilderExample5{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }

6) StringBuilder capacity() method


The capacity() method of StringBuilder class returns the current capacity of the Builder.
The default capacity of the Builder is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.

1. class StringBuilderExample6{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }

7) StringBuilder ensureCapacity() method


The ensureCapacity() method of StringBuilder class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.

1. class StringBuilderExample7{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
23

11. sb.ensureCapacity(50);//now (34*2)+2


12. System.out.println(sb.capacity());//now 70
13. }
14. }

Difference between String and StringBuffer


There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:

No. String

1) String class is immutable.

2) String is slow and consumes more memory when you concat too many strings because every
it creates new instance.

3) String class overrides the equals() method of Object class. So you can compare the conten
two strings by equals() method.

Performance Test of String and StringBuffer


1. public class ConcatTest{
2. public static String concatWithString() {
3. String t = "Java";
4. for (int i=0; i<10000; i++){
5. t = t + "Tpoint";
6. }
7. return t;
8. }
9. public static String concatWithStringBuffer(){
10. StringBuffer sb = new StringBuffer("Java");
11. for (int i=0; i<10000; i++){
12. sb.append("Tpoint");
13. }
14. return sb.toString();
15. }
16. public static void main(String[] args){
17. long startTime = System.currentTimeMillis();
18. concatWithString();
19. System.out.println("Time taken by Concating with String: "+(System.currentTimeM
illis()-startTime)+"ms");
24

20. startTime = System.currentTimeMillis();


21. concatWithStringBuffer();
22. System.out.println("Time taken by Concating with StringBuffer: "+(System.curren
tTimeMillis()-startTime)+"ms");
23. }
24. }
Time taken by Concating with String: 578ms
Time taken by Concating with StringBuffer: 0ms

String and StringBuffer HashCode Test


As you can see in the program given below, String returns new hashcode value when you
concat string but StringBuffer returns same.

1. public class InstanceTest{


2. public static void main(String args[]){
3. System.out.println("Hashcode test of String:");
4. String str="java";
5. System.out.println(str.hashCode());
6. str=str+"tpoint";
7. System.out.println(str.hashCode());
8.
9. System.out.println("Hashcode test of StringBuffer:");
10. StringBuffer sb=new StringBuffer("java");
11. System.out.println(sb.hashCode());
12. sb.append("tpoint");
13. System.out.println(sb.hashCode());
14. }
15. }
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462

Difference between StringBuffer and


StringBuilder
Java provides three classes to represent a sequence of characters: String, StringBuffer,
and StringBuilder. The String class is an immutable class whereas StringBuffer and
StringBuilder classes are mutable. There are many differences between StringBuffer and
StringBuilder. The StringBuilder class is introduced since JDK 1.5.

A list of differences between StringBuffer and StringBuilder are given below:

No. StringBuffer StringBuilder


25

1) StringBuffer StringBuilder is non-synchronized i.e. not thread safe.


is synchronized i.e. thread It means two threads can call the methods of StringBuilder
safe. It means two threads simultaneously.
can't call the methods of
StringBuffer simultaneously.

2) StringBuffer is less StringBuilder is more efficient than StringBuffer.


efficient than StringBuilder.

StringBuffer Example
1. //Java Program to demonstrate the use of StringBuffer class.
2. public class BufferTest{
3. public static void main(String[] args){
4. StringBuffer buffer=new StringBuffer("hello");
5. buffer.append("java");
6. System.out.println(buffer);
7. }
8. }
hellojava

StringBuilder Example
1. //Java Program to demonstrate the use of StringBuilder class.
2. public class BuilderTest{
3. public static void main(String[] args){
4. StringBuilder builder=new StringBuilder("hello");
5. builder.append("java");
6. System.out.println(builder);
7. }
8. }
hellojava

Performance Test of StringBuffer and StringBuilder


Let's see the code to check the performance of StringBuffer and StringBuilder classes.

1. //Java Program to demonstrate the performance of StringBuffer and StringBuilder classe


s.
2. public class ConcatTest{
3. public static void main(String[] args){
4. long startTime = System.currentTimeMillis();
26

5. StringBuffer sb = new StringBuffer("Java");


6. for (int i=0; i<10000; i++){
7. sb.append("Tpoint");
8. }
9. System.out.println("Time taken by StringBuffer: " + (System.currentTimeMill
is() - startTime) + "ms");
10. startTime = System.currentTimeMillis();
11. StringBuilder sb2 = new StringBuilder("Java");
12. for (int i=0; i<10000; i++){
13. sb2.append("Tpoint");
14. }
15. System.out.println("Time taken by StringBuilder: " + (System.currentTimeMi
llis() - startTime) + "ms");
16. }
17. }
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms

…………………………………………….

W3school

Java is one of the popular general-purpose programming languages which is


concurrent, have classes & objects and also provide codes to set up in modules
so that some codes can be re-used and specifically intended to let your
applications "write once, run anywhere" (WORA) feature.

Table of Contents

1. Methods in Java

2. Types of Methods

3. The syntax for Creating methods in Java

4. Calling Methods in Java

5. Passing Parameters

6. Passing Parameters by Value

Methods in Java
Java methods are an assortment of statements clustered together for performing
an operation. When you call any pre-defined function such as toString(), a series
of logical stepwise set of codes run in the background which is already stored and
made ready in the library. In other words, methods in Java are containers in which
27

you can put, for different operations on different data (which are variables) to carry
out a specific task in your Java code. Also, you can group Java operations
providing a name which will be the name of the method.

It is to be noted that Java methods must have to be located within a Java class.
Java methods are similar to what you call functions and procedures in languages
like JavaScript, C, Pascal, etc.). A Java method is a single or a collection of Java
statement(s) performing some action or tasks on some data (variables) which may
or may not return any end result.

Types of Methods
Methods can be of two broad categories. These are:

• Standard Library Methods


• User-defined Methods

These classifications are being made based on whether the Java method is defined
by the programmer or available and pre-existing in Java's standard library or
additional libraries.

Some examples of Standard libraries are:

• print() method comes under java.io.PrintSteam which prints the string that is
written within the quotation.
• sqrt() is a method of Math class which returns the square root of that specific
number.

The syntax for Creating methods in Java


Syntax:

modifier returnType NameofMethod(Parameter List) {

// method body

Example:

public static int funie(int g, int d) {

// body of the method


28

Here, public static are modifiers where: public sets the visibility of the method,
statics used so that this method is shared among all instances of the class it
belongs to; int specifies the type of value method will return, i.e. the return
type; funie is the name of method used here, g and d is the formal parameters' list
of type integer.

Calling Methods in Java


Methods won't be going to perform anything until and unless you call them on a
specific part of your program to do some action. In other words, to use method(s),
programmers should call them by the method name. Two approaches are there to
call a method. One, where a method returns a value and the other where methods
do not return anything (i.e., no return value). Here are two examples shows two
different ways of calling methods:

• Ex: System.out.println("Hello, Methods, I do not return anything");


• int output = fun(2, 6);
Example:
public class Example {

public static void main(String argu[]) {

int val1 = 62;

int val2 = 8;

int res = fun(val1, val2);

System.out.println("Result is: " + res);

public static int fun(int g1, int g2) {

int ans;

ans = g1 + g2;

return ans;

}
29

Example:

Result is: 70

Passing Parameters
Parameters can be passed in two ways: by value or by reference. In this section,
you will study about this:

Passing Parameters by Value


In the above example, you have seen the arguments having values are passed the
unction. These arguments must have to be in the same sequence as their
respective parameters defined in method specification. Passing parameters using
value(s) means calling a method with the help of parameter.

Example:

public void swapping(int s1, int s2) {

int temp = s1;

s1 = s2;

s2 = temp;

Alternatively other than pass by value, you can use pass by reference which
represents the aliasing of data and changes done in aliased value gets reflected
your original value. In case of passing by reference, any changes done on a value
within different scope gets preserved even when the scope is exited.

Example:

public class AnotherExample {

public void printOut(StringBuffer str2) {

str2.append("Reference");

System.out.println(str2); // prints passBy reference


30

public static void main(String argu[]) {

AnotherExample ae = new AnotherExample();

StringBuffer str1 = new StringBuffer("passBy ");

ae.printOut(str1);

System.out.println(str1); // prints passBy reference

Value of reference-object in str1 is passed to str2. Now, the reference value of str1
and str2 refers to the same object.

Parameter Passing Techniques in Java with Examples


There are different ways in which parameter data can be passed into and out
of methods and functions. Let us assume that a function B() is called from another
function A(). In this case A is called the “caller function” and B is called the “called
function or callee function”. Also, the arguments which A sends to B are
called actual arguments and the parameters of B are called formal arguments.
Types of parameters:
• Formal Parameter : A variable and its type as they appear in the prototype of
the function or method.
Syntax:
function_name(datatype variable_name)
• Actual Parameter : The variable or expression corresponding to a formal
parameter that appears in the function or method call in the calling environment.
Syntax:
func_name(variable name(s));
Important methods of Parameter Passing
1. Pass By Value: Changes made to formal parameter do not get transmitted
back to the caller. Any modifications to the formal parameter variable inside the
called function or method affect only the separate storage location and will not
be reflected in the actual parameter in the calling environment. This method is
also called as call by value.
Java in fact is strictly call by value.
31

Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate
// Call by Value

// Callee
class CallByValue {

// Function to change the value


// of the parameters
public static void Example(int x, int y)
{
x++;
y++;
}
}

// Caller
public class Main {
public static void main(String[] args)
{

int a = 10;
int b = 20;

// Instance of class is created


CallByValue object = new CallByValue();

System.out.println("Value of a: " + a
+ " & b: " + b);

// Passing variables in the class function


object.Example(a, b);

// Displaying values after


32

// calling the function


System.out.println("Value of a: "
+ a + " & b: " + b);
}
}
Output:
Value of a: 10 & b: 20
Value of a: 10 & b: 20
Shortcomings:
• Inefficiency in storage allocation
• For objects and arrays, the copy semantics are costly
2. Call by reference(aliasing): Changes made to formal parameter do get
transmitted back to the caller through parameter passing. Any changes to the
formal parameter are reflected in the actual parameter in the calling
environment as formal parameter receives a reference (or pointer) to the actual
data. This method is also called as <em>call by reference. This method is
efficient in both time and space.

filter_none
edit
play_arrow
brightness_4
// Java program to illustrate
// Call by Reference

// Callee
class CallByReference {

int a, b;

// Function to assign the value


// to the class variables
CallByReference(int x, int y)
{
a = x;
33

b = y;
}

// Changing the values of class variables


void ChangeValue(CallByReference obj)
{
obj.a += 10;
obj.b += 20;
}
}

// Caller
public class Main {

public static void main(String[] args)


{

// Instance of class is created


// and value is assigned using constructor
CallByReference object
= new CallByReference(10, 20);

System.out.println("Value of a: "
+ object.a
+ " & b: "
+ object.b);

// Changing values in class function


object.ChangeValue(object);

// Displaying values
// after calling the function
System.out.println("Value of a: "
+ object.a
+ " & b: "
+ object.b);
}
}
Output:
Value of a: 10 & b: 20
Value of a: 20 & b: 40
Please note that when we pass a reference, a new reference variable to the
same object is created. So we can only change members of the object whose
reference is passed. We cannot change the reference to refer to some other
object as the received reference is a copy of the original reference. Please see
example 2 in Java is Strictly Pass by Value!

Call by Value and Call by Reference in Java


There is only call by value in java, not call by reference. If we call a method passing a value, it is
known as call by value. The changes being done in the called method, is not affected in the calling
method.

Example of call by value in java


34

In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }

download this example


Output:before change 50
after change 50

Another Example of call by value in java


In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed.
In this example we are passing object as a value. Let's take a simple example:

1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:before change 50
after change 150
35

Potrebbero piacerti anche