Basic Java – 13 || Decimal values v/s Octal base(8) values in JAVA.

Any numeric value which fulfills below conditions would be treated as octal base(8) values:

  1. Should have three or more digits
  2. Should start with 0

Octal base number system

The octal number system is like a binary number system having the base of 8. It works on 0-7 digits values.

Example of Octal numbers, 010, 011, 0111 etc.

Octal Base
Octal Base

As mentioned in the above example, we can see that it is like binary conversion just base gets changed to octal base(8) value. Below are the steps to formalize this process:

  1. The integer value is 011
  2. Consider the total number of digits is n
  3. Consider single digit as d3d2d1 (We can also consider it as di )
  4. E is the Exponential value which gets started at 0 and from the left side
  5. Value of E would increase by 1 to n-1.
  6. 8E x di
  7. Summation of the above formula for all the digits will get us an octal value.

Whenever the compiler finds any numeric value starting with 0 and having 3 or more digits, it treats it as an Octal base values.

Try to print int i = 011, the output will be 9 which is the octal value of 011. But here is a trick to print value as it is 011. We could achieve this by using System.out.format() method.

System.out.format(“Display in Octal format: %03o“,temp); (o is O for owl not zero).

System.out.format(“Display in Decimal format: %03d“,temp);


Related Links:

Java File Handling:

OOPs Concept:

Java Question And Answer:

Java Programs:


Code Example:

/**
 * @author ashok.kumar
 *
 */
public class Test1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		int l=10;
		
		System.out.println("Numeric:" + l);
		
		
		int m=010;
		
		System.out.println("Octal value:" + m);
		
		int n=0100;
		
		System.out.println("Octal value:" + n);
		
		int mn=1110;
		
		System.out.println("Numeric:" + mn);
		
		int jk=0112;
		
		System.out.println("Octal value: "+jk);
		
		int temp=0111;
		
		System.out.format("Display in Octal format: %04o",temp);
	}
}

Output:
Numeric:10
Octal value:8
Octal value:64
Numeric:1110
Octal value: 74
Display in Octal format: 0111

More Examples:

Difference between int x= 10 and y=010 in Java.



871total visits,1visits today

Leave a Reply

Your email address will not be published. Required fields are marked *