How to Convert an Integer to Octal in Java

Java wrapper class Integer provides an utility function toOctalString(int) which returns an integer in octal form. However, in this post, we will also see an example on how we can convert integer to octal form mathematically without using Java API classes.

If you divide a number with 8, what you get in the reminder is the last digit of its octal form. We repeat this until dividend becomes zero, get the reminder in each iteration and mathematically append them together.

Program:

package com.techstackjournal;

public class IntegerToOctal {

	public static void main(String[] args) {

		int num = 246;
		int rem = 0, oct = 0, pwr = 0;
		
		while (num > 0) {
			rem = num % 8;
			num = num / 8;
			oct = oct + rem * power(10, pwr);
			pwr++;
		}

		System.out.println(oct);
	}

	private static int power(int n, int p) {
		int result = 1;
		while (p > 0) {
			result = result * n;
			p--;
		}
		return result;
	}

}


Output:

366

Dry Run

Iterationnumoct
(A)
num%8
(B)
num/8
pwrpower(10, pwr)
(C)
oct
A+(B*C)
12460630016
23066311066
3366302100366
See also  String to Integer Conversion