Q:

Java Convert Decimal to Octal

belongs to collection: Java Conversion Programs

0

We can convert decimal to octal in java using Integer.toOctalString() method or custom logic.

Java Decimal to Octal conversion: Integer.toOctalString()

The Integer.toOctalString() method converts decimal to octal string. The signature of toOctalString() method is given below:

 

public static String toOctalString(int decimal)  

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Let's see the simple example of converting decimal to octal in java.

//Java Program to demonstrate the use of Integer.toOctalString() method  
public class DecimalToOctalExample1{  
public static void main(String args[]){  
//Using the predefined Integer.toOctalString() method  
//to convert decimal value into octal  
System.out.println(Integer.toOctalString(8));  
System.out.println(Integer.toOctalString(19));  
System.out.println(Integer.toOctalString(81));  
}}  

 

Output:

10
23
121

 

Java Decimal to Octal conversion: Custom Logic

We can convert decimal to octal in java using custom logic.

//Java Program to demonstrate the decimal to octal conversion  
//using custom code  
public class DecimalToOctalExample2{    
//creating method for conversion so that we can use it many times  
public static String toOctal(int decimal){    
    int rem; //declaring variable to store remainder  
    String octal=""; //declareing variable to store octal  
    //declaring array of octal numbers  
    char octalchars[]={'0','1','2','3','4','5','6','7'};  
    //writing logic of decimal to octal conversion   
    while(decimal>0)  
    {  
       rem=decimal%8;   
       octal=octalchars[rem]+octal;   
       decimal=decimal/8;  
    }  
    return octal;  
}    
public static void main(String args[]){      
//Calling custom method to get the octal number of given decimal value  
System.out.println("Decimal to octal of 8 is: "+toOctal(8));  
System.out.println("Decimal to octal of 19 is: "+toOctal(19));  
System.out.println("Decimal to octal of 81 is: "+toOctal(81));  
}}

 

Output:

Decimal to octal of 8 is: 10
Decimal to octal of 19 is: 23
Decimal to octal of 81 is: 121

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Java Convert Octal to Decimal...