For working professionals
For fresh graduates
More
Step by Step Java Tutorial Con…
1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
Now Reading
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
The string is one of the most used variable types in Java. Strings are frequently used in Java to represent text-based data. They are a collection of letters and numbers encased in double quotations.
If you want to download this tutorial in PDF format for further reading: Download Tutorial PDF
You can use the Scanner class, which is a component of the java.util package to accept string input from the user. Utilizing the Scanner class is the most commonly used method, but you can also use the BufferedReader class and other methods.
This tutorial will explore the techniques, best practices, and commonly asked questions related to accepting string input in Java. By mastering this fundamental skill, you'll be well-equipped to create dynamic and interactive Java programs that effectively handle textual data and user interactions.
To take string input in Java, we can use the java.util.Scanner class that provides methods to read input from various sources, including the standard input (keyboard) and files. We can also use the BufferedReader class or Command Line Arguments.
Let us use the Scanner class to explain the general process and syntax to take string input in Java.
1. Import the necessary package (java.util.Scanner):
import java.util.Scanner; // We are using the Scanner class for this program
2. Create a Scanner object:
Scanner scanner = new Scanner(System.in);
3. Create provisions for user input:
System.out.print("Enter a string: ");
4. Read the input as a string:
String inputString = scanner.nextLine();
The nextLine() method reads the entire input line, including any spaces or special characters, and returns it as a string.
From the above section, we now have a general idea about using the Scanner class in Java. Let us look at some examples of taking string input in Java with two essential methods from the Scanner class:
import java.util.Scanner;
public class upGradTutorials {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
// Close the scanner to free resources
scanner.close();
}
}
The above program starts by importing the java.util.Scanner class, which is used to read user input. The program then creates a Scanner object, scanner, to read input from the standard input (keyboard). It prompts the user to enter their name by displaying the message "Enter your name: ".
The nextLine() method of the Scanner object reads the entire line of input as a string and stores it in the name variable. The program then displays a greeting message using the entered name by concatenating it with the string "Hello, " and "!". Finally, the scanner.close() method is called to close the Scanner object and release any associated resources.
import java.util.Scanner;
public class upGradTutorials {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = scanner.next();
System.out.println("Word entered: " + word);
scanner.close();
}
}
This program demonstrates the next() method in Java to read a single word as input from the user. The Scanner class is imported to enable reading user input. A Scanner object named scanner is created to read input from the standard input (keyboard). The program prompts the user to enter a word by displaying the message "Enter a word: ".
The next() method of the Scanner object is used to read the next word from the input as a string and store it in the variable word. The program then displays the word entered by concatenating it with the string "Word entered: ". Finally, the scanner.close() method is called to close the Scanner object and release any associated resources.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class upGradTutorials {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter a line of text: ");
String line = reader.readLine();
System.out.println("Line entered: " + line);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The above program demonstrates the usage of the BufferedReader class in Java to read a line of text as input from the user. The BufferedReader class, along with InputStreamReader and System.in, is imported to enable reading user input. A BufferedReader object named reader is created by wrapping an InputStreamReader object around System.in. This allows reading input from the standard input (keyboard).
The program prompts the user to enter a line of text by displaying the message "Enter a line of text: ". The readLine() method of the BufferedReader object is used to read the entire line of input as a string and store it in the variable line. The program then displays the entered line by concatenating it with the string "Line entered: ".
In case of any input/output errors, the program catches and prints the exception stack trace. Finally, the close() method is called on the BufferedReader object to close it and release any associated resources.
public class upGradTutorials {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Command line arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
} else {
System.out.println("No command line arguments provided.");
}
}
}
In the above program, the main method accepts an array of strings, args, as command line arguments. The program first checks if any command line arguments are provided by checking the length of the args array. If there are command line arguments, it enters a loop and displays each argument on a separate line using a for loop.
If no command line arguments are provided, it prints the message "No command line arguments provided." This program allows you to pass arguments to the Java program when executing it from the command line. The provided command line arguments are then accessed and processed within the program.
If command line arguments are provided when running the program, the program will display the following:
We must run the program with the command line arguments (apple, banana and orange): java upGradTutorials apple banana orange
After we provide the command line arguments, this will be the output:
When working with text-based data and user interactions, receiving string input is a crucial component of Java programming. The Scanner class makes reading string input from files or the console simple. Remember to handle exceptions and validate the input as necessary to ensure your program behaves appropriately.
You can make Java programs more interactive and user-friendly by being familiar with standard methods for validating, transforming, and processing string input. You can supply text-based data through string input, which can then be processed, changed, or stored to meet your program's needs.
1. Is it possible for me to accept several strings on a single line?
Yes, the next() method of the Scanner class can take several strings as input on a single line. This method reads the subsequent token from the input, a string of characters mostly separated by spaces. To read several strings entered on the same line, call the next() method multiple times.
2. Can I use a file instead of the console to input strings?
Yes, by constructing a Scanner object with a File object corresponding to the file we wish to read, we may use the Scanner class to read string input from a file. We would supply the File object to the Scanner constructor instead of System.in. Using this technique, we can read strings from a file and process them accordingly.
3. How can I change string inputs in Java to another data type?
We can use the methods the corresponding wrapper classes offer if we need to convert string input to any other data type, such as an integer or a double. For instance, we can use Double.parseDouble() to turn a string into a double or Integer.parseInt() to turn a string into an integer.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.