×

Java Programs

Java Practice

Java program to convert number from Decimal to Octal

This program will convert integer (Decimal) number to its equivalent Octal Number.
There are two programs:
1) Without using any predefine method and
2) Using Integer.toOctalString() method.

Without using any predefine method

// java program to convert decimal to octal

import java.util.*;

public class ConvDec2Oct {
  public static void main(String args[]) {
    int num, counter = 0;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter any integer number: ");
    num = sc.nextInt();

    //to store maximum 32 digits
    int octalVal[] = new int[32];

    while (num > 0) {
      octalVal[counter++] = num % 8;
      num = num / 8;
    }

    /*print octal values stored in octalVal*/
    for (int i = counter - 1; i >= 0; i--) {
      System.out.print(octalVal[i]);
    }
  }
}

Output

Complie 	:	javac ConvDec2Oct.java
Run		:	java ConvDec2Oct
Output
Enter any integer number: 12345
30071

Using Integer.toOctalString() method

//java program to convert decimal to octal

import java.util.*;

public class ConvDec2Oct {
  public static void main(String args[]) {
    int num;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter any integer number: ");
    num = sc.nextInt();

    String str = Integer.toOctalString(num);
    System.out.println("Octal number is : " + str);
  }
}

Output

Complie 	:	javac ConvDec2Oct.java
Run		:	java ConvDec2Oct
Output
Enter any integer number: 12345
Octal number is : 30071

Java Number System Conversion Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.