Difference between float and double java

  • Float data type in java is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the mantissa
  • Where as Double is  is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of mantissa.
  • Default value of float is 0.0f.
  • Default value of double is 0.0d.
  • Floating points numbers also known as real numbers and in java there are two types of floating point one is float and another one is double.

In Java, both double ;and float  are used for storing decimal numbers, but they are not the same in the following ways:


floatdouble
Size32-bit (4 bytes)64-bit (8 bytes)
Precision~6-7 decimal digits~15-16 decimal digits
Default Type No (needs f or F)Yes (default for decimals)
Performance Faster on some processorsHigher precision, may be slower
Range ±3.4 × 10³⁸±1.8 × 10³⁰⁸
Usage When memory is a concernWhen high precision is needed

When to Use:

  • Use float when dealing with graphics or in game development when memory savings are more significant than precision.
  • Use double for scientific calculations, financial applications, or whenever high precision is critical.

  • Float specifies single precision and double specifies double precision.
  • According to the IEEE standards, float is a 32 bit representation of a real number while double is a 64 bit representation
  • Normally we use double instead of float to avoid common overflow of range of numbers
  • Check below diagram for width and range of float and double data types


float vs double java


 When do you use float and when do you use double:

  • Use double data type for all your calculations and temp variables. 
  • Use float when you need to maintain an array of numbers - float[] array (if precision is sufficient), and you are dealing with over tens of thousands of float numbers.
  • Most of the math functions or operators convert/return double, and you don't want to cast the numbers back to float for any intermediate steps.

How many significant digits have floats and doubles in java?

  • In java float can handle about 7 decimal places.
  • And double can handle about 16 decimal places

Program #1: write a java example program which explains differences between float and double in java

  1. package com.instanceofjava.floatvsdouble;

  2. import java.math.BigDecimal;


  3. public class FloatVsDouble {

  4. /**
  5. * @website: www.instanceofjava.com
  6. * @category: float vs double in java with example program
  7. */
  8. public static void main(String[] args) {
  9.     float  a=10.8632667283322234f;
  10.     double b=10.8632667283322234f;
  11.     
  12.      System.out.println("float value="+a);
  13.      System.out.println("double value="+b);
  14.         
  15.      b=10.8632667283322234d;
  16.         
  17.     System.out.println("float value="+a);
  18.     System.out.println("double value="+b);
  19.        

  20. }

  21. }

Output:

  1. float value=10.863267
  2. double value=10.863266944885254
  3. float value=10.863267
  4. double value=10.863266728332224

Difference between float and double java


How to open a webpage using java code

  • We can open a website or web page using java.
  • By calling browse() method of java.awt.Desktop.getDesktop() and passing required webpage url as an URI.
  • In order to make URI create a object fro java.net.uri class objet by passing URL of the web page which need to open
  • java.awt.Desktop.getDesktop().browse(uri);
  • Lets see a java program on how to open website url.
                



Program #1: Simple Java Program to open a website or webpage using java.awt.Desktop

  1. package com.instanceofjava.openwebpage;

  2. import java.awt.Desktop;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.net.URI;

  6. public class OpenVLCPlayer {

  7. /**
  8. * @website: www.instanceofjava.com
  9. * @category: how to open a webpage in browser using java code
  10. */
  11.  
  12. public static void main(String[] args)  {
  13. try {
  14. URI uri= new URI("http://www.instanceofjava.com");
  15. java.awt.Desktop.getDesktop().browse(uri);
  16. System.out.println("Web page opened in browser");
  17.  
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. }
  21. }

  22. }

Output:


  1. Web page opened in browser
     

how to open a webpage using java code

JSP Jstl if else statement with mutilple conditions

  • JSTL means Java Server pages standard Tag Library.
  • JSTL is a collection of useful JSP tags to simplify the JSP development.
  • Lets see how to write  if and if else statements  in java server pages using JSTL



JSTL If condition in JSP :

  • We can use JSTL tags by providing 
  • <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Program  #1: Write a program to how to use JSTL if condition in Java server pages


  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
  4. /TR/html4/loose.dtd">
  5.  
  6. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  7. <html>
  8. <head>
  9. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  10. <title>JSTL if condition</title>
  11. </head>
  12. <body>
  13.  
  14.  <c:set var="age" scope="session" value="${20}"/>
  15. <c:if test="${age > 18}">
  16.    <p>My age is: <c:out value="${age}"/><p>
  17. </c:if>
  18. </body>
  19. </html>
Output:


jstl if condition
JSTL If  else condition in JSP :
  • We use  c:when and c:otherwise tags in JSTL like if else in java

Program  #2: Write a program to how to use JSTL if  else condition in Java server pages


  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
  4. /TR/html4/loose.dtd">
  5.  
  6. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  7. <html>
  8. <head>
  9. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  10. <title>JSTL if else condition</title>
  11. </head>
  12. <body>
  13.  
  14.  <h1>c:when, c:otherwise, c:choose</h1>  
  15.  
  16. <c:set  var="year" value="2016" ></c:set>  
  17. <c:choose>  
  18. <c:when test="${year%4==0}">  
  19. <c:out value="leap year"></c:out>  
  20. </c:when>  
  21. <c:otherwise>  
  22. <c:out value="Not Leap year"></c:out>  
  23. </c:otherwise>  
  24. </c:choose>
  25.  
  26. </body>
  27. </html>
Output:


jstl if else statement





JSTL  multiple If  else conditions in JSP :
  • We use  c:when and c:otherwise tags in JSTL like if else if else in java server pages.
  • Lest wee how to use if else ladder and compare string in jstl  multiple if else conditions.
  • Jstl if else statement multiple conditions

Program  #3: Write a program to how to use  comparing string in JSTL multiple  if  else condition in Java server pages


  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
  4. /TR/html4/loose.dtd">
  5.  
  6. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  7. <html>
  8. <head>
  9. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  10. <title>JSTL multiple if else condition/ if else ladder</title>
  11. </head>
  12. <body>
  13.  
  14. <c:set  var="Day" value="Friday" ></c:set>  
  15. <c:choose>  
  16. <c:when test="${Day=='Sunday'}">  
  17. <c:out value="Its SunDay"></c:out>  
  18. </c:when> 
  19. <c:when test="${Day=='Monday'}"> 
  20. <c:out value="Its MonDay"></c:out>  
  21. </c:when>  
  22. <c:when test="${Day=='Tuesday'}"> 
  23. <c:out value="Its TuesDay"></c:out>  
  24. </c:when>  
  25. <c:when test="${Day=='Wednesday'}"> 
  26. <c:out value="Its Wednesday"></c:out>  
  27. </c:when>  
  28. <c:when test="${Day=='Thursday'}"> 
  29. <c:out value="Its ThursDay"></c:out>  
  30. </c:when>  
  31. <c:when test="${Day=='Friday'}"> 
  32. <c:out value="Its FriDay"></c:out>  
  33. </c:when>  
  34. <c:otherwise>  
  35. <c:out value="Its Saturday"></c:out>  
  36. </c:otherwise>  
  37. </c:choose>  
  38.  
  39. </body>
  40. </html>
Output:


jstl if statement multiple conditions

Merge sort algorithm in java with example program

  • Merge sort one of the recursive sorting algorithm.
  • First divide the list of unsorted elements in two two parts. left half and right half.

  • Divide the left part elements in to sub lists until it become single element.
  • Divide right half of array or list of elements in to sub lists until it becomes one element in list.
  • After dividing all elements in two parts in to single entity. 
  • Merge the elements into two by comparing lesser element will be first. apply same at right half
  • Merge all the elements in the left part until it become single sorted list
  • Now we have two sorted parts.
  • Means two parts sorted in ascending order and smaller element will be in first position.
  • Compare fist elements of two parts , lesser one should be takes first place in new sorted list
  • New sorted list or array having only one element now.
  • Compare two lists elements and place in sorting order and merge it. 
  • Finally we have all elements sorted.
  • Compared to remaining algorithms like selection sort, insertion sort and bubble sort  merge sort works faster.
  • Lets see what will be the time complexity of merge sort algorithm.

Time complexity of merge sort algorithm:


1.Best case  time complexity:      O(n log (n))
2.Average case time complexity: O(n log (n))
3.Worst case time complexity:    O(n log (n))
4.Worst case space complexity:  O(n)


Merge sort in java with explanation diagram

Implement merge sort in java


Program#1: Java program to implement merge sort algorithm data structure

  1. package com.instanceofjava.mergesortalgorithm;

  2. public class MergeSortAlgorithm {

  3.    private int[] resarray;
  4.    private int[] tempMergArray;
  5.    private int length;
  6.  
  7.  public static void main(String a[]){
  8.         
  9.  int[] inputArr ={6,42,2,32,15,8,23,4};
  10.         System.out.println("Before sorting");

  11.        for(int i:inputArr){
  12.           System.out.print(i);
  13.            System.out.print(" ");
  14. }

  15.  MergeSortAlgorithm mergesortalg = new MergeSortAlgorithm();

  16.        mergesortalg.sort(inputArr);
  17.        System.out.println();

  18.        System.out.println("After sorting");
  19.        for(int i:inputArr){
  20.            System.out.print(i);
  21.            System.out.print(" ");
  22.        }
  23.  }
  24.     
  25. public void sort(int inputArray[]) {

  26.        this.resarray = inputArray;
  27.        this.length = inputArray.length;
  28.        this.tempMergArray = new int[length];
  29.        doMergeSort(0, length - 1);

  30. }
  31.  
  32. private void doMergeSort(int lowerIndex, int higherIndex) {
  33.         
  34.     if (lowerIndex < higherIndex) {

  35.    int middle = lowerIndex + (higherIndex - lowerIndex) / 2;

  36.            //to sort left half of the array
  37.    doMergeSort(lowerIndex, middle);

  38.            // to sort right half of the array
  39.    doMergeSort(middle + 1, higherIndex);

  40.            //merge two halfs
  41.     mergehalfs(lowerIndex, middle, higherIndex);
  42. }
  43. }
  44.  
  45. private void mergehalfs(int lowerIndex, int middle, int higherIndex) {
  46.  
  47.        for (int i = lowerIndex; i <= higherIndex; i++) {
  48.         tempMergArray[i] = resarray[i];
  49.        }

  50.        int i = lowerIndex;
  51.        int j = middle + 1;
  52.        int k = lowerIndex;

  53.   while (i <= middle && j <= higherIndex) {
  54.            if (tempMergArray[i] <= tempMergArray[j]) {
  55.             resarray[k] = tempMergArray[i];
  56.                i++;
  57.            } else {
  58.             resarray[k] = tempMergArray[j];
  59.                j++;
  60.            }
  61.            k++;
  62.       }

  63.      while (i <= middle) {
  64.         resarray[k] = tempMergArray[i];
  65.            k++;
  66.            i++;
  67.        }
  68.    }

  69. }

Output:

  1. Before sorting
  2. 6  42  2  32  15  8  23  4
  3. After sorting
  4. 2  4  6  8  15  23  32  42 

How to use Javascript confirm dialogue box

  • Confirm dialogue box in java script used to display a message for an action weather its is required to perform or not.
  • JavaScript confirm dialogue box contains two buttons "Ok" and "Cancel".
  • If user clicks on OK button confirm dialogue box returns true. If user clicks on cancel button it returns false.
  • So based on the user entered option we can continue our program. So confirm dialogue box used to test an action is required or not from user.



  • Its not possible to change values of confirm dialogue box buttons from "Ok" and "Cancel"to "Yes" and "No".
  • We need to use custom popups or jquery popups to use "Yes" and "No".
  •   var res= confirm("Are you sure to continue?");

How to use Javascript  confirm dialogue box:

  1. function myFunction() {
  2.     var text;
  3.     var res= confirm("Are you sure to continue?");
  4.     if (res == true) {
  5.         text= "You clicked OK!";
  6.     } else {
  7.         text= "You clicked Cancel!";
  8.     }
  9.     document.getElementById("demo").innerHTML = txt
  10. }
  11. </script>

Javascript confirm delete onclick:

  • If we are deleting a record from database then we need to ask user  to confirm deletion if ye really want to delete record then user checks Ok otherwise cancel based on this we can proceed furthur.
  • To implement this functionality we need to call a JavaScript function onClick()  whenever user clicks on delete record button.

Program#1: JavaScript program to show confirm dialogue box on clicking delete student record.

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <p>Click the button to delete student record</p>
  6.  
  7. <button onclick="toConfirm()">Delete student record </button>
  8.  
  9. <p id="student"></p>
  10. <script>
  11. function toConfirm() {
  12.     var text;
  13.     var r = confirm("You clicked on a button to delete student recored. Clik ok ro proceed");
  14.     if (r == true) {
  15.        //code to delete student record.
  16.         text = "You clikced on ok. Student record deleted";
  17.     } else {
  18.         text = "You clicked on cancel. transaction cancelled.";
  19.     }
  20.     document.getElementById("student").innerHTML = text;
  21. }
  22. </script>
  23.  
  24. </body>
  25. </html>

javascript confirm delete yes no

  • If we click on Ok then it will delete student record. otherwise it wont.

javascript onclick confirm dialog

Insertion sort algorithm in java programming

  • Sorting means arranging elements of a array or list in ascending or descending order.
  • We have various sorting algorithms in java.

  • Iterative and recursive algorithms.
  • Insertion sort is iterative type of algorithm.
  • Insertion sort algorithm is in place algorithm
  • The basic idea behind insertion sort is to divide our list in to two parts , sorted and un sorted.
  • At each step of algorithm a number is moved from un sorted part to sorted part.
  • Initially take 1st element as sorted element. 
  • Noe take second element and compare with first element if it less than the 1st element then swap two numbers means place lesser value in first position.
  • So now have two elements in sorted part. Take third element and compare with second element if it is less than the second element then we need to compare it with 1st element if is less than first element we need keep that in first place. Take an element  from unsorted portion and compare with sorted portion and place it in correct position in order to make sorted.
  • This will be repeated until entire list will be sorted.

Time complexity of Insertion sort:

1.Best case  time complexity:      O(n2)
2.Average case time complexity: O(n2)
3.Worst case time complexity:     O (n2)
4.Worst case space complexity:  O(1)


Implementation of Insertion sort algorithm in java

Implement insertion sort in java


Program #1: Write a java example program on insertion sort algorithm.

  1. package com.instanceofjava.insertionsortalgorithm;

  2. public class InsertionSort {

  3. /**
  4. * @website: www.instanceofjava.com
  5. * @category: insertion sort algorithm in java
  6. */
  7.      
  8. public static int[] doInsertionSort(int[] array){
  9.          
  10.      int temp;
  11.  
  12.   for (int i = 1; i < array.length; i++) {
  13.  
  14.             for(int j = i ; j > 0 ; j--){
  15.                 if(array[j] < array[j-1]){
  16.                     temp = array[j];
  17.                     array[j] = array[j-1];
  18.                     array[j-1] = temp;
  19.                 }
  20.             }
  21.  
  22.        }
  23.         return array;
  24.  }
  25.  
  26.   static void printArray(int[] inputarray){
  27.  
  28.     for(int i:inputarray){
  29.              System.out.print(i);
  30.              System.out.print(", ");
  31.          }
  32.     System.out.println();
  33.   }
  34.     
  35.  public static void main(String a[]){
  36.    
  37.    int[] array = {16,12,3,11,9,21,5,6};
  38.  
  39.     System.out.println("Before sorting elements");
  40.     printArray(array);
  41.  
  42.     int[] resarray = doInsertionSort(array);
  43.  
  44.     System.out.println("After sorting elements");
  45.     printArray(array);
  46.        
  47. }
  48. }

Output:

  1. Before sorting elements
  2. 16, 12, 3, 11, 9, 21, 5, 6, 
  3. After sorting elements
  4. 3, 5, 6, 9, 11, 12, 16, 21,
Select Menu