Showing posts with label CoreJava Interview. Show all posts
Showing posts with label CoreJava Interview. Show all posts

Thursday, July 19, 2012

Why override tostring method in java ?




The toString() method in the Object class is used to display some information regarding any object.
If any code needs some information of an object of a class, then it can get it by using this method

The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method.


package com.example.generics;

public class ToStringMethodTest {
private String companyName;
private String companyAddress;
public ToStringMethodTest(String companyName, String companyAddress) {
this.companyName = companyName;
this.companyAddress = companyAddress;
}
public static void main(String[] args) {
ToStringMethodTest test = new ToStringMethodTest("ABC private Ltd","10, yy Street, CC Town");
System.out.println(test.toString());
}

public String toString() {
return ("Company Name: " + companyName + "n" +
"Company Address: " + companyAddress);
}
  }

OUTPUT:

Company Name: ABC private LtdnCompany Address: 10, yy Street, CC Town

But if you comment the toString() method...you will get output below

com.example.generics.ToStringMethodTest@9304b1


What we have just now seen is just a sample of how a meaningful override of the toString() method would prove to be of great use in displaying an object’s information when we try printing an object using the System.out.println statement during debugging processs.

Friday, July 6, 2012

How to get decimal HTML entity from String in Java?



Below is the method for returning the decimal entity.........

public static String getHTMLEntity(String value) {
StringBuffer testBuffer = new StringBuffer();
char[] test = value.toCharArray();
if (test != null) {
int size1 = test.length;


for (int j = 0; j < size1; j++) {
testBuffer.append("&#");
testBuffer.append(Character.codePointAt(test, j));
testBuffer.append(";");
}
}
return testBuffer.toString();
}


OUTPUT for "सड्फलक्ल क्लजकलसदफ  क्ळज्सलड्फ"


&#2360;&#2337;&#2381;&#2347;&#2354;&#2325;&#2381;&#2354;&#32;&#2325;&#2381;&#2354;&#2332;&#2325;&#2354;&#2360;&#2342;&#2347;&#32;&#32;&#2325;&#2381;&#2355;&#2332;&#2381;&#2360;&#2354;&#2337;&#2381;&#2347;

How to print text from string of HTML decimal entity in Java?


Below is the Code..........


String encodeString="&#2360;&#2337;&#2381;&#2347;&#2354;&#2325;&#2381;&#2354;&#32;&#2325;&#2381;&#2354;&#2332;&#2325;&#2354;&#2360;&#2342;&#2347;&#32;&#32;&#2325;&#2381;&#2355;&#2332;&#2381;&#2360;&#2354;&#2337;&#2381;&#2347;";



 StringBuffer sb = new StringBuffer();
   Matcher m = Pattern.compile("\\&#(\\d+);").matcher(s);
   while (m.find()) {
       int uc = Integer.parseInt(m.group(1));
       m.appendReplacement(sb, "");
       sb.appendCodePoint(uc);
   }
   m.appendTail(sb);



System.out.print(sb.toString());


OUTPUT :
सड्फलक्ल क्लजकलसदफ  क्ळज्सलड्फ

How to get unicode characters from String ?


Below is the Example.....

StringBuffer a = new StringBuffer();
try {
String line = "Shailesh Shukla";
for (int index = 0; index < line.length(); index++) {
String hexCode = Integer.toHexString(line.codePointAt(index))
.toUpperCase();
String hexCodeWithAllLeadingZeros = "0000" + hexCode;
String hexCodeWithLeadingZeros = hexCodeWithAllLeadingZeros
.substring(hexCodeWithAllLeadingZeros.length() - 4);
a.append("\\u" + hexCodeWithLeadingZeros + " ");
}
} catch (Exception e) {
}
System.out.println(a.toString());

OUTPUT For String "Shailesh Shukla"

\u0053 \u0068 \u0061 \u0069 \u006C \u0065 \u0073 \u0068 \u0020 \u0053 \u0068 \u0075 \u006B \u006C \u0061 

Monday, July 2, 2012

Create an object from a string in Java?

import java.lang.reflect.*;

Class [] classParm = null;
Object [] objectParm = null;

try {
    String name = "com.rgagnon.MyClass";
    Class cl = Class.forName(name);
    java.lang.reflect.Constructor co = cl.getConstructor(classParm);
    return co.newInstance(objectParm);
}
catch (Exception e) {
    e.printStackTrace();
    return null;
}



Another example, but this time we are passing a parameter to the //constructor and calling a method dynamically.

public class Test {
    public static void main(String args[]) {
        
        try {
            String name = "java.lang.String";
            String methodName = "toLowerCase";
            
            // get String Class
            Class cl = Class.forName(name);
            
            // get the constructor with one parameter
            java.lang.reflect.Constructor constructor =cl.getConstructor(new Class[] {String.class});
            
            // create an instance
            Object invoker =constructor.newInstance (new Object[]{"REAL'S HOWTO"});
            
            // the method has no argument
            Class  arguments[] = new Class[] { };
            
            // get the method
            java.lang.reflect.Method objMethod = cl.getMethod(methodName, arguments);
            
            // convert "REAL'S HOWTO" to "real's howto"
            Object result =objMethod.invoke(invoker, (Object[])arguments);
            
            System.out.println(result);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Tuesday, May 29, 2012

What is Template Design Patter in Java?


An abstract class defines various methods and has one non-overridden method which calls the various methods.
Wikipedia Says:
A
 template method defines the program skeleton of an aligorithm.The aligorithm itself is made abstract,and the subclasses override the abstract methods to provide concrete behavior.First a class is created that provides the basic steps of an aligorithm design.These steps are implemented using abstract methods.Later on subclasses change the abstract methods to implement real actions.Thus the general aligorithm is saved in one place but the concrete steps may be changed by the subclasses.
Non-Abstract Methods are completly controlled by the Template Method.In contrast the
 template method need not be changed and is not an abstract operation and thus may guarentee required steps before and after the abstract operations.Thus the template method is invoked and as a consequence the non-abstract methods and abstract methods are called in the correct sequence.
Intent: Define the skeleton of an aligorithm in an operation,deferring some steps to subclasses.Template methods lets subclasses redefine certain steps of an aligorithm without changing the aligorithm structure .[DesignPatterns, p. 325]
Motivation:
Sometimes we want to specify the order of operations that a method uses,but allow subclasses to provide their own implementation of some of these operations.When ever we see two methods in subclasses,it makes sense to bring the methods together into a superclass method.
Applicability:
Use the Template method pattern:
·         To implement the invariant parts of an aligorithm once and leave it up to subclasses to implement the behavior that can vary.
·         To localize common behavior among subclasses and place it in a common class(in this case a superclass) to avoid code duplication.This is a classic example of “code refactoring”.
·         To control how subclasses extend superclass operations.You can define a template method that calls “hook” operations at specific points,there by permitting extensions only at that point.
THE TEMPLATE METHOD IS A FUNDAMENTAL TECHNIQUE FOR CODE REUSE
Problem:
Two different component have significant similarities,but demonstrate no reuse of common interface or implementation.If a change common to both components becomes necessary,duplicate effort must be expended.
Discussion:
The component designer decides which steps of an aligorithm are invariant(or standard) and which are variant(or customizable).The invariant steps are implemented in an abstract base class,while the variant steps are either given a default implementation or no implementation at all.The “variant” steps represent “hooks”,or “placeholders” that can or must be supplied by the component’s client in a concrete derived class.
The component designer mandates the required steps of an aligorithm,and the ordering of the steps,but allow the component client to extend or replace some number of steps.
Template methods
 are prominently used in frameworks.Each framework implements the invariant pieces of domain’s architecture,and defines “placeholders” for all necessary or interesting client customization options.The inverted control structure has been affectionately labelled “the hollywood principle” – Don’t call us we will call you.

Usage:
The template method is used to:
·         Let subclasses implement behavior that can vary.
·         Avoid duplication in the code.We look for general code in the aligorithm and implement variants in the subclasses.
·         Control at what point(s) subclassing is allowed.
Implementation Issues:
·         Operations which must be overridden by subclasses should be made abstract.
·         If the template method itself should not be overidden by subclasses it should be made final.
·         To allow a subclass to insert code at a specific spot in the operation of the aligorithm,insert “hook” operations into the template method.These hook operations may do nothing by default.
·         Try to minimize the number of operations that a subclass must override.
·         In a template method parent class calls the operations of a subclass and not the other way round.
Example:
The template method defines a skeleton of an aligorithm in an operation and defers some steps to subclasses.Home Builders use the template method when developing a new subdivision.A typical subdivision consits of a limited number of floor plans with diff variations available for each.Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the later stages of construction to produce a wider variety of models. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]
Template method pattern could be refactored using an interface that explicitly signals the methods requested to subclasses and also the state needed by them from the abstract class.
Rules of Thumb:
Strategy is like Template Method except in its granularity.[Coplien, C++ Report, Mar 96, p88]
Template method uses inheritance to vary part of an aligorithm.Strategy uses delegation to vary the entire aligorithm. [GOF, p330]
Also Alex has a good explanation of why he hates Template Pattern.Even i do agree to some extent.
Below example gives an implementation of Template Design Pattern.
package patterns;

abstract class TitleInfo {
 private String titleName;

 // The Template Method.
 // Calls the concrete class methods,is not overridden

 public final String processTitleInfo() {
  StringBuffer titleInfo=new StringBuffer();
  titleInfo.append(this.getTitleBlurb());
  titleInfo.append(this.getDvdEncodingRegionInfo());
  return titleInfo.toString();
 }

 public final void setTitleName(String titleNameIn) {
  this.titleName=titleNameIn;
 }

 public final String getTitleName() {
  return this.titleName;
 }

 public abstract String getTitleBlurb();

 public String getDvdEncodingRegionInfo() {
  return " ";
 }

}

class DvdTitleInfo extends TitleInfo {
 String star;
 char encodingRegion;

 public DvdTitleInfo(String titleName,String star,char encodingRegion) {
  this.setTitleName(titleName);
  this.setStar(star);
  this.setEncodingRegion(encodingRegion);
 }

 public char getEncodingRegion() {
  return encodingRegion;
 }

 public void setEncodingRegion(char encodingRegion) {
  this.encodingRegion = encodingRegion;
 }

 public String getStar() {
  return star;
 }

 public void setStar(String star) {
  this.star = star;
 }

 public String getTitleBlurb() {
  return ("DVD: " + this.getTitleName() + ", starring " + this.getStar());
 }

 public String getDvdEncodingRegionInfo() {
        return (", encoding region: " + this.getEncodingRegion());
    }
}

class BookTitleInfo extends TitleInfo {
 private String author;

 public BookTitleInfo(String titleName,String author) {
  this.setAuthor(author);
  this.setTitleName(titleName);
 }

 public String getAuthor() {
  return author;
 }

 public void setAuthor(String author) {
  this.author = author;
 }

 public String getTitleBlurb() {
  return ("Book: " + this.getTitleName() + ", Author: " + this.getAuthor());
 }
}

public class TemplatePatternDemo {

 public static void main(String[] args) {
  TitleInfo bladeRunner=new DvdTitleInfo("Blade Runner","Harrison Ford",'1');
  TitleInfo electricSheep=new BookTitleInfo("Do Androids Dream of Electric Sheep?","Philip");

  System.out.println(" ");
  System.out.println("Testing bladeRunner" + bladeRunner.processTitleInfo());
  System.out.println("Testing electricSheep" + electricSheep.processTitleInfo());
 }
}

CallBack example in java?


Create a class Callback.java

package com.etretatlogiciels.callback.example;

public interface Callback
{
 void methodToCall();
}

Create another class CallbackImpl.java

package com.etretatlogiciels.callback.example;

public class CallbackImpl implements Callback
{
 @Override
 public void methodToCall()
 {
  System.out.println( "I've been called back!" );
 }
}
Create another class Caller.java

package com.etretatlogiciels.callback.example;

/**
 * This is my idea of how a formal call-back mechanism works. There are examples in the
 * real world, very common in Android code, for instance: look for View.OnClickListener().
 */
public class Caller
{
 public Callback callback = null;

/* register a method to be called back at some future, arbitrary point */
 public void register( Callback callback )
 {
  this.callback = callback;
 }

/* how Caller invokes the call-back method at the appropriate juncture  */
 public void execute()
 {
  this.callback.methodToCall();
 }

/* directly execute a method (I don't see this is a "call-back" at all) */
 public void execute( Callback callback )
 {
  callback.methodToCall();
 }

 public static void main( String args[] )
 {
  Caller  caller   = new Caller();
  Callback callback = new CallbackImpl();

  /* Demonstrate simple calling back.
   */
  caller.register( callback );
  caller.execute();

/*Demonstrate direct calling back (here, immediate execution) by creating an "on
*the fly" call-back. In a real world example, caller.execute( Callback callback )* would be a mechanism that properly establishes a situation in which, later, the* "direct" call would issue. This is very common in Android code as noted above.
*/
  caller.execute( new Callback()
   {
    public void methodToCall()
    {
   System.println( "This is our \"on the fly\" method..." );
    }
   }
  );
 }
}

Below is the output
I've been called back!
This is our "on the fly" method...

CallBack Example in Java ?


interface Callable
{
    public void callBackMethod();
}
class Worker
{
    // Worker gets a handle to the boss object via the Callable interface.
    // There's no way this worker class can call any other method other than
    // the one in Callable.
    public void doSomeWork(Callable myBoss)
    {
        myBoss.callBackMethod();
        // ERROR!
        //myBoss.directMethod();
    }
}
class Boss implements Callable
{
    public Boss()
    {
        // Boss creates a worker object, and tells it to do some work.
        Worker w1 = new Worker();
        // Notice, we're passing a reference of the boss to the worker.
        w1.doSomeWork(this);
    }
    public void callBackMethod()
    {
        System.out.println("What do you want?");
    }
    public void directMethod()
    {
        System.out.println("I'm out for coffee.");
    }
}
public class CallBack
{
    // Main driver.
    public static void main(String[] args)
    {
        Boss b = new Boss();
        b.directMethod();
    }
}

CallBack Using Inner Class in Java ?



Create interface seperately Incrementable .java


interface Incrementable {
  void increment();
}


Also create Callbacks.java
// Very simple to just implement the interface:

class Callee1 implements Incrementable {
  private int i = 0;

  public void increment() {
    i++;
    System.out.println(i);
  }
}

class MyIncrement {
  void increment() {
    System.out.println("Other operation");
  }

  static void f(MyIncrement mi) {
    mi.increment();
  }
}

// If your class must implement increment() in
// some other way, you must use an inner class:

class Callee2 extends MyIncrement {
  private int i = 0;

  private void incr() {
    i++;
    System.out.println(i);
  }

  private class Closure implements Incrementable {
    public void increment() {
      incr();
    }
  }

  Incrementable getCallbackReference() {
    return new Closure();
  }
}

class Caller {
  private Incrementable callbackReference;

  Caller(Incrementable cbh) {
    callbackReference = cbh;
  }

  void go() {
    callbackReference.increment();
  }
}

public class Callbacks {

  public static void main(String[] args) {
    Callee1 c1 = new Callee1();
    Callee2 c2 = new Callee2();
    MyIncrement.f(c2);
    Caller caller1 = new Caller(c1);
    Caller caller2 = new Caller(c2.getCallbackReference());
    caller1.go();
    caller1.go();
    caller2.go();
    caller2.go();
  }
}

Output :


Other operation
1
2
1
2

String Versus StringBuffer ?


An understanding of the difference between Java Strings and StringBuffers can lead to great performance increases. Although it may seem not to be the case given Java's String concatenation syntax (like a=a+"hi"), Strings are in actuality read-only (ie, immutable) after they are created so that they cannot change. As a result of this, when you concatenate Strings via the + operator, in the background a temporary StringBuffer gets created and the toString method is called on the StringBuffer to create the new String, and this operation is fairly time-consuming.
However, much less overhead is required to concatenate a String onto a StringBuffer object via the StringBuffer append method. You can basically think of each append as adding another String piece into a linked list that makes up the StringBuffer. So you basically have a StringBuffer consisting of a String chunk which then points to another String chunk which points to another String chunk, etc...
The benefits of StringBuffer become clear when you have a situation involving many concatenations. To illustrate this, let's try concatenating 10,000 "a" Strings together via the String + operator and via a StringBuffer append method and monitor the time required to perform these operations. The StringVersusStringBuffer class below illustrates this.
package test;

public class StringVersusStringBuffer {
         public static void main(String[] args) {
                 try {
                          final int NUM_REPEATS = 10000;
                          String string = "";
                          long start = System.currentTimeMillis();
                          for (int i = 0; i < NUM_REPEATS; i++) {
                                   string = string + "a";
                          }
                          long end = System.currentTimeMillis();
                          System.out.println("String loop time (ms): " + (end - start));

                          StringBuffer sb = new StringBuffer();
                          start = System.currentTimeMillis();
                          for (int i = 0; i < NUM_REPEATS; i++) {
                                   sb.append("a");
                          }
                          end = System.currentTimeMillis();
                          System.out.println("StringBuffer loop time (ms): " + (end - start));
                 } catch (Exception e) {
                          e.printStackTrace();
                 }
         }
}

OutPut :
String loop time (ms) : 156
StringBuffer loop time (ms) : 0

Wednesday, March 14, 2012

What are differences among throw, throws, and Throwable in Java?


1) In Java, all error's and execption's class are drieved from java.lang.Throwable class. It is the top of the hierarchy of classes of error and exceptions. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.

2) throws is a post-method modifier and specifies which execptions may be thrown by the method. If they are checked exceptions, the compiler will guarantee the code invoking that method must catch these checked exceptions.

3) throw statement is used to throw an error or exceptions. throw statement requires a single argument: a instance of any subclass of the Throwable class or Throwable class. Executingthrow statement triggers the JVM to throw this exception and causes an exception to occur.

How can you compare NaN values in Java?


Floating-point numbers are ordered from -∞, -y (negative finite nonzero values), -0, +0, +y, +∞. The float and double types represent 32- and 64-bit IEEE 754 floating-point numbers.
The special number NaN (not-a-number) is unordered and has the following characters:
  • The numerical comparison operators <, <=, >, and >= always return false if either or both operands are NaN.
  • The equality operator == returns false if either operand is NaN.
  • The inequality operator != returns true if either operand is NaN .
In particular, x != x is true if and only if x is NaN, and (x == y) will be false if x or y is NaN.
To verify a floating point value is NaN, use the Double.isNaN() method instead. The x == NaN will not work because "The equality operator == returns false if either operand is NaN". NaN is never equal to any other number, not even itself.
The wrapper classes such as Float and Double have the same behavior when using the above comparison operators. Comparing two NaN Float objects using Float.equals() will yieldtrue even even though Float.NaN==Float.NaN has the value false. This is one of two special cases in Float class and described in Float class document. Such behavior make it possible to use an NaN Float object as a key in a HashMap. For example,
public class Program {        
  public static void main(String[] s){
    Double a = new Double(Double.NaN);
    Double b = new Double(Double.NaN);
   
    if( Double.NaN == Double.NaN )
      System.out.println("True");
    else
      System.out.println("False");
        
    if( a.equals(b) )
      System.out.println("True");
    else
      System.out.println("False");
  }
}
The output is
False
True