Signup/Sign In
LAST UPDATED: DECEMBER 1, 2020

How to convert Java Decimal to Octal

In Java, the Decimal value can be converted into Octal value either by using Integer.toOctalString() method or own custom code. Let's see the examples.

1. Integer.toOctalString() Method

The toOctalString() method is a part of Integer class which converts the decimal into octal strings which further can be converted into any type.

Example 1:

Here, the decimal values are converted into octal strings by using the toOctalString() method. See the example below.

public class StudyTonight
{    
	public static void main(String args[])
	{    
		int d1 = 7;
		int d2 = -232;
		int d3 = 30402;

		String h1 = Integer.toOctalString(d1);
		String h2 = Integer.toOctalString(d2);
		String h3 = Integer.toOctalString(d3);

		System.out.println("Octal value is : " +h1);
		System.out.println("Octal value is : " +h2);
		System.out.println("Octal value is : " +h3);
	}    
}


Octal value is : 7
Octal value is : 37777777430
Octal value is : 73302

Example 2:

The decimal values can be converted into octal values using custom logic.

public class StudyTonight
{    
	public static void main(String [] args)
	{  
		int dec = 34673;
		int r;   
		String oct = "";   
		char octchars[]={'0','1','2','3','4','5','6','7'};  

		while(dec>0)  
		{  
			r = dec%8;   
			oct = octchars[r]+oct;   
			dec = dec/8;  
		}  
		System.out.println("Octal value is " +oct);  
	}
}


Octal value is 103561



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.