CustomTags.java
This is the File which defines the Property of the Tag

package com.mugil.custTags;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class CustomTags extends TagSupport  
{
  private static final long serialVersionUID = 1L;
	
  public int doStartTag() throws JspException 
  {		
     StringBuffer SamBuffer = new StringBuffer();
     SamBuffer.append("Sample Message");
		
     try
     {
	pageContext.getOut().write(SamBuffer.toString());
     }
     catch (IOException e)
     {
	e.printStackTrace();
     }
		
  	return EVAL_PAGE;
   }
	
   public int doEndTag() throws JspException 
   {
      return EVAL_PAGE;
   }
}

DisplayName.tld
This xml file creates the Relation between the tag and the property of the tag as defined in the java file.

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <shortname>Example TLD</shortname>
  <tag>
    <name>Hello</name>
    <tagclass>com.mugil.custTags.CustomTags</tagclass>
    <bodycontent>empty</bodycontent>
  </tag>
</taglib>

Sample.jsp
JSP File in which the custom tag is Used.

<%@taglib prefix="DisplayName" uri="/WEB-INF/tld/DisplayName.tld"%>
.
.
.
.
<body>
 <h1>
    <DisplayName:Hello/>
 </h1>
</body>
.
.
.

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
  <web-app version="3.0">
   <servlet>
     <servlet-name>TestServlet</servlet-name>
     <servlet-class>com.mugil.custTags.TestServlet</servlet-class>
   </servlet>
   <servlet-mapping>
     <servlet-name>TestServlet</servlet-name>
     <url-pattern>/TestServlet/</url-pattern>
   </servlet-mapping>
  </web-app>

Output

OP

c:forEach

 <body>
   <c:forEach var="i" begin="1" end="100">
     <c:out value="${i}"/><br/>
   </c:forEach>
 </body>

Accessing Value in Bean
SampleMenu.java(bean)

  public class SampleMenu
  {
    String name;
  
    public String getName()
    {
      return name;
    }
	
    public void setName(String name)
    {
      this.name = name;
    }
  }

MenuList.java

   List<SampleMenu> arrMenuList = new ArrayList<SampleMenu>();		
   SampleMenu objSampleMenu     = new SampleMenu();

   objSampleMenu.setName("Link1");
   arrMenuList.add(objSampleMenu); 

   objSampleMenu.setName("Link2");
   arrMenuList.add(objSampleMenu);

   objSampleMenu.setName("Link3");
   arrMenuList.add(objSampleMenu);

   request.setAttribute("arrMenuList", arrMenuList);
   RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/Sample.jsp");
   dispatcher.forward(request, response);

Sample.java

 
   <body>
     <c:forEach	var="i" items="${arrMenuList}">
	     <c:out value="${i.name}"/>
     </c:forEach>
   </body>

Output
Link1 Link2 Link3

If Else

 
<c:if test="${user.userGender eq 1}">Male</c:if>
<c:if test="${user.userGender eq 0}">Female</c:if>

(or)

 
  <c:choose>
    <c:when test="${user.userGender eq 1}">Male</c:when>
    <c:otherwise>Female</c:otherwise>
  </c:choose>

Alternative to If Else Statement

 
 <c:out value="${user.userGender eq 1 ? 'Male': 'Female'}"/>

If Else If

<c:choose>
    <c:when test="${empty example1}"> 
        <!-- do stuff -->
    </c:when> 
    <c:otherwise> 
        <c:choose>
            <c:when test="${empty example2}"> 
                <!-- do different stuff -->
            </c:when> 
            <c:otherwise> 
                <!-- do default stuff -->
            </c:otherwise>
        </c:choose>
    </c:otherwise> 
</c:choose>

If Else If

<c:choose>
    <c:when test="${empty example1}">
    </c:when>
    <c:when test="${empty example2}">
    </c:when>
    <c:otherwise>
    </c:otherwise>              
</c:choose>

Passing a Variable from Java to JSP Page By SetAttribute

Sample.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
  request.setAttribute("Name", "Mugil Vannan");
  RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/Sample.jsp");
  dispatcher.forward(request, response);
}

Sample.jsp

  <body>
    <c:out value="${Name}"/>
  </body>

Web.xml

  <servlet>
     <servlet-name>Sample</servlet-name>
     <servlet-class>com.sponsor.infonovum.MenuList</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>Sample</servlet-name>
     <url-pattern>/Sample/</url-pattern>
  </servlet-mapping>

How to remove last element in a array and store it in same Array

 
import java.util.Arrays;

public class SimpleArray 
{
  public static void main(String[] args) 
  {
    String[] arrNames1 = {"Mugil", "Mani", "Vinu", "Shivaji", "Raman"};
    String[] arrNames2 = new String[arrNames1.length-1]; 
		
    for(int i=0;i<arrNames1.length-1;i++)
      arrNames2[i] = arrNames1[i];
		
    arrNames1 = arrNames2.clone();
		
    for (int i = 0; i < arrNames1.length; i++) 
      System.out.println(arrNames1[i]);		
  }
}

MySQL TIMEDIFF function runs well in MySQL but with JDBC it generate SQL Exception.
The problem is that the TIMEDIFF(expr1,expr2) function returns expr1 – expr2 expressed as a time value.

This value is handled by java.sql.Time. But TIMEDIFF( , ) may return (for example) 12:45:00 or 40:30:01 as the case may be. For first value it works but for the second value it is not a proper time value according to java.sql.Time, hence the exception.

To get rid of this problem is to use concat as follows

CONCAT('',TIMEDIFF(expr1,expr2))

Now the returned value will be a String instead of a Time and which prevents JDBC from parsing it.

Set

  • Set prevents duplication.The common use of set is to check for duplication
  • Since its is helpful for lookups for duplicate value HashSet provides an optimized implementation
  • If you want the result to be sorted use TreeSet instead of HashSet
Posted in Set.

Why ArrayList Faster than LinkedList during Random Access?
ArrayList has direct references to every element in the list, so it can get the n-th element in constant time. LinkedList has to traverse the list from the beginning to get to the n-th element.

Why LinkedList faster than ArrayList during Insertion/Deletion?
ArrayList is slower because it needs to copy part of the array in order to remove the slot that has become free. If the deletion is done using the ListIterator.remove() API, LinkedList just has to manipulate a couple of references; if the deletion is done by value or by index, LinkedList has to potentially scan the entire list first to find the element(s) to be deleted.

  • LinkedList takes constant-time insertions or removals. I can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list.
  • ArrayLists allows random access, so I can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. Also, if I add more elements than the capacity of the underlying array, a new array (twice the size) is allocated, and the old array is copied to the new one, so adding to an ArrayList is O(n) in the worst case but constant on average.
  • Iterating over both the Types is equally cheap.
  • If you have large lists, the memory usage is different. Each element of a LinkedList has more overhead since pointers to the next and previous elements are also stored

When should I use LinkedList?

  • When you need efficient removal in between elements or at the start.
  • When you don’t need random access to elements, but can live with iterating over them one by one

When should I use ArrayList?

  • When you need random access to elements (“get the nth. element”)
  • When you don’t need to remove elements from between others. It’s possible but it’s slower since the internal backing-up array needs to be reallocated.
  • Adding elements is amortized constant time (meaning every once in a while, you pay some performance, but overall adding is instantly done)
Operation Linked List Array List
Access O(n) O(1)
Insertion Access time + O(1) Access time + O(n)
Deletion Access time + O(1) Access time + O(n)

When you are simple moving through List but you are not modifying the List object foreach is more efficient.In case you want to perform operations on each element of list individually taking out the element in such case use Iterator.

List<Fruits> arrFruits = new ArrayList<Fruits>();
Iterator<Fruits> itFrt = arrFruits.iterator();

while(itFrt.hasNext())
{
 Fruits frt = itFrt.next();
 System.out.println(frt);
}

ListIterator

  • While using Iterator in particular to List using a ListIterator is more powerful over Iterator.
  • ListIterator is bidirectional
  • It also keep track of Indexes of next and previous elements
  • It can replace last element it visited using set method
 List<fruits> arrFruits     = fruits.arrayList(5);
 ListIterator<fruits> itFrt = arrFruits.listIterator();

 while(itFrt.hasNext())
 {
   System.out.println(it.next()); 
   System.out.println(it.nextIndex()); 
   System.out.println(it.previousIndex()); 
 }
  • List maintains elements in Particular Sequence.
  • Two types of List 1.ArrayList and 2.LinkedList
  • ArrayList is faster while accessing elements but slower while Insertion and Deletion
  • LinkedList is slow in random access but faster during insertion and deletion

Operations in ArrayList

class Fruits
{	
  String Name = "Fruit";
}

class Apple extends Fruits
{	
 public Apple()
 {
   Name = "Apple";
 }
}

class Orange extends Fruits
{	
 public Orange()
 {
  Name = "Orange";
 }
}

class Mango extends Fruits
{	
 public Mango()
 {
  Name = "Mango";
 }
}

Adding Element – List.add()

List<Fruits> arrFruits = new ArrayList<Fruits>();
Fruits objApple  = new Apple();
Fruits objMango  = new Mango();
arrFruits.add(objApple);
arrFruits.add(objMango);

Removing Element – List.remove()

arrFruits.remove(objApple);

Removing by Index – List.remove()

arrFruits.remove(1);

Index of Element – List.indexOf()

arrFruits.indexOf(objMango);

Index of Element – List.indexOf()

arrFruits.indexOf(objMango);

SubList – List.subList(StartPOS, EndPOS)

List<Fruits> arrNewFruits = arrFruits.subList(0,2);

containsAll – NewList.containsAll(OrgList)

 arrNewFruits.containsAll(arrFruits);

set Value at Index

 arrNewFruits.set(1, new Orange());

removeAll

 arrFruits.removeAll(arrFruits);

addAll

 arrFruits.addAll(arrNewFruits);

retainAll – set Intersection Operation
retainAll performs set Interscetion Operation by taking Two ArrayList. It Retains Boolean true if intersection finds element false otherwise.

List<Integer> arrNums1 = new ArrayList<Integer>();
arrNums1.add(1);
arrNums1.add(2);
arrNums1.add(3);
		
List<Integer> arrNums2 = new ArrayList<Integer>();
arrNums2.add(1);

System.out.println(arrNums1.retainAll(arrNums2));
System.out.println(arrNums1);