• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer
  • Home
  • Java Tutorial
  • Java Posts
  • Node.js
  • Spring Core
  • Algorithms
  • Docker
  • Blogging
  • Misc
Tech Stack Journal

Tech Stack Journal

How to Convert an Integer to Octal in Java

April 24, 2020 by Admin Leave a Comment

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

Filed Under: Java

Previous Post: « How to Reverse an Integer in Java
Next Post: Finding Maximum of Three Numbers in Java »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *


Primary Sidebar

More to See

Arrays.asList in Java Examples

February 21, 2021 By Admin

[Solved] Why List.add throws UnsupportedOperationException in Java?

February 20, 2021 By Admin

Secondary Sidebar

Categories

  • Algorithms
  • Blogging
  • Docker
  • Java
  • Misc
  • Node.js
  • Spring Core
  • Windows

Archives

  • February 2021 (6)
  • January 2021 (1)
  • December 2020 (1)
  • September 2020 (2)
  • August 2020 (5)
  • July 2020 (4)
  • June 2020 (1)
  • May 2020 (4)
  • April 2020 (22)
  • November 2019 (3)
  • September 2019 (2)
  • August 2019 (6)

Footer

Navigation

  • Home
  • Java Tutorial
  • Java Posts
  • Node.js
  • Spring Core
  • Algorithms
  • Docker
  • Blogging
  • Misc

Recent

  • How to Make File Explorer Open to This PC instead of Quick Access in Windows 10
  • Arrays.asList in Java Examples
  • [Solved] Why List.add throws UnsupportedOperationException in Java?
  • How to Convert an Array to List in Java?
  • How Many Spaces in a Tab?

Search

Copyright © 2021 · Tech Stack Journal · Log in