Programming in Java-Unit IV
Programming in Java-Unit IV
Before introducing the thread concept, we were unable to run more than one task in
parallel. It was a drawback, and to remove that drawback, Thread Concept was
introduced.
A Thread is a very light-weighted process, or we can say the smallest part of the process
that allows a program to operate more efficiently by running multiple tasks
simultaneously.
In order to perform complicated tasks in the background, we used the Thread concept
in Java. All the tasks are executed without affecting the main program. In a program or
process, all the threads have their own separate path for execution, so each thread of a
process is independent.
Another benefit of using thread is that if a thread gets an exception or an error at the
time of its execution, it doesn't affect the execution of the other threads. All the threads
share a common memory and have their own stack, local variables and program
counter. When multiple threads are executed in parallel at the same time, this process is
known as Multithreading.
o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.
import java.io.*;
import java.util.*;
g1.start();
Output
Thread Started Running...
t1.start();
System.out.println(Thread.currentThread().getName()
Output:
Main thread is- main
Thread-0, executing run() method!
The output shows two active threads in the program – main thread and Thread-
0, main method is executed by the Main thread but invoking the start on
RunnableImpl creates and starts a new thread – Thread-0. What happens
when Runnable encounters an exception ? Runnable can’t throw checked
exception but RuntimeException can be thrown from the run(). Uncaught
exceptions are handled by the exception handler of the thread, if JVM can’t
handle or catch exceptions, it prints the stack trace and terminates the flow.
Thread Class
A thread is a program that starts with a method() frequently used in this class
only known as the start() method. This method looks out for the run() method
which is also a method of this class and begins executing the body of the run()
method. Here, keep an eye over the sleep() method which will be discussed
later below.
Note: Every class that is used as thread must implement Runnable interface
and over ride it’s run method.
Syntax:
public class Thread extends Object implements Runnable
Thread(ThreadGroup group,
Allocates a new Thread object.
Runnable target)
group.
Thread(ThreadGroup group,
Allocates a new Thread object.
String name)
Now let us do discuss all the methods of this class are illustrated as follows:
Methods Action Performed
Throws CloneNotSupportedException as a
clone()
Thread can not be meaningfully cloned
import java.lang.*;
// Main class
// Method 1
// Print statement
{
// Creating random threads
// Thread 1
+ t1.getPriority());
// Thread 1
+ t2.getPriority());
// Thread 3
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// IllegalArgumentException
// 2
+ t1.getPriority());
// 5
+ t2.getPriority());
// 8
+ t3.getPriority());
// Main thread
System.out.println(
+ Thread.currentThread().getName());
System.out.println(
+ Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println(
+ Thread.currentThread().getPriority());
Output
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Output explanation:
Thread with the highest priority will get an execution chance prior to other
threads. Suppose there are 3 threads t1, t2, and t3 with priorities 4, 6, and 1.
So, thread t2 will execute first based on maximum priority 6 after that t1 will
execute and then t3.
The default priority for the main thread is always 5, it can be changed later.
The default priority for all other threads depends on the priority of the parent
thread.
Now geeks you must be wondering out what if we do assign the same priorities
to threads then what will happen. All the processing in order to look after
threads is carried with help of the thread scheduler. One can refer to the below
example of what will happen if the priorities are set to the same and later
onwards we will discuss it as an output explanation to have a better
understanding conceptually and practically.
Applying Synchronization
Multi-threaded programs may often come to a situation where multiple threads try to
access the same resources and finally produce erroneous and unforeseen results.
Why use Java Synchronization?
Java Synchronization is used to make sure by some synchronization method that only one
thread can access the resource at a given point in time.
Java provides a way of creating threads and synchronizing their tasks using synchronized
blocks.
A synchronized block in Java is synchronized on some object. All synchronized blocks
synchronize on the same object and can only have one thread executed inside them at a
time. All other threads attempting to enter the synchronized block are blocked until the
thread inside the synchronized block exits the block.
Note: Synchronized blocks in Java are marked with the synchronized keyword.
Thread Synchronization is used to coordinate and ordering of the execution of the threads
in a multi-threaded program. There are two types of thread synchronization are
mentioned below:
Mutual Exclusive
Cooperation (Inter-thread communication in Java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. There are three types of Mutual Exclusive mentioned below:
Synchronized method.
Synchronized block.
Static synchronization.
Example of Synchronization
Below is the implementation of the Java Synchronization:
// synchronized.
import java.io.*;
import java.util.*;
// A Class used to send a message
class Sender {
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
catch (Exception e) {
System.out.println("Thread interrupted.");
Sender sender;
// Receives a message object and a string
// message to be sent
msg = m;
sender = obj;
// at a time.
synchronized (sender)
sender.send(msg);
}
// Driver class
class SyncDemo {
S1.start();
S2.start();
try {
S1.join();
S2.join();
catch (Exception e) {
System.out.println("Interrupted");
Output
Sending Hi
Hi Sent
Sending Bye
Bye Sent
The output is the same every time we run the program.
Inter-thread communication
Inter-thread Communication in Java
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
o wait()
o notify()
o notifyAll()
wait() method
The wait() method causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a
specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException
notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If
any threads are waiting on this object, one of them is chosen to be awakened. The
choice is arbitrary and occurs at the discretion of the implementation.
Syntax:
notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
The wait() method releases the lock. The sleep() method doesn't release the lock.
It should be notified by notify() or After the specified amount of time, sleep is completed.
notifyAll() methods
Test.java
class Customer{
int amount=10000;
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
All the legacy classes are synchronized. The java.util package defines the
following legacy classes:
1. HashTable
2. Stack
3. Dictionary
4. Properties
5. Vector
It is used when we want to create a default vector having the initial size of 10.
2) Vector(int size)
It is used to create a vector of specified capacity. It accepts two parameters size and
increment parameters to specify the initial capacity and the number of elements to
allocate each time when a vector is resized for the addition of objects.
4) Vector(Collection c)
It is used to create a vector with the same elements which are present in the collection.
It accepts the collection as a parameter.
Output:
Stack only defines the default constructor, which creates an empty stack. Stack includes
all the methods defined by Vector, and adds several of its own.
Stack( )
Apart from the methods inherited from its parent class Vector, Stack defines the
following methods −
boolean empty()
1
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack
contains elements.
2 Object peek( )
Returns the element on the top of the stack, but does not remove it.
3 Object pop( )
Returns the element on the top of the stack, removing it in the process.
Example
The following program illustrates several of the methods supported by this collection −
Live Demo
import java.util.*;
public class StackDemo {
Output
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
The Enumeration interface defines the methods by which you can enumerate (obtain
one at a time) the elements in a collection of objects.
This legacy interface has been superceded by Iterator. Although not deprecated,
Enumeration is considered obsolete for new code. However, it is used by several
methods defined by the legacy classes such as Vector and Properties, is used by
several other API classes, and is currently in widespread use in application code.
The methods declared by Enumeration are summarized in the following table −
boolean hasMoreElements( )
1
When implemented, it must return true while there are still more elements to extract, and false
when all the elements have been enumerated.
2 Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
Example
import java.util.Vector;
import java.util.Enumeration;
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()) {
System.out.println(days.nextElement());
}
}
}
This will produce the following result −
Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
It contains the collections framework, legacy collection classes, event model, date and time
facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-
number generator, and a bit array).
Following are the Important Classes in Java.util package :
1. AbstractCollection: This class provides a skeletal implementation of the Collection interface, to
minimize the effort required to implement this interface.
2. AbstractList: This class provides a skeletal implementation of the List interface to minimize the
effort required to implement this interface backed by a “random access” data store (such as an
array).
3. AbstractMap<K,V>: This class provides a skeletal implementation of the Map interface, to
minimize the effort required to implement this interface.
4. AbstractMap.SimpleEntry<K,V>: An Entry maintaining a key and a value.
5. AbstractMap.SimpleImmutableEntry<K,V>: An Entry maintaining an immutable key and value.
6. AbstractQueue: This class provides skeletal implementations of some Queue operations.
7. AbstractSequentialList: This class provides a skeletal implementation of the List interface to
minimize the effort required to implement this interface backed by a “sequential access” data store
(such as a linked list).
8. AbstractSet: This class provides a skeletal implementation of the Set interface to minimize the
effort required to implement this interface.
9. ArrayDeque: Resizable-array implementation of the Deque interface.
10. ArrayList: Resizable-array implementation of the List interface.
11. Arrays: This class contains various methods for manipulating arrays (such as sorting and
searching).
12. BitSet: This class implements a vector of bits that grows as needed.
13. Calendar: The Calendar class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH,
HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next
week.
14. Collections: This class consists exclusively of static methods that operate on or return collections.
15. Currency: Represents a currency.
16. Date: The class Date represents a specific instant in time, with millisecond precision.
17. Dictionary<K,V>: The Dictionary class is the abstract parent of any class, such as Hashtable, which
maps keys to values.
18. EnumMap,V>: A specialized Map implementation for use with enum type keys.
19. EnumSet: A specialized Set implementation for use with enum types.
20. EventListenerProxy: An abstract wrapper class for an EventListener class which associates a set of
additional parameters with the listener.
21. EventObject: The root class from which all event state objects shall be derived.
22. FormattableFlags: FomattableFlags are passed to the Formattable.formatTo() method and modify
the output format for Formattables.
23. Formatter: An interpreter for printf-style format strings.
24. GregorianCalendar: GregorianCalendar is a concrete subclass of Calendar and provides the
standard calendar system used by most of the world.
25. HashMap<K,V>: Hash table based implementation of the Map interface.
26. HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap
instance).
27. Hashtable<K,V>: This class implements a hash table, which maps keys to values.
28. IdentityHashMap<K,V>: This class implements the Map interface with a hash table, using
reference-equality in place of object-equality when comparing keys (and values).
29. LinkedHashMap<K,V>: Hash table and linked list implementation of the Map interface, with
predictable iteration order.
30. LinkedHashSet: Hash table and linked list implementation of the Set interface, with predictable
iteration order.
31. LinkedList: Doubly-linked list implementation of the List and Deque interfaces.
32. ListResourceBundle: ListResourceBundle is an abstract subclass of ResourceBundle that manages
resources for a locale in a convenient and easy to use list.
33. Locale – Set 1, Set 2: A Locale object represents a specific geographical, political, or cultural
region.
34. Locale.Builder: Builder is used to build instances of Locale from values configured by the setters.
35. Objects: This class consists of static utility methods for operating on objects.
36. Observable: This class represents an observable object, or “data” in the model-view paradigm.
37. PriorityQueue: An unbounded priority queue based on a priority heap.
38. Properties: The Properties class represents a persistent set of properties.
39. PropertyPermission: This class is for property permissions.
40. PropertyResourceBundle: PropertyResourceBundle is a concrete subclass of ResourceBundle that
manages resources for a locale using a set of static strings from a property file.
41. Random: An instance of this class is used to generate a stream of pseudorandom numbers.
42. ResourceBundle: Resource bundles contain locale-specific objects.
43. ResourceBundle.Control: ResourceBundle.Control defines a set of callback methods that are
invoked by the ResourceBundle.getBundle factory methods during the bundle loading process.
44. Scanner: A simple text scanner which can parse primitive types and strings using regular
expressions.
45. ServiceLoader: A simple service-provider loading facility.
46. SimpleTimeZone: SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone
for use with a Gregorian calendar.
47. Stack: The Stack class represents a last-in-first-out (LIFO) stack of objects.
48. StringTokenizer: The string tokenizer class allows an application to break a string into tokens.
49. Timer: A facility for threads to schedule tasks for future execution in a background thread.
50. TimerTask: A task that can be scheduled for one-time or repeated execution by a Timer.
51. TimeZone: TimeZone represents a time zone offset, and also figures out daylight savings.
52. TreeMap<K,V>: A Red-Black tree based NavigableMap implementation.
53. TreeSet: A NavigableSet implementation based on a TreeMap.
54. UUID: A class that represents an immutable universally unique identifier (UUID).
55. Vector: The Vector class implements a growable array of objects.
56. WeakHashMap<K,V>: Hash table based implementation of the Map interface, with weak keys.
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.
StringTokenizer(String str, String It creates StringTokenizer with specified string and delimiter.
delim)
StringTokenizer(String str, String It creates StringTokenizer with specified string, delimiter and
delim, boolean returnValue) returnValue. If return value is true, delimiter characters are considered
to be tokens. If it is false, delimiter characters serve to separate tokens.
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
Object nextElement() It is the same as nextToken() but its return type is Object.
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. }
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
No. Constructor Description
2) Date(long milliseconds) Creates a date object for the given milliseconds since January 1, 1970
java.util.Date Methods
No. Method Description
1) boolean after(Date date) tests if current date is after the given date.
2) boolean before(Date date) tests if current date is before the given date.
3) Object clone() returns the clone object of current 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 date.
instant)
8) int hashCode() 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.
Output:
This class also provides additional fields and methods for implementing a
concrete calendar system outside the package.
Calendar defines the range of values returned by certain calendar fields.
Class declaration
Following is the declaration for java.util.Calendar class −
extends Object
Field
Following are the fields for java.util.Calendar class −
static int ALL_STYLES − This is the style specifier for getDisplayNames indicating names
in all styles, such as "January" and "Jan".
1 protected Calendar()
This constructor constructs a Calendar with the default time zone and locale.
Class methods
Sr.No. Method & Description
void clear()
4
This method sets all the calendar field values and the time value (millisecond offset from the
Epoch) of this Calendar undefined.
Object clone()
6
This method creates and returns a copy of this object.
int getFirstDayOfWeek()
18
This method gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in
France.
int getMinimalDaysInFirstWeek()
26 This method gets what the minimal days required in the first week of the year are; e.g., if the
first week is defined as one that contains the first day of the first month of a year, this method
returns 1.
Date getTime()
28
This method returns a Date object representing this Calendar's time value (millisecond offset
from the Epoch").
long getTimeInMillis()
29
This method returns this Calendar's time value in milliseconds.
TimeZone getTimeZone()
30
This method gets the time zone.
int hashCode()
31
This method Returns a hash code for this calendar.
boolean isLenient()
33
This method tells whether date/time interpretation is to be lenient.
boolean isSet(int field)
34
This method determines if the given calendar field has a value set, including cases that the
value has been set by internal fields calculations triggered by a get method call.
void set(int year, int month, int date, int hourOfDay, int minute)
39
This method sets the values for the calendar fields YEAR, MONTH, DAY_OF_MONTH,
HOUR_OF_DAY, and MINUTE.
void set(int year, int month, int date, int hourOfDay, int minute, int second)
40
This method sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR,
MINUTE, and SECOND.
String toString()
47
This method return a string representation of this calendar.
import java.util.GregorianCalendar;
The following are the constructors.
GregorianCalendar()
1
This constructs a default GregorianCalendar using the current time in
the default time zone with the default locale.
2
This constructs a GregorianCalendar with the given date set in the
default time zone with the default locale.
GregorianCalendar(Locale aLocale)
5
This constructs a GregorianCalendar based on the current time in the
default time zone with the given locale.
Sr.No. Constructor & Description
GregorianCalendar(TimeZone zone)
7
This constructs a GregorianCalendar based on the current time in the
given time zone with the given locale.
Example
Live Demo
import java.util.GregorianCalendar;
public class Demo {
public static void main(String[] args) {
GregorianCalendar cal = (GregorianCalendar)
GregorianCalendar.getInstance();
System.out.println("" + cal.getTime());
}
}
Output
Mon Nov 19 15:57:40 UTC 2018
Methods
Methods Description
nextBoolean() Returns the next uniformly distributed pseudorandom boolean value from the random number
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 g
nextFloat() Returns the next uniformly distributed pseudorandom Float value between 0.0 and 1.0 from
generator's sequence
nextGaussian() Returns the next pseudorandom Gaussian double value with mean 0.0 and standard deviation
number generator's sequence.
nextInt() Returns a uniformly distributed pseudorandom int value generated from this random number g
nextLong() Returns the next uniformly distributed pseudorandom long value from the random number gen
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. }
Test it Now
Output:
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:
2) Scanner(File source, String charsetName) It constructs a new Scanner that produces valu
specified file.
4) Scanner(InputStream source, String charsetName) It constructs a new Scanner that produces valu
specified input stream.
10) Scanner(Path source, String charsetName) It constructs a new Scanner that produces valu
specified file.
Java Scanner Class Methods
The following are the list of Scanner methods:
2) pattern delimiter() It is used to get the Pattern which the Scanner class is currently
using to match delimiters.
3) Stream<M findAll() It is used to find a stream of match results that match the
atchResult provided pattern string.
>
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.
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 IOExceptio ioException() It is used to get the IOException last thrown by this Scanner's
) n readable.
19 MatchResu match() It is used to get the match result of the last scanning operation
) lt performed by this scanner.
20 String next() It is used to get the next complete token from the scanner which
) is in use.
23 boolean nextBoolean() It scans the next token of the input into a boolean value and
) returns that value.
28 String nextLine() It is used to get the input string that was skipped of the Scanner
) object.
31 int radix() It is used to get the default radix of the Scanner use.
)
34 Scanner skip() It skips input that matches the specified pattern, ignoring
) delimiters
37 Scanner useDelimiter() It is used to set the delimiting pattern of the Scanner which is in
) 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.
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: