Tutorial Playlist
191 Lessons1. 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
Now Reading
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
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
Java is a versatile programming language that offers a wide range of features for developers. One powerful aspect of it is its ability to handle command line arguments, which allows programs to receive input directly from the user when they are executed. In this comprehensive guide, we will explore the usage of Java command line arguments, with a particular focus on formatting strings using the String.format() method. By understanding the various format specifiers and techniques, you can enhance your string manipulation capabilities in Java. So let's dive in!
Before we delve into the intricacies of string formatting, let's start with a brief overview of Java command line arguments. When you execute a Java program from the command line, you can provide additional data or parameters known as command line arguments. These are passed as strings and can be accessed by the program at runtime. They allow you to customize the behavior of your program without modifying its source code.
The String.format() method in Java is a powerful tool for manipulating strings with ease. It enables you to construct formatted strings by specifying format specifiers that act as placeholders for the values you want to insert. Let's explore some commonly used format specifiers:
Examples of using String.format() to format Strings
To illustrate the usage of String.format(), let's consider an example where we want to display a personalized greeting message. We can achieve this by using the Java string format placeholder to substitute the user's name:
public class JavaStringFormatExample {
public static void main(String[] args) {
String name = "John";
String greeting = String.format("Hello, %s!", name);
System.out.println(greeting);
}
}
Output:
The code creates a variable name with the value "John". It then uses the String.format() method to format a greeting message by inserting the value of the name into the placeholder %s.
In addition to inserting values, format specifiers can also be used to control the alignment and padding of strings. For example, let's say we want to display a list of products with their corresponding prices. We can align the product names to the left and pad the prices with spaces to create a neat tabular format:
public class JavaStringFormatExample {
public static void main(String[] args) {
String product1 = "Apple";
String product2 = "Banana";
double price1 = 0.99;
double price2 = 1.25;
String formattedString = String.format("%-10s %10s%n%-10s %10s", "Product", "Price", product1, price1, product2, price2);
System.out.println(formattedString);
}
}
Output:
The code creates a formatted string with two columns, "Product" and "Price", and aligns them using a width of 10 characters. It then inserts the values of variables product1, price1, product2, and price2 into the formatted string.
Apart from formatting strings, the String.format() method allows you to format various numeric types, including integers, floating-point numbers, and hexadecimal numbers.
Java string format integer:
public class JavaStringFormatExample {
public static void main(String[] args) {
int number = 42;
String formattedNumber = String.format("The answer is: %d", number);
System.out.println(formattedNumber);
}
}
Output:
The code assigns the value 42 to the variable number. It then uses the String.format() method to create a formatted string with the placeholder %d representing an integer.
public class JavaStringFormatExample {
public static void main(String[] args) {
double pi = Math.PI;
String formattedPi = String.format("The value of pi is approximately %.2f", pi);
System.out.println(formattedPi);
}
}
Output:
The code assigns the value of π (pi) to the variable pi and formats it as a string with two decimal places, then prints the formatted string "The value of pi is approximately 3.14" to the console.
public class JavaStringFormatExample {
public static void main(String[] args) {
int decimalNumber = 255;
String formattedHex = String.format("The hexadecimal representation is: %x", decimalNumber);
System.out.println(formattedHex);
}
}
Output:
The code assigns the value of 255 to the variable decimalNumber and formats it as a hexadecimal representation using the String.format() method.
When formatting numeric values, you can specify precision and width to control the formatting precisely. For instance:
public class JavaStringFormatExample {
public static void main(String[] args) {
double value = 123.456789;
String formattedValue = String.format("Formatted value: %.2f, Width: %10.2f", value, value);
System.out.println(formattedValue);
}
}
Output:
The code above demonstrates how to format a floating-point number with a precision of two decimal places and a width of ten characters.
In addition to strings and numbers, the String.format() method also allows you to format dates using format specifiers. Let's see some Java string format examples in date formatting:
import java.time.LocalDate;
public class JavaStringFormatExample {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
String formattedDate = String.format("Today's date is: %tF", currentDate);
System.out.println(formattedDate);
}
}
Output:
In the code snippet above, the format specifier "%tF" formats the date in the ISO-8601 format (YYYY-MM-DD). The resulting output will be "Today's date is: 2023-06-09".
Java provides various format specifiers to customize the date formatting according to your requirements. Here's an example that demonstrates the usage of some commonly used specifiers:
import java.util.Date;
public class JavaStringFormatExample {
public static void main(String[] args) {
Date now = new Date();
String formattedDate = String.format("Current date and time: %tc%nYear: %tY, Month: %tB, Day: %td", now, now, now, now);
System.out.println(formattedDate);
}
}
Output:
In the code snippet above, "%tc" formats the complete date and time, "%tY" extracts the year, "%tB" retrieves the full month name, and "%td" displays the day of the month.
Examples of date formatting using String.format()
To further illustrate the date formatting capabilities of String.format(), let's consider an example where we want to display a custom date format:
import java.util.Calendar;
public class JavaStringFormatExample {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(2023, 5, 9); // June 9, 2023
String formattedDate = String.format("Formatted date: %1$tb %1$td, %1$tY", calendar);
System.out.println(formattedDate);
}
}
Output:
In this example, "%1$tb" represents the abbreviated month name, "%1$td" represents the day of the month, and "%1$tY" represents the year.
The Formatter class in Java provides an alternative approach to formatting strings, numbers, and dates. It offers more flexibility and control over the formatting process. Let's explore the key aspects of the Formatter class:
The Formatter class serves as the central component for formatting operations. It provides methods for constructing formatted strings and writing them to various output destinations.
To create a Formatter object, you can pass different types of destinations, such as OutputStream, File, or StringBuilder. Here's an example that demonstrates the creation of a Formatter object:
import java.util.Formatter;
public class Main {
public static void main(String[] args) {
Formatter formatter = new Formatter(System.out);
String name = "Alice";
int age = 25;
double salary = 5000.50;
formatter.format("Name: %s, Age: %d, Salary: %.2f", name, age, salary);
formatter.close();
}
}
Output:
In the code snippet above, we create a Formatter object and use its format() method to construct a formatted string.
The syntax of the Java String format() function is straightforward. It takes a format string as the first parameter, followed by the values to be inserted into the placeholders. Let's examine the syntax and parameters in detail:
The return value of Java String format()
The Java String format() function returns a formatted string based on the specified format string and arguments. It does not modify the original string. Here's an example that demonstrates the return value of the format() function:
String formattedString = String.format("Value: %d", 42);
System.out.println(formattedString);
In the code above, the format() function constructs a formatted string with the value 42 inserted. The resulting string is assigned to the formattedString variable and then printed.
Exceptions of Java String format()
The Java String format() function can throw a runtime exception if the format string is invalid or if the arguments are incompatible with the format specifiers. For example:
try {
String formattedString = String.format("Invalid format: %d", "text");
System.out.println(formattedString);
} catch (IllegalFormatException e) {
System.err.println("Invalid format: " + e.getMessage());
}
In the code above, an IllegalFormatException will be thrown since we are trying to insert a string argument into a placeholder expecting an integer value.
The format() method in Java also allows you to specify a locale for localized formatting. By providing a locale, you can ensure that the formatting adheres to specific language and cultural conventions. Here's an example:
import java.util.Locale;
double value = 1234.56;
Locale locale = new Locale("fr", "FR");
String formattedValue = String.format(locale, "Valeur formatée: %.2f", value);
System.out.println(formattedValue);
In this example, we specify the French locale using the "fr" language code and "FR" country code. The formatted value will be "Valeur formatée: 1234,56" with a comma as the decimal separator.
Java command line arguments provide a convenient way to customize the behavior of your programs. By understanding the intricacies of Java string formatting using the String.format() method, you can manipulate strings effectively and create visually appealing outputs. We explored the usage of format specifiers, padding and aligning strings, formatting numbers and dates, as well as the capabilities of the Formatter class. With this practical guide, you now have the knowledge to harness the power of Java string formatting and take your programming skills to the next level. So go ahead, experiment, and create beautifully formatted outputs in your Java applications.
1. How to convert long to Java string format?
Ans: The different code snippets used to convert long to Java string format are the ‘+’ operator, Long.tostring(), string.valueOf(), new Long(longl), string.format(), and DecimalFormat and the StringBuilder and StringBuffer append functions.
2. How can I format multiple arguments in Java String format?
Ans: To format multiple arguments in Java String format, you can include multiple placeholders in the format string and provide the corresponding values as additional arguments. For example, "Name: %s, Age: %d" expects two arguments, a string for the name and an integer for the age.
3. How can I specify decimal places in Java String format?
Ans: You can specify decimal places in Java String format by using the %f format specifier with precision. For example, "Value: %.2f" will format a floating-point number with two decimal places.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...