PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How do I convert an Int to an Int[] in java?

 July 20, 2022     arrays, converters, integer, java, type-conversion     No comments   

Issue

I want to convert a primitive Java integer value:

int myInt = 4821;

To an integer array:

int[] myInt = {4, 8, 2, 1};

Solution

There can be so many ways to do it. A concise way of doing it's using Stream API as shown below:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int myInt = 4821;
        int[] arr = 
            String.valueOf(Math.abs(myInt)) // Convert the absolute value to String
            .chars()                        // Get IntStream out of the String
            .map(c -> c - 48)               // Convert each char into numeric value
            .toArray();                     // Convert the stream into array

        // Display the array
        System.out.println(Arrays.toString(arr));
    }
}

Output:

[4, 8, 2, 1]

Notes:

  1. ASCII value of '0' is 48, that of '1' is 49 and so on.
  2. Math#abs returns the absolute value of an int value
    • e.g. Math.abs(-5) = 5 and Math.abs(5) = 5


Answered By - Arvind Kumar Avinash
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing