How to read a file in java with example program

  • We can read java file using buffered reader class in java
  • We need to import java.io.BufferedReader in order to read java text file.
  • Create object of java.io.BufferedReader class by passing new FileReader("C:\\Sample.txt") object to the constructor.
  • In order to read line by line call readLine() method of BufferedReader class which returns current line. Initially first line of java text file



 Program #1: Write a java program to read a file line by line using BufferedReader class

  1. package com.instanceofjava.javareadfile;

  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.io.IOException;

  5. public class ReadFileBufferedReader {

  6. /**
  7. * @Website: www.instanceofjava.com
  8. * @category: How to read java read file line by line using buffered reader
  9. */

  10. public static void main(String[] args) {

  11. BufferedReader breader = null;

  12.  try {

  13. String CurrentLine;

  14. breader = new BufferedReader(new FileReader("E://Sample.txt"));

  15. while ((CurrentLine = breader.readLine()) != null) {
  16. System.out.println(CurrentLine);
  17. }

  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. } finally {
  21.     try {
  22. if (breader != null)
  23. breader.close();
  24.      } catch (IOException ex) {
  25. ex.printStackTrace();
  26.      }
  27. }

  28. }

  29. }

 Output:
 
  1. Java open and read file
  2. Read file line by line in java
  3. Example java program to read a file line by line
  4. java read file line by line example
  
Program #2: Write a java program to read a file line by line using BufferedReader class using Eclipse

how to read a file in java

Can an abstract class have a constructor in Java

  • Yes we can define a constructor in abstract class in java.

  • Then next question will come like when we can not create object of abstract class then why to define constructor for abstract class.
  • It is not possible to create object of abstract class directly but we can create object of abstract class from sub class which is actually extending abstract class.
  • When we define a abstract class a class must extend that abstract class then only there will be use of that class
  • Then when we create object of class which extends abstract class constructor of sub class will be called from that abstract class constructor will be called and memory will be created for all non static members.
  • If we are not defining any constructor default constructor will be executed.
  • So we can define any number of constructor in abstract class.
  • And it is recommended to define constructor as protected. Because there is only one scenario which we can create object is from subclass so define abstract class constructor as protected always.

Order of  execution of  constructor in Abstract class and  its sub class.

  •  When we  create object of  class which is extending abstract class then it will call abstract class constructor through sub class constructor.
  • Lest see a java example program on abstract class constructor in java

Program #1: Does abstract class have constructor???

  1. package com.instanceofjava.abstractclassconstructor;
  2. public  abstract class AbstractDemo {
  3.  
  4. AbstractDemo(){
  5.         System.out.println("No argument constructor of abstract class");
  6.  }
  7.  
  8. }


  1. package com.instanceofjava.abstractclassconstructor;
  2. public class Test extends AbstractDemo{
  3.  
  4.     Test(){
  5.         System.out.println("Test class constructor");
  6.     }
  7.     
  8. public static void main(String[] args) {
  9.         Test obj = new Test();
  10.        
  11.  
  12. }
  13.  
  14. }


Output: 

  1. No argument constructor of abstract class
  2. Test class constructor

Can we define parameterized constructor in abstract class?

  • Yes we can define parameterized constructor in abstract class.
  • But we need to make sure that the class which is extending abstract class have a constructor and it should call super class parameterized constructor
  • We can call super class parameterized constructor in sub class by using super() call
  • For example: Super(2) ;
  • What will happen if we are not placing super call in sub class constructor?
  • Compiler time error will come.

Program #2: Can we define parameterized constructor in abstract class in java?

  1. package com.instanceofjava.abstractclassconstructor;
  2. public abstract class AbstractDemo {
  3.  
  4. AbstractDemo( int x){
  5.          System.out.println("No argument constructor of abstract class x="+x);
  6.  }
  7.  
  8. }


  1. package com.instanceofjava.abstractclassconstructor;
  2. public class Test extends AbstractDemo{
  3.  
  4.     Test(){
  5.         super(10);
  6.         System.out.println("Test class constructor");
  7.     }
  8.     
  9. public static void main(String[] args) {
  10.         Test obj = new Test();
  11.        
  12.  
  13. }
  14.  
  15. }


Output:
 
  1. No argument constructor of abstract class  x=10
  2. Test class constructor

Program #3: What will happen if we are not placing super call in sub class constructor?


does abstract class have constructor in java

How to generate unique random numbers in java

  • In java we can generate random number in two ways 
  • By using Random class
  • By using Math.random



Program #1:  Java Example program to generate random numbers using random class within  the range of 1 to 10

  • First we need to create object of java.util.Random class.
  • After creating object of java.util.Random class then we need call nextInt() method by passing range
  • int range = maximum - minimum + 1;
  • int randomNum =  rn.nextInt(range) + minimum;

  1. package com.randomnumbergenerator;

  2. import java.util.Random;
  3. import java.util.Scanner;

  4. public class RandomNumber {

  5. /**
  6. * @Website: www.instanceofjava.com
  7. * @category: how to generate random numbers in java within range
  8. */
  9. public static void main(String[] args) {
  10. Scanner in = new Scanner(System.in);
  11. System.out.println("Enter minimum number");
  12. int minimum=in.nextInt();
  13. System.out.println("Enter maximum number");
  14. int maximum=in.nextInt();
  15. Random rn = new Random();
  16. int range = maximum - minimum + 1;
  17. int randomNum =  rn.nextInt(range) + minimum;
  18. System.out.println("Random Number= "+randomNum);

  19. }

  20. }

Output:

  1. Enter minimum number
  2. 1
  3. Enter maximum number
  4. 10
  5. Random Number= 4


Program #2:  Java Example program to generate random numbers using Math.random  within  the range of 1 to 10

  • By using Math.random() method also we can generate random number in java
  • int randomNum = minimum + (int)(Math.random() * maximum);

  1. package com.randomnumbergenerator;

  2. import java.util.Random;
  3. import java.util.Scanner;

  4. public class RandomNumber {

  5. /**
  6. * @Website: www.instanceofjava.com
  7. * @category: how to generate random numbers in java within range
  8. */
  9. public static void main(String[] args) {
  10. Scanner in = new Scanner(System.in);
  11. System.out.println("Enter minimum number");
  12. int minimum=in.nextInt();
  13. System.out.println("Enter maximum number");
  14. int maximum=in.nextInt();
  15.   
  16.   int randomNum = minimum + (int)(Math.random() * maximum);
  17. System.out.println("Random Number= "+randomNum);

  18. }

  19. }

Output:

  1. Enter minimum number
  2. 1
  3. Enter maximum number
  4. 10
  5. Random Number=5


Program #3:  Java Example program to generate 10 random numbers using Random class  within  the range of 1 to 100 using for loop.

  1. package com.randomnumbergenerator;

  2. import java.util.Random;
  3. import java.util.Scanner;

  4. public class RandomNumber {

  5. /**
  6. * @Website: www.instanceofjava.com
  7. * @category: how to generate random numbers in java within range
  8. */
  9. public static void main(String[] args) {
  10. Random randomNumGenerator = new Random();
  11.  
  12.            for (int idx = 1; idx <= 10; ++idx){
  13.               int randomInt = randomNumGenerator.nextInt(100);
  14.               System.out.println("Random Number= "+randomInt);
  15.  
  16. }       

  17. }

  18. }

Output:

  1. Random Number= 17
  2. Random Number= 3
  3. Random Number= 74
  4. Random Number= 59
  5. Random Number= 81
  6. Random Number= 90
  7. Random Number= 2
  8. Random Number= 32
  9. Random Number= 11
  10. Random Number= 75


random number generator java




How to generate random numbers in java without repetitions

  • lets see how to generate unique random numbers in java
  • By using Collections.shuffle();


Program #4:  Java Example program to generate 4 random numbers using Random class  within  the range of 1 to 100 without duplicate / java generate unique random number between 1 and 100


  1. package com.randomnumbergenerator;


  2. public class RandomNumber {

  3. /**
  4. * @Website: www.instanceofjava.com
  5. * @category: how to generate random numbers in java within range
  6. */
  7. public static void main(String[] args) {
  8.   ArrayList<Integer> list = new ArrayList<Integer>();
  9.             for (int i=1; i<10; i++) {
  10.                 list.add(new Integer(i));
  11.             }
  12.             Collections.shuffle(list);
  13.             for (int i=0; i<4; i++) {
  14.                 System.out.println("Random Number= "+(list.get(i)));
  15.             }
  16. }       

  17. }

  18. }

Output:

  1. Random Number= 7
  2. Random Number= 3
  3. Random Number= 2
  4. Random Number= 9

Program #5:  Java Example program to generate 10 random numbers. random number generator that doesn't repeat java

  1. package com.randomnumbergenerator;


  2. public class RandomNumber {

  3. /**
  4. * @Website: www.instanceofjava.com
  5. * @category: how to generate 10 random numbers in java within range
  6. */
  7.  
  8. public static final int SET_SIZE_REQUIRED = 10;
  9.  public static final int NUMBER_RANGE = 100;
  10.  
  11.  public static void main(String[] args) {
  12.  
  13.             Random random = new Random();
  14.  
  15.             Set set = new HashSet<Integer>(SET_SIZE_REQUIRED);
  16.  
  17.             while(set.size()< SET_SIZE_REQUIRED) {
  18.                 while (set.add(random.nextInt(NUMBER_RANGE)) != true)
  19.                     ;
  20.             }
  21.             assert set.size() == SET_SIZE_REQUIRED;
  22.             System.out.println(set);
  23.         }
  24. }


Output:

  1. [48, 99, 24, 58, 44, 77, 14, 95, 31, 79]

How to assign multiple classes to one html element

  • In HTML if we want to apply any styles to any elements we will use cascading style sheets.
  • By using CSS we can apply styles to an element in HTML
  • If some style is needed for more than one type of element then we cant make a style and name it and where ever that style is required we can place that style for that element.

  • So like this it is always possible to apply multiple styles or multiple classes to HTML elements.
  • We can specify more than one CSS class to an element.
  • By using class attribute we can specify multiple  CSS classes to a single element and all classes must be separated by a space.
  • For example if we are applying multiple classes to a div tag.
  • <div class="class1 class2"></div>
  • Here class is the attribute and class1 and class2 are the two different CSS classes.
  • Lets take an example of one paragraph element and two css classes 
  • Fist we define a <p> element with no styles.
  • Second one more <p> element with one style
  • Third one more <p> element with two styles.  
  • HTML multiple classes

 

#1: Html example file to show how to assign multiple CSS classes to an HTML element :

 

  1. <!DOCTYPE html>
  2. <html>
  3.  
  4. <title>Cascading Style Sheet</title>
  5.  
  6. <style type="text/css">
  7.  
  8. .class1 {  
  9. text-align: center;
  10. color: red; 
  11. }
  12.  
  13. .class2 { font-size: 300%; }
  14.  
  15. </style>
  16. </head>
  17. <body>
  18. <p >   How to assign multiple classes to html element<p>
  19. <p class="class1">How to assign multiple classes to html element<p>
  20. <p class="class1 class2">How to assign multiple classes to html element<p>
  21.  
  22. </body>
  23. </html>


html multiple classes

Builder design pattern in java with example program

  • Design patterns are solutions to software design problems.
  • Design patterns classified into three types.
  • Creational, Structural and behavioral design patterns.

  • Creational patterns helps us to create objects in a manner suitable to the given situation.
  • Builder design pattern is one of the creational  design pattern in java.
  • Builder  design pattern helps us to create complex class object.
  • Builder design pattern helps us to separate the construction process of a complex object from its representation so that same object construction process can be created in different representations.
  • Means it will separate complex construction into two parts  initialization of class instance and return  class instance.
  • When a class having more number of fields and constructor of that class take care of assigning initial values. 
  • And when we want to create object of the class we need to pass all  parameters and should be in same order which constructor is accepting.
  • Builder design pattern helps us to create same class object by passing required number of fields by using separate builder class object.
  • Builder design pattern is useful when object creation is very complex.

Advantages of builder design pattern:

  • Builder design pattern simplifies complex object creation.
  • Builder design pattern provides separation between instance creation and representation
  • Re usability

 Program #1: Builder design pattern in java with example program

Employee:
  1. package com.designpatternsinjava.builderdesignpattern;

  2. public class Employee {

  3. String name;
  4. String company;
  5. int id;
  6. String passport_number;
  7. String temp_address;
  8. String perm_address;
  9. int salary;

  10. Employee(String name,String company,int id,String passport_number,String
  11. temp_address,String perm_address,int salary){
  12. this.name=name;
  13. this.company=company;
  14. this.id=id;
  15. this.passport_number=passport_number;
  16. this.temp_address=temp_address;
  17. this.perm_address=perm_address;
  18. this.salary=salary;
  19. }

  20. public String toString(){
  21.  return "Name="+name+" \n Company="+company+"\n id="+id+"\n
  22.    passport_number="+passport_number+"" +"\n temp_address="+temp_address+"\n
  23.    perm_address"+perm_address+"\n
  24.    salary="+salary;

  25. }
  26. }

EmployeeBuilder

  1. package com.designpatternsinjava.builderdesignpattern;

  2. public class EmployeeBuilder {


  3. String name;
  4. String company;
  5. int id;
  6. String passport_number;
  7. String temp_address;
  8. String perm_address;
  9. int salary;
  10. public EmployeeBuilder setName(String name) {
  11. this.name = name;
  12. return this;
  13. }

  14. public EmployeeBuilder setCompany(String company) {
  15. this.company = company;
  16. return this;
  17. }

  18. public EmployeeBuilder setId(int id) {
  19. this.id = id;
  20. return this;
  21. }

  22. public EmployeeBuilder setPassport_number(String passport_number) {
  23. this.passport_number = passport_number;
  24. return this;
  25. }

  26. public EmployeeBuilder setTemp_address(String temp_address) {
  27. this.temp_address = temp_address;
  28. return this;
  29. }

  30. public EmployeeBuilder setPerm_address(String perm_address) {
  31. this.perm_address = perm_address;
  32. return this;
  33. }

  34. public EmployeeBuilder setSalary(int salary) {
  35. this.salary = salary;
  36. return this;
  37. }
  38. public Employee build(){
  39. return new Employee(name, company, id, passport_number, temp_address,
  40. perm_address, salary);
  41. }

  42. }

BuilderDemo


builder design pattern java code

  • To create object of employee class  we need to provide all the fields values to the constructor.
  • So it is somewhat difficult to pass all values all times.
  • Employee builder class taken all variables of Employee and in setter methods accepts a value and returns EmployeBuilder object.
  • And EmployeBuilder class has build method which will  assign all values to employee and returns Employee object.
  • Employee empobj= new EmployeeBuilder().setName("Saidesh").setId(1234).build();
  • Now we create object of Employee class by creating EmployeBuilder class object and caling calling setter methods whatever we have.
  • Is is very easy to set the values because we have corresponding setter method name is same as variable name.
  • After setting the values we need  to call build method so that it will return employee object with values.

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

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