📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, you will learn about the Integer toString() method in Java programming and how to use it with an example.
1. Java Integer toString() Method Overview
Definition:
The toString() method of the Java Integer class returns a string representation of an integer.
Syntax:
1. Integer.toString(int i) 2. Integer.toString(int i, int radix)
Parameters:
int i: The integer to be converted to a string.
int radix: The base of the numeral system to be used for representing the integer in string form (optional parameter, default is 10).
Key Points:
- By default, the method returns the string representation of the integer in base-10.
- If you provide a radix, it can represent the integer in different numeral systems, such as binary (base-2), octal (base-8), or hexadecimal (base-16).
- The method is static, so it's called on the class (Integer) rather than an instance of the class.
2. Java Integer toString() Method Example
import java.util.Arrays; import java.util.List; public class ToStringExample { public static void main(String[] args) { int number = 255; // Convert integer to string in base 10 (default) String numberStr = Integer.toString(number); System.out.println("String representation (base 10): " + numberStr); // Convert integer to string in different bases List<Integer> radixes = Arrays.asList(2, 8, 16); for (int radix : radixes) { String result = Integer.toString(number, radix); System.out.println("String representation (base " + radix + "): " + result); } } }
Output:
String representation (base 10): 255 String representation (base 2): 11111111 String representation (base 8): 377 String representation (base 16): ff
Explanation:
In the example, we began by converting the integer 255 to its string representation using the default base 10 method.
We then converted the same integer to string representations using different bases: binary (base-2), octal (base-8), and hexadecimal (base-16).
The output showcases the various string representations of the integer in the specified bases.
Comments
Post a Comment
Leave Comment