Friday, March 18, 2011

Core Java Questions

Here I am trying to put informations i have collected from different sites while i was doing job hunt + my own experiments together.




Diffrenece between == and .equals in JAVA

Remember String is immutable.
The operator, ==, tests to see if two object reference variables refer to the exact same instance of an object.

The method, .equals(), tests to see if the two objects being compared to each other are equivalent -- but they need not be the exact same instance of the same object.

Integer i = new Integer(10);
Integer j = i;

in the above code. i == j is true because both i and j refer to the same object.

Example #2:

Integer i = new Integer(10);
Integer j = new Integer(10);

In the above code, i == j is false because, although they both have the value 10, they are two different objects.

Also, in the above code, i.equals(j) is true because although they are two different objects, they are equivalent in the fact that they represent the same number, 10.
In case of String comparison, its different

posted Thursday, March 08, 2012 03:59:25
Slight Different from this Context but felt like Posting

Let say we have
String s1 = "abc"
String s2 = "abc"
and do
s1==s2 will always give you True
This is possible becuase of String Interning.
In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.
The single copy of each string is called its 'intern' and is typically looked up by a method of the string class, for example String.intern() in Java. All compile-time constant strings in Java are automatically interned using this method.

Whenever you create a new String object (say String s1="same"), the system will check whether there is any such "same" in the pool, if it found one, it will assign that reference to the string variable s1.
let say i have another String  s2="same", since there is already a "same", system will give that ref to s2
String s3=s2 //both s1,s2,s3 will have same ref so s1==s3 will be true
s2="not same"// since there is no such string in the pool, "not same" will be stored in memory and that ref will be assigend to s2
now s1==s2 will b false
s1==s3 will be true
If you print .hashCode(), all object with same string value will have same hashcode.

Overriding equals and Why always override hashcode() if overriding equals()?
In Java, every object has access to the equals() method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects.

You must have to override both equals() and hashCode() method in Java , otherwise your value object will not be able to use as key object in HashMap because working of HashMap is based on equals() and hashCode


public class OverRidingEquals {

/**
* @param args
*/
int age;
String name;
public  OverRidingEquals(int age,String name){
this.name = name;
this.age = age;
}
public static void main(String[] args) {

OverRidingEquals person1 = new OverRidingEquals(10,"aaa");
OverRidingEquals person2 = new OverRidingEquals(10,"aaa");
System.out.println(person1.hashCode());
System.out.println(person2.hashCode());
System.out.println(person1.equals(person2));
Map<OverRidingEquals, OverRidingEquals> myMap= new HashMap<OverRidingEquals, OverRidingEquals>();
myMap.put(new OverRidingEquals(10,"aaa"), person1);
System.out.println(myMap.get(new OverRidingEquals(10,"aaa")));  //Line 20
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
OverRidingEquals otherPerson = (OverRidingEquals)obj;
return (this.age == otherPerson.age && this.name == otherPerson.name);
}
@Override
public int hashCode() {

return this.age;
}
}
If you didnt override hashcode, Line 20 will return null coz (new OverRidingEquals(10,"aaa") has different hashcode than the one we actually put in hashmap



Q1. Difference between HashMap and HashTable?
A1.The HashMap class is roughly equivalent to Hashtable (Both the class extends interface Map), except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.
If we try to add null as key or as value, hashtable will throw NullpointerException.
If we put null or same key string multiple time in a hashmap, it will compile and runs fine but it will take only the last kay/value pair entered.


Both hashtable and hashmap makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.


Map map = new HashMap();
            map.put(null, null);
            map.put(null, "value2");
            map.put("key", "value1");
            map.put("key", "value2");
            System.out.println("Size : "+map.size()+"Value : "+map.get("key").toString());

Output -> Size : 2 Value : value2
hashTable.put(null, "asd"); //java.lang.NullPointerException
hashTable.put("key", null); //java.lang.NullPointerException

NB: In Java collections, interfaces List and Set are extending collection interface whereas Map doesn’t extends any interface.
HashTable was introduced first

Q: What is HashMap and Map?
A: Map is Interface and Hashmap is class that implements that.


Q: What is the difference between an Interface and an Abstract class?
A: An abstract class is intended to be created to be used as a base and that’s the reason why it cannot be final J .
An abstract class can have concrete methods as well as abstract methods.

If you have some common feature used across the application by your child classes and you enforce your child classes to have particular method signature (prototype) and have their own implementations for some other methods, then go for Abstract class.
Example
Lets say I have methods doBeforeSave(object),save(object),doAfterSave(object)  in order decorate an object b4 save and save it in the DB and so on. Let’s assume that we have n number of modules and all are going to have these functionalities. Assume save(obj) is going to be same in all modules and doBeforeSave(object) and doAftersave have different business requirements and they are going to have different implementations for different modules. So first thing we would do is take these 3 methods to a parent class and let the modules extends this parent class. Properly implement save(obj) in the parent class. Since the other 2 methods are going to have different implementation but we want everyone should follow same signature, we should declare them as abstract method and hence the holding class should be of Abstract class as well.

An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.

1. If don’t worry about the actual implementation but will enforce the developers to stick on specified method signature.
2.For multiple inheritance, For example we have
Class Actor and Class Director, so if you are an actor you can extend the Class Actor and if you are director you can extend the Class Director. An Actor can be director as well and Java doesn’t support multiple inheritance.




Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 

Garbage collection cannot be forced. This indicates that Garbage Collector is an independent thread and is on a priority which is decided by the JVM, so you may not enforce Garbage Collection. 


You can always call System.gc() as a normal method call. But, This does not guarantee that the Garbage Collection thread will clean up memory chunks which are no longer required. The execution of the Garbage Collector Thread for collecting the discarded objects is with the JVM, and JVM periodically cleans up the same.

A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. 

A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

A: Vector is synchronized whereas arraylist is not.

A: A Constructor should have the same name as the class itself
It shouldn’t have any return type and is invoked using the new operator.
First statement in a constructor should ‘this’ or ‘super’, if neither of this is specified compiler automatically inserts a call to the parameter less super class constructor.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q: State the significance of public, private, protected, default modifiers
A: 

A class cab only public, abstract & final
public : Public class is visible in other packages, field is visible everywhere.
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method.
protected : Is available to all classes in the same package and also available to all subclasses of this class.
default :it is visible to all within the package.


Q: What is static in java?
A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.


Q: What is final,finally and finalize?

A: final – constant declaration.
finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state.


Q: What if the main method is declared as private?
A: The program compiles properly but at runtime it will give "Main method not public." message.






Q: What if the static modifier is removed from the signature of the main method?
A: Program compiles. But at runtime throws an error "NoSuchMethodError".


Q: Can I have multiple main methods in the same class?
A: No the program fails to compile. The compiler says that the main method is already defined in the class.


Q: Can I import same package/class twice? Will the JVM load the package twice at runtime?
A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.


Q: What are Checked and UnChecked Exception?
A: A checked exception are subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown

NullpoiterException is an unchecked Exception.

Q: What is Overriding?
A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.

"The difference in return type only is not sufficient for method overloading in java". It will throw a compile time error 'Duplicate Method'. compiler will check only the name of the method and the arguments  the return type does not play any part in deciding which overloaded method should be called.mean to call.


Q:Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol.


Q: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.


Q: What is serialization?
A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.


Q: What is the difference between error and an exception?
A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).


Q: If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
A: To have your class instance as Exception, your class must extend Throwable/Exception class. Because Java does not allow multiple inheritance and does not provide any exception interface and you have already extending some other class, you cannot make that possible. one other way to achieve this is make your super class extends Throwable/Exception.


Q: Difference throw and throws
A: public void myMethod() throws MyException 


if (param < 10) 
throw new MyException("Too low!); 
}
}
The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method.

Q: Is it necessary that each try block must be followed by a catch block?
A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.



public void test() {

try {
method();
} finally {
}
}
public void method() throws DerivedClass {
}
It will thow compilation error 'Unhandled Exception', we should throw this exception from test()

Q: If I write return at the end of the try block, will the finally block still execute?
A: Yes, even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

finally block will not execute if we put a System.exit(0); in the try block.

Q: What are the steps in the JDBC connection?
A: Register the database driver by using :
Class.forName(\" driver classs for that specific database\" );
Create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");
Exceute the query :
stmt.exceuteUpdate();



Q: What is the difference between a Statement and a PreparedStatement?
A: Prepared statements offer better performance, as they are pre-compiled. Prepared statements reuse the same execution plan for different arguments rather than creating a new execution plan every time. Prepared statements use bind arguments, which are sent to the database engine. This allows mapping different requests with same prepared statement but different arguments to execute the same execution plan.

Prepared statements are more secure because they use bind variables, which can prevent SQL injection attack.

Most relational databases handles a JDBC / SQL query in four steps:
1. Parse the incoming SQL query
2. Compile the SQL query
3. Plan/optimize the data acquisition path
4. Execute the optimized query / acquire and return data
Prepared statements do steps 1-3 only once.


Q: Calling Exception and RuntimeException methods.
A: public void sayhi() throws Exception{}

public void sayhello() throws RuntimeException{
}


sayhi() should be inside try{} block inside the calling class, but sayhello() shouldn't be.




Q: Aggregation Composition

Composition - One class has another class.
Aggregation - One class is a kind of another class.
·         Aggregation represents a "has-a" relationship whereas Composition represents a "contains-a" OR "whole-part" relationship.
·         In case of Aggregation, both the entities will continue to have their independent existence whereas in case of Composition the lifetime of the entity representing 'part' of the "whole-part" is governed by the entity representing 'whole'.
·         Aggregation represents a loose form of relationship as compared to that represented by Composition which depicts a stronger relationship.
·        In UML notation, an Aggregation relationship is depicted by an unfilled diamond and a solid line whereas a Composition relationship is depicted by a filled diamond and a solid line.

Read below for more details
Aggregation - this is special type of association used for modelling 'Possession' (not Ownership) with the restriction that it's NOT cyclic. That means, an entity can't have an aggregation relationship with itself. This is the reason why an aggregation relationship doesn't form a Graph, instead it forms a Tree.

Aggegation is normally understood as a "has-a" relationship. Here both the entities continue to have their own independent existence. In UML notation, an aggregation isdepicted by an unfilled diamond and a solid line. For example: Consider two entitiesEmployee (EmpNo, Name, EmailId, Salary, DeptNo, Address) and Address (FlatNo, PlotNo, StreetName, Area, PinCode). As we might have noticed that every Employee has an Address, but the lifetime of the an Address instance is not governed by any Employee instance. It may continue to exist even after the reclaimation of the Employee instance. Right?

Composition - this is also a special type of association used for modelling 'Ownership'. This is very similar to Aggregation with the only difference that it depicts a Whole-part relationship and the 'part' entity doesn't have its own independent existence. Composition indicates that the child objects are conceptually a part of the parent and make no sense on their own For example: Consider two entities Employee (EmpNo, Name, EmailId, Salary, Address) and EmailId (ID, domain). Now an independent instance of EmailId entity doesn't really make sense unless it's associated with an Employee instance.

Composition is normally understood as a "contains-a" relations. Similar to Aggregation, a Composition also forms a Tree only and not a Graph as it can't be cyclic. In UML notation, a Compsoition is depicted by a filled diamond and a solid line.
A restricted aggregation is called composition

Synchronized method and block/statement.


Synchronized method
Sysnchronized methods has two effects, First, When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.


Synchronized Statement
Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock: Most often I use this to synchronize access to a list or map but I don't want to block access to all methods of the object.


Q: Intrinsic Locks and Synchronization
Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.") Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.

Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.


package test;

public class SynchTest implements Runnable{


      private int c = 0;
      /**
       * @param args
       */
      public static void main(String[] args){
            new SynchTest().test();
      }
      public void test() {

            // Create the object with the run() method
            Runnable runnable = new SynchTest();
            Runnable runnable2 = new SynchTest();
            // Create the thread supplying it with the runnable object
            Thread thread = new Thread(runnable,"thread-1");
            Thread thread2 = new Thread(runnable,"thread-2");
//          Here the key point is passing same object, if you pass runnable2 for thread2, then its not
//          applicable for synchronization test and that wont give expected output
//          Synchronization method means "it is not possible for two invocations of synchronized 
//          methods    on the same object to interleave"
            
// Start the thread
            thread.start();
            thread2.start();
      }
     

    public synchronized  void increment() {
      System.out.println("Begin thread "+Thread.currentThread().getName());
        System.out.println(this.hashCode()+"Value of C = "+c);
//        If we uncomment this for synchronized block, then the result would be different
//        synchronized(this){
        for(int i=0;i<9999999;i++){
            c+=i;
//        }
        }
        System.out.println("End thread "+Thread.currentThread().getName());
    }

//    public synchronized void decrement() {
//        System.out.println("Decrement "+Thread.currentThread().getName());
//    }
    public int value() {
        return c;
    }
      @Override
      public void run() {

            this.increment();
      }
}

Cross check  different outputs with synchronized method,block and without synchronization.
Q:How do you do switch with String?
A: public class EnumTest {
public enum Day
{
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
   THURSDAY, FRIDAY, SATURDAY,NOVALUE; 
   public static Day toDay(String str)
   {
       try {
           return valueOf(str);
       } 
       catch (Exception ex) {
           return NOVALUE;
       }
   }
}
public static void main(String[] args) {

new EnumTest().test(Day.SATURDAY);
}
public void test(Day day){
String str=day.toString();
switch (Day.toDay(str))
{
   case SATURDAY:
    System.out.println("SATURDAY");
    break;
   case SUNDAY:
    System.out.println("SUNDAY");
       break;
   case NOVALUE:
    System.out.println("NOVALUE");
       break;
   default:
    System.out.println("default");
}
}
}

Java Client to post XML content to a REST Service


import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.methods.PostMethod;

public class RawTestPOST {


public static void main(String[] args) {


String strURL = "http://lxsrtdev02:8080/GeneratePSIDService/ATSServices";

    PostMethod post = new PostMethod(strURL);
    try {
    InputStream stream = HttpClientTutorial.class.getResourceAsStream("/test.xml");
        String myString = new HttpClientTutorial().getString(stream);
        post.setRequestBody(myString);
        post.setRequestHeader("Content-type",
                "text/xml; charset=ISO-8859-1");
        HttpClient httpclient = new HttpClient();

        int result = httpclient.executeMethod(post);

        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
    }
}
public String getString(InputStream inputStream) throws IOException{

BufferedInputStream bis = new BufferedInputStream(inputStream);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
      byte b = (byte)result;
      buf.write(b);
      result = bis.read();
    }        
    return buf.toString();
}
   }



Solving the "sun.security.validator.ValidatorException: PKIX path building failed" Error



First you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, using openssl to download it, or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)
Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At $JAVA_HOME/jre/lib/security/ for JDKs or $JAVA_HOME/lib/security for JREs, there's a file named cacerts, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:
It will most likely ask you for a password. The default password as shipped with java is "changeit". Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with assurance that you're talking to the right server and only the right server (as long as they don't lose their private key).

First you need to download the certificate.
Open the URL in IE
Click on lock or 'certificate Error'
Click on view Certificate
Select 'Details' tab and click on 'copy to file'
Give a file name n save it

Next  step is you need to add this certificate in keystore
Open a command prompt


Go to C:\Program Files (x86)\Java\jdk1.6.0_27\jre\lib\security
Run keytool -import -alias puslqa -keystore  mycerts -file puslqa.cer
Use password changeit
puslqa.cer will be added to mycerts

In eclipse, you can refer this cert by the below line of codes


System.setProperty("javax.net.ssl.trustStore", "C:/Program Files (x86)/Java/jdk1.6.0_27/jre/lib/security/mycerts");  
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");


function x(String... strings){}

This is the Java way to pass varargs (variable number arguments).


That feature is called varargs, and it's a feature introduced in Java 5. It means that function can receive multiple String arguments:
x("foo", "bar");
x("foo", "bar", "baz");
x(new String[]{"foo", "var", "baz"}); // you can even pass an array
Then, you can use the String var as an array:
function x(String... strings){
    for(String whatever : strings){
        // do what ever you want
    }

    // the code above is is equivalent to
    for( int i = 0; i < strings.length; i++){
        // classical for. In this case you use strings[i]
    }
}


String DATE_FORMAT = "yyyy-MM-dd hh:mm a"; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); System.out.println("Today is " + sdf.format(c1.getTime()));
How do we enable JDK Logging?
Use the below property file


handlers = java.util.logging.FileHandler
com.google.api.client.http.level = ALL

java.util.logging.FileHandler.level = ALL
java.util.logging.FileHandler.pattern = /appdata/opt/JBossAS/jboss-eap-5.1/jboss-as/server/HRBlockDomain/ColsV1log/GoogleHttpClient%u.log
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.append=true
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter



and in the java code Use the below code

final InputStream inputStream = Sample.class.getResourceAsStream("/httplogging.properties");
    try
    {
       LogManager.getLogManager().readConfiguration(inputStream);
       logger.fatal("/httplogging.properties loaded for Google HTTP Client Logging");
    }
    catch (final Exception e)
    {
    logger.fatal("Could not load default logging.properties file");
       logger.fatal(e.getMessage());
    }
Or use the argument like below
-Djava.util.logging.config.file=C:/MyProjects/new-workspace/HRBGoogleMapsAPI-New-V12/resources/httplogging.properties




Difference Java1.4 and JAVA1.5

Generics

List v = new ArrayList();
  v.add("test");
  Integer i = (Integer)v.get(0);        // Run time error

List<String> v = new ArrayList<String>();

  v.add("test");
  Integer i = v.get(0); // (type error)  Compile time error

Auto-boxing/Auto-Unboxing


The idea of auto-boxing and auto-unboxing is to make it easier to convert between primitive data types, like int and boolean, and their equivalent Classes, like Integer and Boolean. It is sometimes frustrating to have to do such a conversion, especially if the purpose of the conversion is just for a method call, after which the results must be converted back to their original form again.


VarArgs


Another new feature is the ability to define methods that accept a variable number of arguments. For example:



public class Java5Test {


/**

* @param args
*/
public static void main(String[] args) {
int aa[] = new int[2];
aa[0]=new Integer(1);
aa[1]=new Integer(2);
// auto boxing
System.out.println(aa[0]+aa[1]);

new Java5Test().print(new String[]{"foo", "var", "baz"});
new Java5Test().print(new String("one"),new String("two"));

}

// VarArgs
void print(String... strings){
   for(String whatever : strings){
       System.out.println(whatever);
   }
}


Difference between String and StringBuffer/StringBuilder in Java

Well, the most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized whereas StringBuilder is not synchronized
StringBuffer came first. Sun was concerned with correctness under all conditions, so they made it synchronized to make it thread-safe just in case.

StringBuilder came later. Most of the uses of StringBuffer were single-thread and unnecessarily paying the cost of the synchronization.

Simply use StringBuilder unless you really are trying to share a buffer between threads.
StringBuilder sb = new StringBuilder("Hello");
sb.append("World");


What is the difference between Set and List?
List
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. 
The user can access elements by their integer index (position in the list), and search for elements in the list.

Set
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
Both interfaces Set and List conform to Java's interface named Collection



What is the difference between Enumeration and Iterator ?
Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.
Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.


When to use LinkedList<> over ArrayList<>?
LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list.
ArrayLists, on the other hand, allow random access, so you 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 you 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.

Write a class in java that translates a number from 0 to 3000 to Roman numerals.
Base characters:
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
Some conversion examples:
I = 1
II = 2
III = 3
IV = 4
V = 5
VI = 6
VII = 7
VIII = 8
IX = 9
X = 10
XX = 20
XXX = 30
XL = 40
L = 50
LX = 60
LXX = 70
LXXX = 80
XC = 90
C = 100
CC = 200
CCC = 300
CD = 400
D = 500
DC = 600
DCC = 700
DCCC = 800
CM = 900
CXCIII = 193
DLXXXVII = 587
MCDXCII = 1492
MMCMLXIV = 2964


package com.tes;

public class MyExpedia {

public static void main(String[] args) {
new MyExpedia().convertToRoman(587);
}
public void convertToRoman(int iInput){
StringBuffer sRoman=new StringBuffer();
getRoman(iInput, sRoman);
System.out.println("The Roman numeral equivalent is: " +  sRoman); //shows numeral to Rom conversion
}
public int getRoman(int iInput,StringBuffer sRoman){
if (iInput >= 1000){
iInput = iInput - 1000;
sRoman.append ("M");
return getRoman(iInput,sRoman);
}
if (iInput >= 900){
iInput = iInput - 900;
sRoman.append ("CM");
return getRoman(iInput,sRoman);
}
if (iInput >= 500){
iInput = iInput - 500;
sRoman .append ("D");
return getRoman(iInput,sRoman);
}
if (iInput >= 400){
iInput = iInput - 400;
sRoman .append ("CD");
return getRoman(iInput,sRoman);
}
if (iInput >= 100){
iInput = iInput - 100;
sRoman .append ("C");
return getRoman(iInput,sRoman);
}
if (iInput >= 90){
iInput = iInput - 90;
sRoman .append ("XC");
return getRoman(iInput,sRoman);
}
if (iInput >= 50){
iInput = iInput - 50;
sRoman .append ("L");
return getRoman(iInput,sRoman);
}
if (iInput >= 40){
iInput = iInput - 40;
sRoman .append ("XL");
return getRoman(iInput,sRoman);
}
if (iInput >= 10){
iInput = iInput - 10;
sRoman .append ("X");
return getRoman(iInput,sRoman);
}
if (iInput >= 9){
iInput = iInput - 9;
sRoman .append ("IX");
return getRoman(iInput,sRoman);
}
if (iInput >= 5){
iInput = iInput - 5;
sRoman .append ("V");
return getRoman(iInput,sRoman);
}
if (iInput >= 4){
iInput = iInput - 4;
sRoman .append ("IV");
return getRoman(iInput,sRoman);
}
if (iInput >= 1){
iInput = iInput - 1;
sRoman .append ("I");
return getRoman(iInput,sRoman);
}
return 0;
}
}


What is the Java volatile keyword?
Essentially, volatile is used to indicate that a variable's value will be modified by different threads.
Declaring a volatile Java variable means:
The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";

Singleton class in java 1.5
Use annotation @Singleton
OR your own class like below
public class Singleton {
  private static Singleton uniqInstance;

  private Singleton() {
  }

