Posts

Showing posts from June, 2012

Thread vs Runnable

Thread is a block of code which can execute concurrently with other threads in the JVM. You can create and run a thread in either ways; Extending  Thread  class, Implementing  Runnable interface. Both approaches do the same job but there have been some differences. Almost everyone have this question in their minds:  which one is best to use?  We will see the answer at the end of this post. The most common difference is When you  extends Thread  class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class). When you  implements Runnable , you can save a space for your class to extend any other class in future or now. When you  extends Thread  class, each of your thread creates unique object and associate with it. When you  implements Runnable , it shares the same object to multiple threads.   1)If you want to extend the Thread class then it will make your class unable to extend other classes as j

Externalizable vs Serializable

Externalizable is an interface that enables you to define custom rules and your own mechanism for serialization. Serializable defines standard protocol and provides out of the box serialization capabilities. Externalizable extends Serializable. Implement writeExternal and readExternal methods of the Externalizable interface and create your own contract / protocol for serialization. Saving the state of the supertypes is responsibility of the implementing class. These two methods readExternal and writeExternal (Externalizable) supersedes this customized implementation of readObject and writeObject. In object de-serialization (reconsturction) the public no-argument constructor is used to reconstruct the object. In case of Serializable, instead of using constructor, the object is re-consturcted using data read from ObjectInputStream. The above point subsequently mandates that the Externalizable object must have a public no-argument constructor. In the case of Seriablizable it is not

Difference between Vector and ArrayList in java:

java.util. Vector came along with the first version of java development kit (JDK). java.util.ArrayList was introduced in java version1.2, as part of java collections framework. As per java API, in Java 2 platform v1.2,vector has been retrofitted to implement List and vector also became a part of java collection framework. All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized. All the new implementations of java collection framework is not synchronized. Vector and ArrayList both uses Array internally as data structure. They are dynamically resizable. Difference is in the way they are internally resized. By default, Vector doubles the size of its array when its size is increased. But, ArrayList increases by half of its size when its size is increased. Therefore as per Java API the only main difference is, Vector’s methods are synchronized and ArrayList’s methods are not synchronized. Vector or ArrayList? Which is better to use in java? In gen

Encapsulation, Information Hiding And Abstraction

Encapsulation means drawing a boundary around something. It means being able to talk about the inside and the outside of it. Object-oriented languages provide a way to do this. Some provide several ways. If you have been sick, you would have had medicines for sure. One of the tablets that you would have received is a capsule. I hope you would have seen it. Now this kind of tablet, is a bit different from the others. From the outside its just a cap, and it hides everything that is contained within. But what lies inside may be 2 or 3 or more powders loosely arranged and packed within. An object is something similar. It is created with the immense power of a class. while the composition of the class could be anything (as compared to the capsule), one may not know wht is contained when you create the object handle as in A obj = new A(); you may say obj here is like the capsule to all those who want to consume it in their programs. So, with this object one can use its inheren

System.out.println

Image
What is System.out.println System .out.println prints the argument passed, into the System.out which is generally stdout. System – is a final class and cannot be instantiated. Therefore all its memebers (fields and methods) will be static and we understand that it is an utility class. As per javadoc, “…Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array …” out – is a static member field of System class and is of type PrintStream . Its access specifiers are public final . This gets instantiated during startup and gets mapped with standard output console of the host. This stream is open by itself immediately after its instantiation and ready to accept data. When running a program from windows command line, it is the standard console. println – println prin

Explanation of Top Ten classes in java

java.lang.String String class will be the undisputed champion on any day by popularity and none will deny that. This is a final class and used to create / operate immutable string literals. It was available from JDK 1.0 java.lang.System Usage of System depends on the type of project you work on. You may not be using it in your project but still it is one of the popular java classes around. This is a utility class and cannot be instantiated. Main uses of this class are access to standard input, output, environment variables, etc. Available since JDK 1.0 java.lang.Exception Throwable is the super class of all Errors and Exceptions. All abnormal conditions that can be handled comes under Exception. NullPointerException is the most popular among all the exceptions. Exception is at top of hierarchy of all such exceptions. Available since JDK 1.0 java.util.ArrayList An implementation of array data structure. This class implements List interface and is the most popular member or java

Difference of String, StringBuffer and StringBuilder.

String is immutable whereas StringBuffer and StringBuilder can change their values. The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer. Criteria to choose among String, StringBuffer and StringBuilder If your text is not going to change use a string Class because a String object is immutable. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous. StringBuilder was introduced in Java 1.5 (so if you happen to use versions 1.4 or below you’ll have to use StringBuffer) 

Dead lock

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Here's an example. Alphonse and Gaston are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time. public class Deadlock {     static class Friend {         private final String name;         public Friend(String name) {             this.name = name;         }         public String getName() {             return this.name;         }         public synchronized void bow(Friend bower) {             System.out.format("%s: %s"                 + "  has bowed to me!%n",                 this.name, bower.getName());             bower.bowBack(this);         }         public synchronized void bowBack(Friend bower) {  

Core Java -----Question and Answers

Q1. What is the output for the below code ? public class Test{     int _$;     int $7;     int do; public static void main(String argv[]){       Test test = new Test(); test.$7=7; test.do=9;    System.out.println(test.$7); System.out.println(test.do); System.out.println(test._$);    } } 1 7 9 0 2 7 0 0 3 Compile error - $7 is not valid identifier. 4 Compile error - do is not valid identifier. You have choosen : 4 Correct Answer is : 4 You were correct. Explanations : $7 is valid identifier. Identifiers must start with a letter, a currency character ($), or underscore ( _ ). Identifiers cannot start with a number. You can't use a Java keyword as an identifier. do is a Java keyword. Q2. What is the output for the below code ? public class B {       public static synchronized void printName(){         try{              System.out.println("printName");                 Thread.sleep(5*1000);                        }catch(InterruptedException e

SCJP1.6 Question and Answers

Question – 1 What is the output for the below code ? 1.         public class A { 2.         int add(int i, int j){ 3.                     return i+j; 4.                     } 5.         } 6.         public class B extends A{ 7.         public static void main(String argv[]){ 8.         short s = 9; 9.         System.out.println(add(s,6)); 10.        } 11.        } Options are A. Compile fail due to error on line no 2 B. Compile fail due to error on line no 9 C. Compile fail due to error on line no 8 D. 15 Answer : B is the correct answer. Cannot make a static reference to the non-static method add(int, int) from the type A. The short s is autoboxed correctly, but the add() method cannot be invoked from a static method because add() method is not static. Question – 2 What is the output for the below code ? public class A { int k; boolean istrue; static int p; public void printValue() { System.out.print(k); System.out.print(istrue); System.out.print(p); }