Final Example]

  1. Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.
  2. Final is a keyword.
class FinalEg
{
   public static void main(String[] args) 
   {
      final int x = 600;
      x = 400;// Compile Time Error
    }
}

Finally Example

  1. Finally is used to place important code, it will be executed whether exception is handled or not.
  2. Finally is a block.
class FinallyEg
{
	public static void main(String[] args) 
	{
		try {
			int x = 500;
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			System.out.println("finally block is executed");
		}
	}
}

Finalize Example

  1. Finalize is used to perform clean up processing just before object is garbage collected.
  2. Finalize is a method.
class FinalizeEg 
{
	public void finalize() 
        {
	   System.out.println("finalize called");
	}

	public static void main(String[] args) 
        {
		FinalizeExample f1 = new FinalizeExample();
		FinalizeExample f2 = new FinalizeExample();
		f1 = null;
		f2 = null;
		System.gc();
	}
}

Difference between throw and throws in Java

void doCalc() throws ArithmeticException
{  
   .
   .
   throw new ArithmeticException("sorry");  
}  

throw

  1. Java throw keyword is used to explicitly throw an exception.
  2. Checked exception cannot be propagated using throw only.
  3. Throw is followed by an instance.
  4. Throw is used within the method.
  5. You cannot throw multiple exceptions.

throws

  1. Java throws keyword is used to declare an exception.
  2. Checked exception can be propagated with throws.
  3. Throws is followed by class.
  4. Throws is used with the method signature.
  5. You can declare multiple exceptions e.g.
    public void method()throws IOException,SQLException.

Similarities: Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.

Differences: StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.

Meaning of synchronized (synchronization): When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.

Which one to use when? StringBuilder : When you need a string, which can be modifiable, and only one thread is accessing and modifying it. StringBuffer : When you need a string, which can be modifiable, and multiple threads are accessing and modifying it.

Note : Don’t use StringBuffer unnecessarily, i.e., don’t use it if only one thread is modifying and accessing it because it has lot of locking and unlocking code for synchronization which will unnecessarily take up CPU time. Don’t use locks unless it is required.

Simply use StringBuilder unless you really are trying to share a buffer between threads. StringBuilder is the unsynchronized (less overhead = more efficient)

When a String is there and you add use concat like one below

  
 String x = "Java";
 x.concat("Rules !");
 sysout(x);

Now in the above there would be 2 string object created with output Java.When you used append in stringBuilder or stringBuffer the changes were applied over the object itself

  
 StringBuiler x = new StringBuiler("Java");
 x.append("Rules !");
 sysout(x);

the output would be Java Rules !

I will give you an example first:

public interface LoginAuth{
   public String encryptPassword(String pass);
   public void checkDBforUser();
}

Now suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods:

public class DBMySQL implements LoginAuth{
          // Needs to implement both methods
}
public class DBOracle implements LoginAuth{
          // Needs to implement both methods
}
public class DBAbc implements LoginAuth{
          // Needs to implement both methods
}

But what if encryptPassword() is not database dependent, and it’s the same for each class? Then the above would not be a good approach.

Instead, consider this approach:

public abstract class LoginAuth{
   public String encryptPassword(String pass){
            // Implement the same default behavior here 
            // that is shared by all subclasses.
   }

   // Each subclass needs to provide their own implementation of this only:
   public abstract void checkDBforUser();
}

Now in each child class, we only need to implement one method – the method that is database dependent.

Technical Differences

  1. Implementing an interface consumes very little CPU, because it’s not a class, just a bunch of names, and therefore there is no expensive look-up to do. It’s great when it matters such as in embedded devices
  2. Abstract classes, unlike interfaces, are classes. They are more expensive to use because there is a look-up to do when you inherit from them.
  3. Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.
  4. Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).
  5. When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an an abstract class can extend another abstract class and abstract methods from the parent class don’t have to be defined.
  6. Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.
  7. A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
  8. A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).

Consider using abstract classes if :
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields.

Consider using interfaces if :

You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
You want to take advantage of multiple inheritance of type.

abstract class establishes “is a” relation with concrete classes. interface provides “has a” capability for classes.

Passing Parameters in Command Context

public class AvgStockVolPerMonthMapper extends Mapper<LongWritable, Text, TextPair, LongPair> {

	private static NYSEParser parser = new NYSEParser();
	private static TextPair mapOutputKey = new TextPair();
	private static LongPair mapOutputValue = new LongPair();

	private static Set<String> stockTickers = new HashSet<String>();

	protected void setup(Context context) throws IOException, InterruptedException {
		String stockTicker = context.getConfiguration().get("filter.by.stock");
		if (stockTicker != null) {
			String[] tickers = stockTicker.split(",");

			for (String ticker : tickers) {
				stockTickers.add(ticker);
			}
		}
	}

	public void map(LongWritable lineOffset, Text record, Context context) throws IOException, InterruptedException {
		parser.parse(record.toString());

		if (stockTickers.isEmpty() || (!stockTickers.isEmpty() && stockTickers.contains(parser.getStockTicker()))) {
			
			if(parser.getStockTicker().equals("AAN")|| parser.getStockTicker().equals("AEB")|| parser.getStockTicker().equals("TCB")|| parser.getStockTicker().equals("XAA"))
			{
				mapOutputKey.setFirst(new Text(parser.getTradeMonth()));
				mapOutputKey.setSecond(new Text(parser.getStockTicker()));
	
				mapOutputValue.setFirst(new LongWritable(parser.getVolume()));
				mapOutputValue.setSecond(new LongWritable(1));
				
				context.write(mapOutputKey, mapOutputValue);
			}			
		}
	}

}

dispatcher-servlet.xml

 <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

HomeController.java

package com.mugil.controls;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {	
	@RequestMapping("/home")	
	public String testMethod()
	{
		return "home";
	}
}

style.css

h1
{
  color : red;
}

DAOService.java

public class DAOService 
{
	private List<Person> arrPersons = new ArrayList<Person>(); 
			
	public DAOService()
	{
		
		Person objPerson = new Person();
		objPerson.setName("Person 1");
		objPerson.setLocation("Teynampet");
		
		arrPersons.add(objPerson);
		
		Person objPerson2 = new Person();
		objPerson2.setName("Person 2");
		objPerson2.setLocation("TNagar");
		
		arrPersons.add(objPerson2);
	}

	public List getList()
	{
		return this.arrPersons;
	}
}

ListPerson.java

@Controller
@RequestMapping("/List")
public class ListPerson 
{	
	@Autowired
	private DAOService objDAOService;
	
	@RequestMapping("/PersonList")
	public String listPersons(Model model)
	{
		DAOService objDAOService = new DAOService();
		
		model.addAttribute("personList", this.objDAOService.getList());
		
		return "display_list";
	}
}

display_list.jsp

<title>Insert title here</title>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
</head>
<body>	
	<table>
		<c:forEach items="${personList}" var="objPerson"> 
			<tr>
				<td>${objPerson.name}</td>
				<td>${objPerson.location}</td>
			</tr>
		</c:forEach>
	</table>
</body>

applicationContext.xml

<bean name="DAOService" class="com.mugil.controls.DAOService"></bean>

pom.xml

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

Method Arguments in Controller

@Controller
@RequestMapping("/Control1")
public class TestController 
{	
	@RequestMapping("/Control2")		
	public String TestMe(HttpSession session, HttpServletRequest request)
	{
		request.setAttribute("name", "Mugil Vannan");
		session.setAttribute("Test", "TestValue");
		System.out.println("1");
		return "hello";
	}
	
	@RequestMapping(value="/Control2", method=RequestMethod.POST)
	public String TestMe2(HttpSession session, HttpServletRequest request)
	{
		System.out.println(session.getAttribute("Test"));
		System.out.println(request.getParameter("cboArea"));		
		return "display";
	}
}

Alternate of HttpServletRequest request

@RequestMapping(value="/Control2", method=RequestMethod.POST)
public String TestMe2(HttpSession session, @RequestParam("cboArea") String Area)
{
  System.out.println(session.getAttribute("Test"));
  System.out.println(Area);		
  return "display";
}

Loggable.java

package com.mugil.shapes;
public @interface Loggable {
}

.java

@Aspect
public class LoggingAspect 
{
@Around("@annotation(com.mugil.shapes.Loggable)")
	public void LoggingAdvice2(ProceedingJoinPoint pjp)
	{
		Object objObject = null;		
		
		try {
			System.out.println("Code before Method Execution Goes here");			
			objObject = pjp.proceed();
			System.out.println("Code after Method Execution Goes here");
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Triangle.xml

public class Triangle 
{
   private String name;

   @Loggable
   public String getName() 
   {
     return name;
   }
.
.
}
Posted in AOP.

spring.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

	<aop:aspectj-autoproxy />
        <bean id="customerBo" class="CustomerBoImpl" />
	<bean name="objTriangle" class="com.mugil.shapes.Triangle">
         	<property name="name" value="Triangle Name"></property>
        </bean>
        <bean name="objCircle" class="com.mugil.shapes.Circle">
    	        <property name="name" value="Circle Name"></property>
        </bean>
        <bean id="shapeService" class="com.mugil.shapes.ShapeService" autowire="byName"/>    	
        <bean name="loggingAspect" class="com.mugil.shapes.LoggingAspect"/>
          <aop:config>
    	     <aop:aspect id="loggingAspect" ref="loggingAspect">
    		<aop:pointcut expression="execution(* com.mugil.shapes.*.get*())" id="allGetters"/>
    		<aop:around method="LoggingAdvice2" pointcut-ref="allGetters"/>
    	     </aop:aspect>
          </aop:config>
</beans>

spring.xml

<aop:aspect id="loggingAspect" ref="loggingAspect">

equivalent to

@Aspect
public class LoggingAspect {

spring.xml

<aop:pointcut expression="execution(* com.mugil.shapes.*.get*())" id="allGetters"/>

equivalent to

@Pointcut("execution(* com.mugil.shapes.*.get*())")
public void allGetters()
{	 
}

spring.xml

<aop:around method="LoggingAdvice2" pointcut-ref="allGetters"/>

equivalent to

@Around("allGetters()")
public void LoggingAdvice2(ProceedingJoinPoint pjp)
{
.
.

<aop:pointcut expression="execution(* com.mugil.shapes.*.get*())" id="allGetters"/>
<aop:around method="LoggingAdvice2" pointcut-ref="allGetters"/>

could be replaced using pointCut

<aop:around method="LoggingAdvice2" pointcut="execution(* com.mugil.shapes.*.get*())"/>
Posted in AOP.

Aspect Oriented Programming answers cross-cutting concern.Cross-cutting concern is one that can affect the whole application and should be centralized in one location in code as possible, such as transaction management, authentication, logging, security etc.

Aspect – A module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement.

Advice – This is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework.

LoggingAspect.java

package com.mugil.shapes;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect 
{
	@Before("execution(public String getName())")
	public void loggingAdvice()
	{
		System.out.println("This is Logging Advice");
	}
}

DrawingApp.java

package com.mugil.shapes;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawingApp 
{
	public static void main(String[] args) 
	{
		ApplicationContext objContext = new ClassPathXmlApplicationContext("Spring-Customer.xml");
		ShapeService  objCircle = (ShapeService) objContext.getBean("shapeService", ShapeService.class);
		System.out.println(objCircle.getObjCircle().getName());
System.out.println(objCircle.getObjTriangle().getName());
	}
}

Circle.java

package com.mugil.shapes;

public class Circle {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Triangle.java

package com.mugil.shapes;

public class Triangle {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}	
}

Output

This is Logging Advice
Circle Name
This is Logging Advice
Triangle Name

@Before(“execution(public String getName())”)
Applies for all the methods with getName() signature (Triangle and Circle Class)

Output

This is Logging Advice
Circle Name
This is Logging Advice
Triangle Name

@Before(“execution(public String com.mugil.shapes.Circle.getName())”)
Applies for the methods with getName() signature (Circle Class)

Output

This is Logging Advice
Circle Name

@Before(“execution(public String com.mugil.shapes.*.getName())”)
Applies for getName() method in Triangle and Circle Class

Output

This is Logging Advice
Circle Name
This is Logging Advice
Triangle Name

@Before(“execution(public * get*())”)
Applies for all getters method in Triangle,Circle and ShapeService Class

Output

This is Logging Advice
This is Logging Advice
Circle Name
This is Logging Advice
This is Logging Advice
Triangle Name

@Before(“execution(public String getName(*))”)
Applies to all getName() method with one or more argument.

@Before(“execution(public String getName(..))”)
Applies to all getName() method with zero or more argument.

Pointcut – This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples.

DrawingApp.java

package com.mugil.shapes;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class LoggingAspect 
{	
	@Before("allGetters()")
	public void loggingAdvice1()
	{
		System.out.println("This is Logging Advice 1");
	}
	
	@Before("allGetters()")
	public void loggingAdvice2()
	{
		System.out.println("This is Logging Advice 2");
	}
		
	@Pointcut("execution(* getName())")
	public void allGetters()
	{	
	}
}
  1. allGetters() method will be called when ever the getName() method of Circle (or) Triangle gets called
  2. Before allGetters() method gets called the loggingAdvice1() and loggingAdvice2() method gets called.

Output

This is Logging Advice 1
This is Logging Advice 2
Circle Name
 @Pointcut("execution(* com.mugil.shapes.*.get*(..))")

Applies for all the Getters within shapes package

 @Pointcut("execution(public * com.mugil.shapes.*.get*(..))")

Applies for all the Public Getters within shapes package

 @Pointcut("within(com.mugil.shapes.*)")

within applies for everything within class whereas execution applies only to the methods.

Runs for all methods getters and setters in com.mugil.shapes.* package.

@Pointcut("args(..)")

Runs for all methods getters and setters.

Join point – This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.

Using JoinPoint we can have access to the Object in the advice method.

LoggingAspect.java

package com.mugil.shapes;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class LoggingAspect {
	
	@Before("allGetters()")
	 public void LogginAdvice(JoinPoint joinpoint)
    {
		System.out.println("advice is run");
	    System.out.println(joinpoint.toString());
    }
	
	@Before("args(name)")
	public void LoggingAdvice2(String name)
	{
		System.out.println("-- " + name);
	}
	
	@Pointcut("execution(* com.mugil.shapes.*.get*())")
	public void allGetters()
	{	
	}
}

DrawingApp.java

public class DrawingApp {
	public static void main(String[] args) {
		ApplicationContext objContext = new ClassPathXmlApplicationContext("Spring-Customer.xml");
		ShapeService  objCircle = (ShapeService) objContext.getBean("shapeService", ShapeService.class);
objCircle.getObjTriangle().setName("Test Tri");
		System.out.println(objCircle.getObjTriangle().getName());	
	}
}

Output

advice is run
execution(Triangle com.mugil.shapes.ShapeService.getObjTriangle())
-- Test Tri
advice is run
execution(Triangle com.mugil.shapes.ShapeService.getObjTriangle())
advice is run
execution(String com.mugil.shapes.Triangle.getName())
Test Tri

LoggingAspect.java

@Aspect
public class LoggingAspect {
	
	@Before("allGetters()")
	 public void LogginAdvice(JoinPoint joinpoint)
    {
		System.out.println("advice is run");
	    System.out.println(joinpoint.toString());
    }
	
	@AfterReturning(pointcut ="args(name)", returning="returnString")
	public void LoggingAdvice2(String name, String returnString)
	{
		System.out.println("This is Input to Method " + name);
		System.out.println("This is Returned  from  Method " + returnString);
	}
	
	@AfterThrowing(pointcut="args(name)", throwing="ex")
	public void LoggingAdvice4(String name, RuntimeException ex)
	{
		System.out.println("This will be Printed incase of Exception is Thrown in Method");		
		System.out.println(ex);
	}

	
	@Pointcut("execution(* com.mugil.shapes.*.get*())")
	public void allGetters()
	{	
	}
}

Using Around

@Around("allGetters()")
	public void LoggingAdvice2(ProceedingJoinPoint pjp)
	{
		Object objObject = null;		
		
		try {
			System.out.println("Code before Method Execution Goes here");			
			objObject = pjp.proceed();
			System.out.println("Code after Method Execution Goes here");
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
Posted in AOP.