  public static synchronized Singleton getInstance() {
    if (uniqInstance == null) {
      uniqInstance = new Singleton();
    }
    return uniqInstance;
  }
  // other useful methods here



Collection
Collection interface which is part of rt.jar in java.util package
Collections is a class inside same package

Collection -the root of the collection hierarchy.
Set -a collection that cannot contain duplicate elements.
List - an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position).
Queue -a collection used to hold multiple elements prior to processing.
Map -an object that maps keys to values.
SortedSet -a Set that maintains its elements in ascending order.
SortedMap -a Map that maintains its mappings in ascending key order. 
Set Sample

public static void main(String[] args) {
           SortedSet<Integer > integers = new TreeSet<Integer>();
//         Sorted set save them in sorted order
           Set<String> strings = new HashSet<String>();
           strings.add(new String("a"));
           strings.add("a");
           strings.add("ab");
           strings.add("ac");
//Prints a ac ab No order No Duplicates
           integers.add(new Integer(1));
           integers.add(new Integer(10));
           integers.add(new Integer(122));
           integers.add(new Integer(13));
           integers.add(new Integer(144));
//         Prints 1 10 13 122 144
List sample
public static void main(String[] args) {
           List<Integer> integers = new ArrayList<Integer>();
           List<String> strings = new ArrayList<String>();
           strings.add("a");
           strings.add("a");
           strings.add("aaa");
//         Prints a a aaa Same order in which they are added. Allows duplicates
            integers.add(new Integer(100));
            integers.add(new Integer(12));
            integers.add(new Integer(130));
            integers.add(new Integer(14));
//         Prints 100 12 130 14 in the same order which they are added
            Collections.reverse(integers); //14 130 12 100
            Collections.sort(integers); // 12 14 100 130
Difference between Set and List
Set
Ordered lists of element (unique or not)
Conform to Java's interface named List
Can be accessed by index
·         LinkedList
·         ArrayList
List
Lists of unique elements:
Conform to Java's interface named Set
Cannot be accessed by index
·         HashSet (unordered)
·         LinkedHashSet (ordered)
·         TreeSet (sorted by natural order or by provided comparator)
Both interfaces Set and List conform to Java's interface named Collection

How to sort a list of Integer objects
Collections.sort(integers);
Integer class implements Comparable interface and it has implementation for compare method so Collections.sort(integers) will sort the objects based on the integer numbers
Java 5 features
Annotation, Generics, Enum, Autoboxing, variable arguments

Lazy instantiation

One of the memory conservation techniques Java programmers find useful is lazy instantiation. With lazy instantiation, a program refrains from creating certain resources until the resource is first needed -- freeing valuable memory space.
Lazy instantiation in Java falls into two categories:
Lazy class loading
Lazy object creation
Lazy class loading
The Java runtime has built-in lazy instantiation for classes. Classes load into memory only when they're first referenced. 

Lazy object creation
The first time you use the 'new' keyword on a class type that previously hasn't been loaded, the Java runtime will load it for you

public final class MyClass
{
// private LoadImage mb_ = new LoadImage(); This will create LoadImage object when the class is loaded
//irrespective of you are going to load image or not
  private LoadImage mb_ ; //null, implicit.. This is called lazy loading..Object will be created only when its really required
  //private helper used by this class
  private void showImage(String message)
  {
    if(mb_==null) { //first call to this method
mb_=new LoadImage();
        mb_.show();
}
  }
}

Is Array List Default Size is Zero or 10?
public static void main(String[] args)
{
System.out.println("Hello World! "+new ArrayList().size()); //Prints 0
}
When you create an array list with the default constructor an array list is created with a capacity of 10..
The capacity is the size of the array used to store the elements in the list.
when you try to use size method of the array list you get the number of elements in the list.
Capacity and the Number of Elements in the list are different


Why initialCapacity of Hashtable is 11 while the DEFAULT_INITIAL_CAPACITY in HashMap is 16 and requires a power of 2?
I will post the answer soon
HashMap
An instance of HashMap has two parameters that affect its performance: initial capacity(16) and load factor(.75). The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets. So (16 X .75 = 12) if the size increase beyond 12, its capasity will be doubled to 32
16,32,64,128..

HashTable
11,23,47,95 (prime numbers)

Increase Console Output in Eclipse
By default, Eclipse limits the amount of text in the console output window. So if you are running a program which produces a lot of output, the Console will only display the last n lines and you lose the rest.

Here is a tip which will allow you to have unlimited output in the console:
Go to Window > Preferences > Run/Debug > Console
Uncheck "Limit Console Output" (Alternatively you can increase the Console buffer size.)





No comments:

Post a Comment