Decimal to Octal Program in Java

Advertisements

Prev Tutorial Next Tutorial

Convert Decimal to Octal Program in Java

There are two way to convert decimal number into octal number, which is given below;

  • Using predefined method Integer.toOctalString(int num)
  • Writing our own logic for conversion

Convert Decimal to Octal in Java

import java.util.Scanner;
class DecimalToOctal
{
  public static void main(String args[])
  {
    Scanner input = new Scanner( System.in );
    System.out.print("Enter a decimal number : ");
    int num =input.nextInt();
 
    String octalString = Integer.toOctalString(num);
    System.out.println("Method 1: Decimal to octal: " + octalString);

  }
}

Output

Enter a decimal number : 123
Decimal to octal: 173

Code Explanation

Using predefined method toOctalString(int) Pass the decimal number to this method and it would return the equivalent octal number.

Convert Decimal to Octal in Java

import java.util.Scanner;

class DecimalToOctal
{
  public static void main(String args[])
  {
    Scanner input = new Scanner( System.in );
    System.out.print("Enter a decimal number : ");
    int num =input.nextInt();
  
    // For storing remainder
    int rem;
 
    // For storing result
    String str=""; 
 
    // Digits in Octal number system
    char dig[]={'0','1','2','3','4','5','6','7'};
 
    while(num>0)
    {
       rem=num%8; 
       str=dig[rem]+str; 
       num=num/8;
    }
    System.out.println("Decimal to octal: "+str);
  }
}

Output

Enter a decimal number : 123
Decimal to octal: 173

Syntax to compile and run java program

Syntax

for compile -> c:/>javac DecimalToOctal.java
for run -> c:/>java DecimalToOctal

Prev Tutorial Next Tutorial

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements