Sei sulla pagina 1di 46

Java Annotations 03/06/2012 Annotation is code about the code, that is metadata about the program itself.

In other words, organized data about the code, embedded within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too. We have basic java comments infrastructure using which we add information about the code / logic so that in future, another programmer or the same programmer ca n understand the code in a better way. Javadoc is an additional step over it, wh ere we add information about the class, methods, variables in the source code. T he way we need to add is organized using a syntax. Therefore, we can use a tool and parse those comments and prepare a javadoc document which can be distributed separately. Javadoc facility gives option for understanding the code in an external way, ins tead of opening the code the javadoc document can be used separately. IDE benefi ts using this javadoc as it is able to render information about the code as we d evelop. Annotations were introduced in JDK 1.5 Uses of Annotations Annotations are far more powerful than java comments and javadoc comments. One m ain difference with annotation is it can be carried over to runtime and the othe r two stops with compilation level. Annotations are not only comments, it brings in new possibilities in terms of automated processing. In java we have been passing information to compiler for long. For example take serialization, we have the keyword transient to tell that this field is not seri alizable. Now instead of having such keywords decorating an attribute annotation s provide a generic way of adding information to class/method/field/variable. Th is is information is meant for programmers, automated tools, java compiler and r untime. Transient is a modifier and annotations are also a kind of modifiers. More than passing information, we can generate code using these annotations. Tak e webservices where we need to adhere by the service interface contract. The ske leton can be generated using annotations automatically by a annotation parser. T his avoids human errors and decreases development time as always with automation . Frameworks like Hibernate, Spring, Axis make heavy use of annotations. When a la nguage needs to be made popular one of the best thing to do is support developme nt of frameworks based on the language. Annotation is a good step towards that a nd will help grow Java. When Not to Use Annotations Do not over use annotation as it will pollute the code. It is better not to try to change the behaviour of objects using annotations. Th ere is sufficient constructs available in oops and annotation is not a better me chanism to deal with it. We should not what we are parsing. Do not try to over generalize as it may compl icate the underlying code. Code is the real program and annotation is meta. Avoid using annotation to specify environment / application / database related i nformation. Annotation Structure There are two main components in annotations. First is annotation type and the n ext is the annotation itself which we use in the code to add meaning. Every anno tation belongs to a annotation type. Annotation Type: @interface <annotation-type-name> { method declaration; } Annotation type is very similar to an interface with little difference. We attach @ just before interface keyword. Methods will not have parameters. Methods will not have throws clause.

Method return types are restricted to primitives, String, Class, enums, annotati ons, and arrays of the preceding types. We can assign a default value to method. Meta Annotations Annotations itself is meta information then what is meta annotations? As you hav e rightly guessed, it is information about annotation. When we annotate a annota tion type then it is called meta annotation. For example, we say that this annot ation can be used only for methods. @Target(ElementType.METHOD) public @interface MethodInfo { } Annotation Types 1. Documented When a annotation type is annotated with @Documented then wherever this annotati on is used those elements should be documented using Javadoc tool. 2. Inherited This meta annotation denotes that the annotation type can be inherited from supe r class. When a class is annotated with annotation of type that is annotated wit h Inherited, then its super class will be queried till a matching annotation is found. 3. Retention This meta annotation denotes the level till which this annotation will be carrie d. When an annotation type is annotated with meta annotation Retention, Retentio nPolicy has three possible values: @Retention(RetentionPolicy.RUNTIME) public @interface Developer { String value(); } o Class When the annotation value is given as class then this annotation will be compiled and included in the class file. o Runtime The value name itself says, when the retention value is Runtime this annotation wi ll be available in JVM at runtime. We can write custom code using reflection pac kage and parse the annotation. I have give an example below. o Source This annotation will be removed at compile time and will not be available at com piled class. 4. Target This meta annotation says that this annotation type is applicable for only the e lement (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, F IELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE. @Target(ElementType.FIELD) public @interface FieldInfo { } Built-in Java Annotations @Documented, @Inherited, @Retention and @Target are the four available meta anno tations that are built-in with Java. Apart from these meta annotations we have the following annotations. @Override When we want to override a method, we can use this annotation to say to the comp iler we are overriding an existing method. If the compiler finds that there is n o matching method found in super class then generates a warning. This is not man datory to use @Override when we override a method. But I have seen Eclipse IDE a utomatically adding this @Override annotation. Though it is not mandatory, it is considered as a best practice. @Deprecated When we want to inform the compiler that a method is deprecated we can use this. So, when a method is annotated with @Deprecated and that method is found used i n some place, then the compiler generates a warning. @SuppressWarnings This is like saying, I know what I am doing, so please shut up! We want the compil

er not to raise any warnings and then we use this annotation. Custom Annotations We can create our own annotations and use it. We need to declare a annotation ty pe and then use the respective annotation is java classes. Following is an example of custom annotation, where this annotation can be used on any element by giving values. Note that I have used @Documented meta-annotati on here to say that this annotation should be parsed by javadoc. /* * Describes the team which wrote the code */ @Documented public @interface Team { int teamId(); String teamName(); String teamLead() default "[unassigned]"; String writeDate(); default "[unimplemented]"; } Annotation for the Above Example Type ... a java class ... @Team( teamId = 73, teamName = "Rambo Mambo", teamLead = "Yo Man", writeDate = "3/1/2012" ) public static void readCSV(File inputFile) { ... } ... java class continues ... Marker Annotations We know what a marker interface is. Marker annotations are similar to marker int erfaces, yes they dont have methods / elements. /** * Code annotated by this team is supreme and need * not be unit tested - just for fun! */ public @interface SuperTeam { } ... a java class ... @SuperTeam public static void readCSV(File inputFile) { ... } ... java class continues ... In the above see how this annotation is used. It will look like one of the modif iers for this method and also note that the parenthesis {} from annotation type is omitted. As there are no elements for this annotation, the parenthesis can be optionally omitted. Single Value Annotations There is a chance that an annotation can have only one element. In such a case t hat element should be named value. /** * Developer */ public @interface Developer { String value(); } ... a java class ... @Developer("Popeye") public static void readCSV(File inputFile) { ... } ... java class continues ... How to Parse Annotation We can use reflection package to read annotations. It is useful when we develop tools to automate a certain process based on annotation. Example: package com.javapapers.annotations;

import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Developer { String value(); } package com.javapapers.annotations; public class BuildHouse { @Developer ("Alice") public void aliceMethod() { System.out.println("This method is written by Alice"); } @Developer ("Popeye") public void buildHouse() { System.out.println("This method is written by Popeye"); } } package com.javapapers.annotations; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class TestAnnotation { public static void main(String args[]) throws SecurityException, ClassNotFoundException { for (Method method : Class.forName( "com.javapapers.annotations.BuildHouse").getMethods()) { // checks if there is annotation present of the given type Developer if (method .isAnnotationPresent(com.javapapers.annotations.Developer.class)) { try { // iterates all the annotations available in the method for (Annotation anno : method.getDeclaredAnnotations()) { System.out.println("Annotation in Method " + method + " : " + anno); Developer a = method.getAnnotation(Developer.class); if ("Popeye".equals(a.value())) { System.out.println("Popeye the sailor man! " + method); } } } catch (Throwable ex) { ex.printStackTrace(); } } } } } Output: Annotation in Method public void com.javapapers.annotations.BuildHouse.aliceMet hod() : @com.javapapers.annotations.Developer(value=Alice) Annotation in Method public void com.javapapers.annotations.BuildHouse.buildHou se() : @com.javapapers.annotations.Developer(value=Popeye) Popeye the sailor man! public void com.javapapers.annotations.BuildHouse.buildHo use() apt / javac for Annotation Processing In previous version of JDK apt was introduced as a tool for annotation processin g. Later apt was deprecated and the capabilities are included in javac compiler. javax.annotation.processing and javax.lang.model contains the api for processin g. Java Marker Interface 29/05/2008

Marker interface is used as a tag to inform a message to the java compiler so th at it can add special behaviour to the class implementing it. Java marker interf ace has no members in it. Lets take the java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the ja va compiler in some way that there is a possibility of serializing this java cla ss. In this scenario, marker interfaces are used. The java class which may be se rialized has to implement the java.io.Serializable marker interface. In such way , we are intimating the java compiler. From java 1.5, the need for marker interface is eliminated by the introduction o f the java annotation feature. So, it is wise to use java annotations than the m arker interface. It has more feature and advantages than the java marker interfa ce. Is Runnable a marker interface? First point, there is no reference or definition about marker interface from Jav a specification/api. This is yet another inconclusive debate. Marker Interface is a term coined by (book / web) authors. Since we dont have Javas definition it is l eft to us to arrive at a decent definition. This is one popular question asked i n java interview. My answer to the interviewer, there are better questions ask t han this to ask. Runnable is not a marker interface, you might say run is used to start a method and this is a special instruction to the JVM. When you run a java class the java in terpreter calls the main method, because of this would you say every java class as marker class? My definition for marker interface An interface is called a marker interface when it is provided as a handle by java interpreter to mark a class so that it can provide special behaviour to it at r untime and they do not have any method declarations. In the above definition and they do not have any method declarations is added beca use, till now all the marker interfaces provided by java do not have method decl arations. I dont think, in future there will be any new marker interfaces added :-) We cannot create marker interfaces, as you cannot instruct JVM to add special be havior to all classes implementing (directly) that special interface. Java Marker Interface Examples java.lang.Cloneable java.io.Serializable java.util.EventListener Difference Between Interface and Abstract Class 23/04/2008 1. Main difference is methods of a Java interface are implicitly abstract a nd cannot have implementations. A Java abstract class can have instance methods that implements a default behavior. 2. Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. 3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.. 4. Java interface should be implemented using keyword implements; A Java abst ract class should be extended using keyword extends. 5. An interface can extend another Java interface only, an abstract class c an extend another Java class and implement multiple Java interfaces. 6. A Java class can implement multiple interfaces but it can extend only on e abstract class. 7. Interface is absolutely abstract and cannot be instantiated; A Java abst ract class also cannot be instantiated, but can be invoked if a main() exists. 8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection. When can an object reference be cast to a Java interface reference?

23/04/2008 When a Java object implements the referenced interface it can be cast to the Jav a interface reference. An interface reference can point to any object of a class that implements this i nterface i.e. see the example below: interface Foo{ void display(); } public class TestFoo implements Foo{ void display(){ System.out.println(Hello World); } public static void main(String[] args){ Foo foo = new TestFoo(); foo.display(); } } Java interface 23/04/2008 A java class containing all the methods as abstract is called an interface. A me thod that has no implementation and which is expected to be implemented by a sub class is called an abstract method. Java interface can contain constants. When a n interface needs to be instantiated it should be implemented by a class and all its abstract methods should be defined. If all the methods are not implemented in the class then it becomes a java abstract class and so cannot be instantiated . Variables declared in a java interface by default is final. interface I1 { void show(); void display(); } class A implements I1 { public void show(){System.out.println(Hi);} public void display(){System.out.println(Friend);} } public static void main(String [] args){ A o=new A(); o.show();o.display(); } } Probleam: Multiple inheritence concept ignore this case.why interface used? Bcoz declare two methods declare in interface and a class define those methods.if th is class remove line Implements I1 then also class just same work .Then this cas e what benefits of used interface???? How can you invoke a defined method of an abstract class? 14/04/2008 An abstract class cannot be instantiated directly. An abstract class has to be s ub-classed first and then instantiated. Only then the method defined in the abst ract class can be invoked. What is an abstract class? 14/04/2008 A class containing atleast one abstract method is called an abstract class. A me thod that has no implementation and which is expected to be implemented by a sub class is called an abstract method. An Abstract class cannot be instantiated. It is expected to be extended by a subclass. An abstract class may contain static variables declared. Any class with an abstract method must be declared explicitl y as abstract. A class may be declared abstract even if it has no abstract metho

ds. This prevents it from being instantiated. The abstract class may or may not have the abstract method. But if you have any abstract method then the class should be Abstract. An abstract class is simple a class which cant be instantiated. An abstract method defined within an abstract class must be implemented by all o f its subclass. Abstract method cannot be instantiated,it is generally used for inherited. What is an Abstract Class Complete reference Posted by Yash on August 10, 2011Leave a comment (1)Go to comments A class that has to contain atleast one abstract method is declared an abstract class. A method that has no implementation and which is expected to be implemented by a subclass is called an abstract method. An Abstract class cannot be instantiated. It is expected to be extended by a subclass. An abstract class may contain static variables declared. Any class with an abstract method must be declared explicitly as abstract. A class may be declared abstract even if it has no abstract methods. This preven ts it from being instantiated. ? 1 2 3 4 5 6 7 8 public abstract class Drawing { abstract void draw(); // declare fields // declare non-abstract methods } Abstract Class FAQ Q: Must a superclass be abstract or concrete? A: A superclass may be abstract or concrete, provided the concrete class is not declared final. In both cases, you can add supplementary methods to those inheri ted from the superclass. To extend abstract classes you must fulfil any abstract methods that are declared by the superclass. Q: Must abstract classes contain at least one abstract method? A: No, abstract classes are not required to have any abstract methods, they can simply be marked abstract for general design reasons. An abstract class may cont ain a full set of functional, integrated methods but have no practical use in it s basic form, for example. In other words, they may require extension with addit ional methods to fulfil a range of different purposes. If the purpose is not spe cified by abstract method signatures, the range of potential applications for su bclasses can be very broad. Something like this compiles absolutely fine. ? 1 2 3 4 5 public abstract class MyAbstractClass { // Empty } Q: How can an abstract method be inherited?

A: A subclass inherits all non-private fields and methods of its superclass whet her the methods are abstract or have concrete implementations. If a subclass doe s not implement an abstract method, the subclass must be declared abstract itsel f. That means that an abstract method can be inherited through numerous abstract classes without any concrete implementation. Q: Do I have to implement all abstract methods? A: Yes, it is possible to extend an abstract class without implementing its abst ract methods, but in this case the subclass must also be declared abstract. If t he subclass is not declared abstract, the compiler will throw an error. So ultim ately it is necessary for any concrete subclass to implement the abstract method s. Q: Can a static method be abstract? A: The abstract keyword cannot be applied to static method declarations. The com piler will reject the class with the error illegal combination of modifiers. Howev er, an abstract class can have static variables and methods, which can be access ed directly using the standard dot notation, e.g. AbstractExample.staticMethod() . It follows that static methods must be concrete. Q: Why cant abstract methods be declared static? A: The rule against static abstract methods is fundamentally a Java language des ign decision, which is not explained in the Java Language Specification. The abs tract inheritance and implementation scheme is concerned with forming a structur ed collaboration of classes with deferred implementation of its abstract instanc e methods. This scheme can be verified at compile time to ensure it is safe at r untime. Static methods must be concrete because they are attached to a specific host cla ss and must be available to execute in a static context, when no object instance exists. It is not possible to assign an implementation to a static method at ru ntime, there is no mechanism to do that in Java. It is also worth noting that static methods cannot be overridden by a subclass i n Java. Static methods with the same signature effectively hide the superclass m ethod. The concept of implementing a static method in a subclass would fail for the same reason. Q: Why cant an abstract method be declared private? A: The private and abstract method modifiers do not make sense in combination an d the compiler should normally fail with a warning in this case. An abstract met hod must be overridden by any subclass, but subclasses do not have access to the ir superclass private fields, so a private abstract method could never be fulfill ed. Q: We can have private abstract methods in some cases, cant we? A: If you attempt to compile a class with a private abstract method it will fail with the message illegal combination of modifiers: abstract and private. An abstr act method must be declared with implicit package visibility or with the protect ed or public keywords. The fundamental principle is that an abstract method must be visible to any potential subclass. If an abstract method was private it woul d not be visible to any subclass and could not be implemented. The concrete implementation of the abstract method in a subclasses must have the same level of visibility or greater. If an abstract method has package visibili ty, its subclass implementations must have the same, protected or public visibil ity. If an abstract method has protected visibility, concrete implementations mu st have the same or public visibility. If an abstract method has public visibili ty the concrete versions must also be public. Q: Can I call a static method on an abstract class? A: In Java it is possible to execute the static methods of abstract classes, sin ce an object instance is not required in this context.Since abstract classes can not be instantiated in their own right, no instance methods can be called except through their subclasses. Q: Can I declare a constructor for an abstract class? A: This may sound odd, but an abstract class may have constructors, but they can not be used to instantiate the abstract class. If you write statements to call t he constructor the compiler will fail and report the class is abstract; cannot be

instantiated.Constructors in abstract classes are designed only to be used by th eir subclasses using a super() call in their own constructors. Though the abstra ct class cannot stand as an instance in its own right, when its abstract methods are fulfilled by a subclass, its constructors can be called upon to deliver sto ck template-like initialisation behaviour, for example. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 public abstract class AbstractConstructor { public AbstractConstructor() { // Statements } public AbstractConstructor(final int size) { // Statements } public static void main(String[] args) { // Not permitted // AbstractConstructor instance1 = new AbstractConstructor(); // Not permitted either // AbstractConstructor instance2 = new AbstractConstructor(4); } } public class ConcreteSubclass extends AbstractConstructor { private static final int INDEX = 4; public ConcreteSubclass() {

super(INDEX); } } What is an abstract method ? Posted by Yash on August 10, 2011Leave a comment (6)Go to comments A method without any implementation is called an Abstract method. Its subclass i s expected to implement this method. ? 1 2 3 4 5 6 7 8 public abstract class Drawing { abstract void draw(); /* Abstract Method */ // declare fields // declare non-abstract methods } How can you invoke a defined method of an abstract class? Posted by Yash on August 10, 2011Leave a comment (0)Go to comments An abstract class cannot be instantiated directly. An abstract class has to be s ub-classed first and then instantiated. Only then the method defined in the abst ract class can be invoked. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public abstract class MyAbstractClass { public abstract void myAbstractMethod() ; public static void main(String[] args) { // Not permitted // MyAbstractClass instance1 = new MyAbstractClass (); }

} public class ConcreteSubclass extends MyAbstractClass { public void myAbstractMethod() { System.out.println("Called from concrete class"); } public static void main(String[] args) { ConcreteSubclass instance1 = new ConcreteSubclass (); instance1.myAbstractMethod(); } } Difference between equals() and == operator Posted by Santanu on August 16, 2011Leave a comment (0)Go to comments Both equals and == operators are used to compare two string objects.The main dif ference between the two comparison technique is equals() compares the content of the two string objects while == compares the two references to which they are r eferring to.If both the references are referring to same string objects then == comparison satisfies.== condition checking doesnt satisfies if two different stri ng objects having same content are referred by two different references. == comp ares the address of the objects while equals() compares the content of the objec ts.see the difference between the two string comparison technique in the followi ng code snippet. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 String s1 = new String(Comparison); String s2 = new String(Comparison); if (s1 == s2) { System.out.println(Both references are referring to same object); } if(s1.equals(s2)) { System.out.println(Both strings have same content); } Out put: Both strings have same content Explanation: Though both the references are referring to same string but the objects for both the strings are different.Hence the two references s1 and s2 refers to two diff erent string object whose contents are same. But equals() method compares the contents of the objects which are referenced by the reference s1 and s2.

When both the references refer to the same object then == condition satisfies. e.g ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 String s1 = new String(Comparison); String s2 = s1;//Assigning s1 reference to s2 i,e both the reference s1 and s2 r efer to same string object. if (s1 == s2) { System.out.println(Both references are referring to same object); } if(s1.equals(s2)) { System.out.println(Both strings have same content); } o/p Both references are referring to same object Both strings have same content Explanation: As both the references now refer to same object == condition satisfies here. Object Oriented Programming(OOPS) Concepts Posted by Dev on August 8, 2011Leave a comment (0)Go to comments Q1) What is polymorphism? Ans) Polymorphism gives us the ultimate flexibility in extensibility. The abilti y to define more than one function with the same name is called Polymorphism. In java,c++ there are two type of polymorphism: compile time polymorphism (overloa ding) and runtime polymorphism (overriding). When you override methods, JVM determines the proper methods to call at the prog rams run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class. Overloading occurs when several methods have same names with Overloading is determined at the compile time. Different method signature and different number or type of parameters. Same method signature but different number of parameters. Same method signature and same number of parameters but of different type ? 1 2 3 4 5 6 7

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 Example of Overloading int add(int a,int b) float add(float a,int b) float add(int a ,float b) void add(float a) int add(int a) void add(int a) //error conflict with the method int add(int a) Example: Overloading Class BookDetails{ String title; String publisher; float price; setBook(String title){ } setBook(String title, String publisher){ } setBook(String title, String publisher,float price){ } } Example: Overriding class BookDetails{ String title; setBook(String title){ }

} class ScienceBook extends BookDetails{ setBook(String title){} //overriding setBook(String title, String publisher,float price){ } //overloading } Q2) What is inheritance? Ans) Inheritance is the property which allows a Child class to inherit some prop erties from its parent class. In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in ch ild class. In above example the child has inherit its family name from the parent class jus t by inheriting the class. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class Parent{ public String parentName; public int parentage; public String familyName; } public class Child extends Parent{ public String childName; public int childAge; public void printMyName(){ System.out.println( My name is + chidName+ +familyName) } } Q3) What is multiple inheritance and does java support? Ans) If a child class inherits the property from multiple classes is known as mu ltiple inheritance. Java does not allow to extend multiple classes but to overcome this problem it a llows to implement multiple Interfaces. Q4) What is abstraction? Ans) Abstraction is way of converting real world objects in terms of class. For example creating a class Vehicle and injecting properties into it. E.g ? 1 2

3 4 5

public class Vehicle {

public String colour; public String model; } Q5) What is encapsulation? Ans) The encapsulation is achieved by combining the methods and attribute into a class. The class acts like a container encapsulating the properties. The users are exposed mainly public methods.The idea behind is to hide how thinigs work an d just exposing the requests a user can do. Q6) What is Association? Ans) Association is a relationship between two classes. In this relationship the object of one instance perform an action on behalf of the other class. The typi cal behaviour can be invoking the method of other class and using the member of the other class. ? 1 2 3 4 5 public class MyMainClass{ public void init(){ new OtherClass.init(); } } Q7) What is Aggregation? Ans) Aggregation has a relationship between two classes. In this relationship th e object of one class is a member of the other class. Aggregation always insists for a direction. ? 1 2 3 public class MyMainClass{ OtherClass otherClassObj = new OtherClass(); } Q8) What is Composition? Ans) Composition is a special type of aggregation relationship with a difference that its the compulsion for the OtherClass object (in previous example) to exis t for the existence of MyMainClass. Java Interview Questions Part 1 Posted by Yash on August 17, 2011Leave a comment (0)Go to comments Q: What are the difference between an Interface and an Abstract class ? Q: What is garbage collection in Java, and when is it used ? Q: Explain Synchronization and Multithreading. Q: What are the different methods of creating Threads ? Q: Differences between pass by reference and pass by value ? Q: Differences between HashMap and Map ? Q: Differences between HashMap and HashTable ? Q: Differences between Vector and ArrayList ? Q: Differences between Awt and Swing ? Q: What is the difference between a constructor and a method ? Q: What is an Iterator ? Q: Explain public, private, protected, default modifiers. Q: What is an abstract class ? Q: What is static in java ? Q: What is final ? Q: What are the difference between an Interface and an Abstract class ? A: An abstract class can contain both abstract instance methods as well as that

implement a default behavior. An Interface can only declare constants and insta nce methods, but cannot implement any default behavior and all methods are impli citly abstract. All interface methods are public and abstract by default and hav e no implementation. An abstract class is a class which may have the usual flavo rs of class members (private, protected, etc.), and can also have some abstract methods. Q: What is 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 reus ed. A Java object is subject to garbage collection when it becomes unreachable t o the program in which it is used, in other words, when there are no references attached to that object. Q: Explain Synchronization and Multithreading. A: Multithreading is the mechanism to achieve a parallelism in program where dif ferent independent codes can run parallely as seperate threads. 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 variab le while another thread is in the process of using or updating same shared varia ble. This usually leads to significant errors. Thus synchronization enables a ma naged access to the shared resources. Q: What are the different methods of creating Threads ? A: A thread can be implemented by 2 mechanisms. By First method implementing the runnable interface or by Second method by extending from the Thread class. The first method is more advantageous, cause when you are going for multiple inheri tance, you wont be able to extend multiple classes, so implementing runnable int erface would be helpful. Q: Differences between pass by reference and pass by value ? A: Pass By Reference means the passing the address itself rather than passing th e value. Passby Value means passing a copy of the value to be passed. Java is st rictly Pass by Value. Q: Differences between HashMap and Map ? A: Map is Interface and Hashmap is class that implements Map. Q: Differences between HashMap and HashTable ? A: The HashMap class is roughly equivalent to Hashtable, except that it is unsyn chronized and permits null values. HashMap allows null values as key and value w hereas Hashtable doesnt allow. HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is s ynchronized. Q: Differences between Vector and ArrayList ? A: Vector is synchronized whereas arraylist is not. Q: Differences between Awt and Swing ? A: AWT are heavy-weight componenets. Swings are light-weight components. Hence s wing works faster than AWT. Hence, Swing are more preferred than AWT. Q: What is the difference between a constructor and a method ? A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a retur n type (which can be void), and is invoked using the dot operator. Q: What is an Iterator ? A: Instead of traditional loop traversal for lists, some collection classes prov ide traversal of their contents via a java.util.Iterator interface. This interfa ce allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators, generally it is not advisable to modify the collection itself while traversing an Iterator. Q: Explain public, private, protected, default modifiers. A: public : Public class is visible in other packages, methods or field is visib le everywhere (class must be public too) private : Private variables or methods may be used only by an instance of the sa

me class that declares the variable or method, A private feature may only be acc essed by the class that owns the feature. protected : Is available to all classes in the same package and also available t o all subclasses of the class that owns the protected feature.This access is pro vided even to subclasses that reside in a different package from the class that owns the protected feature. default :What you get by default ie, without any access modifier (ie, public pri vate or protected).It means that it is visible to all within a particular packag e. Q: What is an abstract class ? A: Abstract class is a template that must be extended/subclassed (to be useful). A class that is abstract may not be instantiated (ie, you may not call its cons tructor, but can contain constructor), abstract class may contain static data. A ny class with an abstract method is automatically abstract itself, and must be d eclared as such. A class may be declared abstract even if it has no abstract methods. This preven ts it from being instantiated. Q: What is static in java ? A: Static means one per class, not one for each object no matter how many instan ce 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 d one 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 stati c method in a subclass, as long as the original method was not declared final. H owever, you cant override a static method with a nonstatic method. In other words , you cant change a static method into an instance method in a subclass. Q: What is final ? A: A final class cant be extended ie., final class may not be subclassed. A final method cant be overridden when its class is inherited. You cant change value of a final variable (is a constant). Java Interview Questions Part 2 Posted by Yash on August 18, 2011Leave a comment (0)Go to comments Q: Can main method be declared as private ? Q: What if the static modifier is removed from the main method signature ? Q: What if I write static public void main, instead of public static void main ? Q: What if I do not provide the String array as the argument to the method ? Q: What is the first argument of the String array in main method ? Is it the nam e of the program itself (as in C/C++) ? Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null ? Q: How can we check that the argument array is not null but empty ? Q: Error: command java not recognized as internal or external command. What envi ronment variables do I need to set on my machine in order to be able to run Java programs ? Q: Can an application have more than one classes having main method ? Q: Can I have multiple main methods in the same class ? Q: Do I need to import java.lang package any time ? Why ? Q: Can I import same package/class twice ? Will the JVM load the package twice a t runtime ? Q: What are Checked and UnChecked Exception ? Q: What is Overriding ? Q: What are different types of inner classes ? Q: Can main method be declared as private ? A: The program compiles properly with private main method, but at runtime it wil l give Main method not public. message. Because the JVM internally tries to call t he main method, and only the public methods are visible to the JVM, not private ones. Q: What if the static modifier is removed from the main method signature ? A: The program compiles fine. But at runtime throws an error NoSuchMethodError. Q: What if I write static public void main, instead of public static void main ?

A: Program compiles and runs properly. The order of specifiers doesnt make differ ence. (Infact the only thing that matters is the return type must be just before the method name.) Q: What if I do not provide the String array as the argument to the method ? A: Program compiles but throws a runtime error NoSuchMethodError. The JVM looks fo r a main method with a String[] parameter, which its unable to find. Q: What is the first argument of the String array in main method ? Is it the nam e of the program itself (as in C/C++) ? A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null ? A: It is empty. But NOT null. Q: How can we check that the argument array is not null but empty ? A: ArrayName.length returns the size of any array(assuming the name of array her e is ArrayName), in this case Print args.length inside your main method. It will p rint 0, which means a zero sized array. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length. Q: Error: command java not recognized as internal or external command. What envi ronment variables do I need to set on my machine in order to be able to run Java programs ? A: Sometimes you may end up with an error like command java not recognized as int ernal or external command. This is because of not setting the CLASSPATH and PATH for the java libraries. These paths can be set from My computer > rt. click on m y computer > properties > Advanced tab > Environment Properties button. Here you can edit the CLASSPATH/PATH values by appending the JVM bin folders path. Q: Can an application have more than one classes having main method ? A: Yes it is possible to have more than one classes in your applications each ha ving its own main method. While starting the application we mention the class na me to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes ha ving main method. 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 al ready defined in the class. Q: Do I need to import java.lang package any time ? Why ? A: No. java.lang package is by default loaded by the JVM internally. Q: Can I import same package/class twice ? Will the JVM load the package twice a t runtime ? A: One can import the same package or same class multiple times. Neither compile r nor JVM complains about it. And the JVM internally loads the class only once n o matter how many times the same class is imported by you. Q: What are Checked and UnChecked Exception ? A: A Checked Exception is some subclass of Exception (orthe Exception class itse lf), excluding class RuntimeException and its subclasses. Making an exception checked forces the programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputSt reams read() method. Unchecked Exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, th e compiler doesnt force client programmers either to catch the exception or decla re it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by Strings charAt() method or a NullPointerException or ArithmeticException etc etc. Checked exceptions must be caught at compile time. Runtime exceptions do not nee d to be. 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. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private. i.e a private met hod in superclass can be overidden by a public method in subclass, but not vice versa. Q: What are different types of inner classes ? A: There are 4 kinds of inner classes : Nested top-level classes, Member classes , Local classes, Anonymous classes. Nested top-level classes - If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level cl ass. Any class outside the declaring class accesses the nested class with the declari ng class name acting similarly to a package. eg, outer.inner. Top-level inner cl asses implicitly have access only to static variables.There can also be inner in terfaces. All of these are of the nested top-level variety. Member classes Member inner classes are just like other member methods and membe r variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level class es is that member classes have access to the specific instance of the enclosing class. Local classes Local classes are like local variables, specific to a block of cod e. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members, the modifiers public, protected, private, and static are not usable. Anonymous classes Anonymous inner classes extend local inner classes one level f urther. As anonymous classes have no name, you cannot provide a constructor. Java Interview Questions Part 3 Posted by Yash on August 18, 2011Leave a comment (0)Go to comments Q: Are the imports checked for validity at compile time? e.g. will the code cont aining an invalid import such as java.lang.XYZ compile ? Q: Does importing a package imports the subpackages as well ? e.g. Does importin g com.java.MyPackage.* also import com.java.MyPackage.MyInnerPackage.*? Q: What is the difference between declaring a variable and defining a variable ? i.e difference between declaration and definition ? Q: What is the default value of an object reference declared as an instance vari able ? What are the default values of primitives like int, float, char datatypes ? Q: Can a top level class be private or protected ? Q: What type of parameter passing does Java support ? Is java Pass by Value or P ass by Reference ? Q: Primitive data types are passed by reference or pass by value ? Q: Objects are passed by value or by reference ? Q: What is serialization ? Q: How do I serialize an object to a file ? Q: Which methods of Serializable interface should be implemented ? Q: How can we customize the seralization process ? i.e. how can we have a contro l over the serialization process ? Q: What is the common usage of serialization ? Where is serialization most frequ ently required ? Q: What is Externalizable interface ? Q: When you serialize an object, what happens to the object references included in the object ? Q: What one should take care of while serializing the object ? Q: What happens to the static fields of a class during serialization ? Q: Are the imports checked for validity at compile time? e.g. will the code cont aining an invalid import such as java.lang.XYZ compile ? A: Yes the imports are checked for the semantic validity at compile time. The co

de containing above line of import will not compile. It will throw an error sayi ng: Cannot resolve symbol symbol : class XYZ location: package lang import java.lang.XYZ; Q: Does importing a package imports the subpackages as well ? e.g. Does importin g com.java.MyPackage.* also import com.java.MyPackage.MyInnerPackage.*? A: No you will have to import the subpackages explicitly. Importing com.MyPackag e.* will import classes in the package MyPackage only. It will not import any cl ass in any of its subpackage MyInnerPackage. Q: What is the difference between declaring a variable and defining a variable ? i.e difference between declaration and definition ? A: In declaration we just mention the type of the variable and its name. It is no t initialized by us. But defining means declaration + initialization. e.g String name; is just a declaration while String name = new String (Bond); Or S tring s = Bond; are both definitions. Q: What is the default value of an object reference declared as an instance vari able ? What are the default values of primitives like int, float, char datatypes ? A: Java object has a default value of null unless we define it explicitly. The tab le gives the default values for various datatypes. : Data Type Default Value (for fields) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char \u0000 String (or any object) null boolean false Q: Can a top level class be private or protected ? A: No. A top level class can not be private or protected. It can have either publ ic or no modifier(i.e. default modifier). If it does not have a modifier it is su pposed to have a default access.If a top level class is declared as private the compiler will complain that the modifier private is not allowed here. This means t hat a top level class can not be private. Same is the case with protected. Q: What type of parameter passing does Java support ? Is java Pass by Value or Pass by Reference ? A: In Java the arguments are always passed by value. Q: Primitive data types are passed by reference or pass by value ? A: Everything in java is passed by Pass by Value including Primitive data types. Q: Objects are passed by value or by reference ? A: Java only supports pass by value. With objects, the object reference itself i s passed by value and so both the original reference and parameter copy both ref er to the same object . 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. Serialization can be used to write down objects into files. Q: How do I serialize an object to a file ? A: The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is conn ected to a FileOutputStream. This will save the object to a file. Q: Which methods of Serializable interface should be implemented ? A: No method. The serializable interface is an empty interface, it does not cont ain any methods. So we do not implement any methods. And such interfaces are kno wn as Marker Interfaces.

Q: How can we customize the seralization process ? i.e. how can we have a contro l over the serialization process ? A: Yes it is possible to have control over serialization process. The class shou ld implement Externalizable interface. This interface contains two methods namel y readExternal and writeExternal. You should implement these methods and write t he logic for customizing the serialization process. Q: What is the common usage of serialization ? Where is serialization most frequ ently required ? A: Whenever an object is to be sent over the network, objects need to be seriali zed. Moreover if the state of an object is to be saved, objects need to be seril azed. Another usage of serialization can be in Game development where the state of a p layer has to be saved each time user saves his game. Q: What is Externalizable interface ? A: Externalizable is an interface which contains two methods readExternal and wr iteExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serializatio n process by implementing these methods. Q: When you serialize an object, what happens to the object references included in the object ? A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. T his is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect. Q: What one should take care of while serializing the object ? A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException . Q: What happens to the static fields of a class during serialization ? A: There are three exceptions in which serialization doesnot necessarily read an d write to the stream. These are: 1. Serialization ignores static fields, because they are not part of ay particul ar state state. 2. Base class fields are only hendled if the base class itself is serializable. 3. Transient fields. Java Interview Questions Part 4 Posted by Yash on August 18, 2011Leave a comment (0)Go to comments Q: How can we find out the size of an object ? Is there any sizeOf() operator in java ? Q: How can we find out the time a method takes for execution without using any e xternal tool ? Q: What are wrapper classes ? Q: Why do we need wrapper classes ? Q: What are checked exceptions ? Q: What are runtime exceptions ? Q: What is the difference between error and an exception ? Q: How to create custom exceptions ? Q: How can i throw an object of my class to as an exception object ? 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 ? Q: How does an exception propagate through the code? Q: What are the different ways to handle exceptions? Q: What is the basic difference between the 2 approaches of exception handling v ia try catch block and by using the throws clause ? When should we use which ap proach ? Q: Is it necessary that each try block must be followed by a catch block ? Q: Will the finally block still execute if we write return at the end of the tr y block ? Q: Will the finally block still execute if we write System.exit (0); at the en d of the try block ?

Q: How can we find out the size of an object ? A: No there is no sizeof operator in Java. So there is no direct way to determin e the size of an object directly in Java. ? 1 2 3 4 5 6 7 8 9 10 // Complex Method (for your Information) Runtime rt = Runtime.getRuntime(); long mem1 = rt.freeMemory(); System.out.println("Free memory is: " + mem1); //create an object Object o = new Object(); long mem2 = rt.freeMemory(); System.out.println("Free memory is now: " + mem2); System.out.println("Object size might be: " + (mem2-mem1)); Q: How can we find out the time a method takes for execution without using any external tool ? A: The execution time of any method can be calculated by reading the system time just before the method is invoked and immediately after method returns. Take th e time difference, which will give you the time taken by a method for execution. ? 1 2 3 4 5 6 7 //Code for the same long start = System.currentTimeMillis (); method (); long end = System.currentTimeMillis (); System.out.println ("Time taken for execution is " + (end - start)); Remember that if the time taken for execution is too small, it might show that i t is taking zero milliseconds for execution. Try it on a method which is big eno ugh, add some 1000s of iterations so as observe considerable amount of output. Q: What are wrapper classes ? A: Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Doub le etc corresponding to int, char, double respectively. Q: Why do we need wrapper classes? A: It is sometimes easier to deal with primitives rather than objects. Again mos t of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods which help easy interconversio n of primitives and objects. For all these reasons we need wrapper classes. And since we create instances of these classes we can store them in any of the colle ction classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object. Q: What are checked exceptions? A: Checked exception are those exceptions which the Java compiler forces you to

catch.The programmer has to handle these exceptions. e.g. IOException are checke d Exceptions. Any exception except Runtime Exception falls in this category. Q: What are runtime exceptions? A: Runtime exceptions are the other type of exceptions which are thrown at runti me because of either wrong input data or because of wrong logic implemented etc. These are not checked by the compiler at compile time, and the programmer is no t forced to implement these exceptions. Q: What is the difference between error and an exception? A: An Error is an irrecoverable condition occurring at runtime. Such as OutOfMem ory error. These are JVM errors and you can not repair them at runtime programat ically. 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 mos t of the cases it is possible to recover from an exception (probably by giving u ser a feedback for entering proper values etc.). Q: How to create custom exceptions? A: Any class extending the Exception class or its child becomes capable of actin g as an exception class. Your class should extend class Exception, or some more specific type for acting as a custom exception class. Q: How can i throw an object of my class to as an exception object ? A: Our class should extend from Exception class. Or we can extend our class from some more precise exception type also. 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: We can not do anytihng in this scenario. Because Java does not allow multiple inheritance and neither has provided any exception interface. Q: How does an exception propagate through the code? A: An unhandled exception travels up the method stack in search of a matching ha ndler. When an exception is thrown from a code which is wrapped in a try block f ollowed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If any matching typ e is not found then the exception moves up the method stack and reaches the call er method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then the JVMs defau lt exception handler handles the exception and finally the program terminates. Q: What are the different ways to handle exceptions? A: There are two ways to handle exceptions : 1. By wrapping the desired code in a try block followed by a catch block to catc h the exceptions. 2. List the desired exceptions in the throws clause of the method and let the ca ller of the method hadle those exceptions. Q: What is the basic difference between the 2 approaches of exception handling v ia try catch block and by using the throws clause ? When should we use which ap proach ? A: In the first approach as a programmer of the method, you urself are dealing w ith the exception. This is fine if you are in a best position to decide should b e done in case of an exception. Whereas if the programmer does not know how to handle the exception, or does not want the responsibility of handling exception, then do not use this approach. I n this case use the second approach. In the second approach we are forcing the c aller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughou t the java libraries we use. 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 acatch block OR a finally block. But any one of t hem is mandatory. And if catch block is absent, whatever exceptions are likely t o be thrown should be declared in the throws clause of the method.

Q: Will the finally block still execute if we write return at the end of the tr y block ? A: Yes even we you write return statement as the last statement in the try block with no exception occuring, the finally block will execute. The finally block w ill execute and then the control returns. Q: Will the finally block still execute if we write System.exit (0); at the en d of the try block ? A: No in this case the finally block does not execute because when we say System .exit (0); the control immediately goes out of the program, and thus finally blo ck never gets a chance to execute. How to get date, month, year values from the current date Posted by Yash on August 19, 2011Leave a comment (0)Go to comments This code snippet uses the java.utils Calendar class and its inbuilt methods for fetching the date, month and year values from the Calendar Object. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

package org.java.util;

import java.util.Calendar; public class DateCalendarExample { public static void main(String[] args) { /* * Get all the information from the date object, * using the Calendar Methods. */ Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DATE); // Month is Zero Indexed, so add 1 int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR); System.out.println("Current Date: " + cal.getTime()); System.out.println("Day: " + day); System.out.println("Month: " + month); System.out.println("Year: " + year); } } Code Snippet Examples, Java Zone, java.util

How do I check for an empty string? Posted by Santanu on August 21, 2011Leave a comment (2)Go to comments To check weather a string is empty or not we can use java.lang.String.isEmpty(). It returns true if length of the string is zero(0) otherwise false. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

56 57 58 59 60 61 62 63

package com.techGuru.example;

public class SampleCode { public static void main(String[] args) { String str1 = "abc"; String str2 = ""; String str3 = " "; String str4 = "\r"; String str5 = null; System.out.println("is str1 is empty:"+str1.isEmpty()); //str1 is not empty as it contains the "abc" value System.out.println("is str2 is empty:"+str2.isEmpty()); //str2 is empty as the string length is zero here. System.out.println("is str3 is empty:"+str3.isEmpty()); //though the str3 seems to be empty but contains a //white space character(blank here); //that is why the string length is one here. System.out.println("is str4 is empty:"+str4.isEmpty()); //In this case also though the \r is not a printable //character but the string lenth is not zero //System.out.println("is str5 is empty:"+str5.isEmpty()); //The above statement will through an exception if //uncommented.The reason is as the reference str5 //is not initialized and we are trying to execute //a method on a uninitialized reference so it through //null pointer exception. } }

output: is str1 is empty:false is str2 is empty:true is str3 is empty:false is str4 is empty:false Java Interview Questions Part 5 Posted by Yash on August 22, 2011Leave a comment (0)Go to comments Q: Is an Empty .java file a valid source file ? Q: Can a .java file contain more than one java classes ? Q: Is String a primitive data type in Java ? Q: Is main a keyword in Java ? Q: Is next a keyword in Java ? Q: Is delete a keyword in Java ? Q: Is exit a keyword in Java ? Q: What happens if you dont initialize an instance variable of any of the primit ive types in Java ? Q: What are the different scopes for Java variables ? Q: What is the default value of the local variables ? Q: How many objects are created in the following piece of code ? MyClass c1, c2, c3; c1 = new MyClass (); c3 = new MyClass (); Q: Can a public class MyClass be defined in a source file named MySecondClass.ja va ? Q: Can main method be declared final ? Q: What will be the output of the following statement ? System.out.println (1 + 3); Q: What will be the default values of all the elements of an array defined as an instance variable ? Q: Is Empty .java file a valid source file? A: Yes, an empty .java file is a perfectly valid source file. Note: An empty jav a file refers to a file with no content inside it. Q: Can a .java file contain more than one java classes? A: Yes, a .java file contain more than one java classes, provided there is only one public class. And that public class must have the main method. Q: Is String a primitive data type in Java? A: No String is not a primitive data type in Java, its an Object. It is one of t he most extensively used object. Strings in Java are instances of String class d efined in java.lang package. Q: Is main a keyword in Java? A: No, main is not a keyword in Java. Q: Is next a keyword in Java? A: No, next is not a keyword. Q: Is delete a keyword in Java? A: No, delete is not a keyword in Java. delete is a keyword in C/C++. Java does no t make use of explicit destructors the way C++ does. Q: Is exit a keyword in Java? A: No. To exit a program explicitly you use exit method in System object System. exit(0). Q: What happens if you dont initialize an instance variable of any of the primit ive types in Java? A: Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0, a boolean will be initialized to false. Bu t any local variable needs to be initialized explicitly, else we would get an co

mpilation error. Q: What will be the initial value of an object reference which is defined as an instance variable? A: The object references are all initialized to null in Java. However in order t o do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references. Q: What are the different scopes for Java variables? A: The scope of a Java variable is determined by the context in which the variab le is declared. Thus a java variable can have one of the three scopes at any giv en point in time. 1. Instance : - These are typical object level variables, they are initialized t o default values at the time of creation of object, and remain accessible as lon g as the object accessible. 2. Local : - These are the variables that are defined within a method. They rema in accessbile only during the course of method excecution. When the method finis hes execution, these variables fall out of scope. 3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance. Q: What is the default value of the local variables? A: The local variables are not initialized to any default value, neither primiti ves nor object references. If you try to use these variables without initializin g them explicitly, the java compiler will not compile the code. It will complain abt the local varaible not being initialized. Q: How many objects are created in the following piece of code? MyClass obj1, obj2, obj3; obj1 = new MyClass (); obj3 = new MyClass (); A: Only 2 objects are created, obj1 and obj3. The reference obj2 is only declare d and not initialized. Memory is not allocated to objects unless we initialize i t using the new keyword. Q: Can a public class MyClass be defined in a source file named MySecondClass.ja va? A: No if the source file contains a public class, then the source file name must be the same as the public classs name within it, with a .java extension. Q: Can main method be declared final? A: Yes, the main method can be declared final, in addition to being public stati c. Q: What will be the output of the following statement? System.out.println (1 + 3); A: It will print 13. Since the first parameter before + is a string, + operator wi ll concatenate the two values instead of adding them, hence o/p: 13. Note + is the o nly Overloaded operator in Java. Q: What will be the default values of all the elements of an array defined as an instance variable? A: If the array is an array of primitive types, then all the elements of the arr ay will be initialized to the default value corresponding to that primitive type . e.g. All the elements of an array of int will be initialized to 0, while that of boolean type will be initialized to false. Whereas if the array is an array o f references (of any type), all the elements will be initialized to null. Java Interview Questions Part 6 Posted by Yash on August 22, 2011Leave a comment (0)Go to comments Q: Can an unreachable object become reachable again ? Q: What method must be implemented by all threads ? Q: What are synchronized statements and synchronized methods ? Q: What is Externalizable ? Q: What modifiers are allowed for methods in an Interface ? Q: Are there some alternatives to inheritance ? Q: What does it mean that a method or field is static ?

Q: What is the difference between preemptive scheduling and time slicing ? Q: What is the catch or declare rule for method declarations ? Q: How are this() and super() used with constructors ? Q: What are the steps in the JDBC connection ?* Q:What is the difference between static and non-static variables ? Q: Can an unreachable object become reachable again ? A: An unreachable object can become reachable again. This can happen when the ob jects finalize() method is invoked and the object performs an operation which cau ses it to become accessible to reachable objects e.g assigning the object to som e other reachable object. Q: What method must be implemented by all threads ? A: All tasks must implement the run() method, whether they are a subclass of Thr ead or implement the Runnable interface. Q: What are synchronized methods and synchronized statements ? A: Synchronized methods are methods that are used to control access to an object . A thread only executes a synchronized method after it has acquired the lock fo r the methods object or class. Synchronized statements are similar to synchronize d methods. A synchronized statement can only be executed after a thread has acqu ired the lock for the object or class referenced in the synchronized statement. Q: What is Externalizable? A: Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(Objec tOuput out) and readExternal(ObjectInput in) Q: What modifiers are allowed for methods in an Interface? A: Only public and abstract modifiers are allowed for methods in interfaces. Q: What are some alternatives to inheritance? A: Delegation is an alternative to inheritance. Delegation means that you includ e an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesnt force you to accept all the methods of t he super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass). Q: What does it mean that a method or field is static? A: Static variables and methods are instantiated only once per class. In other w ords they are class variables, not instance variables. If you change the value o f a static variable in a particular object, the value of that variable changes f or all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). Thats how library m ethods like System.out.println() work out is a static field in the java.lang.Sys tem class. Q: What is the difference between preemptive scheduling and time slicing? A: Under preemptive scheduling, the highest priority task executes until it ente rs the waiting or dead states or a higher priority task comes into existence. Un der time slicing, a task executes for a predefined slice of time and then reente rs the pool of ready tasks. The scheduler then determines which task should exec ute next, based on priority and other factors. Q: What is the catch or declare rule for method declarations? A: If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. Q: How are this() and super() used with constructors? A: This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. Q: What are the steps in the JDBC connection? A: While making a JDBC connection we go through the following steps : Step 1 : Register the database driver by using : Class.forName(\ driver classs for that specific database\ ); Step 2 : Now create a database connection using :

Connection con = DriverManager.getConnection(url,username,password); Step 3: Now Create a query using : Statement stmt = Connection.Statement(\select * from TABLE NAME\); Step 4 : Exceute the query : stmt.exceuteUpdate(); Q: What is the difference between static and non-static variables? A: A static variable is associated with the class as a whole rather than with sp ecific instances of a class. Non-static variables take on unique values with eac h object instance. JVM, JDK and JRE A basic Explanation Posted by Dev on September 10, 2011Leave a comment (1)Go to comments From a JAVA prospective if we visualize, we come up with two group of people. Th ere are Java coders or developers around (and frankly speaking there are a hand full who are really good at it both from conceptual and programming aspects) and the other group are the ones who use this java applications. Wondering why I started off like this So here it is From the users prospective he just needs a JRE i.e Java Runtime Environment to ru n a Java application . JRE is just a minimal set of programmes which executes th e java class files developed by the JAVA developer. So in technical terms If you need to execute a java program you need a JRE and in a nutshell we can say: FIGURE 1: JRE : Java Virtual Machine + Java Packages Classes(like util, lang , math and many more.) + Runtime libraries. Java Virtual Machine interprets the byte code into the machine code depending up on the underlying operating system and hardware combination. (JVM is the one who allows JAVA to be platform independent at the cost of. guess what, JVM itself be ing Platform Dependent) NOW THE OTHER SIDE OF THE COIN From the developers prospective JVM and Runtime libraries are just not enough to serve their purpose. They need a JDK i.e Java Development kit. And as the name i mplies it is a complete package for Developers.Now Coming back to technical ter ms JDK : Tools required to develop Java program (like Java application launcher (ja va.exe) ,compiler (javac.exe), and few others) + (ofcourse the ) Java Virtual Machine (Dont tell me the Developer wont need to run his own code) And the compiler in the JDK actually converts the JAVA code into Byte Code whic h the JVM interprets. FIGURE 2: Naturally since JRE just needs to run the code it doesnt need a compiler but only JVM and class libraries to see what the output of the compiler has to offer. Ne edless to mention if you are having a JDK installed you wont need a JRE, but th e reverse is not true and the installation must be requirement oriented. Now if know you are a Developer or a User, you know what to look for. Is Java Pass by Value, or Pass by Reference ? Posted by Yash on September 8, 2011Leave a comment (2)Go to comments Just start believing this statement, and ill show you how it works: Java DOES NOT support Pass by Reference. Java is Always PASS BY VALUE. Now lets dig little into how Pass by Value and Pass by Reference actually work. Pass by value, is a mechanism where we pass the value of any variable to a metho d, and therefore any modifications that we made to that variable in that method does not reflect in the original variable in the parent code block. In this case its the local value of the variable gets modified and not the actual variable v alue. Pass by reference, on the other hand is a mechanism where we pass the address of the variable to any method, and hence any modifications made to the local varia ble actually take place at the memory address that was passed. Therefore the val ue of the parent block variable reflects the changes made in the called function . This Address Passing is common in procedural programming languages like C/C++. I f youre an java programmer, and if this Address Passing thing sounds weird, its per fectly fine. Because java doesnt play with addresses anyways.

Now coming to our point : Java is Pass by Value. Yes each time we pass any parameter to our method, it always gets the value of t he parameter, and not its address. Yes this is how java works. Everything is pas s-by-value. It works alike for both Primitives and Objects. Yes even objects are Passed by Value. Now youll claim that youve seen scenarios where you pass an object to a method, an d you can see the modifications reflected onto the parent object after the metho d returns. How do we explain this ? Its actually not that complex. Java is still pass-by-value, its just that in thi s case the value of reference gets passed. Confused ! Take it like this, instead of passing the Object or its Reference, it passes the the value which the actual reference holds (the reference to the hea p object). Therefore both the actual object and the parameter, hold the same val ue in their references, and therefore both are actually pointing to the same jav a object in the heap. And now you know since both references (original one and p arameter one) are pointing to the same heap object, any changes made to either o f them would be reflected on the other one. That is very much how java works. I hope I made the explanation simple enough. If you have any confusions just pos t it right here. Contradictions and discussions are invited too. What is meant by Strings are Immutable ? Posted by Yash on September 8, 2011Leave a comment (1)Go to comments We have often studied at many places that Strings are immutable. But we easily m odify and append to any String value. So ever wondred what being immutable actua lly refers to ? Yes, Strings are immutable, but it doesnt mean that the values of the string vari able cannot be changed. It just means that the string object that was created on the heap corresponding to the string, cannot be mutated. In other words the obj ect on heap is the one that is immutable. So actually whenever we try to modify any String value, these steps work in back ground : creation of a New Object. appending new value to the NEW object. updating the reference of the string variable to this new object. old object is ready for Garbage Collection if there are no other references to i t. Hence, every time an a string modification/append/alteration is done, which invo lves mutation (change in value) of the string, we are actually having a NEW Stri ng object instead of the old one. StringBuffers on the other hand are mutable. A ll alterations take place on the same object. And that is why StringBuffers and StringBuilders are proffered performance wise too. The code snippet below prints the hashcode of String and StringBuffer objects b efore and after operation on them: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

17

public class StringsImmutable { public static void main(String [] args) { String superhero = "Wolverine"; StringBuffer nweSuperhero = new StringBuffer("Wolverine");

System.out.println("Hashcode for STRING before concatenation:\t"+superhe ro.hashCode()); superhero += " flashy blades"; System.out.println("Hashcode for STRING after concatenation:\t"+superher o.hashCode()); System.out.println("\nHashcode for STRING BUFFER before append:\t"+nweSu perhero.hashCode()); nweSuperhero.append(" flashy blades"); System.out.println("Hashcode for STRING BUFFER after append:\t"+nweSuper hero.hashCode()); } } FIGURE 3: Eclipse IDE must know keyboard shortcuts Posted by Yash on September 8, 2011Leave a comment (1)Go to comments Eclipse IDE is definitely one of the best tool gifted to programmers. If you are into java programming for a time now, you can understand what a role Eclipse ID E plays in your life. Eclipse id developers popular choice not only because its open source and free, but also because of its ease of use, extensiblity, plugin support, views and perspectives and the great UI. Eclipse is also the basis of m any commertial IDEs like Flex IDE, Rational XDE, Websphere Application Developer etc. Technologies like Flex and Android also provide easy to integrate plugins for their respective development environments. Well this was little praise for the master IDE, and now without wasting any time , coming directly to the topic, Must Know keyboard shortcuts for eclipse, that m ake you more faster in your work, instead of spending most of your time browsing through your code or workspace. So here they come : Opening any Resource : Key shortcuts cntrl+shft+R : Opens an resource/file anywh ere in your project. Very helpful for jumping to any other file in your project in a flash. Open Type : Key shortcuts cntrl+shft+T : Similar to open resource type, except t hat now it would filter the search for a particular file type. Used to filter do wn your search for resource. Toggle between open files : Key shortcuts cntrl+E : A quick toggle between all t he open files. Search for Anything : Key shortcuts cntrl+H : The Search master key, search for files, file name pattern, text within file, particular file type, process search , Java search, Javascript search, and much more, its all here in these two keys. Yes you would definitely be using this. jump to a particular line : Key shortcuts cntrl+L : Does it need any clarificati ons ? Search a method in a class : Key shortcuts cntrl+O : Jump directly to any method in your class. Search a method of super class from sub class : Key shortcuts cntrl+O+O : Pressi ng double O shows you the list of all methods present in super class. Open a type hierarchy : Key shortcuts cntrl+T : Opens type of files implementing the item(method, class etc). Comment a bulk of code at a time: Key shortcuts cntrl+shft+/ : Simple; and uncom ment by cntrl+Shift+\.

Format your code: Key shortcuts cntrl+shft+F : If you think your code gets too m essy by the time you reach its completion, no bothering for formatting now. Ecli pse does it all. Just hit the magic keys. Auto complete: Key shortcuts cntrl+space. Get all properties dot(.) notation : Key shortcuts . : yes , its just a dot. Pretty neat list. I suggest you to try all of them atleast once, and later theyll come by practice. Ending my post here, we would meet next time with other cool features of Eclipse . How do I terminate a Java application? Posted by Jayant on September 6, 2011Leave a comment (2)Go to comments In an application we sometimes want terminate the execution of our application, for instance because it cannot find the required resource. To terminate it we can use exit(status) method in java.lang.System class or in t he java.lang.Runtime class. When terminating an application we need to provide a status code, a non-zero status assigned for any abnormal termination. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 package org.techguru.examples.lang; import java.io.File; public class AppTerminate { public static void main(String[] args) { File file = new File("config.xml"); int errCode = 0;

if (!file.exists()) { errCode = 1; } else { errCode = 0; } // When the error code is not zero go terminate if (errCode > 0) { System.exit(errCode); } } } The call to System.exit(status) is equals to Runtime.getRuntime().exit(status). Actually the System class will delegate the termination process to the Runtime c lass. How do I get the current month name? Posted by Jayant on September 6, 2011Leave a comment (2)Go to comments To get the current month name from the system we can use java.util.Calendar clas s. TheCalendar.get(Calendar.MONTH) returns the month value as an integer startin g from 0 as the first month and 11 as the last month. This mean January equals t o 0, February equals to 1 and December equals to 11. Lets see the code below: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import java.util.Calendar; public class GetMonthNameExample {

public static void main(String[] args) { String[] monthName = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; Calendar cal = Calendar.getInstance(); String month = monthName[cal.get(Calendar.MONTH)]; System.out.println("Month name: " + month); } } On the first line inside the main method we declare an array of string that keep our month names. Next we get the integer value of the current month and at the last step we look for the month name inside our previously defined array. The example result of this program is: ? 1 Month name: January The better way to get the month names or week names is to use the java.text.Date FormatSymbols class. The example on using this class can be found on the followi ng links: How do I Get a List of Weekday Names?. How do I do a date add or subtract? Posted by Jayant on September 6, 2011Leave a comment (0)Go to comments The java.util.Calendar allows us to do a date arithmetic function such as add or subtract a unit of time to the specified date field. The method that done this process is the Calendar.add(int field, int amount). Wh ere the value of the field can be Calendar.DATE, Calendar.MONTH, Calendar.YEAR. So this mean if you want to subtract in days, months or years use Calendar.DATE, Calendar.MONTH or Calendar.YEAR respectively. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

23 24 25 26 27 28 29 30 31

import java.util.Calendar;

public class CalendarAddExample { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); System.out.println("Today : " + cal.getTime()); // Subtract 30 days from the calendar cal.add(Calendar.DATE, -30); System.out.println("30 days ago: " + cal.getTime()); // Add 10 months to the calendar cal.add(Calendar.MONTH, 10); System.out.println("10 months later: " + cal.getTime()); // Subtract 1 year from the calendar cal.add(Calendar.YEAR, -1) System.out.println("1 year ago: " + cal.getTime()); } } In the code above we want to know what is the date back to 30 days ago. The sample result of the code is shown below: ? 1 2 3 Today : Tue Jan 03 06:53:03 ICT 2006 30 days ago: Sun Dec 04 06:53:03 ICT 2005 Code Snippet Examples How do I check if a string is a valid number? Posted by Jayant on September 6, 2011Leave a comment (0)Go to comments When creating a program we will use a lot of string to represent our data. The d ata might not just information about our customer name, email or address, but wi ll also contains numeric data represented as string. So how do we know if this s tring contains a valid number? Java provides some wrappers to the primitive data types that can be used to do t he checking. ? 1 2 3

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

package org.techguru.example.lang;

public class NumericParsingExample { public static void main(String[] args) { String age = "15"; String height = "160.5"; String weight = "55.9"; try { int theAge = Integer.parseInt(age); float theHeight = Float.parseFloat(height); double theWeight = Double.parseDouble(weight); System.out.println("Age: " + theAge); System.out.println("Height: " + theHeight); System.out.println("Weight: " + theWeight); } catch (NumberFormatException e) { e.printStackTrace();

} } } In the example code we use Integer.parseInt(), Float.parseFloat(), Double.parseD ouble() methods to check the validity of our numeric data. If the string is not a valid number NumberFormatException will be thrown. The result of our example: ? 1 2 3 4 5 Age: 15 Height: 160.5 Weight: 55.9 Code Snippet Examples How to pass command line arguments to a JAVA application Posted by finoni on September 6, 2011Leave a comment (0)Go to comments While invoking a Java application we can pass any number of parameters to it as command-line arguments. As we know,all executable classes contains main() method , we can pass command-line arguments as parameters to this main() method as: public static void main(String[] args) {} As soon as the application is launched,the parameters are passed as an array of strings to the main() method by runtime system. Below example displays each of i ts command-line argument in a separate line. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package org.techguru.example; public class CommandLineArgument { public static void main(String[] args) {

//To check no. of parameters passed we use args.length for(int i=0;i<args.length;i++) { System.out.println("Parameter"+(i+1)+": "+args[i]); } } } Now when we run the application by giving command java CommandLineArgument follo wed by parameters as follows: java CommandLineArgument ONE TWO THREE The output will be : ONE TWO THREE Parameters passed in command-line are separated by spaces. That is why in above example application didnt took ONE TWO THREE as one parameter. To pass it as one parameter we should give command as: java CommandLineArgument ONE TWO THREE Now the application interpret it as one arguement and the output will be: ONE TWO THREE How do I check a string starts with a specified word? Posted by Jayant on September 6, 2011Leave a comment (0)Go to comments To test if a string has a defined prefix we can use the String.startsWith() meth od. This method returns a boolean true as the result if the string has the defin ed prefix. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

29

package org.techguru.example.lang;

public class StartsWithSample { public static void main(String[] args) { String str = "The quick brown fox jumps over the lazy dog"; // // See if the fox is a quick fox. // if (str.startsWith("The quick")) { System.out.println("Yes, the fox is the quick one"); } else { System.out.println("The fox is a slow fox"); } } } Code Snippet Examples How do I check a string ends with a specified word? Posted by Jayant on September 6, 2011Leave a comment (0)Go to comments The String.endsWith() method can be use to check if a string ends with a specifi ed suffix. It will returns a boolean true if the suffix is found at the end of t he string object. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

25 26 27 28 29

package org.techguru.example.lang;

public class EndsWithSample { public static void main(String[] args) { String str = "The quick brown fox jumps over the lazy dog"; // // well, does the fox jumps over a lazy dog? // if (str.endsWith("lazy dog")) { System.out.println("The dog is a lazy dog"); } else { System.out.println("Good dog!"); } } } Code Snippet Examples How to convert String Object to Date object ? Posted by Dev on September 6, 2011Leave a comment (0)Go to comments The following snippet shows how a string representation of date(dd/MM/yyyy or an y other pattern) can be converted to a Date Object (java.util.Date). To convert our string to date object we use the java.text.SimpleDateFormat that extendsjava.text.DateFormat abstract class and helps us read our string and con vert it into a date object. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

19 20 21 22 23 24 25 26 27 28 import import import import

package org.techguru.util; java.text.DateFormat; java.text.ParseException; java.text.SimpleDateFormat; java.util.Date;

public class StringToDate { public static void main(String[] args) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); try { Date today = df.parse("20/12/2005"); System.out.println("Today = " + df.format(today)); } catch (ParseException e) { e.printStackTrace(); } } } And here is the result of our code: ? 1 Today = 20/12/2005 We need to create an instance of SimpleDateFormat with dd/MM/yyyy format (Other fo rmats can also be used) . Using the parse(String source) method we can get the Date instance(i.e the retur n type is java.util.Date). Because parse method can throw java.text.ParseExcepti on exception if the supplied date is not in a valid format; we need to catch it and this utility also might help us to analyze Invalid dates as well. Here are the list of defined patterns that can be used to format the date taken from the Java class documentation. Letter Date / Time Component Examples G Era designator AD y Year 1996; 96 M Month in year July; Jul; 07 w Week in year 27 W Week in month 2 D Day in year 189 d Day in month 10 F Day of week in month 2 E Day in week Tuesday; Tue a Am/pm marker PM H Hour in day (0-23) 0

k Hour in day (1-24) 24 K Hour in am/pm (0-11) 0 h Hour in am/pm (1-12) 12 m Minute in hour 30 s Second in minute 55 S Millisecond 978 z Time zone Pacific Standard Time; PST; GMT-08:00 Z Time zone -0800 java.util Working with java.util.Date Posted by Dev on September 1, 2011Leave a comment (0)Go to comments Finding Day from a given Date : public static void getDayofTheDate() { // Taking a new Date object Date d1 = new Date(); String day = null; // Diff date formats are available for diff results // Use the format EEEE for retrieving Day of the week DateFormat f = new SimpleDateFormat("EEEE"); try { day = f.format(d1); } catch (Exception e) { e.printStackTrace(); } System.out.println("The day for " + d1 + " is " + day); } Comparing Dates public static void compare2Dates() { SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy"); String DATE_FORMAT = "dd-MM-yyyy"; Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.set(2011, 02, 24); cal2.set(2011, 05, 30); System.out.print(fm.format(cal1.getTime()) + " is "); if (cal1.before(cal2)) { System.out.println("less than " + fm.format(cal2.getTime ())); } else if (cal1.after(cal2)) { System.out.println("greater than " + fm.format(cal2.getT ime())); } else if (cal1.equals(cal2)) { System.out.println("is equal to " + fm.format(cal2.getTi me())); } } Add days to a Date public static void addToDate() { String DATE_FORMAT = "dd-MM-yyyy"; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); //Gets a calendar using the default time zone and locale. Calendar c1 = Calendar.getInstance(); Date d1 = new Date(); c1.set(1999, 0, 20); //(year,month,date) System.out.println("c1.set(2009,0 ,20) : " + c1.getTime()); c1.add(Calendar.DATE, 15); System.out.println("Date + 20 days is : "+ sdf.format(c1.getTime

())); System.out.println(); System.out.println("-------------------------------------"); } Days between two dates public static void daysBetween2Dates() { String DATE_FORMAT = "dd-MM-yyyy"; Calendar c1 = Calendar.getInstance(); //returns GregorianCalenda r(); Calendar c2 = Calendar.getInstance(); //returns GregorianCalenda r(); c1.set(2010, 0, 20); c2.set(2011, 0, 22); System.out.println("Days Between " + c1.getTime() + " and " + c2.getTime() + " is"); System.out.println((c2.getTime().getTime() - c1.getTime() .getTime()) / (24 * 3600 * 1000)); } Validate a Date public static void validateAGivenDate() { //If the Date parsed results in an invalid Date the code throws //an IllegalArgumentException String dt = "20011223"; String invalidDt = "20031315"; String dateformat = "yyyyMMdd"; Date dt1 = null, dt2 = null; try { SimpleDateFormat sdf = new SimpleDateFormat(dateformat); sdf.setLenient(false); dt1 = sdf.parse(dt); dt2 = sdf.parse(invalidDt); } catch (ParseException e) { System.out.println(e.getMessage()); } catch (IllegalArgumentException e) { System.out.println("Invalid date"); } } How do I know the length of a string? Posted by Jayant on August 28, 2011Leave a comment (1)Go to comments This is a simple code snippet to get the length of a string specified in a Strin g object. For this we use theString.length() method call which returns the strin g length as an int value. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14

15

package org.techguru.lang;

public class StringLength { public static void main(String[] args) { String name = "This is a demo string"; /* * Get the length of the string by * string.length() method. */ int length = name.length(); System.out.println("Length of string: " + length); } } Code Snippet Examples, j How can we implement a Singleton pattern? Posted by Yash on August 28, 2011Leave a comment (0)Go to comments Before learning how to implement singleton pattern, lets first look into what a singleton pattern is. A singleton pattern is used when we need to have only a s ingle instance of a class to be created inside our application. By using this pa ttern we ensure that a class can only have a single instance by protecting the c lass creation process, by setting the class constructor into private access modi fier. To get the class instance, our singleton class provides a method for example a g etInstance() method, this will be the only method that can be accessed to get th e instance (instead of direct object creation via constructor). ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package org.techguru.example.singleton; public class MySingletonClass { private static MySingletonClass myInstance = new MySingletonClass(); private MySingletonClass() { // private constructor created }

public static synchronized MySingletonClass getInstance() { return myInstance; } public void someMethod() { // put other methods and logic } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Cloning is restricted."); } } These are some points you need to implement for Singleton : 1. Singleton needs a static variable to keep a single instance. 2. The constructor of the class needs to have a private access modifier. By this you will not allow any other class to create an instance of this singleton instance, because no one has access to the constructor. 3. Since no other class can instantiate this singleton instance, we should provide a method that returns the instance,so that any other class can get and u se the singleton instance, for examplegetInstance(). 4. If our singleton instance can be used in a multi threaded application we need to make sure that instance creation process doesnt result in more that one instance, so we add a synchronizedkeywords to protect more than one thread acces s this method at the same time. 5. It is also advisable to override the clone() method of the java.lang.Obj ect class and throwCloneNotSupportedException to restrict another instance creat ion by cloning the singleton object. And this is how we use our Singleton class: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 package org.techguru.example.singleton; public class SingletonDemo { public static void main(String[] args) throws Exception { /* * Gets an instance of singleton object and then use the * someMethod() method. */ MySingletonClass instance = MySingletonClass.getInstance(); instance.doSomething(); } } Code Snippet Examples, Java concepts

Potrebbero piacerti anche