Java Example program convert Decimal to Binary

  • On of the way to convert decimal number to its binary representation using the Integer.toBinaryString() method. This method takes an integer as an argument and returns its binary representation as a string. Here is an example:
public static String decimalToBinary(int decimal) {
    return Integer.toBinaryString(decimal);
}

We can call this method and pass a decimal number as an argument, and it will return the binary representation of that number. For example:

int decimal = 10;
String binary = decimalToBinary(decimal);
System.out.println(binary); // Output: 1010

In the above method will return a string representation of the binary number, if we want to have it as an integer you can use Integer.parseInt(binary, 2) to convert it to an int.

Another way to convert a decimal number to its binary representation is by using bit shifting and bitwise operations. You can repeatedly divide the decimal number by 2 and keep track of the remainder. The remainder represents the least significant bit of the binary representation. You can then reverse the order of the remainders to get the binary representation of the decimal number.

In summary, In Java you can use the Integer.toBinaryString() method to convert a decimal number to its binary representation as a string, and you can use Integer.parseInt(binary, 2) to convert it to an int. Also, you can use bit shifting and bitwise operations to convert a decimal number to its binary representation.

Another way to convert a decimal number to its binary representation is by using bit shifting and bitwise operations. 
This method involves repeatedly dividing the decimal number by 2 and keeping track of the remainders. The remainders represent the least significant bits of the binary representation.


public static String decimalToBinaryUsingBitOperation(int decimal) {
    StringBuilder binary = new StringBuilder();
    while (decimal > 0) {
        binary.append(decimal % 2);
        decimal = decimal >> 1;
    }
    return binary.reverse().toString();
}

the function uses a while loop to divide the decimal number by 2 and keep track of the remainders. The remainders are appended to a StringBuilder object. The while loop continues until the decimal number is 0. At the end of the loop, the binary representation of the decimal number is obtained by reversing the order of the remainders using the reverse() method of the StringBuilder. The binary representation is then returned as a string.

This method will also work for negative decimal numbers, but the result will be the two's complement representation of the negative number, it will have a leading 1 in the most significant bit.

It's worth noting that, the above method will return the binary representation as a string, if you want to have it as an integer you can use Integer.parseInt(binary, 2) to convert it to an int.

In summary, there are different ways to convert a decimal number to its binary representation in Java. One way is to use the Integer.toBinaryString() method, another way is by using bit shifting and bitwise operations, this method uses a while loop to repeatedly divide the decimal number by 2 and keep track of the remainders, which represent the binary representation of the decimal number. The result can be returned as a string or as an integer by using the Integer.parseInt(binary, 2)

  • We can convert binary to decimal in three ways
    1.Using Integer.toBinaryString(int num);
    2.Using Stack
    3.Using Custom logic 


1.Write a Java Program to convert decimal to binary in java using Integer.toBinaryString(int num)

  1. import java.util.Scanner;
  2. public class ConvertDecimalToBinary{
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  System.out.println("\nBinary representation of 1: ");
  11.  System.out.println(Integer.toBinaryString(1));
  12.  System.out.println("\nBinary representation of 4: ");
  13.  System.out.println(Integer.toBinaryString(4));
  14.  System.out.println("Binary representation of 10: ");
  15.  System.out.println(Integer.toBinaryString(10));
  16.  System.out.println("\nBinary representation of 12: ");
  17.  System.out.println(Integer.toBinaryString(12));
  18.  System.out.println("\nBinary representation of 120: ");
  19.  System.out.println(Integer.toBinaryString(120));
  20.  System.out.println("\nBinary representation of 500: ");
  21.  System.out.println(Integer.toBinaryString(500));

  22. }
  23.  
  24. }





Output:

  1. Binary representation of 1: 
  2. 1
  3. Binary representation of 4: 
  4. 100
  5. Binary representation of 10: 
  6. 1010
  7. Binary representation of 12: 
  8. 1100
  9. Binary representation of 120: 
  10. 1111000
  11. Binary representation of 500: 
  12. 111110100

2.Write a Java Program to convert decimal to binary in java


  1. import java.util.Scanner;
  2. import java.util.Stack;
  3. public class ConvertDecimalToBinary{
  4.  
  5.     /**
  6.      *www.instanceofjava.com
  7.      */
  8.  
  9.  
  10.  public static void main(String[] args) {
  11.         
  12. Scanner in = new Scanner(System.in);
  13.          
  14. // Create Stack object
  15. Stack<Integer> stack = new Stack<Integer>();
  16.      
  17. //Take  User input from keyboard
  18.  System.out.println("Enter decimal number: ");
  19.  int num = in.nextInt();
  20.     
  21. while (num != 0)
  22. {
  23.    int d = num % 2;
  24.    stack.push(d);
  25.    num /= 2;
  26.  
  27.  } 
  28.      
  29.  System.out.print("\nBinary representation is:");
  30.  
  31. while (!(stack.isEmpty() ))
  32.  {
  33.    System.out.print(stack.pop());
  34.  }
  35.         
  36.  
  37. System.out.println();
  38.  
  39. }
  40.  
  41. }
  42.  
  43. }


Output:

  1. Enter decimal number: 
  2. 12
  3.  
  4. Binary representation is:1100

java program convert decimal to binary


3.Write a Java Program to convert decimal to binary in java


  1. import java.util.Scanner;
  2. public class ConvertDecimalToBinary{
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8. public static void convertDeciamlToBinary(int num){
  9.  
  10.   int binary[] = new int[40];
  11.          int index = 0;
  12.  while(num > 0){
  13.            binary[index++] = num%2;
  14.            num = num/2;
  15.  }

  16. for(int i = index-1;i >= 0;i--){
  17.            System.out.print(binary[i]);
  18. }
  19.  
  20. }
  21.  
  22.  public static void main(String[] args) {
  23.         
  24. System.out.println("Binary representation of 1: ");
  25. convertDeciamlToBinary(1);
  26.  
  27. System.out.println("\nBinary representation of 4: ");
  28. convertDeciamlToBinary(4);
  29.  
  30. System.out.println("\nBinary representation of 10: ");
  31. convertDeciamlToBinary(10);
  32.  
  33. System.out.println("\nBinary representation of 12: ");
  34.  convertDeciamlToBinary(12);
  35.  
  36. }
  37.  
  38. }


Output:

  1. Binary representation of 1: 
  2. 1
  3. Binary representation of 4: 
  4. 100
  5. Binary representation of 10: 
  6. 1010
  7. Binary representation of 12: 
  8. 1100

You Might Like:

 


Java programming interview questions

  1. Print prime numbers? 
  2. What happens if we place return statement in try catch blocks 
  3. Write a java program to convert binary to decimal 
  4. Java Program to convert Decimal to Binary
  5. Java program to restrict a class from creating not more than three objects
  6. Java basic interview programs on this keyword 
  7. Interfaces allows constructors? 
  8. Can we create static constructor in java 
  9. Super keyword interview questions java 
  10. Java interview questions on final keyword
  11. Can we create private constructor in java
  12. Java Program Find Second highest number in an integer array 
  13. Java interview programming questions on interfaces 
  14. Top 15 abstract class interview questions  
  15. Java interview Questions on main() method  
  16. Top 20 collection framework interview Questions
  17. Java Interview Program to find smallest and second smallest number in an array 
  18. Java Coding Interview programming Questions : Java Test on HashMap  
  19. Explain java data types with example programs 
  20. Constructor chaining in java with example programs 
  21. Swap two numbers without using third variable in java 
  22. Find sum of digits in java 
  23. How to create immutable class in java 
  24. AtomicInteger in java 
  25. Check Even or Odd without using modulus and division  
  26. String Reverse Without using String API 
  27. Find Biggest substring in between specified character
  28. Check string is palindrome or not?
  29. Reverse a number in java?
  30. Fibonacci series with Recursive?
  31. Fibonacci series without using Recursive?
  32. Sort the String using string API?
  33. Sort the String without using String API?
  34. what is the difference between method overloading and method overriding?
  35. How to find largest element in an array with index and value ?
  36. Sort integer array using bubble sort in java?
  37. Object Cloning in java example?
  38. Method Overriding in java?
  39. Program for create Singleton class?
  40. Print numbers in pyramid shape?
  41. Check armstrong number or not?
  42. Producer Consumer Problem?
  43. Remove duplicate elements from an array
  44. Convert Byte Array to String
  45. Print 1 to 10 without using loops
  46. Add 2 Matrices
  47. Multiply 2 Matrices
  48. How to Add elements to hash map and Display
  49. Sort ArrayList in descending order
  50. Sort Object Using Comparator
  51. Count Number of Occurrences of character in a String
  52. Can we Overload static methods in java
  53. Can we Override static methods in java 
  54. Can we call super class static methods from sub class 
  55. Explain return type in java 
  56. Can we call Sub class methods using super class object? 
  57. Can we Override private methods ? 
  58. Basic Programming Questions to Practice : Test your Skill
  59. Java programming interview questions on collections

Java Example Program to convert binary to decimal


  • Famous interview java question on conversions . 
  • We can convert binary to decimal in two ways
    1.Using Integer.parseInt() method
    2.Using custom logic



1.Write a Java Program to convert binary to decimal number in java without using Integer.parseInt() method.

  1. import java.util.Scanner;
  2. public class DecimalFromBinary {
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  Scanner in = new Scanner( System.in );
  11.  System.out.println("Enter a binary number: ");
  12.  
  13.   int  binarynum =in.nextInt();
  14.   int binary=binarynum;
  15.         
  16. int decimal = 0;
  17. int power = 0;
  18.  
  19. while(true){
  20.  
  21.  if(binary == 0){
  22.  
  23.         break;
  24.  
  25.  } else {
  26.  
  27.    int tmp = binary%10;
  28.    decimal += tmp*Math.pow(2, power);
  29.    binary = binary/10;
  30.    power++;
  31.  
  32.  }
  33. }
  34.         System.out.println("Binary="+binary+" Decimal="+decimal); ;
  35. }
  36.  
  37. }

Output:


  1. Enter a binary number: 
  2. 101
  3. Binary=101 Decimal=5




2.Write a Java Program to convert binary to decimal number in java using Integer.parseInt() method.



  1. import java.util.Scanner;
  2. public class ConvertBinaryToDecimal{
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  Scanner in = new Scanner( System.in );
  11.  
  12.  System.out.println("Enter a binary number: ");
  13.  String binaryString =input.nextLine();
  14.  
  15.  System.out.println("Result: "+Integer.parseInt(binaryString,2));

  16.  
  17. }
  18.  
  19. }


Output:


  1. Enter a binary number:
  2. 001
  3. Result: 1

java program to convert binary to decimal


You Might like:

Get collection values from hashtable example

1.Basic java collection framework example program to get Value collection from hashtable

  •   Collection values()   This method used to get collection of values
  •  Important note is that if any value is removed from set the original hashtable key also removed
  1. package com.setviewHashtable;
  2.  
  3. import java.util.Hashtable;

  4. import java.util.Enumeration;
  5. import java.util.Iterator;
  6. import java.util.Set;
  7.  
  8. public class HashtableExample{
  9.  
  10. public static void main(String[] args) {
  11.   
  12.  //create Hashtable object
  13.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
  14.        
  15. //add key value pairs to Hashtable
  16. hashtable.put("1","Java Interview Questions");
  17. hashtable.put("2","Java Interview Programs");
  18. hashtable.put("3","Concept and example program");
  19. hashtable.put("4","Concept and interview Questions");
  20. hashtable.put("5","Java Quiz");
  21. hashtable.put("6","Real time examples");
  22.  
  23.  
  24.  Collection c = hashtable.values();
  25.  System.out.println("Values of Collection created from Hashtable are :");
  26. //iterate through the Set of keys
  27.  
  28.  Iterator itr = c.iterator();
  29.  while(itr.hasNext())
  30.  System.out.println(itr.next());
  31.            
  32.  c.remove("Java Quiz");
  33.            
  34. System.out.println("Elements in hash table");
  35. Enumeration e=hashtable.elements();
  36.         
  37.  
  38.  while (e.hasMoreElements()) {
  39.         System.out.println(e.nextElement());
  40. }    

  41. }
  42.  
  43. }
     



Output:

  1. Values of Collection created from Hashtable are :
  2. Real time examples
  3. Java Quiz
  4. Concept and interview Questions
  5. Concept and example program
  6. Java Interview Programs
  7. Java Interview Questions
  8. Elements in hash table
  9. Real time examples
  10. Concept and interview Questions
  11. Concept and example program
  12. Java Interview Programs
  13. Java Interview Questions


Java Collections example program Get Set view of Keys from Hashtable example

1.Basic java collection framework example program to get set view from hashtable

  • Set keySet()   This method used to get set view of the keys of hashtable
  •  Important note is that if any key is removed from set the original hashtable key also removed
  1. package com.setviewHashtable;
  2.  
  3. import java.util.Hashtable;

  4. import java.util.Enumeration;
  5. import java.util.Iterator;
  6. import java.util.Set;
  7.  
  8. public class HashtableExample{
  9.  
  10. public static void main(String[] args) {
  11.   
  12.  //create Hashtable object
  13.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
  14.        
  15. //add key value pairs to Hashtable
  16. hashtable.put("1","Java Interview Questions");
  17. hashtable.put("2","Java Interview Programs");
  18. hashtable.put("3","Concept and example program");
  19. hashtable.put("4","Concept and interview Questions");
  20. hashtable.put("5","Java Quiz");
  21. hashtable.put("6","Real time examples");
  22.  
  23.  
  24.  Set st = hashtable.keySet();       
  25.  System.out.println("Set created from Hashtable Keys contains :");
  26. //iterate through the Set of keys
  27.  
  28.  Iterator itr = st.iterator();
  29.  while(itr.hasNext())
  30.  System.out.println(itr.next());
  31.            
  32.  st.remove("1");
  33.            
  34. System.out.println("Elements in hash table");
  35. Enumeration e=hashtable.keys();
  36.         
  37.  
  38.  while (e.hasMoreElements()) {
  39.         System.out.println(e.nextElement());
  40. }    

  41. }
  42.  
  43. }
     



Output:

  1. Set created from Hashtable Keys contains :
  2. 6
  3. 5
  4. 4
  5. 3
  6. 2
  7. 1
  8. Elements in hash table
  9. 6
  10. 5
  11. 4
  12. 3
  13. 2

Java collections interview programming questions

java collections interview programs


Top 100 Java Programs asked in Interviews
  1. Introduction to Collection Framework  

  2. Collection Interface in Java 
  3. Top 20 collection framework interview questions for freshers and experienced

Collection set interface: 

  1. Collection Set Interface    

Hashset Class in Collection framework: (Java programming questions)

  1. Hashset class in java  
  2.  
  3.  
  4.  

LinkedHashSet Class in Collection framework: (Java programming questions)

  1.  

Treeset Class in Collection framework: (Java programming questions)
 
  1.  
  2.  



 Collection List Interface:

  1. Collection List Interface 

ArrayList Class in Collection framework: (Java programming questions)

  1.    
  2.  
  3.  
  4.  
  5. Top 100 Java Programs asked in Interviews 

Map Interface In java

  1. Map interface  

HashMap Class in Collection framework: (Java programming questions)

  1.  
  2.  
  3. Convert keys of a map to List 
  4. Convert Values of a map to List 

 Hashtable Class in Collection framework: (Java interview programming questions)

  1.  
  2.  
  3.  
  4. Top 100 Java Programs asked in Interviews  

Java collections programming interview questions 

  1. Top 20 collection framework interview questions for freshers and experienced  
  2. Collection vs Collections
  3. Difference between enumeration and iterator and list iterator? 
  4. Difference between arraylist and vector 
  5. Differences between HashMap and Hash-table  
  6. Comparable vs Comparator 
  7. Custom iterator in java   
  8. Top 100 Java Programs asked in Interviews 

Remove all elements from hashtable java example

1.Basic java example program to remove all elements from hashtable
  • Object remove(Object key)    This method used to remove value pair from hashtable
  • void clear() this method removes all elements from hashtable
  •  
  1. package com.removevalueHashtable;
  2.  
  3. import java.util.Hashtable;

  4. import java.util.Enumeration;
  5.  
  6. public class HashtableExample{
  7.  
  8. public static void main(String[] args) {
  9.   
  10.  //create Hashtable object
  11.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
  12.        
  13. //add key value pairs to Hashtable
  14. hashtable.put("1","Java Interview Questions");
  15. hashtable.put("2","Java Interview Programs");
  16. hashtable.put("3","Concept and example program");
  17. hashtable.put("4","Concept and interview Questions");
  18. hashtable.put("5","Java Quiz");
  19. hashtable.put("6","Real time examples");
  20.  
  21. Object obj = ht.remove("2");
  22. System.out.println(obj + " Removed from Hashtable");
  23.  
  24. Enumeration e=hashtable.elements();
  25.           
  26.  
  27.  while (e.hasMoreElements()) {
  28.         System.out.println(e.nextElement());
  29. }    
  30. hashtable.clear();
  31.  
  32.  System.out.println("Total key value pairs in Hashtable are : " + hashtable.size());

  33. }
  34.  
  35. }
     



Output:

  1. Java Interview Programs Removed from Hashtable
  2. Real time examples
  3. Java Quiz
  4. Concept and interview Questions
  5. Concept and exampe program
  6. Java Interview Questions
  7. Total key value pairs in Hashtable are : 0

Remove key value pair from hashtable java example

1.Basic java example program to iterate keys of hashtable
  • Object remove(Object key)    This method used to remove value pair from hashtable
  1. package com.removevalueHashtable;
  2.  
  3. import java.util.Hashtable;

  4. import java.util.Enumeration;
  5.  
  6. public class HashtableExample{
  7.  
  8. public static void main(String[] args) {
  9.   
  10.  //create Hashtable object
  11.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
  12.        
  13. //add key value pairs to Hashtable
  14. hashtable.put("1","Java Interview Questions");
  15. hashtable.put("2","Java Interview Programs");
  16. hashtable.put("3","Concept and example program");
  17. hashtable.put("4","Concept and interview Questions");
  18. hashtable.put("5","Java Quiz");
  19. hashtable.put("6","Real time examples");
  20.  
  21. Object obj = ht.remove("2");
  22. System.out.println(obj + " Removed from Hashtable");
  23.  
  24. Enumeration e=hashtable.elements();
  25.           
  26.  
  27.            
  28. // display search result
  29.  while (e.hasMoreElements()) {
  30.         System.out.println(e.nextElement());
  31. }    

  32. }
  33.  
  34. }
     



Output:

  1. Java Interview Programs Removed from Hashtable
  2. Real time examples
  3. Java Quiz
  4. Concept and interview Questions
  5. Concept and exampe program
  6. Java Interview Questions
Select Menu