What is Proxy Design Pattern?

Provide a surrogate or placeholder for another object. This Place holder object provides some advantages, few are as below.

#1. to Access Remote Object.
#2. to control access of few methods of original object.
#3. it may be costly(consumes more memory or time) to use original object.
…and many more.

Below is an example, of using place holder object of VideoProxy instead of original Video object.

As shown in example below, object of Video class loads video file, even to display thumb nail. As known it consumes more memory to load multiple video thumb nails, in a single screen.

To keep memory consumption minimal, ProxyVideo has been implemented, which displays an Image to display thumb nail. And the video file is loaded, only when user want to play the video, that too only the specific video file which the user opted to view, will be loaded to play.

public interface IVideo {
   void displayThumbnail();
   void playVideo();
}

public class Video implements Image {

   private String fileName;

   public Video(String fileName){
      this.fileName = fileName;
   }

   @Override
   public void displayThumbnail() {
      loadVideoFromStorage();
      System.out.println("Displaying Thumbnail of " + fileName);
   }

   private void loadVideoFromStorage(){
      System.out.println("Loading actual video... " + fileName);
   }

   @override
   public void playVideo()
   {
      loadVideoFromStorage();
   }
}

public class ProxyVideo implements IVideo{

   private Video objVideo;
   private String fileName;

   public Video(String fileName){
      this.fileName = fileName;
   }

   @Override
   public void displayThumbnail() {
      String thumbnail_name = fileName+"_thumbnail.jpg";
      System.out.println("Display Thumbnail Image..."+thumbnail_name);
   }

   @Override
   public void playVideo() {
      objVideo = new Video(fileName);
      objVideo.playVideo();
   }
}

In this example, Aggregation is used(Read more on Composition and Aggregation), instead inheritance can be used here.

Difference between Proxy and Adapter Pattern

Adapter Pattern is to change the interface of class A to the expectations of another class B. The typical implementation is a wrapper class or set of classes.

Proxy Pattern is similar, but the purpose is different. The purpose of the proxy pattern is to create a stand-in for a real resource. As already briefed, this stand-in is required as the actual object is remotely located or it is expensive to create actual object or you want to give controlled access to methods of actual class, etc…

You may also like to read:
What is Factory Design Pattern
How to implement Singleton Design Pattern
Can Adapter Pattern use Composition
Adapter Pattern using Inheritance

Factory method Design Pattern in Java

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Advantages of Factory Pattern

1.It can be used to unify the creation of objects sharing a commonality, e.g. in caching: CacheFactory -> Memcache, Filecache, … Working with each cache is similar, but setting up different caching strategies may differ vastly. When using the factory method you can switch between different caching strategies more easily, at best by just chaning one line of code factory(“Memcache”, options),without having to worry about the intricacies of the specific backend;
2.Improves loose Coupling

Also, disadvantage of Factory Pattern is loose coupling by means of additional objects results in decreased performance.

Below is an example of Factory Design Pattern.

public interface ImageReader {
    public DecodedImage getDecodedImage();
}

public class GifReader implements ImageReader {
    public GifReader( InputStream in ) {
        // check that it's a gif, throw exception if it's not, then if it is decode it.
    }

    public DecodedImage getDecodedImage() {
       return decodedImage;
    }
}

public class JpegReader implements ImageReader {
    public JpegReader( InputStream in) {
    }

    public DecodedImage getDecodedImage() {
      return decodedImage;
    }
}

public class PngReader implements ImageReader {
    public PngReader( InputStream in) {
    }

    public DecodedImage getDecodedImage() {
      return decodedImage;
    }
}

public class ImageFactory {

   //use getShape method to get object of type shape
   public static ImageReader getImageReader(String fileName){
      //open file and get type of file
      String file_type = ;
      if(file_type.equalsIgnoreCase("GIF")){
         return new GifReader();

      } else if(file_type.equalsIgnoreCase("JPEG")){
         return new JpegReader();

      } else if(file_type.equalsIgnoreCase("PNG")){
         return new PngReader();
      }

      return null;
   }
}

public class MyImageDemo{
   public static void main(String args[])
   {
       String image_file_name = "abc.gif";
       ImageReader ir = ImageFactory.getImageReader(image_file_name);
       DecodedImage di = ir.getDecodedImage();

       //DecodedImage object may be used to display image,etc...
   }
}

Starting a thread from another thread instead of main thread

Below is an example showing how to start another Thread, from non main thread.

#1.In main method, a thread t1 is started.
#2.In run() method of thread t1, another thread t2 is started.

class thread1 implements Runnable{
public void run(){
System.out.println("inside thread 1 now printing numbers");
for(int i=0;i<10;i++){
System.out.println(i);
}

Thread t2=new Thread(new thread2());

t2.start();


}
}
class thread2 implements Runnable{

public void run(){
System.out.println("inside thread2...");
System.out.println("program which we run has shown that we can invoke or start another thread"
+" out of the main thread also");
}
}
public class threaddemo {
public static void main (String[] args) {
Thread t1= new Thread(new thread1());
System.out.println("starting thread 1");

t1.start();


}

}


Output-

starting thread 1
inside thread 1 now printing numbers
0
1
2
3
4
5
6
7
8
9
inside thread2…
program which we run has shown that we can invoke or start another thread out of the main thread also

You may like to read:
Multi threading example
purpose of PipedInputStream and PipedOutputStream
What is block level synchronization?
What is class level synchronization?

Properties class

The Properties class extends the Hashtable class and implements the Map interface.It represents the persistent set of properties.
Each key and its  value associated with it in the property list is a string.This class has the following constructors:-

public Properties()
public Properties(Properties def)
The first constructor constructs an empty property list with no default values.

The  second constructor will create a empty property with a default def. The property list def is searched if the property key is not found in the original property list.

Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key,String value) sets the property in the properties object.
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String comment) writes the properties in the OutputStream object.
storeToXML(OutputStream os, String comment) writers the properties in the writer object for generating xml document.
public void storeToXML(Writer w, String comment, String encoding) writers the properties in the writer object for generating xml document with specified encoding.


Below example shows how to use Properties class to set key and value pairs, and get the value.

   import    java.io.*;
   import    java.util.*;
   public      class    Test {
   public      static      void    main(String[] args)  throws    Exception{
 Properties p=  new    Properties();
 p.setProperty(“name”,”ravi”);
 p.setProperty(“email”,”ravi@gmail.com”);
 p.getProperty(“name”);
 }
 }


Below example shows how to use Properties class to get configuration values, from a properties file.

   import    java.util.*;
   import    java.io.*;
   public      class    LoadDemo {
   public      static      void    main(String[] args)  throws    Exception{
     FileReader reader=  new    FileReader(“newFile.properties”);

     Properties p=  new    Properties();
     p.load(reader);

     System.out.println(p.getProperty(“username”));
     System.out.println(p.getProperty(“password”));
 }
 }


Below example shows how to use Properties class to set key and value pairs, to a properties file.

 import java.io.*;
 import java.util.*;
 public class PropertiesExample {
           public static void main(String args[]) {
      try {
   Properties std_code = new Properties();

     grades.setProperty(“Bangalore”, “080”);
    grades.setProperty(“Delhi”, “011”);
     grades.setProperty(“Mumbai”, “022”);
    grades.setProperty(“Chennai”, “044”);
    grades.setProperty(“Kolkata”, “033”);

   // Save the grades properties using store() and an output stream
  FileOutputStream out = new FileOutputStream “stdcodes.properties”);
     std_code.store(out, null);
     out.close();

  // load the properties file using load() and an input stream
   FileInputStream in = new FileInputStream(“stdcodes.propertie  std_code.load(in);
   in.close();

    // iterate properties file to get key-value pairs
     for (String key : std_code.stringPropertyNames()) {
     String value = std_code.getProperty(key);
      System.out.println(“The STD code of  ” + key + ” is: ” + value);
                              }

       } catch (IOException eio) {
     System.out.println(eio.getMessage());
      eio.printStackTrace();
                    }
           }
 }


Below example shows how to retrieve and store Configuration properties in a XML file.
NOTE: Below is sample XML file format

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>This is to test</comment>
<entry key="pname1">pval1</entry>
<entry key="pname2">pval</entry>
<entry key="pname3">pval3</entry>
<entry key="pname4">pval4</entry>
</properties>
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.*;

 public class PropertiesloadfromXMLDemo {

    public static void main(String[] args) {
    Properties pro = new Properties();

    // add some properties
    pro.put("pname1", "pval1");
    pro.put("pname2", "pval2");

    try {

    // create a output and input as a xml file
    FileOutputStream fos = new FileOutputStream("abcproperties.xml");
    FileInputStream fis = new FileInputStream("abcproperties.xml");

    // store the properties in the specific xml
    pro.storeToXML(fos, null);

    // load key/values from the xml
    pro.loadFromXML(fis);

    // Now print all the key/values to Standard output
    pro.list(System.out);

    } catch (IOException ex) {
    ex.printStackTrace();
    }

    }
 }

Difference between Composition and Aggregation

In Object oriented languages, Composition, Aggregation and Inheritance are the most common relationships exist between classes.

Composition in Java

Composition is has-a relationship. Also sometimes referred as non-separable part of the whole.
Composition is more stronger relationship compared to Aggregation. Here composed object cannot exist without composing object, and both objects have same life time.

As shown in below code snippet, object of B(i..e obj) cannot exist without object of B. Object of B gets created only along with object of A. Also obj1 does not continue to exist, after object of A gets destroyed.

class A{
B obj;
//… other data members and methods, of class A
}

Aggregation

Aggregation is also a has-a relationship. Also sometimes referred as separable part to whole.
Aggregation is a weaker relationship compared to Composition.
As shown in below code snippet, object of D(i..e obj1) can exist even before object of C gets created. Also obj1 may continue to exist even after object of C is destroyed.

class C{
D obj1;
//… other data members and methods, of class C
}
Composition is Strong Has-A relationship Aggregation is a Weak Has-A relationship.

To understand difference between Composition and Aggregation, lets us take an example of a College with few Departments, and each Department with Lecturers.

aggregation and composition
aggregation and composition

Relationship between College and Department is Composition, and relationship between Department and Lecturer is Aggregation.

class College
{
  private List depts;

  public College()
  {
    depts.add(new Department("Computer Dept"));
    depts.add(new Department("Electrical Dept"));
    depts.add(new Department("Electronics Dept"));
  }

  //...other methods in College class
}

A Department cannot exist without College, hence difference between them is Strong and hence Composition.
When College no more exist, Department cannot exist.

Relationship between Department and Lecturer can be Aggregation, as it is weaker. A Lecturer can exist, even before Department exist. And Lecturer may continue to exist even after Department gets destroyed.

class Department
{
  private Lecturer my_obj;

  public void setLecturer(Lecturer lect)
  {
    my_obj = lect;
  }
  //...other methods in Department class
}

How to Compress and Uncompress file in Java

A file or folder can be compressed in Java using any of the following classes

  1. DeflaterOutputStream
  2. GZIPOutputStream
  3. ZipOutputStream


Above classes are in the package java.util.zip. Also note that GZIPOutputStream and ZipOutputStream classes are derived from DeflaterOutputStream. Any one of them can be used to compress file or folder, they just differ in compress format.

Below is simple program to compress a file, using DeflaterOutputStream.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.DeflaterOutputStream;

public class CompressFile {
public static void main(String args[]){
	try {
FileOutputStream fos = new FileOutputStream("compressed.zip");
//assuming that abcd.txt file is in execution path of program
	FileInputStream fis = new FileInputStream("abcd.txt");

	DeflaterOutputStream dout = new DeflaterOutputStream(fos);
	int j;

	while((j=fis.read()) != -1)
        {
	dout.write((byte)j);

	dout.flush();
	}

	fis.close();
	fos.close();

}catch(Exception e){
System.out.println(e);
r.printStackTrace();
}
System.out.println("Done");
}
}


A compressed file or folder, can be uncompressed using any of below classes

  1. InflaterInputStream
  2. GZIPInputStream
  3. ZipInputStream

Above classes are in the package java.util.zip. Also note that GZIPInputStream and ZipInputStream classes are derived from InflaterInputStream.

Below is simple program to uncompress a file, using InflaterInputStream

import java.io.*;
import java.util.zip.InflaterInputStream;

class UnCompressFile{
public static void main(String args[]){

try{
FileOutputStream fos=new FileOutputStream("abcd.txt");

FileInputStream fis=new FileInputStream("compress.zip");
InflaterInputStream inf=new InflaterInputStream(fis);

int k;

while((k=inf.read())!=-1)
{
fos.write((byte)k);
fos.flush();
}

fis.close();
fos.close();
inf.close();

}catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
}
System.out.println("Done");
}
}

You may also like to read:
How to take input from Standard input
SequenceInputStream example
FileWriter and FileReader example

Purpose of clone() method in Object class

clone() is a method in Object class, and can be used to create duplicate object. Since Object class is base class of all classes in Java, clone() method is available in all classes. In case an object need to invoke clone() method, that class need to implement java.lang.Cloneable interface. If clone() method is invoked without implementing interface, an exception CloneNotSupportedException is being thrown, and cloning is not successful.

Clone object
Also note that below is not cloning an object, as only one object exists, but just another reference(obj1) is created, and not the actual object. Hence this cannot be considered as cloning.

Abc obj1 = new Abc();
Abc obj2 = obj1;

Below is an example, which throws CloneNotSupportedException

class Test{
	int i;
	String str;

	public Object clone()
	{
		try
		{
			return super.clone();
		}
		catch(CloneNotSupportedException ce)
		{
			ce.printStackTrace();
			return null;
		}
	}
}

public class Demo {
	public static void main(String args[])
	{
		Test obj = new Test();

		Test obj_clone = (Test)obj.clone();
	}
}

Output:

java.lang.CloneNotSupportedException: Test
	at java.lang.Object.clone(Native Method)
	at Test.clone(Demo.java:10)
	at Demo.main(Demo.java:25)


Below is right way to clone an object. As shown the class(whose objects can be successfully cloned) need to implement Cloneable interface


class Test implements Cloneable{
	int i;
	String str;

	public Object clone()
	{
		try
		{
			return super.clone();
		}
		catch(CloneNotSupportedException ce)
		{
			ce.printStackTrace();
			return null;
		}
	}
}

public class Demo {
	public static void main(String args[])
	{
		Test obj = new Test();

		obj.i = 10;
		obj.str = new String("testing");

		Test obj_clone = (Test)obj.clone();

		System.out.println("i="+obj.i+", string is "+obj_clone.str);
	}
}


Output:
i=10, string is testing
However, there can be side effects of cloning, if not used properly. As known, Cloning of an object is creation of exact binary copy of the object.

Cloneable is Marker or Tagging interface(and do not declare any methods), which just conveys JVM that objects of the Class are eligible for cloning.

You may also like to read:
printStackTrace output to a String
stack and heap storage in Java
purpose of finalize() Method
How to override toString()

What is RuntimeException class?

As known there are two types of Exceptions Checked and Unchecked Exceptions.

Checked Exceptions are exceptions which are derived from java.lang.Exception class.
Checked Exceptions either need to be enclosed with try and catch block or use throws to further throw the Exception.

Unchecked Exceptions are exceptions which are derived from java.lang.RuntimeException class.
Unlike Checked Exceptions, Unchecked Exceptions does not need try/catch block or throws keyword.

RuntimeException
Relation between Exception classes

Below is an example, showing the exception class inheriting from RuntimeException class.

class SomeRuntimeException extends RuntimeException
{
	SomeRuntimeException(String msg)
	{
		super(msg);
	}
}

public class UnCheckedExceptionExample {
	public static void main(String args[])
	{
	int val = 0;

	System.out.println("Before throwing exception");

	if(val == 0)
	{
		throw new SomeRuntimeException("test message");
	}

	System.out.println("After throwing exception");
	}
}

Output:
Before throwing exception
Exception in thread “main” SomeRuntimeException: test message
at UnCheckedExceptionExample.main(UnCheckedExceptionExample.java:18)

You may also like to read:
what is printStackTrace() method
Output printStackTrace() to a String
Purpose of synchronized keyword

How to create your own Exception class

While developing applications in Java, you would often need to create your own Exceptions based on the need, along with built in Exception classes like ClassNotFoundException, NumberFormatException, ArithmeticException, ArrayIndexOutofBoundsException, etc… You can also create your own Exceptions, TestException

Below is an example to create an Exception class,

//Create our own Exception
class TestException extends Exception
{
	public String toString()
	{
		return "This is only Test Exception";
	}
}

public class MyOwnExceptionDemo {
	public static void main(String[] args) {
	try
	{
		throw new TestException();
	}
	catch(TestException te)
	{
		te.printStackTrace();

		//How to get class name from an object
		System.out.println("Exception class name:"+te.getClass().getName());
		System.out.println(te.toString());
	}
	}

}

You may also like to read:
what is printStackTrace() method
Output printStackTrace() to a String
Purpose of synchronized keyword

Jsp implicit objects

In JSP implicit objects are the objects created by implicitly, and can be directly used in Jsp programs with out declaring them. This is basically to reduce the code written by developer.

Below is list of Jsp implicit objects, along with the details

Implicit Object name Instance of class Brief
request javax.servlet.http.HttpServletRequest Used to retrieve all request parameters submitted from HTML page and to retrieve Cookies on Browser.

response

javax.servlet.http.HttpServletRespone used to send response from servlet to HTML Page, add Cookies to Browser, in Request Dispatcher

out

java.io.PrintWriter Used to send output from Servlet to Browser, generally HTML code

session

javax.servlet.http.HttpSession Stores details of current session in progress, using this session attributes can be set and get.

config

javax.servlet.ServletConfig used to retrieve initialization parameters which are specific to each servlet

application

javax.servlet.ServletContext used to retrieve initialization parameters which are common to all servlets

exception

java.lang.Throwable Has details of exception being thrown from a Jsp page.

pageContext

javax.servlet.jsp.PageContext Using this object you can find attribute, get attribute, set attribute and remove attribute at any of levels JSP Page (PAGE_CONTEXT) or HTTP Request (REQUEST_CONTEXT) or HTTP Session (SESSION_CONTEXT) or Application Level ( APPLICATION_CONTEXT)

page

java.lang.Object class and represents the current JSP page. page object provide reference to the generated servlet class. This object is very rarely used.