×

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal:
  • Using toOcatlString() method
  • Using user-defined logic
Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer wrapper class that converts decimal to an octal string. The signature of the method is given below: public static String toOctalString(int decimal) Example In the following example, we have invoked the toOctalString() method of Integer wrapper class. The method parses an integer argument which you want to convert and returns the octal representation of the decimal number.
public class DecimalToOctalExample
{
public static void main(String args[])
{
System.out.println(Integer.toOctalString(21));
System.out.println(Integer.toOctalString(67));
}
}
Output
25
103
Using user-defined logic You can also convert decimal to octal in using user-defined logic. Example In the following example, we have defined a method of name conversion. Inside the method body, we have taken two variables rem (represent remainder) of type integer, and octal (represent octal number) of type String. We have also taken an array octalchar[]of characters, and assign values from '0'to '7' into it. The method has a while loop that checks the condition and performs the iterations. Let’s see how the while loop will be executed. Remember: The second statement of the while loop performs concatenation instead of addition.If you change the sequence of the statement octal=octal+octalchars[rem]then the output will be 41 which is the wrong output. So remember the sequence while you write this statement. For first iteration decimal=12                                                                                         //passed parameter 12>0                                                                                                        //condition true rem=12%8 = 4                                                                                   //finds remainder octal=octalchars[4]+octal = 4                                      //updated value of octal is 4 decimal=12/8 = 1                                                              //updated value of decimal is 1 For second iteration decimal=1 1>0                                                                                                           //conditiontrue rem=1%8 = 1                                                                                      //finds remainder octal=octalchars[1]+octal = 14                                    //updated value of octal is 4 decimal=1/8 = 0                                                                                //updated value of decimal is 0 For third iteration decimal=0 0>0                                                                                                         //condition false The while loop terminates the execution, and returns the converted octal value. Similarly you can also perform iteration for the decimal value 75. Hence the third iteration will not be executed. The while loop terminates the execution. The method conversion returns the octalvalue.
public class DecimalToOctalExample1
{
public static String conversion(int decimal)                           //called method
{
int rem;
String octal="";
char octalchars[]={'0','1','2','3','4','5','6','7'};
while(decimal>0)
{
rem=decimal%8;
octal=octalchars[rem]+octal;
decimal=decimal/8;
}
return octal;
}
public static void main(String args[])
{
System.out.println("Decimal to octal of 12 is: "+conversion(12));                                               //methodcalling
System.out.println("Decimal to octal of 75 is: "+conversion (75));
}
}
Output
Decimal to Octal of 12 is: 14
Decimal to octal of 75 is: 113

Related Topics

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.