[go: up one dir, main page]

0% found this document useful (0 votes)
11 views62 pages

4 Strings

Uploaded by

RAJASEKHAR V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views62 pages

4 Strings

Uploaded by

RAJASEKHAR V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

1

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:

char[] ch={'J','a','v','a',' ','C','l',a','s','s'};


String s=new String(ch);

is same as:

String s="Java Class";

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
2

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?

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


StringExample.java

public class StringExample{


3

public static void main(String args[]){


String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

Output:

java
strings
example

The above code, converts a char array into a String object. And displays the String objects s1, s2,
and s3 on console using println() method.

String Constructors in Java


1. String(byte[] byte_arr)

Construct a new String by decoding the byte array. It uses the platform’s default character
set for decoding.
Example:

byte[] b_arr = {71, 101, 101, 107, 115};


String s_byte =new String(b_arr); //Geeks
2. String(byte[] byte_arr, Charset char_set)
Construct a new String by decoding the byte array. It uses the char_set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s_byte_char = new String(b_arr, cs); //Geeks
3. String(byte[] byte_arr, String char_set_name)
Construct a new String by decoding the byte array. It uses the char_set_name for decoding. It looks
similar to the above constructs and they appear before similar functions but it takes the String(which
contains char_set_name) as parameter while the above constructor takes CharSet.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, "US-ASCII"); //Geeks
4. String(byte[] byte_arr, int start_index, int length)
Construct a new string from the bytes array depending on the start_index(Starting
location) and length(number of characters from starting location).
4

Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 3); // eek
5. String(byte[] byte_arr, int start_index, int length, Charset char_set)
Construct a new string from the bytes array depending on the start_index(Starting
location) and length(number of characters from starting location).Uses char_set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s = new String(b_arr, 1, 3, cs); // eek
6. String(byte[] byte_arr, int start_index, int length, String char_set_name)
Construct a new string from the bytes array depending on the start_index(Starting
location) and length(number of characters from starting location).Uses char_set_name for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks
7. String(char[] char_arr)
Allocates a new String from the given Character array
Example:
char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr); //Geeks
8. String(char[] char_array, int start_index, int count)
Allocates a String from a given character array but choose count characters from the start_index.
Example:
char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr , 1, 3); //eek
9. String(int[] uni_code_points, int offset, int count)
Allocates a String from a uni_code_array but choose count characters from the start_index.
Example:
int[] uni_code = {71, 101, 101, 107, 115};
String s = new String(uni_code, 1, 3); //eek
10. String(StringBuffer s_buffer)
Allocates a new string from the string in s_buffer
Example:
StringBuffer s_buffer = new StringBuffer("Geeks");
String s = new String(s_buffer); //Geeks
11. String(StringBuilder s_builder)
Allocates a new string from the string in s_builder
Example:
StringBuilder s_builder = new StringBuilder("Geeks");
String s = new String(s_builder); //Geeks

String Methods in Java


1. int length()
Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
2. Char charAt(int i)
Returns the character at ith index.
5

"GeeksforGeeks".charAt(3); // returns ‘k’


3. String substring (int i)
Return the substring from the ith index character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
4. String substring (int i, int j)
Returns the substring from i to j-1 index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
5. String concat( String str)
Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
6. int indexOf (String s)
Returns the index within the string of the first occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.
1. String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1
7. int indexOf (String s, int i)
Returns the index within the string of the first occurrence of the specified string, starting at the
specified index.
String s = ”Learn Share Learn”;
int output = s.indexOf("ea",3);// returns 13
8. Int lastIndexOf( String s)
Returns the index within the string of the last occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.
1. String s = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1
9. boolean equals( Object otherObj)
Compares this string to the specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
10. boolean equalsIgnoreCase (String anotherString)
Compares string to another string, ignoring case considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
11. int compareTo( String anotherString)
Compares two string lexicographically.
int out = s1.compareTo(s2);
// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
12. int compareToIgnoreCase( String anotherString)
Compares two string lexicographically, ignoring case considerations.
6

int out = s1.compareToIgnoreCase(s2);


// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
Note: In this case, it will not consider case of a letter (it will ignore whether it is uppercase or
lowercase).
13. String toLowerCase()
Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
14. String toUpperCase()
Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
15. String trim()
Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces
in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
16. String replace (char oldChar, char newChar)
Returns new string by replacing all occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // return “geeksforgeeks”
Note: s1 is still feeksforfeeks and s2 is geeksgorgeeks
17. boolean contains(string) :
Returns true if string contains contains the given string
String s1="geeksforgeeks";
String s2="geeks";
s1.contains(s2) // return true

18. Char[] toCharArray():


Converts this String to a new character array.
String s1="geeksforgeeks";
char []ch=s1.toCharArray(); // returns [ 'g', 'e' , 'e' , 'k' , 's' , 'f', 'o', 'r'
, 'g' , 'e' , 'e' , 'k' ,'s' ]
19. boolean starsWith(string):
Return true if string starts with this prefix.
String s1="geeksforgeeks";
String s2="geeks";
s1.startsWith(s2) // return true
Example of String Constructor and String Methods
Below is the implementation of the above mentioned topic:

// Java code to illustrate different constructors and methods


// String class.
import java.io.*;
7

import java.util.*;

// Driver Class
class Test
{
// main function
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");

// Returns the number of characters in the String.


System.out.println("String length = " + s.length());

// Returns the character at ith index.


System.out.println("Character at 3rd position = "
+ s.charAt(3));

// Return the substring from the ith index character


// to end of string
System.out.println("Substring " + s.substring(3));

// Returns the substring from i to j-1 index.


System.out.println("Substring = " + s.substring(2,5));

// Concatenates string2 to the end of string1.


String s1 = "Geeks";
String s2 = "forGeeks";
System.out.println("Concatenated string = " +
s1.concat(s2));

// Returns the index within the string


// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " +
s4.indexOf("Share"));

// Returns the index within the string of the


// first occurrence of the specified string,
// starting at the specified index.
System.out.println("Index of a = " +
s4.indexOf('a',3));

// Checking equality of Strings


Boolean out = "Geeks".equals("geeks");
System.out.println("Checking Equality " + out);
8

out = "Geeks".equals("Geeks");
System.out.println("Checking Equality " + out);

out = "Geeks".equalsIgnoreCase("gEeks ");


System.out.println("Checking Equality " + out);

//If ASCII difference is zero then the two strings are similar
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is="+out1);
// Converting cases
String word1 = "GeeKyMe";
System.out.println("Changing to lower Case " +
word1.toLowerCase());

// Converting cases
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " +
word2.toUpperCase());

// Trimming the word


String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());

// Replacing characters
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
}
}
Output
String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality ...
9

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) It returns char value for the particular


index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, Object... It returns formatted string with given
args) locale.

5 String substring(int beginIndex) It returns substring for given begin


index.

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

7 boolean contains(CharSequence s) It returns true or false after matching


the sequence of char value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, Iterable<? It returns a joined string.


extends CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with the


10

given object.

11 boolean isEmpty() It checks if string is empty.

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

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the


specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It doesn't


check case.

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

17 String[] split(String regex, int limit) It returns a split string matching regex
and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value


index.

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

21 int indexOf(String substring) It returns the specified substring index.

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

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using


11

specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using


specified locale.

27 String trim() It removes beginning and ending


spaces of this string.

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


an overloaded method.

Special String Operations with Examples


As we know strings are a common and important part of programming, Java has added special support
for several string operations within the syntax of the language. These operations include the automatic
creation of new String instances from string literals, the concatenation of multiple String objects by use of
the + operator, and the conversion of other data types to a string representation.

There are explicit methods available to perform all of these functions, but Java does them automatically as
a convenience for the programmer and to add clarity.

Let's discuss below Special String Operations with examples.

1. String Literals
2. String Concatenation
3. String Concatenation with Other Data Types
4. String Conversion and toString( )

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

String s="javaguides";

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 a string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
12

String s1="Welcome";
String s2="Welcome";//will not create 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 the string constant pool, so 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.

String objects are stored in a special memory area known as a string constant pool.

2. String Concatenation
In general, Java does not allow operators to be applied to String objects. The one exception to this rule is
the + operator, which concatenates two strings, producing a String object as the result. This allows you to
chain together a series of + operations.

For example, the following fragment concatenates three strings:

String age = "9";


String s = "He is " + age + " years old.";
System.out.println(s);

This displays the string "He is 9 years old."

One practical use of string concatenation is found when you are creating very long strings. Instead of
letting long strings wrap around within your source code, you can break them into smaller pieces, using
the + to concatenate them. Here is an example:

// Using concatenation to prevent long lines.


class ConCat {
public static void main(String args[]) {
String longStr = "This could have been " + "a very long line that would have "
+ "wrapped around. But string concatenation " + "prevents this.";
System.out.println(longStr);
}
}

String provides String java.lang.String.concat(String str) method to concatenate the specified string to the
end of this string.

String java.lang.String.concat(String str)


This method returns a string that represents the concatenation of this object's characters followed by the
string argument's characters.

Example:
13

public class ConcatExmaple {


public static void main(String[] args) {
String str = "javaguides";
str = str.concat(".net");
System.out.println("Concatenates the specified string to the end of this string : " + str);

System.out.println("cares".concat("s"));
System.out.println("to".concat("get"));
}
}

Output:

Concatenates the specified string to the end of this string : javaguides.net


caress
toget

3. String Concatenation with Other Data Types


You can concatenate strings with other types of data. For example, consider this slightly different version
of the earlier example:

int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);

In this case, age is an int rather than another String, but the output produced is the same as before. This is
because the int value in age is automatically converted into its string representation within a String object.
This string is then concatenated as before. The compiler will convert an operand to its string equivalent
whenever the other operand of the + is an instance of a String.

Be careful when you mix other types of operations with string concatenation expressions, however. You
might get surprising results. Consider the following:

String s = "four: " + 2 + 2;


System.out.println(s);

This fragment displays

four: 22

rather than the

four: 4

that you probably expected. Here’s why. Operator precedence causes the concatenation of "four" with the
string equivalent of 2 to take place first. This result is then concatenated with the string equivalent of 2 a
second time. To complete the integer addition first, you must use parentheses, like this:
14

String s = "four: " + (2 + 2);

Now s variable contains the string "four: 4".

4. String Conversion and toString( )


When Java converts data into its string representation during concatenation, it does so by calling one of
the overloaded versions of the string conversion method valueOf( ) defined by String.

valueOf( ) is overloaded for all the primitive types and for the type Object. For the primitive types,
valueOf( ) returns a string that contains the human-readable equivalent of the value with which it is called.
For objects, valueOf( ) calls the toString( ) method on the object.

Let's understand the usage of valueOf() and toString() methods with examples.

valueOf( ) Method
The valueOf( ) method converts data from its internal format into a human-readable form.

The Java string valueOf() method converts different types of values into a string. With the help of the
string valueOf() method, you can convert int to string, long to string, boolean to string, character to string,
float to a string, double to string, object to string, and char array to string.

Here are a few of its forms and the signature or syntax of the string valueOf() method is given below:

public static String valueOf(boolean b)


public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)

Example: Let's see an example where we are converting all primitives and objects into strings.

public class StringValueOfExample5 {


public static void main(String[] args) {
boolean b1=true;
byte b2=11;
short sh = 12;
int i = 13;
long l = 14L;
float f = 15.5f;
double d = 16.5d;
char chr[]={'j','a','v','a'};
StringValueOfExample5 obj=new StringValueOfExample5();
String s1 = String.valueOf(b1);
String s2 = String.valueOf(b2);
String s3 = String.valueOf(sh);
15

String s4 = String.valueOf(i);
String s5 = String.valueOf(l);
String s6 = String.valueOf(f);
String s7 = String.valueOf(d);
String s8 = String.valueOf(chr);
String s9 = String.valueOf(obj);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
System.out.println(s8);
System.out.println(s9);
}
}

Output:

true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55

toString() Method
Every class implements toString( ) because it is defined by Object. However, the default implementation
of toString( ) is seldom sufficient. For the most important classes that you create, you will want to
override toString( ) and provide your own string representations.

Fortunately, this is easy to do. The toString( ) method has this general form:

String toString( )

To implement toString( ), simply return a String object that contains the human-readable string that
appropriately describes an object of your class.

For example, they can be used in print( ) and println( ) statements and in concatenation expressions.

The following program demonstrates this by overriding toString( ) for the Box class:

class Box {
double width;
double height;
double depth;

Box(double w, double h, double d) {


16

width = w;
height = h;
depth = d;
}

public String toString() {


return "Dimensions are " + width + " by " + depth + " by " + height + ".";
}
}

class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
}
}

The output of this program is shown here:

Dimensions are 10.0 by 14.0 by 12.0


Box b: Dimensions are 10.0 by 14.0 by 12.0

As you can see, Box’s toString( ) method is automatically invoked when a Box object is used in a
concatenation expression or in a call to println( ).

String Comparison Methods in Java with Examples

String comparison is a common operation in Java that enables you to determine how two strings are
related to each other. Java provides several methods for comparing strings, each serving different use
cases. In this blog post, we'll explore the main string comparison methods available in Java, along with
examples.

String Comparison Methods in Java

1. Using equals(Object anObject)


Compares this string to the specified object.

Example:

String str1 = "Java";


String str2 = "Java";
boolean result = str1.equals(str2);
// Result: true
17

2. Using equalsIgnoreCase(String str)


Compares this string to another string, ignoring case considerations.

Example:

String str1 = "Java";


String str2 = "java";
boolean result = str1.equalsIgnoreCase(str2);
// Result: true

3. Using regionMatches( )
Test if two string regions are equal.

Example:

String str1 = "Welcome to Java";


boolean result = str1.regionMatches(11, "Java", 0, 4);
// Result: true

4. Using startsWith( ) Method


This method checks if this string starts with the specified prefix.

Example:

String str = "Java Programming";


boolean result = str.startsWith("Java");
// Result: true

5. Using endsWith( ) Method


This method checks if this string ends with the specified suffix.

Example:

String str = "Java Programming";


boolean result = str.endsWith("Programming");
// Result: true
18

6. equals( ) Versus ==
The equals() method compares the content, whereas == compares object references.

Example:

String str1 = new String("Java");


String str2 = new String("Java");
boolean result1 = str1.equals(str2); // true
boolean result2 = (str1 == str2); // false

7. Using compareTo( )
Compares two strings lexicographically.

Example:

String str1 = "Apple";


String str2 = "Banana";
int result = str1.compareTo(str2);
// Result: -1

8. Using compareToIgnoreCase(String str)


Compares two strings lexicographically, ignoring case differences.

Example:

String str1 = "Apple";


String str2 = "apple";
int result = str1.compareToIgnoreCase(str2);
// Result: 0

String Searching Methods in Java with Examples


String handling is one of the most essential concepts in Java, and searching within strings is a common
task. In this post, we'll dive into the various string-searching methods available in Java. These methods
help us locate specific characters, substrings, or patterns within a given string.
19

String Searching Methods in Java with Examples

1. Searching for a Character or Substring


indexOf(int ch) and indexOf(int ch, int fromIndex)
These methods search for the first occurrence of a specified character or substring.

Example:

String str = "JavaGuides";


int index = str.indexOf('a');
// Result: 1

2. Searching for the Last Occurrence


lastIndexOf(int ch) and lastIndexOf(int ch, int fromIndex)
They search for the last occurrence of a specified character or substring, starting from the end of the
string. Again, the fromIndex parameter can specify where the search begins.

Example:

String str = "JavaGuides";


int index = str.lastIndexOf('a');
// Result: 3

3. Checking If a String Contains a Sequence


contains(CharSequence sequence)
This method returns true if the string contains the specified sequence of char values.

Example:

String str = "JavaGuides";


boolean result = str.contains("Guides");
// Result: true
20

4. Checking Prefix and Suffix


startsWith(String prefix) and endsWith(String suffix)
These methods check whether the string starts or ends with the specified prefix or suffix.

Example:

String str = "JavaGuides";


boolean startsWith = str.startsWith("Java");
// Result: true

boolean endsWith = str.endsWith("Guides");


// Result: true

5. Matching Regular Expressions


matches(String regex)
This method tells whether or not the string matches the given regular expression.

Example:

String str = "12345";


boolean result = str.matches("\\d+");
// Result: true

String Modifying Methods with Examples


String modification is an essential task in programming, and Java provides several methods to perform
such operations. While strings in Java are immutable, these methods return new strings with the
modifications applied. In this article, we will see some common string-modifying methods with examples.

String Modifying Methods with Examples

1. concat(String str)
Concatenates the specified string to the end of this string.

String str = "Java";


String result = str.concat("Guides");
// Result: "JavaGuides"
21

2. replace(char oldChar, char newChar)


Replaces all occurrences of a specified character with another character.

String str = "Java";


String result = str.replace('a', 'o');
// Result: "Jovo"

3. substring(int beginIndex) and substring(int


beginIndex, int endIndex)
Returns a substring from the original string.

String str = "JavaGuides";


String result1 = str.substring(4);
// Result: "Guides"

String result2 = str.substring(4, 6);


// Result: "Gu"

4. toLowerCase() and toUpperCase()


Converts the string to lower case or upper case.

String str = "Java";


String lower = str.toLowerCase();
// Result: "java"

String upper = str.toUpperCase();


// Result: "JAVA"

5. trim()
Removes leading and trailing white spaces.

String str = " JavaGuides ";


String result = str.trim();
// Result: "JavaGuides"

6. split(String regex)
Splits the string around matches of the given regular expression.
22

String str = "Java,Guides";


String[] result = str.split(",");
// Result: ["Java", "Guides"]

7. replaceAll(String regex, String replacement)


Replaces each substring that matches the given regular expression with the given replacement.

String str = "JavaGuides";


String result = str.replaceAll("a", "o");
// Result: "JovoGuides"

8. join(CharSequence delimiter, CharSequence...


elements)
Joins the given elements with the specified delimiter.

String result = String.join("-", "Java", "Guides");


// Result: "Java-Guides"

Java String valueOf()

The java string valueOf() method converts different types of values into string. By the help of string
valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float
to string, double to string, object to string and char array to string.

In Java, valueOf() method converts data from its internal form into a human-readable form. It is a static
method that is overloaded within a string for all of Java’s built-in types so that each type can be converted
properly into a string.

