Core Java Imp
Core Java Imp
Abstraction:
Abstraction will Show functionality hide complexity. We can
achieve Abstraction in two ways first is by interface and second is by Abstract class. For real life example " All electronic device " viz., Mobile, Pen.
Eg:
Encapsulation:
Encapsulation is the mechanism that binds together code and data
it manipulates and keeps both safe from outside interference and misuse. Encapsulation refers to keeping all the related members (variables and methods) together in an object. Specifying members as private can hide the variables and methods. Objects should hide their inner workings from the outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in an unexpected way, which in turn makes future development and refactoring efforts easy. Encapsulation is the process of binding together the method and data variable as a single entity. It keeps both the data and functionality code safe from outside world .It hide the data within class and make it available only through the method.
The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code. For real life example: A Person's mind is encapsulated, cannot be seen, one can try to read it by interacting with him. or Gems Packet Capsule Medicine
Example code:class check{ private int amount=0; public int getAmount() { return amount; } public void setAmount(int amt) { amount=amt; } } public class Mainclass { public static void main(String[]arg) { int amt = 0; check obj = new check(); obj.setAmount(200); amt = obj.getAmount(); System.out.println("your current amount is"+ amt ); } }
Inheritance:
Mammal IS-A Animal Reptile IS-A Animal Dog IS-A Mammal Hence : Dog IS-A Animal as well.
Real time example: Parent and Child where child acquires all the
properties of a parent.
Polymorphism:
Polymorphism is the feature that allows one interface to be used for general class actions. When the JVM invokes a class instance method, it selects the method to invoke based on the type of the object reference, which is always known at run-time. On the other hand, when the JVM invokes a static method, it selects the method to invoke based
on the actual class of the object, which may only be known at compile time.
Need of Polymorphism
Polymorphism is the association between a generalized
reference and a more specific object. The ability of a reference variable to change behavior according to what object instance it is holding. Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation. Polymorphism exists in three distinct forms in Java: Method overloading Method overriding through inheritance Method overriding through the Java interface.
Overridden methods must have the same name, argument list, and return overrides. The overriding method may not throw any exceptions that may not be thrownby the overridden method. type. The overriding method may not limit the access of the method it
Casting?
Ans:There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference
this is used to refer to the current object instance. super is used to refer to the variables and methods of the super class of the current object instance
What is a stream and what are the types of Streams and classes of the Streams?A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer
Can a method be overloaded based on different return type but same argument type ?
No, because the methods can be called without using their return type in which case there is ambiquity for the compiler.
Association?
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 typical behaviour can be invoking the method of other class and using the member of the other class.
Aggregation?
Aggregation
has
relationship
between
two
classes.
In
this
relationship the object of one class is a member of the other class. Aggregation always insists for a direction.
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); System.out.println(" "); tricky(pnt1,pnt2); System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); } OutPut: X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0 The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.
Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
Final():
Final () method is used for constant declaration. A final variable act as constant, a final class is immutable A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). A final class can't be extended i.e., final class may not be sub classed.
Finally():
Handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc.
Finalize()
method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.
1) Using new keyword This is the most common way to create an object in java. Almost 99% of objects are created in this way MyObject object = new MyObject(); 2) Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object in this way. It is also known as reflection. MyObject object = (MyObject)Class.forName("subin.rnd.MyObject"). newInstance(); 3) Using clone() The clone() can be used to create a copy of an existing object. MyObject anotherObject = new MyObject(); MyObject object = anotherObject.clone(); 4)Using object deserialization Object deserialization is nothing but creating an object from its serialized form. ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject(); 5) Using reflection in another way. this.getClass().getClassLoader().loadClass(com.amar.myobject) .newInstance();
J2SE 1.4 (february 6, 2002) merlin - assert keyword - Regular expressions - Exception chaining (allows an exception to encapsulate original lower-level exception) - Internet protocol version 6 (IPV6) support - Non-blocking nio (new input/output) - Logging API - Image i/o api for reading and writing images in formats like jpeg and png - Integrated XML parser and XSLT processor (JAXP) - Integrated security and cryptography extensions (JCE, JSSE, JAAS) - Java web start J2SE 5.0 (september 30, 2004) tiger [originally numbered 1.5] Generics Allows programmers to specify the types allowed for Collections Allows the compiler to enforce the type specifications //Before List stringList //In JDK 1.5 List<String> stringList; Varargs: the last parameter of a method can now be declared using a type name followed by three dots (e.g. Void drawtext(string... Lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type. Allow a variable number of arguments for methods like printf() or
Method.invoke() Internally parameters are an array of Object Compiler constructs array for the call void printf(String format, Object?args); ? printf(?{0} {1} ?, ?Hello?, ?World?); printf(?PI = {0}?, 3.14159); Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. Autoboxing/unboxing: automatic conversions between primitive types (such as int, boolean) and primitive wrapper classes (such as integer). Enumerations: the enum keyword creates a typesafe, ordered list of values (such as day.monday, day.tuesday, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). - Swing: new skinnable look and feel, called synth. Enhanced for each loop: it internally extends IEnumerable interface and for-each loop is used to access each successive value in a collection of values. Here is a loop written as both a for-each loop and a basic for loop. double[] ar = {1.2, 3.0, 0.8}; int sum = 0; for (double d : ar) { // d gets successively each value in ar. sum += d; } basic for. It requires an extra iteration variable. double[] ar = {1.2, 3.0, 0.8}; int sum = 0;
for (int i = 0; i < ar.length; i++) { // i indexes each element successively. sum += ar[i]; } //Before for(Iterator i = line.iterator();i.hasNext(); ) { String word = (String)i.next(); ? } //In JDK 1.5 for(String word: line) { ? } For each in JSP: <c:forEach var="product" items="$(testattribute}"> <tr><td>${product}</td></tr> </c:forEach> - Automatic stub generation for rmi objects. - Static imports concurrency utilities in package java.util.concurrent. - Scanner class for parsing data from various input streams and buffers. - StringBuilder class (in java.lang package) - Annotations
Abstract class and methods What is an Abstract Class and what is its purpose?
A Class which doesnt provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.
Interface:
Why do you create interfaces, and when MUST you use one?
we create interface bcoz ... 1. To implement multiple inheritance in java. 2. To advertise the compiler that class implementing that interface is ready to deliver the functionality defined by the interface. We use the
interface in cases where the classes need to define the same method but the way of execution is different for every classes depending on their need. e.g.:- If we want to sort between two employee object on the basis of salary we have to implement the comparable interface and define the compareTo()such that it sorts on salary. but if we want to sort two manager object on age basis we again have to implement the comparable interface and define the compareTo() method but the code written inside the compareTo() method is now different from the above one . Now both implement the same interface and define the same method but still the way of execution is different .One sort on age another on salary .implementing comparable interface advertise the compiler that class implementing this interface will compare data but the basis of comparison depends upon the code written in compareTo().
Why is an Interface be able to extend more than one Interface but a Class cant extend more than one Class?
Basically Java doesnt allow multiple inheritances, so a Class is restricted to extend only one class. But an Interface is a pure abstraction model and doesnt have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.
Eg: e.g. interface UsefulAction { public static int ACTION_SUCCESS = 1; public static int ACTION_FAILURE = 0; public int doAction(); } Any class implementing the Useful Action interface must implement the doAction() method which returns an int value and one could reasonably expect that value to correspond one of the constants, so that the calling code can be written thus. int result = doAction(); if (result == ACTION_SUCCESS) { // continue processing } else { // handle the failure } Both yes and no: yes, you can declare interface fields but they will automatically receive "public", "static" and "final" modifiers so they will be constants, so no, there will be no variables. But you surely can declare some Singleton as an Interface static final field which will held some variables inside of it. That's how you can obtain static fields of an Interface. However it is a bad practice and should not be used since Interface declares how the particular object will be used while mutable field is a part of implementation. And for partial implementation abstract classes are preferred
An interface which has no methods is called marker interface. If we implement that interface jvm will provide ability to the object Eg is Serializable. When a class implements this interface then only we can serialize the object. i.e we can save in the file. In other words any class which implements serializable can be serialized which is the additional feature when compared with an ordianary object
Transient variable?
These variables are not included in the process of serialization and are not the part of the objects serialized state. Does the order in which the value of the transient variables and the state of the object using the defaultWriteObject() method are saved during serialization matter? Yes. As while restoring the objects state the transient variables and the serializable variables that are stored must be restored in the same order in which they were saved.
About Main()
Why is main() method static?
To access the static method the object of the class is not needed. The method can be access directly with the help of ClassName. So when a program is started the jvm search for the class with main method and calls it without creating an object of the class.
What happens if you remove public from public static void main?
Until you run the program nothing happens. You would be able to happily compile your program, but when you try to execute it, you will get the below exception. Main Method Not Public
classes?
Can you have an inner class inside a method and what variables can you access?Yes, we can have an inner class inside a method and final variables can be accessed.
Ans) Its default value. E.g. if the transient variable in question is an int, its value after deserialization will be zero. Explanation
The transient variable is not saved as the part of the state of the serailized variable, its value after deserialization is its default value.
public class TestTransientVal implements Serializable{ private static final long serialVersionUID = -22L; private String name; transient private int age; TestTransientVal(int age, String name) { this.age = age; this.name = name; } public static void main(String [] args) { TestTransientVal c = new TestTransientVal(1,"ONE"); System.out.println("Before serialization: - " + c.name + " "+ c.age); try { FileOutputStream FileOutputStream("testTransients.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(c); os.close(); } catch (Exception e) { e.printStackTrace(); } try { FileInputStream fis = new FileInputStream("testTransients.ser"); ObjectInputStream ois = new ObjectInputStream(fis); c = (TestTransientVal) ois.readObject(); fs = new
ois.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("After de-serialization:- " + c.name + " "+ c.age); }} Result of executing above piece of code Before serialization: - Value of non-transient variable ONE Value of transient variable 1 After de-serialization:- Value of non-transient variable ONE Value of transient variable 0
About String
Differences between String and StringBuffer in Java
String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method.
applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilders vs String.
Summary
1) String is immutable while StringBuffer and StringBuilder is mutable object. 2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer. 3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder. 4) Use String if you require immutability, use Stringbuffer in java if you need mutable + threadsafety and use StringBuilder in Java if you require mutable + without thread-safety.
Difference
between
String
and
StringBuffer/StringBuilder?
Well, the most important difference between String and
StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable. By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is If String is immutable then how am I able to change the contents of the object whenever I wish to? . Well, to be precise its not the same String object that reflects the changes you do. Internally a new String object is created to do the changes. So suppose you declare a String object: String myString = Hello;
Next, you want to append Guest to the same String. What do you do? myString = myString + Guest; When you print the contents of myString the output will be Hello Guest. Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String. Now isnt that a performance issue? Yes, it definitely is.
What
is
difference
between
stringbuffer
and
stringbuilder?
StringBuffer and StringBuilder have the same methods with one difference and thats of synchronization. StringBuffer is
synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isnt thread safe). So, if you arent going to use threading then use the StringBuilder class as itll be more efficient than StringBuffer due to the absence of synchronization. Incase you do not know Heres how you use StringBuilder A simple Example to demonstrate that String object is Immutable Incase you still have any doubts regarding String or StringBuilder then do leave a comment. Ill be more than eager to help you out. The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer. Criteria to choose among StringBuffer and StringBuilder 1)If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous Mutable string means we can append to that string. example StringBuffer object is mutable string. String is immutable object.. when we declre String="abc"; a string object abc with fixed length is created. We cant add anything to it .If we do java simply creates a new object.
Stringbuffer can be converted to string objects and compared using compare method.. String objects are immutable. Well let me explain taking an example:Look at the code below along with the comments:String test = "Java"; // Create a string object "java" and assign a reference 'test ' to it.String test2 = test; //create another reference test2. Now both the references point to the //same string object i.e. "java"test = test + "world"; //this statement creates another string object i.e. "java world" and now the reference test refers to this object and not to "java" implying that string objects are immutable. The previous object "java" is then garbage collected if there is no other refrence to it. Right now test2 points to it, so it isnt garbage collected.System.out.println("test "+test);//Having understood the above, u can make out the output of this line. it will be "java world"System.out.println("test2 "+test2);//out put of this will be "java".Hope this makes it clear.
I have one string like "Happy Birthday to you". But i want to print it like "you to Birthday Happy". Pls tell me the program on java?
import java.util.*; class ReverseString1 { public static void main(String[]arg) { String input ="Happy Birthday To You"; Stack stack = new Stack(); StringTokenizer strTok = new StringTokenizer(input); while(strTok.hasMoreTokens()){ stack.push(strTok.nextElement()); } StringBuffer revStr = new StringBuffer(); while(!stack.empty()){
Or
String str =new String("Happy Birthday to you"); StringBuffer sb = new StringBuffer("str"); StringBuffer sb1 = sb.reverse(); System.out.print(sb1);
About Static
Static class ?
A class cannot be declared static. But a class can be said a static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using Class name only
Static Keyword
Static keyword can be used with the variables and methods but not with the class but there are static class. Anything declared as static is related to class and not objects.
Static variable :
Multiples objects of a class shares the same instance of a static variable.Consider the example: public class Counter{ private static int count=0; private int nonStaticcount=0; public void incrementCounter(){
count++; nonStaticcount++; } public int getCount(){ return count; } public int getNonStaticcount(){ return nonStaticcount; } public static void main(String args[]){ Counter countObj1 = new Counter(); Counter countObj2 = new Counter(); countObj1.incrementCounter(); countObj1.incrementCounter(); System.out.println("Static count for Obj1: "+countObj1.getCount()); System.out.println("NonStatic count for Obj1: "+countObj1.getNonStaticcount()); System.out.println("Static count for Obj2: "+countObj2.getCount()) System.out.println("NonStatic count for Obj2: "+countObj2.getNonStaticcount()) } Output Static count for Obj1: 2 NonStatic count for Obj1: 2 Static count for Obj2: 2 NonStatic count for Obj2: 0
In the above program obj1 and obj2 share the same instance of static variable count hence if the value is incremented by one object , the incremented value will be reflected across the other objects.
Static method?
A method defined as static is called static method. A static method can be accessed without creating the objects. Just by using the Class name the method can be accessed. Static method can only access static variables and not local or global non-static variables. For eg: public class Test{ public static void printMe(){ System.out.println("Hello World"); } } public class MainClass{ public static void main(String args[]){ Test.printMe() } } OutPut: Hello World Also static method can call only static methods and not non static methods. But non-static methods can call static mehtods.
and it fails then exception can be caught, logged and application can exit. If System.exit () is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader
machine invokes an instance method, it selects the method to invoke based on the actual class of the object, which may only be known at run time.
else{ System.out.println("Objects are not equal") } if(str1.equals(str2)){ System.out.println("Objects are equal") }else{ System.out.println("Objects are not equal") } Output: Objects are not equal Objects are equal _______________ String str2 = "MyName"; String str3 = str2; if(str2 == str3){ System.out.println("Objects are equal") }else{ System.out.println("Objects are not equal") } if(str3.equals(str2)){ System.out.println("Objects are equal") }else{ System.out.println("Objects are not equal") } OutPut: Objects are equal Objects are equal.
Does
static class'
nested
class
have
access or
to
the
enclosing variables?
No.
non-static
methods
instance
If you compile a file containing inner class how many .class files are created and what are all of them accessible in usual way?
If a inner class enclosed with an outer class is compiled then one .class file for each inner class an a .class file for the outer class is created. e.g. class EnclosingOuter { class Inner{ } } If you compile the above code with command % javac EnclosingOuter.java Two files EnclosingOuter.class EnclosingOuter$Inner.class will be created. Though a separate inner class file is generated, the
inner class file is not accessible in the usual way like, % java EnclosingOuter$Inner.
How to access the inner class from code within the outer class?
The inner class is instantiated only through the outer class instance. class EnclosingOuter { private int noInnerClass = 1; public void getNoOfInnerClasses(){ Inner in = new Inner(); System.out.println(No } class Inner{ public int getNoOfClassesFromOuter(){ return noInnerClass; } } Here the method getNoOfInnerClasses() is called on the outer classs instance through this outer class instance the inner class instance in is created. Of Inner classes is : + in.getNoOfClassesFromOuter());
How to create an inner class instance from outside the outer class instance code?
To create an instance of the inner class you must have the instance class Inner{ } } To create the instance of inner class from class other than the enclosing class. of its enclosing class. e.g. class EnclosingOuter {
1) class OtherThanOuter{ EnclosingOuter out = new EnclosingOuter(); EnclosingOuter.Inner in = out.new Inner(); } 2) class OtherThanOuter{ EnclosingOuter.Inner out = new EnclosingOuter.Inner (); }
Immutable class?
Immutable class is a class which once created, its contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class.
2. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods. E.g. public final class FinalPersonClass { private final String name; private final int age; public FinalPersonClass(final String name, final int age) { super(); this.name = name; this.age = age; } public int getAge() { return age; } public String getName() { return name; }
Immutable objects:
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer. Immutable objects greatly simplify your program, since they :
do not need a copy constructor do not need an implementation of clone allow hashCode to use lazy initialization, and to cache its return value
do not need to be copied defensively when used as a field make good Map keys and Set elements (these objects must not change state while in the collection)
have their class invariant established once upon construction, and it never needs to be checked again
always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
Immutable objects have a very compelling list of positive qualities. Without question, they are among the simplest and most robust kinds of classes you can possibly build. When you create immutable classes, entire categories of problems simply disappear.
All wrapper classes in java.lang are immutable String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger.
Advantages of immutability?
Ans) The advantages are: 1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided. 2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state. 3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction. 4) The best use of the immutable objects is as the keys of a map
How to make sure that Childclass method actually overrides the method of the superclass?
Ans) The @Override annotation can be added to the javadoc for the new method. If you accidently miss an argument or capitalize the method name wrong, the compiler will generate a compile-time error.
Explain
re-entrant,
recursive
and
idempotent
methods/functions?
A method in stack is re-entrant allowing multiple concurrent invocations that do not interfere with each other. A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from
many sorts of algorithms. Allrecursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server.
When an obj is passed through a function, one can set the properties but cannot set a new memory location?
Ans) It is because when u pass an object the address value is passed and stored in some new address . like if address 1234 is passed , it is stored in 4567 location. So if u change in the value of an object it will take the address from 4567 and do 1234.setXXX(). If u set the object to null it will set 4567=null.
Thread?
In Java, thread means two different things: An instance of class java.lang.Thread. A thread of execution: An instance of Thread is justan object.
Like any other object in Java, it has variables and methods, and lives and dies on the heap. But a thread of execution is an individual process (a lightweight process) that has its own call stack. In Java, there is one thread per call stackor, to think of it in reverse, one call stack per thread. Even if you dont create any new threads in your program, threads are back there running. The main() method, that starts the whole ball rolling, runs in one thread, called (surprisingly) the main thread. If you looked at the main call stack (and you can, any time you get a stack trace from something that happens after main begins, but not within another thread), youd see that main() is the first method on the stack the method at the bottom. But as soon as you create a new thread, a new stack materializes and methods called from that thread run in a call stack thats separate from the main() call stack.
3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes. 4. Threads have almost no overhead; processes have considerable overhead. 5. New threads are easily created; new processes require duplication of the parent process. 6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes. 7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process do not affect child processes.
Programs that need to respond to user-initiated events can set up service routines to handle the events without having to insert code in the main routine to look for these events. Threads provide a high degree of control. Imagine launching a complex computation that occasionally takes longer than is satisfactory. A watchdog thread can be activated that will kill the computation if it becomes costly, perhaps in favor of an alternate, approximate solution. Note that sequential programs must muddy the computation with termination code, whereas, a Java program can use thread control to non-intrusively supervise any operation. Threaded applications exploit parallelism. A computer with multiple CPUs can literally execute multiple threads on different functional units without having to simulating multi-tasking (time sharing). On some computers, one CPU handles the display while another handles computations or database accesses, thus, providing extremely fast user interface response times.
{ //the code that has to be executed in a separate new thread goes here } public static void main(String [] args) { NewThread c = new NewThread(); c.start(); } } 2) Implements the Runnable interface. The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created. e.g. class public class NewThread implements Runnable{ public void run(){ // the code that has to be executed in a separate new thread goes here } public static void main(String [] args){ NewThread c = new NewThread(); Thread t = new Thread(c); t.start(); } }
method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g. public void synchronized method(){} public void synchronized staticmethod(){} public void myMethod(){ synchronized (this) { // synchronized keyword on block of code } }
What
is
the
difference
when
the
synchronized
notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. highest priority thread will run first. The
What happens if a start method is not invoked and the run method is directly invoked?
If a thread has been instantiated but not started its said to be in new state. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread.
If code is running a thread, creates a new thread what will be the initial priority of the newly created thread?
When a code running in a thread creates a new thread object , the priority of the new thread is set equal to the priority of the thread which has created it.
background,these not used to run the application code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to complete their execution if all user threads have completed their execution. To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a user thread use isDaemon() method. Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution.
Can
class
have
both
Synchronized
and
non-
synchronized methods?
Yes a class can have both synchronized and non-synchronized methods.
If a class has a synchronised method and nonsynchronised method, can multiple threads execute the non-synchronised methods?
Yes. If a class has a synchronised and non-synchronised methods, multiple threads can access the non-synchronised methods.
Can a thread call multiple synchronized methods on the object of which it hold the lock?
Yes. Once a thread acquires a lock in some object, it may call any other synchronized method of that same object using the lock that it already holds.
Can two threads call two different static synchronized methods of the same class?
No. The static synchronized methods of the same class always block each other as only one lock per class exists. So no two static synchronized methods can execute at the same time.
What is a better way of creating multithreaded application? Extending Thread class or implementing Runnable?
If a class is made to extend the thread class to have a multithreaded application then this subclass of Thread cant extend any other class and the required application will have to be added to this class as it cant be inherited from any other class. If a class is made to implement Runnable interface, then the class can extend other class or implement other interface.
What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and
these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
Can the start() method of the Thread class be overridden? If yes should it be overridden?
Yes the start() method can be overridden. But it should not be overridden as its implementation in thread class has the code to create a new executable thread and is specialised.
What are the methods of the thread class used to schedule the threads?
public static void sleep(long millis) throws InterruptedException public static void yield() public final void join() throws InterruptedException public final void setPriority(int priority) public final void wait() throws InterruptedException public final void notify() public final void notifyAll()
List the methods which when called the thread does not release the locks held?
notify() join() sleep() yield()
List the methods which when called on the object the thread releases the locks held on that object?
wait()
public class ThreadLocal { public Object get(); public void set(Object newValue); public Object initialValue(); } Implementation of ThreadLocal public class ConnectionDispenser { private static class ThreadLocalConnection extends ThreadLocal { public Object initialValue() { return DriverManager.getConnection(ConfigurationSingleton.getDbUrl()); } } private static ThreadLocalConnection conn = new
extend any other type, so application-specific code would have to be added to it rather than inherited. Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.
start() method, but in the latter case the code is actually executed in a new thread.
When you will synchronize a piece of your code?When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
What is deadlock?When two threads are waiting each other and cant precede the program is said to be deadlock.
synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
threads. Non-final fields should be declared private and encapsulated with synchronization. Rather than return references to internal object fields, create an independent copy that has no relation to the original, known as a deep copy. A deep copy of an object duplicates the content and state of the original object and all its constituent fields in such a way that none of its properties refer to instances in the original at any level. These measures will help prevent uncontrolled access to the internal state of objects, but you must also ensure synchronization techniques are applied in a robust, consistent manner that will not cause deadlock or race conditions. It is generally better to use synchronized blocks than synchronized methods for performance reasons. Limit the extent of synchronized blocks and ensure they all use the same object monitor.
What is Serialization?
Serializable is a marker interface. When an object has to be transferred over a network ( typically through rmi or EJB) or persist the state of an object to a file, the object Class needs to implement Serializable interface. Implementing this interface will allow the object converted into bytestream and transfer over a network.
Need of Serialization?
To send state of one or more objects state over the network through a socket. To save the state of an object in a file. An objects state needs to be manipulated as a stream of bytes.
Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
To serialize an array or a collection all the members of it must be serializable. True /False?
True
If a class is serializable but its superclass in not , what will be the state of the instance variables inherited from super class after deserialization?
The values of the instance variables inherited from superclass will be reset to the values they were given during the original construction of the object as the non-serializable super-class constructor will run. E.g.
public class ChildSerializable extends ParentNonSerializable implements Serializable { private static final long serialVersionUID = 1L; String color; ChildSerializable() { this.noOfWheels = 8; this.color = "blue"; } } public class SubSerialSuperNotSerial { public static void main(String [] args) { ChildSerializable c = new ChildSerializable(); System.out.println("Before : - " + c.noOfWheels + " "+ c.color); try { FileOutputStream fs = new FileOutputStream("superNotSerail.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(c); os.close();
} catch (Exception e) { e.printStackTrace(); } try { FileInputStream fis = new FileInputStream("superNotSerail.ser"); ObjectInputStream ois = new ObjectInputStream(fis); c = (ChildSerializable) ois.readObject(); ois.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("After :- " + c.noOfWheels + " "+ c.color); }} Result on executing above code Before : - 8 blue After :- 4 blue The instance variable noOfWheels is inherited from superclass which is not serializable. Therefore while restoring it the non-serializable superclass constructor runs and its value is set to 8 and is not same as the value saved during serialization which is 4.
Use of serialVersionUID?
During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the
secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid. So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown. Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:
Add fields Change a field from static to non-static Change a field from transient to non-transient Add classes to the object tree
Delete fields Change class hierarchy Change non-static to static Change non-transient to transient Change type of a primitive field
So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used . The only way to get rid of the exception is to recompile and deploy the application If we explicitly metion the suid using the statement: private final static long serialVersionUID = <integer value> again.
then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.
Are
the
static
variables
saved
as
the
part
of
serialization?
No. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object Result on executing above code Before : - 8 blue After :- 4 blue The instance variable noOfWheels is inherited from superclass which is not serializable. Therefore while restoring it the non-serializable superclass constructor runs and its value is set to 8 and is not same as the value saved during serialization which is 4.
What are the different ways to make an object eligible for Garbage Collection when it is no longer needed?
1. Set all available object references to null once the purpose of creating the object is served : public class GarbageCollnTest1 { public static void main (String [] args){ String str = "Set the object ref to null"; //String object referenced by variable str is not eligible for GC yet str = null; /*String object referenced by variable str becomes eligible for GC */ } } 2. Make the reference variable to refer to another object : Decouple the reference variable from the object and set it refer to another object, so the object which it was referring to before reassigning is eligible for Garbage Collection. publc class GarbageCollnTest2 { public static void main(String [] args){ String str1 = "Garbage collected after use"; String str2 = "Another String"; System.out.println(str1); //String object referred by str1 is not eligible for GC yet str1 = str2; /* Now the str1 variable referes to the String object "Another String" and the object "Garbage collected after use" is not referred by any variable and hence is eligible for GC */
} } 3) Creating Islands of Isolation : If you have two instance reference variables which are referring to the instances of the same class, and these two reference variables refer to each other and the objects referred by these reference variables do not have any other valid reference then these two objects are said to form an Island of Isolation and are eligible for Garbage Collection. public class GCTest3 { GCTest3 g; public static void main(String [] str){ GCTest3 gc1 = new GCTest3(); GCTest3 gc2 = new GCTest3(); gc1.g = gc2; //gc1 refers to gc2 gc2.g = gc1; //gc2 refers to gc1 gc1 = null; gc2 = null; //gc1 and gc2 refer to each other and have no other valid //references //gc1 and gc2 form Island of Isolation //gc1 and gc2 are eligible for Garbage collection here } }
No. The Garbage Collection can not be forced, though there are few ways by which it can be requested there is no guarantee that these requests will be taken care of by JVM.
If an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this method the object becomes accessible by a live thread of execution and is not garbage collected. Later at some point the same object becomes eligible for Garbage collection, will the finalize() method be called again?
No
How many times does the garbage collector calls the finalize() method for an object?
Only once.
About Exceptions
Difference between Error and Exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you cant repair them at runtime. Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an
exception (probably by giving user a feedback for entering proper values etc.)
Checked exceptions?
Checked exception is those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions. Checked exception are the exceptions which forces the programmer to catch them explicitly in try-catch block. It is a subClass of Exception. Example: IOException.
the responsibility of the method to deal with its own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller 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 throughout the java libraries we use.
Throw keyword?
Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application. The exception thrown should be subclass of Throwable. public void parent(){ try{ child(); }catch(MyCustomException e){ } } public void child{ String iAmMandatory=null; if(iAmMandatory == null){ throw (new MyCustomException("Throwing exception using throw keyword"); } }
Throws keyword?
If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the throws clause at the function declaration. public void parent(){ try{ child(); }catch(MyCustomException e){ } } public void child throws MyCustomException{ //put some logic so that the exception occurs. }
Once the control switches to the catch block does it return back to the try block to execute the balance code?
No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).
Where is the clean up code like release of resources is put in try-catch-finally block and why?
The code is put in a finally block because irrespective of try or catch block execution the control will flow to finally block. Typically finally block contains release of connections, closing of result set etc.
Is it valid to place some code in between try the catch/finally block that follows it?
No. There should not be any line of code present between the try and the catch/finally block. e.g. The following code is wrong. try{} String str = ABC; System.out.println(str = +str); catch(Exception e){}
What happens if the exception is never caught and throws down the method stack?
If the exception is not caught by any of the method in the methods stack till you get to the main() method, the main method throws that exception and the JVM halts its execution.
How do you get the descriptive information about the Exception occurred during the program execution?
All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred. It prints the most recently entered method first and continues down, printing the name of each method as it works its way down the call stack from the top.
Can you catch more than one exceptions in a single catch block?
Ans)Yes. If the exception class specified in the catch clause has subclasses, any exception object that is a subclass of the specified Exception class will be caught by that single catch block. E.g.. try { // Some code here that can throw an IOException } catch (IOException e) { e.printStackTrace(); } The catch block above will catch IOException and all its subclasses e.g. FileNotFoundException etc.
Exception matching?
Exception matching is the process by which the the jvm finds out the matching catch block for the exception thrown from the list of catch blocks. When an exception is thrown, Java will try to find by looking at the available catch clauses in the top down manner. If it doesn't find one, it will search for a handler for a supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack. This process is called exception matching.
What happens if the handlers for the most specific exceptions is placed above the more general exceptions handler?
Compilation fails. The catch block for handling the most specific exceptions must always be placed above the catch block written to handle the more general exceptions. e.g. The code below will not compile. 1 try { // code that can throw IOException or its subtypes } catch (IOException e) { // handles IOExceptions and its subtypes } catch (FileNotFoundException ex) { // handle FileNotFoundException only } The code below will compile successfully :try { // code that can throw IOException or its subtypes } catch (FileNotFoundException ex) { // handles IOExceptions and its subtypes } catch (IOException e){ // handle FileNotFoundException only }
try{ //code that may throw the FileNotFoundException }catch(FileNotFound eFnf){ //no code to handle the FileNotFound exception }
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. Consider if NoClassDefFoundError occurs which is something like java.lang.NoClassDefFoundError src/com/TestClass does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.
StackOverflowError?
The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your application/code has ran out of the memory. It may occur in case of recursive methods or a large amount of data is fetched from the server and stored in some object. This error is generated by JVM. e.g. void swap(){ swap(); }
What happens if an uncaught exception is thrown from during the execution of the finalize() method of an object?
The exception will be ignored and the garbage collection (finalization) of that object terminates
About Collections
What are the classes implementing List interface?
There are three classes that implement List interface: 1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe. 2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block. 3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.
Arraylist
arraylist-in-java-tutorial.html)
v/s
Vector
(http://javarevisited.blogspot.com/2011/05/example-of-
Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe. Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
Arraylist are not synchronized but if you want to make it synchronize then you can do like this List list = Collections.synchronizedList(new ArrayList(...)); While are synchronized. Default increment capacity of Arraylist is 50% while that of Vector is 100% i.e. Suppose you have a Arraylist of 10 objects & if 11th object is added then size of Arraylist will be increased to 15 but in the case of Vector it would be 20. Vectors
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation. Note that these implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set: List list = Collections.synchronizedList(new LinkedList(...)); List list = Collections.synchronizedList(new ArrayList(...)); In List, ArrayList is faster because it is unsynchronized while vector is synchronized. In Map, HashMap is faster because it is unsynchronized while Hahtable is synchronized.
If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?
It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.
If accessing through iterator is slow then why do we need it and when to use it?
For loop does not allow the updation in the array (add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.
I have 100 elements in the array list. i want to delete from 50 to 100 position how can i do it .please write the code ?
Use removeRange method from ArrayList Ex: al.removeRange(50,101); 50 is include in deletion and 101 is excluded
An Employee class is present and its objects are added in an arraylist. Now I want the list to be sorted on the basis of the employeeId of Employee class. What are the steps?
1) Implement Comparable interface for the Employee class and override the compareTo ( Object obj) method in which compare the employeeID 2) Now call Collections.sort() method and pass list as an argument. Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method . 2) Call Collections.sort() on the list and pass comparator as an argument.
Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();
It is preferred because: If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that. The most important one If a function is declared such that it takes list. E.g void showDetails(List list);When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible.
I need to use a collection object in my application which can insert/delete objects at any placed and can
retrieve
any
particular
positioned
object
in
the
collection? Note: I am not using Threads in my class so dont consider about synchronization.?
If you need in a key/value pair then for your requirements HashMap is best. If you need just an list which you can use to retrieve values using index means ArrayList is best. All the collections are best complexity for solving their own nature depends on the application requirement.
2. HashMap does not guarantee that the order of the map will remain constant over time. 3. HashMap is non synchronized whereas Hashtable is synchronized. 4. Iterator in the HashMap is fail-fast while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. 1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released. 2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception wjavascript:void(0)ill be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown. 3)Structurally modification means deleting or inserting element which could effectively change the structure of map. HashMap can be synchronized by Map m = Collections.synchronizeMap(hashMap);
Is it better to have a hashmap with large number of records or n number of small hashmaps?
It depends on the different scenario one is working on:
1) If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map. 2) If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.
ConcurrentHashMap,Collections.synchronizedMap,HashTable.
What is identityHashMap?
Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
reverseOrder(). Then, pass the reverse Comparator to the sort() method. List list = new ArrayList(); Comparator comp = Collections.reverseOrder(); Collections.sort(list, comp)
Memory leak?
A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.
Consider a scenario in which the admin want to sure that if some one has written System.exit() at some part of application then before system shutdown all the resources should be released. How is it possible?
This is possible
In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code.
Reference sites:
http://coffeewithcode.com/2011/07/13/java-interview-question-vii/
http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm http://www.techartifact.com/blogs/2011/07/factory-method-pattern-in-java.html
Step 1: Provide a default Private constructor Step 2: Create a Method for getting the reference to the Singleton Object Step 3: Make the Access method Synchronized to prevent Thread Problems. Step 4: cloning
class SingletonClass { private static SingletonClass singletonObject; /** A private Constructor prevents any other class from instantiating. */ private SingletonClass() { // } public static synchronized SingletonClass getSingletonObject() { Optional Code
if (singletonObject == null) { singletonObject = new SingletonClass(); } return singletonObject; } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } } public class SingletonObjectDemo { public static void main(String args[]) { // SingletonClass obj = new SingletonClass(); //Compilation error not allowed SingletonClass obj = SingletonClass.getSingletonObject(); // Your Business Logic System.out.println("Singleton object obtained"); } }
How do you prevent for creating another instance of Singleton using reflection?
Open to all. In my opinion throwing exception from constructor is an option.
data passed. Here in this article we will understand how we can create an Factory Pattern in Java.
} }// End of class This is a simple class Person having methods for name and gender. Now, we will have two sub-classes, Male and Female which will print the welcome message on the screen. public class Male extends Person { public Male(String fullName) { System.out.println("Hello Mr. "+fullName); } }// End of class
Also, the class Female public class Female extends Person { public Female(String fullNname) { System.out.println("Hello Ms. "+fullNname); } }// End of class Now, we have to create a client, or a SalutationFactory which will return the welcome message depending on the data provided. public class SalutationFactory { public static void main(String args[]) { SalutationFactory factory = new SalutationFactory(); factory.getPerson(args[0], args[1]); }
public Person getPerson(String name, String gender) { if (gender.equals("M")) return new Male(name); else if(gender.equals("F")) return new Female(name); else return null; } }// End of class
The different parts of computer are, say Monitor, RAM and Processor. The different types of computers are PC, Workstation and Server. So, here we have an abstract base class Computer. package creational.abstractfactory; public abstract class Computer { /** * Abstract method, returns the Parts ideal for Server * @return Parts */ public abstract Parts getRAM(); /** * Abstract method, returns the Parts ideal for Workstation * @return Parts */ public abstract Parts getProcessor(); /** * Abstract method, returns the Parts ideal for * PC * @return Parts */ public abstract Parts getMonitor(); }// End of class This class, as you can see, has three methods all returning different parts of computer. They all return a method called Parts. The specification of Parts will be different for different types of computers. Lets have a look at the class Parts. package creational.abstractfactory; public class Parts { /** * specification of Part of Computer, String
*/ public String specification; /** * Constructor sets the name of OS * @param specification of Part of Computer */ public Parts(String specification) { this.specification = specification; } /** * Returns the name of the part of Computer * @return specification of Part of Computer, String */ public String getSpecification() { return specification; } }// End of class And now lets go to the sub-classes of Computer. They are PC, Workstation and Server. package creational.abstractfactory; public class PC extends Computer { /** * Method over-ridden from Computer, returns the Parts ideal for * Server * @return Parts */ public Parts getRAM() { return new Parts("512 MB"); } /**
* Method over-ridden from Computer, returns the Parts ideal for * Workstation * @return Parts */ public Parts getProcessor() { return new Parts("Celeron"); } /** * Method over-ridden from Computer, returns the Parts ideal for * PC * @return Parts */ public Parts getMonitor() { return new Parts("15 inches"); } }// End of class
creational.abstractfactory;
* Method over-ridden from Computer, returns the Parts ideal for * * */ public return } /** Parts new getRAM() Parts("1 { GB"); @return Server Parts
* Method over-ridden from Computer, returns the Parts ideal for * * */ public return } /** * Method over-ridden from Computer, returns the Parts ideal for * * */ public return } }// End of class package creational.abstractfactory; public class Server extends Computer{ /** * Method over-ridden from Computer, returns the Parts ideal for * * */ public return } /** * Method over-ridden from Computer, returns the Parts ideal for * * @return Workstation Parts Parts new getRAM() Parts("4 { GB"); @return Server Parts Parts new getMonitor() Parts("19 { inches"); @return PC Parts Parts new getProcessor() Parts("Intel P { 3"); @return Workstation Parts
*/ public return } /** * Method over-ridden from Computer, returns the Parts ideal for * * */ public return Parts new getMonitor() Parts("17 { inches"); @return PC Parts Parts new getProcessor() Parts("Intel P { 4");
} }// End of class Now lets have a look at the Abstract factory which returns a factory Computer. We call the class ComputerType. package creational.abstractfactory; /** * * * */ public class ComputerType { private Computer comp; public static void main(String[] args) { ComputerType type = new ComputerType(); Computer computer = type.getComputer("Server"); System.out.println("Monitor: "+computer.getMonitor().getSpecification()); System.out.println("RAM: "+computer.getRAM().getSpecification()); System.out.println("Processor: "+computer.getProcessor().getSpecification()); This is of the computer the abstract factory types which of returns one three computers.
} /** * * * @param computerType String, PC / Workstation / Server * @return Computer */ public Computer getComputer(String computerType) { if (computerType.equals("PC")) comp else comp else comp = new Server(); return comp; } }// End of class Running this class gives the output as this: Monitor: RAM: Processor: Intel P 4. 17 4 inches GB = = new new PC(); Workstation(); if(computerType.equals("Workstation")) if(computerType.equals("Server")) Returns a computer for a type
Base Controller :
Provides a centralized controller for managing the handling of requests.
Session Facade :
Encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.