Java Code Example: convert decimal to octal number

This Java program converts a given number into its equivalent octal representation. Here’s how the code works:

  1. The program starts by importing the Scanner class, which is used to read input from the user.
  2. A class named ConvertToOctal is defined that contains a main method.
  3. A variable num of type int is declared to store the input number that the user will provide.
  4. The Scanner object s is created to read input from the user. The program prompts the user to enter a number by using System.out.print method.
  5. The input number is read using the nextInt method of the Scanner class and stored in the variable num.
  6. The Scanner object is closed using the close method.
  7. The octal equivalent of the number is obtained using the toOctalString method of the Integer class, which takes the input number as an argument and returns the octal equivalent as a string.
  8. The octal equivalent of the number is stored in the variable oct.
  9. The program prints the octal equivalent of the number by concatenating the string “Octal value of number ” with the value of num, the string ” is: ” with the value of oct.
  10. The program terminates after the output is displayed.
import java.util.Scanner;

public class ConvertToOctal {
  public static void main(String[] args) {
    int num;

    Scanner s = new Scanner(;
    System.out.print("Please enter a number: ");

    num = s.nextInt();


    String oct = Integer.toOctalString(num);
    System.out.println("Octal value of number " + num + " is: " + oct);
Please enter a number: 15
Octal value of number 15 is: 17