4 Strings
4 Strings
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:
is same as:
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".
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).
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.
Construct a new String by decoding the byte array. It uses the platform’s default character
set for decoding.
Example:
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
import java.util.*;
// Driver Class
class Test
{
// main function
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");
out = "Geeks".equals("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());
// 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
4 static String format(Locale l, String format, Object... It returns formatted string with given
args) locale.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.
given object.
17 String[] split(String regex, int limit) It returns a split string matching regex
and limit.
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
22 int indexOf(String substring, int fromIndex) It returns the specified substring index
starting with given index.
specified locale.
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.
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.
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:
String provides String java.lang.String.concat(String str) method to concatenate the specified string to the
end of this string.
Example:
13
System.out.println("cares".concat("s"));
System.out.println("to".concat("get"));
}
}
Output:
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:
four: 22
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
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:
Example: Let's see an example where we are converting all primitives and objects into strings.
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;
width = w;
height = h;
depth = d;
}
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);
}
}
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 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.
Example:
Example:
3. Using regionMatches( )
Test if two string regions are equal.
Example:
Example:
Example:
6. equals( ) Versus ==
The equals() method compares the content, whereas == compares object references.
Example:
7. Using compareTo( )
Compares two strings lexicographically.
Example:
Example:
Example:
Example:
Example:
Example:
Example:
1. concat(String str)
Concatenates the specified string to the end of this string.
5. trim()
Removes leading and trailing white spaces.
6. split(String regex)
Splits the string around matches of the given regular expression.
22
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
Returns
Output:
3010
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
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.
The String concat() method concatenates the specified string to the end of current string. Syntax:
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.
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
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.
String.format() method allows to concatenate multiple strings using format specifier like %s followed by
the string values or objects.
StrFormat.java
Output:
Hello World
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:
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.
StringJoiner class has all the functionalities of String.join() method. In advance its constructor can also
accept optional arguments, prefix and suffix.
StrJoiner.java
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.
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:
Here, a list of String array is declared. And a String object str stores the result
of Collectors.joining() method.
// StringBuffer append(boolean a)
import java.lang.*;
System.out.println();
}
Output:
Input: We are geeks and its really
Output: We are geeks and its really true
String valueOf(T);
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.
String s = String.valueOf(inti);
String s = String.valueOf(inti);
boolean
int
long
float
double
char
char[]
Object
For the second method-signature parameters are char array, offset and count.
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.
System.out.println(s); // prints 5
Output:
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
Parameters
delimiter : char value to be added with each element
Returns
joined string with delimiter
Exception Throws
NullPointerException if element or delimiter is null.
Since
1.8
Output:
welcome-to-javatpoint
33
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.
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
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
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
Method Description
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.
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
The table below shows the primitive type and the equivalent 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):
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
Constructor Description
Methods Description
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.
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
java.util.Date Methods
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.
5) boolean equals(Date date) compares current date with given date for
equality.
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.
java.util.Date Example
Let's see the example to print date in java using java.util.Date class.
1st way:
Output:
45
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
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.
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.
19. public intgetFirstDayOfWeek() Returns the first day of the week in integer
form.
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.
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.
30. public intgetWeekYear() This method gets the week year represented
by current Calendar.
32. protected final intinternalGet(int field) This method returns the value of the calendar
field passed as the parameter.
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.
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.
Output:
Output:
Output:
At present Date And Time Is: Fri Jan 20 14:26:19 IST 2017
Output:
Output:
Methods
Methods Description
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
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
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
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.
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:
SN Constructor Description
occurrence of a pattern
constructed from the specified
string, ignoring delimiters.
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: