Static method vs final static method in java with example programs

  • Static methods are class level so there are not part of object.
  • So we can not override static methods but we can call super class static method using subclass name or instance also.
  • If we are trying to override static methods in sub class from super class then it will be method hiding not method overriding.

  • Means whenever we call the static method on super class will call super class static method and if we are calling method using sub class it will call sub class method.
  • So it is clear that static methods are hidden not overridden and they are part of class means class level not object level.
  • Now the question is can a method be static and final together?
  • For non static methods if we declare it as final then we are preventing that method from overriding so it can not be overridden in sub class.
  • When we declare static method as final its prevents from method hiding.
  • When we declare final static method and override in sub class then compiler shows an error
  • Compile time error: Cannot override the final method from Super
  • Lets see an example program to understand this better.

Static methods in java

Program #1: Java example program to explain about static method in java

  1. package inheritanceInterviewPrograms;
  2. /*
  3.  * @website: www.instanceofjava.com
  4.  * @category: Deference between staic and final static methods in java
  5.  */


  6. public class Super {
  7.   
  8.  
  9.  static void method(){
  10.  
  11. System.out.println("Super class method");
  12.  }

  13. }

  1. package inheritanceInterviewPrograms;

  2. //  www.instanceofjava.com 

  3. public class Sub extends Super {
  4. static void method(){
  5.  
  6. System.out.println("Sub class method");

  7. }

  8. public static void main (String args[]) {
  9. Super.method();
  10. Sub.method();
  11.  
  12.  
  13. }
  14. }

Output:

  1. Super class method
  2. Sub class method

  • When we override static methods its not overriding it is method hiding and whenever we call method on class name it will call corresponding class method.
  • If we call methods using objects it will call same methods.

Program #2: Java example program to explain about calling super class static method using sub class in java

  1. package inheritanceInterviewPrograms;
  2. /*
  3.  * @website: www.instanceofjava.com
  4.  * @category: Deference between staic and final static methods in java
  5.  */


  6. public class Super {
  7.   
  8.  
  9.  static void method(){
  10.  
  11. System.out.println("Super class method");
  12.  }

  13. }


  1. package inheritanceInterviewPrograms;

  2. //  www.instanceofjava.com 

  3. public class Sub extends Super {
  4. public static void main (String args[]) {
  5. Super.method();
  6. Sub.method();
  7.  
  8.  
  9. }
  10. }

Output:

  1. Super class method
  2. Super class method

  • We can call super class static methods using sub class object or sub class name also.
  • Now lets see what will happen in final static methods

Final static methods in java:

  • Can a method be static and final together in java?
  • When we declare a method as final we can not override that method in sub class.
  • In the same way when we declare a static method as final we can not hide it in sub class means we can not create same method in sub class. 
  • If we try to create same static method in sub class compiler will throw an error.
  • Lets see a java example program on final static methods in inheritance.

Program #3: Java example program to explain about final static method in java

  1. package inheritanceInterviewPrograms;
  2. /*
  3.  * @website: www.instanceofjava.com
  4.  * @category: Deference between staic and final static methods in java
  5.  */


  6. public class Super {
  7.   
  8.  
  9.  final static void method(){
  10.  
  11. System.out.println("Super class method");
  12.  }

  13. }

  1. package inheritanceInterviewPrograms;

  2. //  www.instanceofjava.com 

  3. public class Sub extends Super {
  4. static void method(){  // compiler time error:

  5. System.out.println("Sub class method");
  6.  
  7. }
  8. public static void main (String args[]) {
  9. Super.method();
  10. Sub.method();
  11.  
  12.  
  13. }
  14. }

Output:


difference between static method and final method in java

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
Select Menu