It is called when a string representation of some other type of data is needed for example during a
concatenation operation. You can call this method with any data type and get a reasonable String
representation valueOf() returns java.lang.Integer, which is the object representative of the integer.

Internal implementation
1. public static String valueOf(Object obj) {
2. return (obj == null) ? "null" : obj.toString();
3. }
23

Signature

The signature or syntax of string valueOf() method is given below:

1. public static String valueOf(boolean b)


2. public static String valueOf(char c)
3. public static String valueOf(char[] c)
4. public static String valueOf(int i)
5. public static String valueOf(long l)
6. public static String valueOf(float f)
7. public static String valueOf(double d)
8. public static String valueOf(Object o)

Returns

string representation of given value

Java String valueOf() method example


1. public class StringValueOfExample{
2. public static void main(String args[]){
3. int value=30;
4. String s1=String.valueOf(value);
5. System.out.println(s1+10);//concatenating string with 10
6. }}

Output:

3010

String Concatenation in Java


In Java, String concatenation forms a new String that is the combination of multiple strings. There are two
ways to concatenate strings in Java:

1. By + (String concatenation) operator


2. By concat() method

1) String Concatenation by + (String concatenation) operator


24

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

TestStringConcatenation1.java

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 it's
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 concatenate not only String but
primitive values also. For Example:

TestStringConcatenation2.java

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. }

Output:

80Sachin4040

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.


25

TestStringConcatenation3.java

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. }

Output:

Sachin Tendulkar

The above Java program, concatenates two String objects s1 and s2 using concat() method and stores
the result into s3 object.

There are some other possible ways to concatenate Strings in Java,

1. String concatenation using StringBuilder class

StringBuilder is class provides append() method to perform concatenation operation. The append()
method accepts arguments of different types like Objects, StringBuilder, int, char, CharSequence, boolean,
float, double. StringBuilder is the most popular and fastet way to concatenate strings in Java. It is mutable
class which means values stored in StringBuilder objects can be updated or changed.

StrBuilder.java

1. public class StrBuilder


2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. StringBuilder s1 = new StringBuilder("Hello"); //String 1
7. StringBuilder s2 = new StringBuilder(" World"); //String 2
8. StringBuilder s = s1.append(s2); //String 3 to store the result
9. System.out.println(s.toString()); //Displays result
10. }
11. }

Output:
26

Hello World

In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores the result
of concatenation of s1 and s2 using append() method.

2. String concatenation using format() method

String.format() method allows to concatenate multiple strings using format specifier like %s followed by
the string values or objects.

StrFormat.java

1. public class StrFormat


2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. String s1 = new String("Hello"); //String 1
7. String s2 = new String(" World"); //String 2
8. String s = String.format("%s%s",s1,s2); //String 3 to store the result
9. System.out.println(s.toString()); //Displays result
10. }
11. }

Output:

Hello World

Here, the String objects s is assigned the concatenated result of


Strings s1 and s2 using String.format() method. format() accepts parameters as format specifier followed
by String objects or values.

3. String concatenation using String.join() method (Java Version 8+)

The String.join() method is available in Java version 8 and all the above versions. String.join() method
accepts arguments first a separator and an array of String objects.

StrJoin.java:

1. public class StrJoin


2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. String s1 = new String("Hello"); //String 1
27

7. String s2 = new String(" World"); //String 2


8. String s = String.join("",s1,s2); //String 3 to store the result
9. System.out.println(s.toString()); //Displays result
10. }
11. }

Output:

Hello World

In the above code snippet, the String object s stores the result of String.join("",s1,s2) method. A
separator is specified inside quotation marks followed by the String objects or array of String objects.

4. String concatenation using StringJoiner class (Java Version 8+)

StringJoiner class has all the functionalities of String.join() method. In advance its constructor can also
accept optional arguments, prefix and suffix.

StrJoiner.java

1. public class StrJoiner


2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. StringJoiner s = new StringJoiner(", "); //StringeJoiner object
7. s.add("Hello"); //String 1
8. s.add("World"); //String 2
9. System.out.println(s.toString()); //Displays result
10. }
11. }

Output:

Hello, World

In the above code snippet, the StringJoiner object s is declared and the constructor StringJoiner() accepts
a separator value. A separator is specified inside quotation marks. The add() method appends Strings
passed as arguments.

5. String concatenation using Collectors.joining() method (Java (Java Version 8+)

The Collectors class in Java 8 offers joining() method that concatenates the input elements in a similar
order as they occur.
28

ColJoining.java

1. import java.util.*;
2. import java.util.stream.Collectors;
3. public class ColJoining
4. {
5. /* Driver Code */
6. public static void main(String args[])
7. {
8. List<String> liststr = Arrays.asList("abc", "pqr", "xyz"); //List of String array
9. String str = liststr.stream().collect(Collectors.joining(", ")); //performs joining operation
10. System.out.println(str.toString()); //Displays result
11. }
12. }

Output:

abc, pqr, xyz

Here, a list of String array is declared. And a String object str stores the result
of Collectors.joining() method.

StringBuffer append() Method in Java with Examples


The java.lang.StringBuffer.append() method is used to append the string representation
of some argument to the sequence. There are 13 ways/forms in which the append()
method can be used:
1. StringBuffer append(boolean a) :The java.lang.StringBuffer.append(boolean a) is an
inbuilt method in Java which is used to append the string representation of the boolean
argument to a given sequence.
Syntax :
public StringBuffer append( boolean a)
Parameter : This method accepts a single parameter a of boolean type and refers to
the Boolean value to be appended.
Return Value : The method returns a reference to this object.
Examples:
Input:
string_buffer = "I love my Country"
boolean a = true

Output: I love my Country true


Below program illustrates the java.lang.StringBuffer.append() method:
29

// Java program to illustrate the

// StringBuffer append(boolean a)

import java.lang.*;

public class Geeks {


public static void main(String[] args)
{
StringBuffer sbf1 = new StringBuffer("We are geeks and its really ");
System.out.println("Input: " + sbf1);

// Appending the boolean value


sbf1.append(true);
System.out.println("Output: " + sbf1);

System.out.println();

StringBuffer sbf2 = new StringBuffer("We are lost - ");


System.out.println("Input: " + sbf2);

// Appending the boolean value


sbf2.append(false);
System.out.println("Output: " + sbf2);
}

}
Output:
Input: We are geeks and its really
Output: We are geeks and its really true

String valueOf() in Java


String valueOf() method is present in the String class
of java.lang package. valueOf() in Java is used to convert any non-String variable or
Object such as int, double, char, and others to a newly created String object. It
returns the string representation of the argument passed.

Syntax of valueOf() in Java


The following two signatures are possible:
30

String valueOf(T);

String valueOf(char[], int, int)

The first signature takes in a data type like int and returns a String object. The other possible data
types of T are explained in the parameters section.

The second signature takes in a character array and two other integers, which we will discuss in
the parameters section.

The syntax of valueOf() is as follows:

String s = String.valueOf(inti);

String s = String.valueOf(char c);

String s = String.valueOf(float f);

String s = String.valueOf(double d);

String s = String.valueOf(boolean b);

String s = String.valueOf(inti);

String s = String.valueOf(Object o);

String s = String.valueOf(char[] c);

String s = String.valueOf(char[] data, int offset, int count)

As per the first method signature, T can be:

 boolean
 int
 long
 float
 double
 char
 char[]
 Object

For the second method-signature parameters are char array, offset and count.

 offset is the starting index in the case of a char array


 count is the number of characters to be considered in the sub-array starting with offset
31

The return type is a String class object.

Exceptions of valueOf() in Java


The only exception valueOf() can throw is IndexOutOfBoundsException in the second signature
if:

 offset is negative
 count is negative
 count + offset is greater than the length of the char array

If, instead of int, some other data type is passed, or the number of parameters is less or more than
expected, we will get a compile-time error.

Example of valueof() in Java


class Example {

public static void main(String args[]) {

String s = String.valueOf(5); // converts 5 to string Object

System.out.println(s); // prints 5

Output:

Java String join()


The Java String class join() method returns a string joined with a given delimiter. In the
String join() method, the delimiter is copied for each element. The join() method is
included in the Java string since JDK 1.8.

There are two types of join() methods in the Java String class.

Signature
The signature or syntax of the join() method is given below:
32

1. public static String join(CharSequence delimiter, CharSequence... elements)


2. and
3. public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

Parameters
delimiter : char value to be added with each element

elements : char value to be attached with delimiter

Returns
joined string with delimiter

Exception Throws
NullPointerException if element or delimiter is null.

Since
1.8

Java String join() Method Example


FileName: StringJoinExample.java

1. public class StringJoinExample{


2. public static void main(String args[]){
3. String joinString1=String.join("-","welcome","to","javatpoint");
4. System.out.println(joinString1);
5. }}

Output:

welcome-to-javatpoint
33

Java StringBuffer Class


Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the 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() It creates an empty String buffer with the initial capacity of 16.

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

StringBuffer(int It creates an empty String buffer with the specified capacity as


capacity) length.

Important methods of StringBuffer class


Modifier Method Description
and Type

public append(String s) It is used to append the


synchronized specified string with this string.
StringBuffer The append() method is
overloaded like append(char),
append(boolean), append(int),
append(float), append(double)
etc.

public insert(int offset, String s) It is used to insert the specified


synchronized string with this string at the
StringBuffer specified position. The insert()
34

method is overloaded like


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

public replace(intstartIndex, intendIndex, It is used to replace the string


synchronized String str) from specified startIndex and
StringBuffer endIndex.

public delete(intstartIndex, intendIndex) It is used to delete the string


synchronized from specified startIndex and
StringBuffer endIndex.

public reverse() is used to reverse the string.


synchronized
StringBuffer

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


capacity.

public void ensureCapacity(intminimumCapacity) It is used to ensure the capacity


at least equal to the given
minimum.

public char charAt(int index) It is used to return the


character at the specified
position.

public int length() It is used to return the length


of the string i.e. total number
of characters.

public String substring(intbeginIndex) It is used to return the


35

substring from the specified


beginIndex.

public String substring(intbeginIndex, intendIndex) It is used to return the


substring from the specified
beginIndex and endIndex.

What is a mutable String?


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

1) StringBuffer Class 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. }

Output:

Hello Java

StringBufferExample2.java

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. }
36

7. }

Output:

HJavaello

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() It creates an empty String Builder with the initial capacity of 16.

StringBuilder(String It creates a String Builder with the specified string.


str)

StringBuilder(int It creates an empty String Builder with the specified capacity as


length) length.

Important methods of StringBuilder class

Method Description

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


this string. The append() method is
overloaded like append(char),
append(boolean), append(int), append(float),
37

append(double) etc.

public StringBuilder insert(int offset, It is used to insert the specified string with
String s) this string at 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(intstartIndex, It is used to replace the string from specified


intendIndex, String str) startIndex and endIndex.

public StringBuilder delete(intstartIndex, It is used to delete the string from specified


intendIndex) startIndex and endIndex.

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

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

public void It is used to ensure the capacity at least


ensureCapacity(intminimumCapacity) equal to the given minimum.

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


specified position.

public int length() It is used to return the length of the string


i.e. total number of characters.

public String substring(intbeginIndex) It is used to return the substring from the


specified beginIndex.

public String substring(intbeginIndex, It is used to return the substring from the


intendIndex) specified beginIndex and endIndex.
38

Java StringBuilder Examples


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

1) StringBuilderappend() method
The StringBuilderappend() method concatenates the given argument with this String.

StringBuilderExample.java

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. }

Output:

Hello Java

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

StringBuilderExample2.java

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. }
39

Output:

HJavaello

Java Wrapper Classes


Wrapper classes provide a way to use primitive data types ( int, boolean, etc..)
as objects.

The table below shows the primitive type and the equivalent wrapper class:

Primitive Data Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean

char Character
Sometimes you must use wrapper classes, for example when working with
Collection objects, such as ArrayList, where primitive types cannot be used
(the list can only store objects):

Creating Wrapper Objects


To create a wrapper object, use the wrapper class instead of the primitive type.
To get the value, you can just print the object:

Example
publicclassMain{

publicstaticvoidmain(String[]args){
40

IntegermyInt=5;

DoublemyDouble=5.99;

CharactermyChar='A';

System.out.println(myInt);

System.out.println(myDouble);

System.out.println(myChar);

Output:
5
5.99
A

StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or
one by one to the tokens.
41

Constructors of the StringTokenizer Class


There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) It creates StringTokenizer with specified string.

StringTokenizer(String str, It creates StringTokenizer with specified string


String delim) and delimiter.

StringTokenizer(String str, It creates StringTokenizer with specified string,


String delim, delimiter and returnValue. If return value is true,
booleanreturnValue) delimiter characters are considered to be tokens.
If it is false, delimiter characters serve to separate
tokens.

Methods of the StringTokenizer Class


The six useful methods of the StringTokenizer class are as follows:
42

Methods Description

booleanhasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the StringTokenizer


object.

String nextToken(String It returns the next token based on the delimiter.


delim)

booleanhasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return type is


Object.

intcountTokens() It returns the total number of tokens.

Example of StringTokenizer Class


Let's see an example of the StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.

Simple.java

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
43

Output:

my
name
is
khan

The above Java code, demonstrates the use of StringTokenizer class and its methods
hasMoreTokens() and nextToken().

java.util.Date
The java.util.Date class represents date and time in java. It provides constructors and
methods to deal with date and time in java.

The java.util.Date class implements Serializable, Cloneable and Comparable<Date>


interface. It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

After Calendar class, most of the constructors and methods of java.util.Date class has
been deprecated. Here, we are not giving list of any deprecated constructor and
method.

java.util.Date Constructors

No. Constructor Description

1) Date() Creates a date object representing current date and time.

2) Date(long Creates a date object for the given milliseconds since


milliseconds) January 1, 1970, 00:00:00 GMT.

java.util.Date Methods

No. Method Description

1) boolean after(Date date) tests if current date is after the given date.
44

2) boolean before(Date date) tests if current date is before the given date.

3) Object clone() returns the clone object of current date.

4) intcompareTo(Date date) compares current date with given date.

5) boolean equals(Date date) compares current date with given date for
equality.

6) static Date from(Instant returns an instance of Date object from Instant


instant) date.

7) long getTime() returns the time represented by this date object.

8) inthashCode() returns the hash code value for this date object.

9) void setTime(long time) changes the current date and time to given
time.

10) Instant toInstant() converts current date into Instant object.

11) String toString() converts this date into Instant object.

java.util.Date Example
Let's see the example to print date in java using java.util.Date class.

1st way:

1. java.util.Date date=new java.util.Date();


2. System.out.println(date);

Output:
45

Wed Mar 27 08:22:02 IST 2015

2nd way:

1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);
4. Output:
5. Wed Mar 27 08:22:02 IST 2015

Java Calendar Class


Java Calendar class is an abstract class that provides methods for converting date
between a specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc. It inherits Object class and implements the Comparable interface.

Java Calendar class declaration


Let's see the declaration of java.util.Calendar class.

1. public abstract class Calendar extends Object


2. implements Serializable, Cloneable, Comparable<Calendar>

List of Calendar Methods

No Method Description

1. public void add(int field, int amount) Adds the specified (signed) amount of time to
the given calendar field.

2. public boolean after (Object when) The method Returns true if the time
represented by this Calendar is after the time
represented by when Object.
46

3. public boolean before(Object when) The method Returns true if the time
represented by this Calendar is before the
time represented by when Object.

4. public final void clear(int field) Set the given calendar field value and the
time value of this Calendar undefined.

5. public Object clone() Clone method provides the copy of the


current object.

6. public intcompareTo(Calendar The compareTo() method of Calendar class


anotherCalendar) compares the time values (millisecond offsets)
between two calendar object.

7. protected void complete() It fills any unset fields in the calendar fields.

8. protected abstract void computeFields() It converts the current millisecond time value
time to calendar field values in fields[].

9. protected abstract void computeTime() It converts the current calendar field values in
fields[] to the millisecond time value time.

10. public boolean equals(Object object) The equals() method compares two objects
for equality and Returns true if they are equal.

11. public int get(int field) In get() method fields of the calendar are
passed as the parameter, and this method
Returns the value of fields passed as the
parameter.

12. public intgetActualMaximum(int field) Returns the Maximum possible value of the
calendar field passed as the parameter to
getActualMaximum() method.
47

13. public intgetActualMinimum(int field) Returns the Minimum possible value of the
calendar field passed as parameter to
getActualMinimum() methot.

14. public static Returns a set which contains string set of all
Set<String>getAvailableCalendarTypes() available calendar type supported by Java
Runtime Environment.

15. public static Locale[] getAvailableLocales() Returns an array of all locales available in java
runtime environment.

16. public String getCalendarType() Returns in string all available calendar type
supported by Java Runtime Environment.

17. public String getDisplayName(int field, int Returns the String representation of the
style, Locale locale) calendar field value passed as the parameter
in a given style and local.

18. public Returns Map representation of the calendar


Map<String,Integer>getDisplayNames(int field value passed as the parameter in a given
field, int style, Locale locale) style and local.

19. public intgetFirstDayOfWeek() Returns the first day of the week in integer
form.

20. public abstract This method returns the highest minimum


intgetGreatestMinimum(int field) value of Calendar field passed as the
parameter.

21. public static Calendar getInstance() This method is used with calendar object to
get the instance of calendar according to
current time zone set by java runtime
environment
48

22. public abstract intgetLeastMaximum(int Returns smallest value from all maximum
field) value for the field specified as the parameter
to the method.

23. public abstract intgetMaximum(int field) This method is used with calendar object to
get the maximum value of the specified
calendar field as the parameter.

24. public intgetMinimalDaysInFirstWeek() Returns required minimum days in integer


form.

25. public abstract intgetMinimum(int field) This method is used with calendar object to
get the minimum value of specified calendar
field as the parameter.

26. public final Date getTime() This method gets the time value of calendar
object and Returns date.

27. public long getTimeInMillis() Returns the current time in millisecond. This
method has long as return type.

28. public TimeZonegetTimeZone() This method gets the TimeZone of calendar


object and Returns a TimeZone object.

29. public intgetWeeksInWeekYear() Return total weeks in week year. Weeks in


week year is returned in integer form.

30. public intgetWeekYear() This method gets the week year represented
by current Calendar.

31. public inthashCode() All other classes in Java overload hasCode()


method. This method Returns the hash code
for calendar object.
49

32. protected final intinternalGet(int field) This method returns the value of the calendar
field passed as the parameter.

33. Public booleanisLenient() Return Boolean value. True if the


interpretation mode of this calendar is lenient;
false otherwise.

34. public final booleanisSet(int field) This method checks if specified field as the
parameter has been set or not. If not set then
it returns false otherwise true.

35. public booleanisWeekDateSupported() Checks if this calendar supports week date.


The default value is false.

36. public abstract void roll(int field, boolean This method increase or decrease the
up) specified calendar field by one unit without
affecting the other field

37. public void set(int field, int value) Sets the specified calendar field by the
specified value.

38. public void setFirstDayOfWeek(int value) Sets the first day of the week. The value which
is to be set as the first day of the week is
passed as parameter.

39. public void Sets the minimal days required in the first
setMinimalDaysInFirstWeek(int value) week. The value which is to be set as minimal
days in first week is passed as parameter.

40. public final void setTime(Date date) Sets the Time of current calendar object. A
Date object id passed as the parameter.

41. public void setTimeInMillis(long millis) Sets the current time in millisecond.
50

42. public void setTimeZone(TimeZone value) Sets the TimeZone with passed TimeZone
value (object) as the parameter.

43. public void setWeekDate(intweekYear, Sets the current date with specified integer
intweekOfYear, intdayOfWeek) value as the parameter. These values are
weekYear, weekOfYear and dayOfWeek.

44. public final Instant toInstant() The toInstant() method convert the current
object to an instant.

45. public String toString() Returns string representation of the current


object.

Java Calendar Class Example


1. import java.util.Calendar;
2. public class CalendarExample1 {
3. public static void main(String[] args) {
4. Calendar calendar = Calendar.getInstance();
5. System.out.println("The current date is : " + calendar.getTime());
6. calendar.add(Calendar.DATE, -15);
7. System.out.println("15 days ago: " + calendar.getTime());
8. calendar.add(Calendar.MONTH, 4);
9. System.out.println("4 months later: " + calendar.getTime());
10. calendar.add(Calendar.YEAR, 2);
11. System.out.println("2 years later: " + calendar.getTime());
12. }
13. }
Test it Now

Output:

The current date is : Thu Jan 19 18:47:02 IST 2017


15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019
51

Java Calendar Class Example: get()


1. import java.util.*;
2. public class CalendarExample2{
3. public static void main(String[] args) {
4. Calendar calendar = Calendar.getInstance();
5. System.out.println("At present Calendar's Year: " + calendar.get(Calendar.YEAR));
6. System.out.println("At present Calendar's Day: " + calendar.get(Calendar.DATE));
7. }
8. }
Test it Now

Output:

At present Calendar's Year: 2017


At present Calendar's Day: 20

Java Calendar Class Example: getInstance()


1. import java.util.*;
2. public class CalendarExample3{
3. public static void main(String[] args) {
4. Calendar calendar = Calendar.getInstance();
5. System.out.print("At present Date And Time Is: " + calendar.getTime());
6. }
7. }
Test it Now

Output:

At present Date And Time Is: Fri Jan 20 14:26:19 IST 2017

Java Calendar Class Example: getMaximum()


1. import java.util.*;
52

2. public class CalendarExample4 {


3. public static void main(String[] args) {
4. Calendar calendar = Calendar.getInstance();
5. int maximum = calendar.getMaximum(Calendar.DAY_OF_WEEK);
6. System.out.println("Maximum number of days in week: " + maximum);
7. maximum = calendar.getMaximum(Calendar.WEEK_OF_YEAR);
8. System.out.println("Maximum number of weeks in year: " + maximum);
9. }
10. }
Test it Now

Output:

Maximum number of days in week: 7


Maximum number of weeks in year: 53

Java Calendar Class Example: getMinimum()


1. import java.util.*;
2. public class CalendarExample5 {
3. public static void main(String[] args) {
4. Calendar cal = Calendar.getInstance();
5. int maximum = cal.getMinimum(Calendar.DAY_OF_WEEK);
6. System.out.println("Minimum number of days in week: " + maximum);
7. maximum = cal.getMinimum(Calendar.WEEK_OF_YEAR);
8. System.out.println("Minimum number of weeks in year: " + maximum);
9. }
10. }
Test it Now

Output:

Minimum number of days in week: 1


Minimum number of weeks in year: 1
53

Java Random class


Java Random class is used to generate a stream of pseudorandom numbers. The
algorithms implemented by Random class use a protected utility method than can
supply up to 32 pseudorandomly generated bits on each invocation.

Methods

Methods Description

doubles() Returns an unlimited stream of pseudorandom double values.

ints() Returns an unlimited stream of pseudorandom int values.

longs() Returns an unlimited stream of pseudorandom long values.

next() Generates the next pseudorandom number.

nextBoolean() Returns the next uniformly distributed pseudorandom boolean value


from the random number generator's sequence

nextByte() Generates random bytes and puts them into a specified byte array.

nextDouble() Returns the next pseudorandom Double value between 0.0 and 1.0
from the random number generator's sequence

nextFloat() Returns the next uniformly distributed pseudorandom Float value


between 0.0 and 1.0 from this random number generator's sequence

nextGaussian() Returns the next pseudorandom Gaussian double value with mean 0.0
and standard deviation 1.0 from this random number generator's
sequence.
54

nextInt() Returns a uniformly distributed pseudorandom int value generated


from this random number generator's sequence

nextLong() Returns the next uniformly distributed pseudorandom long value from
the random number generator's sequence.

setSeed() Sets the seed of this random number generator using a single long
seed.

Example 1

1. import java.util.Random;
2. public class JavaRandomExample1 {
3. public static void main(String[] args) {
4. //create random object
5. Random random= new Random();
6. //returns unlimited stream of pseudorandom long values
7. System.out.println("Longs value : "+random.longs());
8. // Returns the next pseudorandom boolean value
9. boolean val = random.nextBoolean();
10. System.out.println("Random boolean value : "+val);
11. byte[] bytes = new byte[10];
12. //generates random bytes and put them in an array
13. random.nextBytes(bytes);
14. System.out.print("Random bytes = ( ");
15. for(int i = 0; i< bytes.length; i++)
16. {
17. System.out.printf("%d ", bytes[i]);
18. }
19. System.out.print(")");
20. }
21. }
Output:
55

Longs value : java.util.stream.LongPipeline$Head@14ae5a5


Random booleanvalue : true
Random bytes = ( 57 77 8 67 -122 -71 -79 -62 53 19 )

Java Scanner
Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various primitive
values.

The Java Scanner class is widely used to parse text for strings and primitive types using a
regular expression. It is the simplest way to get input in Java. By the help of Scanner in
Java, we can get input from the user in primitive types such as int, long, double, byte,
float, short, etc.

The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.

The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(),
nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a
single character from the scanner, you can call next().charAt(0) method which returns a single
character.

Java Scanner Class Declaration


1. public final class Scanner
2. extends Object
3. implements Iterator<String>

How to get Java Scanner


To get the instance of Java Scanner which reads input from the user, we need to pass
the input stream (System.in) in the constructor of Scanner class. For Example:

1. Scanner in = new Scanner(System.in);


56

To get the instance of Java Scanner which parses the strings, we need to pass the strings
in the constructor of Scanner class. For Example:

1. Scanner in = new Scanner("Hello Javatpoint");

Java Scanner Class Constructors

SN Constructor Description

1) Scanner(File source) It constructs a new Scanner that


produces values scanned from the
specified file.

2) Scanner(File source, String It constructs a new Scanner that


charsetName) produces values scanned from the
specified file.

3) Scanner(InputStream source) It constructs a new Scanner that


produces values scanned from the
specified input stream.

4) Scanner(InputStream source, String It constructs a new Scanner that


charsetName) produces values scanned from the
specified input stream.

5) Scanner(Readable source) It constructs a new Scanner that


produces values scanned from the
specified source.

6) Scanner(String source) It constructs a new Scanner that


produces values scanned from the
specified string.

7) Scanner(ReadableByteChannel source) It constructs a new Scanner that


57

produces values scanned from the


specified channel.

8) Scanner(ReadableByteChannel source, It constructs a new Scanner that


String charsetName) produces values scanned from the
specified channel.

9) Scanner(Path source) It constructs a new Scanner that


produces values scanned from the
specified file.

10) Scanner(Path source, String It constructs a new Scanner that


charsetName) produces values scanned from the
specified file.

Java Scanner Class Methods


The following are the list of Scanner methods:

SN Modifier & Type Method Description

1) void close() It is used to close this scanner.

2) pattern delimiter() It is used to get the Pattern which


the Scanner class is currently
using to match delimiters.

3) Stream<MatchResult> findAll() It is used to find a stream of


match results that match the
provided pattern string.

4) String findInLine() It is used to find the next


58

occurrence of a pattern
constructed from the specified
string, ignoring delimiters.

5) string findWithinHorizon() It is used to find the next


occurrence of a pattern
constructed from the specified
string, ignoring delimiters.

6) boolean hasNext() It returns true if this scanner has


another token in its input.

7) boolean hasNextBigDecimal() It is used to check if the next


token in this scanner's input can
be interpreted as a BigDecimal
using the nextBigDecimal()
method or not.

8) boolean hasNextBigInteger() It is used to check if the next


token in this scanner's input can
be interpreted as a BigDecimal
using the nextBigDecimal()
method or not.

9) boolean hasNextBoolean() It is used to check if the next


token in this scanner's input can
be interpreted as a Boolean using
the nextBoolean() method or not.

10) boolean hasNextByte() It is used to check if the next


token in this scanner's input can
be interpreted as a Byte using the
nextBigDecimal() method or not.
59

11) boolean hasNextDouble() It is used to check if the next


token in this scanner's input can
be interpreted as a BigDecimal
using the nextByte() method or
not.

12) boolean hasNextFloat() It is used to check if the next


token in this scanner's input can
be interpreted as a Float using
the nextFloat() method or not.

13) boolean hasNextInt() It is used to check if the next


token in this scanner's input can
be interpreted as an int using the
nextInt() method or not.

14) boolean hasNextLine() It is used to check if there is


another line in the input of this
scanner or not.

15) boolean hasNextLong() It is used to check if the next


token in this scanner's input can
be interpreted as a Long using
the nextLong() method or not.

16) boolean hasNextShort() It is used to check if the next


token in this scanner's input can
be interpreted as a Short using
the nextShort() method or not.

17) IOException ioException() It is used to get the IOException


last thrown by this Scanner's
readable.
60

18) Locale locale() It is used to get a Locale of the


Scanner class.

19) MatchResult match() It is used to get the match result


of the last scanning operation
performed by this scanner.

20) String next() It is used to get the next


complete token from the scanner
which is in use.

21) BigDecimal nextBigDecimal() It scans the next token of the


input as a BigDecimal.

22) BigInteger nextBigInteger() It scans the next token of the


input as a BigInteger.

23) boolean nextBoolean() It scans the next token of the


input into a boolean value and
returns that value.

24) byte nextByte() It scans the next token of the


input as a byte.

25) double nextDouble() It scans the next token of the


input as a double.

26) float nextFloat() It scans the next token of the


input as a float.

27) int nextInt() It scans the next token of the


input as an Int.
61

28) String nextLine() It is used to get the input string


that was skipped of the Scanner
object.

29) long nextLong() It scans the next token of the


input as a long.

30) short nextShort() It scans the next token of the


input as a short.

31) int radix() It is used to get the default radix


of the Scanner use.

32) void remove() It is used when remove operation


is not supported by this
implementation of Iterator.

33) Scanner reset() It is used to reset the Scanner


which is in use.

34) Scanner skip() It skips input that matches the


specified pattern, ignoring
delimiters

35) Stream<String> tokens() It is used to get a stream of


delimiter-separated tokens from
the Scanner object which is in
use.

36) String toString() It is used to get the string


representation of Scanner using.

37) Scanner useDelimiter() It is used to set the delimiting


pattern of the Scanner which is in
62

use to the specified pattern.

38) Scanner useLocale() It is used to sets this scanner's


locale object to the specified
locale.

39) Scanner useRadix() It is used to set the default radix


of the Scanner which is in use to
the specified radix.

Example 1
Let's see a simple example of Java Scanner where we are getting a single input from the
user. Here, we are asking for a string through in.nextLine() method.

1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }

Output:

Enter your name: sonoojaiswal


Name is: sonoojaiswal

You might also like