Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: Transform a given integer to String format

Java Basic: Exercise-166 with Solution

Write a Java program to transform a given integer to String format.

Pictorial Presentation:

Java Basic Exercises: Transform a given integer to String format.

Sample Solution:

Java Code:

import java.util.*;
public class Solution {	
 public static String transform_int_to_string(int n) {
    boolean is_negative = false;
    StringBuilder tsb = new StringBuilder();
    if (n == 0) {
      return "0";
    } else if (n < 0) {
      is_negative = true;
    }
    n = Math.abs(n);
    while (n > 0) {
      tsb.append(n % 10);
      n /= 10;
    }
    if (is_negative) {
      tsb.append("-");
    }
    return tsb.reverse().toString();
  }
    public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
        System.out.print("Input an integer: ");
        int n = in.nextInt();
 		System.out.println("String format of the said integer: " + transform_int_to_string(n));		
		}
}

Sample Output:

Input an integer:  35
String format of the said integer: 35

Flowchart:

Flowchart: Java exercises:Transform a given integer to String format.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to move every positive number to the right and every negative number to the left of a given array of integers.
Next: Write a Java program to move every zero to the right side of a given array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe