Java Online Compiler
Example: Decimal to Octal Conversion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Decimal to Octal Conversion import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize Scanner for user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt user for a decimal number System.out.print("Enter a decimal number: "); int decimalNumber = scanner.nextInt(); // Step 3: Handle the special case of 0 if (decimalNumber == 0) { System.out.println("Octal equivalent: 0"); scanner.close(); return; } // Step 4: Initialize variables for octal conversion int octalNumber = 0; int i = 1; // Multiplier for placing remainders in correct position // Step 5: Perform conversion using a while loop int tempDecimal = decimalNumber; // Use a temporary variable for calculation while (tempDecimal != 0) { int remainder = tempDecimal % 8; // Get the remainder octalNumber = octalNumber + remainder * i; // Add remainder to octal number tempDecimal = tempDecimal / 8; // Divide the number by 8 i = i * 10; // Increase multiplier for next digit } // Step 6: Print the result System.out.println("The decimal number " + decimalNumber + " in octal is: " + octalNumber); // Step 7: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS