Below I have a List of Time to be added together

  List<String> arrTime = new ArrayList<String>();
  int hour      = 0;
  int minutes   = 0;
  int seconds   = 0;
  String Nmin   = null;
  String Nsec   = null;
  String result = null;

  arrTime.add("09:05:25");
  arrTime.add("09:30:15");
  arrTime.add("10:15:01");
  arrTime.add("08:19:49");
  arrTime.add("09:17:40");

  for (Iterator itr = arrTime.iterator(); itr.hasNext();) 
  {
    String Time = (String) itr.next();

    if (Time != null) 
    {
      String[] rowtime = Time.split(":");
      hour            += Integer.parseInt(rowtime[0]);
      minutes         += Integer.parseInt(rowtime[1]);
      seconds         += Integer.parseInt(rowtime[2]);
    }
  }

  hour    += minutes/60;
  minutes += seconds/60;

  minutes %= 60;
  seconds %= 60;

  if (minutes < 10)
   Nmin = "0" + String.valueOf(minutes);
  else
   Nmin = String.valueOf(minutes);
	 
  if (seconds < 10)
   Nsec = "0" + String.valueOf(seconds);
  else
   Nsec = String.valueOf(seconds);

  result = hour + ":" + Nmin + ":" + Nsec;
  
  System.out.println(result);

Output
46:28:10

public class Database 
{
    private static DataSource dataSource;

    static 
    {
        try 
        {
          dataSource = new InitialContext().lookup("jndifordbconc");
        }catch (NamingException e) 
        { 
          throw new ExceptionInInitializerError("'jndifordbconc' not found in JNDI", e);
        }
    }

    public static Connection getConnection() 
    {
      return dataSource.getConnection();
    }
}

public List<Entity> list() throws SQLException 
{
    Connection        connection = null;
    PreparedStatement statement  = null;
    ResultSet         resultSet  = null;
    List<Entity>      entities   = new ArrayList<Entity>();

    try 
    {
        connection = Database.getConnection();
        statement  = connection.prepareStatement("SELECT id, foo, bar FROM entity");
        resultSet  = statement.executeQuery();

        while (resultSet.next()) 
        {
            Entity entity = new Entity();
            entity.setId(resultSet.getLong("id"));
            entity.setFoo(resultSet.getString("foo"));
            entity.setBar(resultSet.getString("bar"));
            entities.add(entity);
         }
    } 
    finally 
    {
        if (resultSet  != null) try { resultSet.close();  } catch (SQLException ignore) {}
        if (statement  != null) try { statement.close();  } catch (SQLException ignore) {}
        if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
    }
    return entities;
}

Time to be Added together

TimeWorked
09:05:25
09:30:15
10:15:01
08:19:49
09:17:40

Code

int hour = 0;
int minute = 0;

for() {
    String[] rowtime= row[i].split(":");
    hour += Integer.parseInt(rowtime[0]);
    minute += Integer.parseInt(rowtime[1]);
}

hour += minute / 60;
minute %= 60;

String result = hour + ":" + minute

if(minute<10)
  Nmin = "0"+ String.valueOf(minute);
else
  Nmin = String.valueOf(minute);
		
 String result = hour + ":" + Nmin;

Inheritance refers to using the structure and behavior of a superclass in a subclass. Polymorphism refers to changing the behavior of a superclass in the subclass.v

Inheritance is more a static thing (one class extends another) while polymorphism is a dynamic/ runtime thing (an object behaves according to its dynamic/ runtime type not to its static/ declaration type).

Inheritance is when a ‘class’ derives from an existing ‘class’. So if you have a Person class, then you have a Student class that extends Person, Student inherits all the things that Person has.

Polymorphism deals with how the program decides which methods it should use, depending on what type of thing it has. If you have a Person, which has a read method, and you have a Student which extends Person, which has its own implementation of read, which method gets called is determined for you by the runtime, depending if you have a Person or a Student

Person p = new Student();
p.read();

The read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a Student is a Person, but the runtime is smart enough to know that the actual type of p is Student.

The main difference is polymorphism is a specific result of inheritance. Polymorphism is where the method to be invoked is determined at runtime based on the type of the object. This is a situation that results when you have one class inheriting from another and overriding a particular method. However, in a normal inheritance tree, you don’t have to override any methods and therefore not all method calls have to be polymorphic

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{	
	int lngCookieSet    = 0;
	String strCookieVal = "";
	
	String cookieName = "Name";

	Cookie[] cookies = request.getCookies();
		
	if(cookies != null && cookies.length > 0)
	{
	  for(int i=0;i<cookies.length;i++)
	  {
	    if(cookieName.equals(cookies[i].getName()))
	    {
	      lngCookieSet = 1;
	      strCookieVal = cookies[i].getValue();
	    }
	  }
	}	
		
	if(lngCookieSet == 1)
	{
	   PrintWriter prw = response.getWriter();	
	   prw.print(strCookieVal);
	}
	else
	{
	   Cookie cook = new Cookie("Name", "Mugil");
	   cook.setMaxAge(24*60*60*365);//1 Year
	   response.addCookie(cook);	
	}
}

1.We should check

cookies != null

otherwise the compiler will generate null pointer exception

2.The

new Cookie

constructor will take Cookie Name and Value as Parameter.

3.The addCookie Will add cookie to response Header to set cookie on Client Side

Posted in JSP.

You can define an abstract method to be protected, and hence not part of the public API of the class. However, that seems like an odd design.

Another thing – instance variables. You can have inheritable instance variables in the abstract class.

Abstract class Methods can be defined at various levels down the path.

In a 100% abstract class, you can also define non constant variables that can be herited. It is not possible with interfaces.

The one case where an “100% abstract class” may be advantageous over an interface is in places where API stability is a key concern.

If you write an API where other people are expected to implement your interface you have to stick to the interface. You can’t add any methods to the interface later on because that would break all clients (you would have to work around this by implement a second interface and let your code check againt the usage with instanceof checks and provide an fallback).

Simple Thread implementing Runnable
Counter.java

public class Counter implements Runnable{
    public void run(){
        System.out.println("I am Counter Run Method");
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Counter objCounter = new Counter();
        Thread objThread = new Thread(objCounter);
        objThread.start();
    }
}
I am Counter Run Method

Main.java(Using Lambda Expression)

public class Main {
    public static void main(String[] args) {
        Thread objThread = new Thread(() -> {
            System.out.println("I am lambda Counter method");
        });

        objThread.start();
    }
}
I am lambda Counter method

new vs runnable vs terminated

  1. When you create thread using new Operator it would be in “new” state
  2. Once you call start method over thread it would Transend to “runnable” state
  3. When run method completed execution it would Transend to “terminated” state

start() vs run()
Thread can be invoked using start or run method. If you use the myThread.start() method it initiates execution of new thread, jvm takes care of execution and scheduling of run method in separate concurrent context. Calling the run method directly myThread.run() will not start a new thread; it will execute the run method in the current thread (ie main thread).

start method of thread class is implemented as when it is called a new Thread is created and code inside run() method is executed in that new Thread. While if run method is executed directly than no new Thread is created and code inside run() will execute on current Thread and no multi-threading will take place

public class Main {
    public static void main(String[] args) {
        Thread objThread = new Thread(() -> {
            System.out.println(Thread.currentThread().getName());
        });

        objThread.start();
    }
}

Output

Thread-0
public class Main {
    public static void main(String[] args) {
        Thread objThread = new Thread(() -> {
            System.out.println(Thread.currentThread().getName());
        });

        objThread.run();
    }
}

Output

main
  1. start() – Initiates the execution of the thread, causing the run method to be called
    myThread.start();
    
  2. run() – Contains the code that will be executed by the thread. This method needs to be
    overridden when extending the Thread class or implementing the Runnable interface.
    Usage: Defined by the user based on the specific task.
  3. sleep(long milliseconds) – Causes the thread to sleep for the specified number of milliseconds,
    pausing its execution.

    Thread.sleep(1000);
    
  4. join() Waits for the thread to complete its execution before the current thread continues. It
    is often used for synchronization between threads.

    myThread.join();
  5. interrupt() Interrupts the thread, causing it to stop or throw an InterruptedException. The thread
    must handle interruptions appropriately.

    myThread.interrupt();
    
  6. isAlive() Returns true if the thread has been started and has not yet completed its execution,
    otherwise returns false.

    boolean alive = myThread.isAlive();
    
  7. setName(String name) Sets the name of the thread.
    myThread.setName("MyThread");
    
  8. getName() Returns the name of the thread.
    String threadName = myThread.getName();
    
  9. getName() Returns the name of the thread.
    String threadName = myThread.getName();
    
  10. setPriority(int priority) Sets the priority of the thread. Priorities range from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY.
    myThread.setPriority(Thread.MAX_PRIORITY);
    
  11. getPriority() Returns the priority of the thread.
    int priority = myThread.getPriority();
    
  12. currentThread() Returns a reference to the currently executing thread object.
    Thread currentThread = Thread.currentThread();
    

Thread Implementation Using Runnable Interface

public class Threads2 implements Runnable 
{	
	public static void main(String[] args) 
	{
		Threads2 objThreads2 = new Threads2();
		Thread t1 = new Thread(new Threads2());
		t1.start();
	}
	
	public void run() 
	{	
		System.out.println("Thread Started");
		
		for(int i=0;i<=5;i++)
		{
			System.out.println(i);
			
			try 
			{
			  Thread.sleep(1000);
			}
			catch (InterruptedException e) 
			{
			  e.printStackTrace();
			}
		}
		
		System.out.println("Thread Stopped");
	}
}

There are Four Constructors we can use in Runnable Method of Implementation of Threads.
Thread() – Calls Thread Version of run Method
Thread(Runnable Target)
Thread(Runnable Target, String Name)
Thread(String Name)

If we dont Pass the Instance of Class To thread Constrctor then it will call its own Run Method

Thread t = new Thread(new MyThread());