Wednesday, 18 April 2018

Java Project - Number System conversion

Here we are trying to create a java project where you will first let user choose what conversion they want to perform.
Allow user to enter value in the required format and then perform the conversion. On the completion of the process print the converted number format.


Note: The project is in progress. If you want to create on your own you can use the template and write code to perform other conversions as well that is missing here.


Controller.java


package NumberSystem;

import java.util.Scanner;

public class Controller {

      public static void main(String[] args) {
            System.out.println("Enter your choice");
            System.out.println("1: To convert decimal to binary ");
            System.out.println("2: To convert binary to decimal");
            System.out.println("3: To convert ........");  // More to be added soon
           
            Scanner scNum = new Scanner(System.in);
            int choice = scNum.nextInt();
            //System.out.println("You enetered: "+ i);
           
            switch(choice){
            case 1:
                  System.out.println("Enter decimal Number");
                  Scanner sc = new Scanner(System.in);
                  int decNum = sc.nextInt();
                  DecimalToBinary dtb = new DecimalToBinary();
                  dtb.decToBinary(decNum);
                  break;
            case 2:
                  System.out.println("Enter decimal Number");
                  Scanner sc1 = new Scanner(System.in);
                  int binNum = sc1.nextInt();
                  BinaryToDecimal binDec = new BinaryToDecimal();
                  binDec.binToDec(binNum);
                  break;
            case 3:
                  break;
            default: System.out.println("Wrong choice");
            }

      }

}


DecimalToBinary.java


package NumberSystem;

public class DecimalToBinary {

      public void decToBinary(int dec){
            if(dec==0){
                  System.out.println(0);
                  return;
            }
            String binaryString = "";
            while(dec>0){
                  int rem = dec%2;
                  binaryString = rem + binaryString;
                  dec = dec/2;
            }
            System.out.println(binaryString);
      }
}


BinaryToDecimal.java


package NumberSystem;

public class BinaryToDecimal {

      public void binToDec(int binNum){
            int decimalForm = 0;
            int power = 0;
           
            if(binNum==0){
                  System.out.println(0);
                  return;
            }
            while(binNum>0){
                  int tmp = binNum%10;
                  decimalForm += tmp*Math.pow(2, power);
                  binNum = binNum/10;
                  power++;
            }
            System.out.println(decimalForm);
      }
}


Saturday, 28 October 2017

Pascal triangle in java

Program: Write a program to enter number of rows and create a Pascal Triangle.
Input: 5
Output:
     1               row=1
    1 1              row=2
   1 2 1             row=3
  1 3 3 1            row=4
 1 4 6 4 1           row=5



Source FilePascalTriangle.java

package triangle;

public class PascalTriangle
{
      public static void main(String args[])
      {
            int rows, i, k, number=1, j;
            rows = 5;  //change number of rows as per need

            for(i=0;i<rows;i++)
            {
                  for(k=rows; k>i; k--)
                  {
                        System.out.print(" ");
                  }
                  number = 1;
                  for(j=0;j<=i;j++)
                  {
                        System.out.print(number+ " ");
                        number = number * (i - j) / (j + 1);
                  }
                  System.out.println();
            }
      }
}



OUTPUT:

     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1




 You may also like to read about:

Monday, 8 May 2017

Sort elements in ArrayList in java

To sort the elements of list be it linked list or array list, you can use
Collections.sort(List list);

Note: 
* Strings are sorted in lexicographic order(see example below)
* Dates are sorted in chronological order(In our example replace String with Date and see the result)
* Integers are sorted in numeric order(In our example replace String with Integer and see the result)


In the given example, the sorting method is highlighted in similar background color. Lets look at each step closely. Its pretty simple to sort a list.
Lets have a look.

package javaRadarArrayList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class SortArrayList {

      public static void main(String[] args) {
            //create Array List
            ArrayList<String> javaRadarList = new ArrayList<String>();

            //Add elements to ArrayList
            javaRadarList.add("Java");
            javaRadarList.add("Jquery");
            javaRadarList.add("Spring");
            javaRadarList.add("Hibernate");
            javaRadarList.add("EJB");

            //use iterator to traverse list
            System.out.println("Before sorting: " +javaRadarList);

            Collections.sort(javaRadarList); //sorting list element

            Iterator<String> itrAfterSort = javaRadarList.iterator();

            System.out.println("After Sorting:");
            while(itrAfterSort.hasNext()){
                  String token = itrAfterSort.next();
                  System.out.println(token);
            }

      }

}


OUTPUT:


Before sorting: [Java, Jquery, Spring, Hibernate, EJB]
After Sorting:
EJB
Hibernate
Java
Jquery
Spring

Friday, 5 May 2017

Binary search on linked list in java

Before performing binary search operation on list:

  • Sort the given list in ascending order using sort(List) method. See the highlighted portion showing Collections.sort(javaRadarList); in the given program below.
  • After sorting, make call to binary search method. See the second highlighted method call Collections.binarySearch(javaRadarList"Spring"); Here first parameter is the list while the second one is the key that is to be searched in the specified list.


Note
If the list contain multiple elements that are equal to the specified object we are searching then there is no guarantee of which one will be found. Say we have multiple Spring object in list then search result will return which Spring index is not guaranteed.



Source fileSearchLinkedList

package javaRadarLinkedList;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

public class SearchLinkedList {

public static void main(String[] args) {
//create Linked List
LinkedList<String> javaRadarList = new LinkedList<String>();
//Add elements to LinkedList
javaRadarList.add("Java");
javaRadarList.add("Jquery");
javaRadarList.add("Spring");
javaRadarList.add("Hibernate");
javaRadarList.add("EJB");

//use iterator to traverse list
System.out.println("Before sorting: " +javaRadarList);

Collections.sort(javaRadarList); //sorting list element

Iterator<String> itrAfterSort = javaRadarList.iterator();
System.out.println("After Sorting:");
while(itrAfterSort.hasNext()){
String token = itrAfterSort.next();
System.out.println(token);
}

//Binary Search can be performed on Sorted List 
int i=Collections.binarySearch(javaRadarList, "Spring");
System.out.println("Given Key is present at index :"+ i +" on sorted list");

}

}



OUTPUT:

Before sorting: [Java, Jquery, Spring, Hibernate, EJB]
After Sorting:
EJB
Hibernate
Java
Jquery
Spring      //this Spring index(=4) is returned for binary search 
Given Key is present at index :4 on sorted list


To-do for readers:  Now try to add more than one Spring element in list and see the result on performing the binary search operation on the list.

Please write your opinion in the comment box about searching the element from the list using binary search mechanism. 


You may also like to read:



Thursday, 4 May 2017

Sort elements in linked list in java

To sort the elements of list be it linked list or array list, you can use
Collections.sort(List list);

Note: 
* Strings are sorted in lexicographic order(see example below)
* Dates are sorted in chronological order(In our example replace String with Date and see the result)
* Integers are sorted in numeric order(In our example replace String with Integer and see the result)


In the given example the sorting method is highlighted in similar background color. Lets look at each step closely. Its pretty simple to sort a list.
Lets have a look.

Source FileSortLinkedList.java


package javaRadarLinkedList;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

public class SortLinkedList {

      public static void main(String[] args) {
            //create Linked List
            LinkedList<String> javaRadarList= new LinkedList<String>();

            //Add elements to LinkedList
            javaRadarList.add("Java");
            javaRadarList.add("Jquery");
            javaRadarList.add("Spring");
            javaRadarList.add("Hibernate");
            javaRadarList.add("EJB");
             
            //use iterator to traverse list
            System.out.println("Before sorting: " +javaRadarList);
           
            Collections.sort(javaRadarList); //sorting list element
           
            Iterator<String> itrAfterSort = javaRadarList.iterator();

            System.out.println("After Sorting:");
            while(itrAfterSort.hasNext()){
                  String token = itrAfterSort.next();
                  System.out.println(token);
            }

      }

}



OUTPUT:

Before sorting: [Java, Jquery, Spring, Hibernate, EJB]

After Sorting:
EJB
Hibernate
Java
Jquery
Spring

Friday, 21 April 2017

Reverse given String in java

This question is generally asked to the fresh college pass outs or the java developer with 1-3 years of experience. 

It's quite simple question. The sole purpose of asking it is to find out if you will preserve the immutability of String or not. Many directly apply reverse() method on given String itself forgetting that no such method exists for String operation.

To reverse a immutable String you will need use of StringBuffer or StringBuilder. Both has a difference among them but using any of them will allow you to serve the purpose.

Here we are showing you the example of StringBuffer.


Source fileReverseString .java


package String_Programs;

public class ReverseString {
       public static void main(String[] args) {
              String str = "Rajneesh";  //Remember, String is immutable
              //use StringBuffer(or Builder) for modification
              StringBuffer sb = new StringBuffer(str); 
              sb.reverse();  //reverse the string builder data             
             
              String modifiedStr = sb.toString();  //StringBuffer to String conversion
              System.out.println(str" when reversed :" + modifiedStr);
       }
}


OUTPUT:

Rajneesh when reversed :hseenjaR


Note

If you want to use StringBuilder then replace this line 

StringBuffer sb = new StringBuffer(str); 

in the above program with 

StringBuilder sb = new StringBuilder(str); 




You may like to read:
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.