Pages

Showing posts with label Java Interview questions. Show all posts
Showing posts with label Java Interview questions. Show all posts

Monday, 28 January 2013

Multithreading Interview Questions

  1. The static class lock is independent of the object lock
  2. wait is called from synchronized context only while sleep can be called without synchronized block. see Why wait and notify needs to call from synchronized method for more detail.

    2) wait is called on Object while sleep is called on Thread. see Why wait and notify are defined in object class instead of Thread.

    3) waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awaken by calling notify method.

    4) wait is normally done on condition, Thread wait until a condition is true while sleep is just to put your thread on sleep.

    5) wait release lock on object while waiting while sleep doesn’t release lock while waiting
  3. Major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee  that current thread will pause or stop but it guarantee that CPU will be relinquish by current Thread as a result of call to Thread.yield() method in java.

    Sleep method in Java has two variants one which takes millisecond as sleeping time while other which takes both mill and nano second for sleeping duration.

    sleep(long millis)
    or
    sleep(long millis,int nanos)
  4. Yield will send the thread from the Running state to the Ready to run state. This is the place where the thread first comes and waits after the call on the start method. Then the scheduler picks up the thread and allows it to run
  5. 1) Thread.sleep() method is used to pause the execution, relinquish the CPU and return it to thread scheduler.

    2) Thread.sleep() method is a static method and always puts current thread on sleep.

    3) Java has two variants of sleep method in Thread class one with one argument which takes milliseconds as duration for sleep and other method with two arguments one is millisecond and other is nanosecond.

    4) Unlike wait() method in Java, sleep() method of Thread class doesn't relinquish the lock it has acquired.

    5) sleep() method throws Interrupted Exception if another thread interrupt a sleeping thread in java.

    6) With sleep() in Java its not guaranteed that when sleeping thread woke up it will definitely get CPU, instead it will go to Runnable state and fight for CPU with other thread.

    7) There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put current thread into Sleeping state and not thread "t".

Basic OOP interview questions

Basic OOP Questions  :
  1. http://stackoverflow.com/questions/1031273/what-is-polymorphism
The abiltiy 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 (overloading) and runtime polymorphism (overriding).
 
When you override methods, JVM determines the proper methods to call at the program’s 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 
 
Shape, rectangle and circle is an example of polymorphism
  1. What is encapsulation ? Combining the data and the methods to act on the data and putting them in a class together
  2. COMPOSITION
    Imagine a software firm that is composed of different Business Units (or departments) like Storage BU, Networking BU. Automobile BU. The life time of these Business Units is governed by the lifetime of the organization. In other words, these Business Units cannot exist independently without the firm. This is COMPOSITION. (ie the firm is COMPOSED OF business units)
    ASSOCIATION
    The software firm may have external caterers serving food to the employees. These caterers are NOT PART OF the firm. However, they are ASSOCIATED with the firm. The caterers can exist even if our software firm is closed down. They may serve another firm! Thus the lifetime of caterers is not governed by the lifetime of the software firm. This is typical ASSOCIATION
    AGGREGATION
    Consider a Car manufacturing unit. We can think of Car as a whole entity and Car Wheel as part of the Car. (at this point, it may look like composition..hold on) The wheel can be created weeks ahead of time, and it can sit in a warehouse before being placed on a car during assembly. In this example, the Wheel class's instance clearly lives independently of the Car class's instance. Thus, unlike composition, in aggregation, life cycles of the objects involved are not tightly coupled.
  3. Tip to remember : Composition RBS, association caterer, aggregation car
  4. IS A relationship means you inherit and extend the functionality of the base class.
    HAS A relationship means the class is using another class, so it has it as a member
  5. Composition is a specific case of aggregation
  6. Does java support pass by value or by reference ? Java supports plain pass by value but the object reference it passes will always be the references. Hence manipulations on the objects will always work.



Java Keywords :
  1. What is the volatile keyword in Java ?  When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it’s updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn’t know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory
  2. ThreadLocal variables
    If you want to maintain a single instance of a variable for all instances of a class, you will use static-class member variables to do it. If you want to maintain an instance of a variable on a per-thread basis, you'll use thread-local variables. ThreadLocal variables are different from normal variables in that each thread has its own individually initialized instance of the variable, which it accesses via get() or set() methods.
    Let's say you're developing a multithreaded code tracer whose goal is to uniquely identify each thread's path through your code. The challenge is that you need to coordinate multiple methods in multiple classes across multiple threads. Without ThreadLocal, this would be a complex problem. When a thread started executing, it would need to generate a unique token to identify it in the tracer and then pass that unique token to each method in the trace.
    With ThreadLocal, things are simpler. The thread initializes the thread-local variable at the start of execution and then accesses it from each method in each class, with assurance that the variable will only host trace information for the currently executing thread. When it's done executing, the thread can pass its thread-specific trace to a management object responsible for maintaining all traces.
    Using ThreadLocal makes sense when you need to store variable instances on a per-thread basis.

  3. I estimate that roughly half of all Java developers know that the Java language includes the keyword volatile. Of those, only about 10 percent know what it means, and even fewer know how to use it effectively. In short, identifying a variable with the volatile keyword means that the variable's value will be modified by different threads. To fully understand what the volatile keyword does, it's first helpful to understand how threads treat non-volatile variables.
    In order to enhance performance, the Java language specification permits the JRE to maintain a local copy of a variable in each thread that references it. You could consider these "thread-local" copies of variables to be similar to a cache, helping the thread avoid checking main memory each time it needs to access the variable's value.
    But consider what happens in the following scenario: two threads start and the first reads variable A as 5 and the second reads variable A as 10. If variable A has changed from 5 to 10, then the first thread will not be aware of the change, so it will have the wrong value for A. If variable A were marked as being volatile, however, then any time a thread read the value of A, it would refer back to the master copy of A and read its current value.
    If the variables in your applications are not going to change, then a thread-local cache makes sense. Otherwise, it's very helpful to know what the volatile keyword can do for you.
  4. http://www.ibm.com/developerworks/java/library/j-5things15/index.html
  5. My understanding : all threads have local copy of the variables. to give them a global copy, use volatile. How is thread local different from normal thread variables. They are accessible from all the functions which are being called from the thread.
  6.  reading a volatile variable is synchronized and writing to a volatile variable is synchronized, but non-atomic operations are not.
  7.  What is a transient variable?
    Ans) If some of the properties of a class are not required to be serialized then the varaibles are marked as transient. When an object is deserialized the transient variables retains the default value depending on the type of variable declared and hence lost its original value.
  8.  static variables/methods/why aren't non static variables accessible by static methods ?
  9.  
Garbage Collection :
  1. http://www.quora.com/How-does-garbage-collection-work-in-the-JVM
  2. http://java-questions.com/garbagecollection_interview_questions.html
  3. http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html
  4. What is a strong reference ?  Specifically, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection. As you don't want the garbage collector destroying objects you're working on
  5. A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself.
  6. Reference Queues : Once a WeakReference starts returning null, the object it pointed to has become garbage and the WeakReference object is pretty much useless. This generally means that some sort of cleanup is required; WeakHashMap, for example, has to remove such defunct entries to avoid holding onto an ever-increasing number of dead WeakReferences.
    The ReferenceQueue class makes it easy to keep track of dead references. If you pass a ReferenceQueue into a weak reference's constructor, the reference object will be automatically inserted into the reference queue when the object to which it pointed becomes garbage. You can then, at some regular interval, process the ReferenceQueue and perform whatever cleanup is needed for dead references
  7. Soft references are like weak references, however the object they refer to stick around for a while. What defines this while part ?
  8.  softly reachable objects are generally retained as long as memory is in plentiful supply.
  9. A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead. How is that different from WeakReference, though?
  10. The difference is in exactly when the enqueuing happens. WeakReferences are enqueued as soon as the object to which they point becomes weakly reachable. This is before finalization or garbage collection has actually happened; in theory the object could even be "resurrected" by an unorthodox finalize() method, but the WeakReference would remain dead. PhantomReferences are enqueued only when the object is physically removed from memory, and the get() method always returns null specifically to prevent you from being able to "resurrect" an almost-dead object.
  11. When a weak reference dies, the object enters the reference queue and using an unorthodox finalize method, that object can be got back.However, when a phantom referenced object dies, this kinda method is not going to work as a phantom reference doesn't even support the get method.
  12. Phantom references allow you to determine exactly when an object was removed from memory
  13. http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html
  14. What is island of isolation ?  an island of isolation is a group of objects that reference each other but they are not referenced by any active object in the application http://stackoverflow.com/questions/792831/island-of-isolation-of-garbage-collection
  15.  In brief, the GC can walk through the web of references from the known static and stack objects, and either
    • copy all objects found to a new memory pool, automatically leaving behind any "dead" objects (this is the "young generation" strategy), or
    • mark all objects found, so that once the whole web of references is walked traversed, it can delete all unmarked objects (this is the "old/tenured generation" strategy).
  16. What are the different ways to call Garbage Collector ? System.gc() and Runtime.getRuntime.gc()
  17. What is the purpose of overriding finalize() method?
    Ans) The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.
  18. Runtime.getRuntime().runFinalizersOnExit(boolean value)
Questions on the Main Method in Java  :
  1. 1. Main method must be declared public, static and void in Java otherwise JVM will not able to run Java program.

    2. JVM throws NoSuchMethodException:main if it doesn't find main method of predefined signature in class which is provided to Java command. E.g. if you run java Helloworld than JVM will search for public static void main String args[]) method in HelloWorld.class file.

    3. Main method is entry point for any Core Java program. Execution starts from main method.

    4. Main method is run by a special thread called "main" thread in Java. Your Java program will be running until your main thread is running or any non-daemon thread spawned from main method is running.

    5. When you see "Exception in Thread main” e.g.
    Exception in Thread main: Java.lang.NullPointerException it means Exception is thrown inside main thread.

    6. You can declare main method using varargs syntax from Java 1.5 onwards e.g.
    public static void main(String... args)

    7. Apart from static, void and public you can use final, synchronized and strictfp modifier in signature of main method in Java.

    8. Main method in Java can be overloaded like any other method in Java but JVM will only call main method with specified signature specified above.

    9. You can use throws clause in signature of main method and can throw any checked or unchecked Exception.

    10. Static initializer block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.


    http://java67.blogspot.com/2012/12/main-method-interview-questions-in-java-answers.html

SCJP Practice Questions
  1. http://stackoverflow.com/questions/5515050/scjp-question-to-figure-when-object-gets-garbage-collected?rq=1
  2. http://stackoverflow.com/questions/5801732/scjp-mock-question-how-many-objects-are-eligible-for-garbage-collection?rq=1
  3. sd
  4. sd

Collections :
  1. http://stackoverflow.com/questions/1440134/java-what-is-the-difference-between-implementing-comparable-and-comparator
  2. Comparable : an object can compare with itself
  3. Comparator : an object can compare two different objects. When the source code is not available and you have to compare client's code, then you use comparator
  4. LinkedList implements both the List and the Queue interfaces
 http://java-questions.com/keywords_interview_questions.html

Sunday, 27 January 2013

eBay interview questions

  1. http://www.vogella.com/articles/JavaDatastructures/article.html - practice the array implementation of hashmap. It will clear your generics concepts and gives the basic way a hashentry is created first
  2. http://docs.oracle.com/javase/6/docs/api/java/util/WeakHashMap.html
  3. http://stackoverflow.com/questions/34510/what-is-a-race-condition
  4. http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern - A singleton can implement an interface, hence, it can be a singleton implementation of an interface. However, an all static methods class cannot implement an interface
  5. Hashtable and collision resolving techniques : How is it done in java ?
  6. Heap implementation
  7. LCA
  8. Coins DP
  9. Eggs problem
  10. http://stackoverflow.com/questions/137783/expand-a-random-range-from-15-to-17
  11. http://www.regular-expressions.info/examples.html - you need to know all kinds of validations - date, email, IP and all kinds of regexes for that.

Why should you use Generics instead of Objects ?

http://stackoverflow.com/questions/5207115/java-generics-t-vs-object

What is the difference between the two ?

public Object doSomething(Object obj) {....}
public T doSomething(T t) {....}

compile time safety that that like works. If the Object version is ued, you won't be sure if the method always returns Foo. If it returns Bar, you'll have a ClassCastException, at runtime.

How would you design an object pool in java ?

Tuesday, 25 December 2012

Exception Handling Java

  1. http://stackoverflow.com/questions/2699580/difference-between-unchecked-exception-or-runtime-exception
  2. http://java-questions.com/Exceptions_interview_questions.html
  3. http://stackoverflow.com/questions/1457863/what-is-the-difference-between-noclassdeffounderror-and-classnotfoundexception
  4. ClassNotFoundException : this is an exception when a class is trying to load some other class using the forname method and findsystem class in the class loader. This is an error of reflection NoClassDefException : The class was there at compile time but is not there at runtime. This is an error and was not expected.
  5. Difference between throws and throw keyword
  6. http://javarevisited.blogspot.com/2012/02/difference-between-throw-and-throws-in.html
  7. http://stackoverflow.com/questions/7049623/how-to-create-checked-unchecked-custom-exceptions-in-java
  8. throws will be used in the function declaration with no error handling inside the function

Java Multithreading

  1. Study from SCJP
  2. Check question answer from http://java-questions.com/Threads_interview1_questions.html

Java Serialization

  1. http://javarevisited.blogspot.com/2011/04/top-10-java-serialization-interview.html
  2. http://www.javaworld.com/javaworld/jw-07-2000/jw-0714-flatten.html
  3. http://www.javaworld.com/community/node/2915
Serialization is Java's method of writing an object to a file and then reading it back. It is used for object persistence. You can implement the serialization interface and implement the write and the read classes. Static members belong to the class and not to the object and cannot be serialized. Hence, you use separate methods for them. If you have some members that you don't want to save during serialization, you should keep it as transient. Besides, if there are some transient properties in your object, then you should not write it directly. You should only write the non-transient and non-static properties separately.

  1. Object serializationallows an object to be transformed into a sequence of bytes that
    can later be re-created (deserialized) into the original object. After deserialization,
    the object has the same state as it had when it was serialized, barring any data
    members that were not serializable. This mechanism is generally known as persist-ence. Java provides this facility through the ObjectInputand ObjectOutputinterfaces,
    which allow the reading and writing of objects from and to streams. These two
    interfaces extend the DataInputand DataOutputinterfaces
  2. The ObjectOutputStreamclass and the ObjectInputStreamclass implement the
    ObjectOutputinterface and the ObjectInputinterface, respectively, providing meth-ods to write and read binary representation of objects as well as Java primitive val-ues.
  3. For example, in order to store objects in a file and thus provide persistent storage
    for objects, an ObjectOutputStreamcan be chained to a FileOutputStream:
    FileOutputStream outputFile = new FileOutputStream("obj-storage.dat");
    ObjectOutputStream outputStream = new ObjectOutputStream(outputFile);
    Objects can be written to the stream using the writeObject()method of the
    ObjectOutputStreamclass:
    ThewriteObject()method can be used to write anyobject to a stream, including
    strings and arrays, as long as the object implements the java.io.Serializableinter-face, which is a marker interface with no methods. The Stringclass, the primitive
    wrapper classes and all array types implement the Serializableinterface. A serial-izable object can be any compound object containing references to other objects,
    and all constituent objects that are serializable are serialized recursively when the
    compound object is written out. This is true even if there are cyclic references
    between the objects. Each object is written out only once during serialization. The
    following information is included when an object is serialized:
    • the class information needed to reconstruct the object.
  4. the values of all serializable non-transient and non-static members, including
    those that are inherited.
  5. Besides, an object is serializable if its constituent objects are all serializable.

What is the difference between .equals and ==

== checks for identity. That is whether the two objects are the same object and point to the same address in memory.

.equals() by default does the same thing, but can be overridden to perform different equality comparisons. (i.e. strings are considered equal if they have the same characters in the same order)

instanceof checks if an instance is an instance of a given class e.g.if ("hello" instanceof String)

To read Java Blogs

  1. http://www.javabeat.net/ - It has a lot of SCJP questions
  2. http://java-questions.com/ - It has a lot of Java interview questions with nice explanations

What is the difference between deep copying and shallow copying in Java ?

Java Notes : Objects

  1. Thejava.langpackage is indispensable when programming in Java. It is automat-ically imported into every source file at compile time. The package contains the
    Objectclass that is the superclass of all classes,
  2.  A class declaration, without the extendsclause, implicitly extends the Objectclass
  3. int hashCode()
    When storing objects in hash tables, this method can be used to get a hash
    value for an object. This value is guaranteed to be consistent during the execu-tion of the program. This method returns the memory address of the object as
    the default hash value of the object
  4. boolean equals(Object obj)
    Object reference and value equality are discussed together with the ==and !=
    operators (see Section 5.11, p. 191). The equals()method in the Objectclass
    returns trueonly if the two references compared denote the same object. The
    equals()method is usually overridden to provide the semantics of object value
    equality, as is the case for the wrapper classes and the Stringclass. For a
    detailed discussion of the equals()method
  5. final Class<?> getClass()
    Returns the runtime classof the object, which is represented by an object of the
    classjava.lang.Classat runtime
  6. protected Object clone() throws CloneNotSupportedException
    New objects that are exactly the same (i.e., have identical states) as the current
    object can be created by using the clone()method, i.e., primitive values and
    reference values are copied. This is called shallow copying. A class can override
    this method to provide its own notion of cloning. For example, cloning a com-posite object by recursively cloning the constituent objects is called deep copying.
    When overridden, the method in the subclass is usually declared publicto
    allow any client to clone objects of the class. If the overriding clone()method
    in the subclass relies on the clone()method in the Objectclass (i.e., a shallow
    copy), the subclass must implement the Cloneablemarker interface to indicate
    that its objects can be safely cloned. Otherwise, the clone()method in the
    Objectclass will throw a checked CloneNotSupportedException.
  7. String toString()
    If a subclass does not override this method, it returns a textual representation
    of the object, which has the following format:
    "<name of the class>@<hash code value of object>"
    Since the default hash value of an object is its memory address, this value is
    printed as a hexadecimal number, e.g., 3e25a5. This method is usually overrid-den and used for debugging purposes. The method call  Sys-tem.out.println(objRef)will implicitly convert its argument to a textual
    representation by calling the toString()method on the argument

Tuesday, 4 December 2012

Equality in Java

Equality. What does it mean for two objects to be equal? If we test equality with (a == b) where a and b are reference variables of the same type, we are testing whether they have the same identity: whether the references are equal. Typical clients would rather be able to test whether the data-type values (object state) are the same. Every Java type inherits the method equals() from Object. Java provides natural implementations both for standard types such as Integer, Double, and String and for more complicated types such as java.io.File and java.net.URL. When we define our own data types we need to override equals(). Java's convention is that equals() must be an equivalence relation:
  • Reflexive: x.equals(x) is true.
  • Symmetric: x.equals(y) is true if and only if y.equals(x) is true.
  • Transitive: if x.equals(y) and y.equals(z) are true, then so is x.equals(z).
In addition, it must take an Object as argument and satisfy the following properties.
  • Consistent: multiple invocations of x.equals(y) consistently return the same value, provided neither object is modified.
  • Not null: x.equals(null) returns false.
Adhering to these Java conventions can be tricky, as illustrated for Date.java and Transaction.java.

Shamelessly copied from : http://algs4.cs.princeton.edu/12oop/. This is just being used as notes for revision purposes.

Monday, 9 July 2012

Static members vs instance members

An instance member is a field or an instance method. These members belong to the instance of a class rather than to the class as a whole. Members which are not explicitly declared static in a class declaration are instance members.

Objects and Reference Variables


Shape rectangle, circle;
rectangle = new Shape();
Shape circle = new Shape();

Shape is class. How many objects and reference variable is created by the above code ?

Solution : Two objects and three reference variables are created. When a reference variable is created, it means a variable is created whether a reference value is assigned or not.

Rules to keep in mind when dealing with Java:
  1. Variables are not objects. Variables contain objects (or null) -- a particular object can be stored in zero or more variables simultaneously. This does not create new objects, see #3.
  2. Mutating an object mutates that object.
  3. Assigning (or passing) an object does not make a copy/clone/duplicate.

References :
  1. http://stackoverflow.com/questions/6499636/java-objects-reference-variables-and-the-garbage-collection-heap

Wednesday, 4 July 2012

How does HashMap work in Java ?

What makes good hash keys ?
Classes which are immutable and implement hashCode() and equals() sensibly, make good hash keys.


Important Points 

  •  if two objects are equal according to the equals() method, they must have the same hashCode()value (although the reverse is not generally true).
  • Under this default implementation, two references are equal only if they refer to the exact same object.
Why does our root object class need hashCode(), when its discriminating ability is entirely subsumed by that of equals()?

The hashCode() method exists purely for efficiency. The Java platform architects anticipated the importance of hash-based collection classes -- such as HashtableHashMap, and HashSet -- in typical Java applications, and comparing against many objects with equals() can be computationally expensive. Having every Java object support hashCode() allows for efficient storage and retrieval using hash-based collections.



The hashmap has a number of "buckets" which it uses to store key-value pairs in. Each bucket has a unique number - that's what identifies the bucket. When you put a key-value pair into the map, the hashmap will look at the hash code of the key, and store the pair in the bucket of which the identifier is the hash code of the key. For example: The hash code of the key is 235 -> the pair is stored in bucket number 235. (Note that one bucket can store more then one key-value pair).
When you lookup a value in the hashmap, by giving it a key, it will first look at the hash code of the key that you gave. The hashmap will then look into the corresponding bucket, and then it will compare the key that you gave with the keys of all pairs in the bucket, by comparing them with equals().
Now you can see how this is very efficient for looking up key-value pairs in a map: by the hash code of the key the hashmap immediately knows in which bucket to look, so that it only has to test against what's in that bucket.
Looking at the above mechanism, you can also see what requirements are necessary on thehashCode() and equals() methods of keys:
  • If two keys are the same (equals() returns true when you compare them), their hashCode()method must return the same number. If keys violate this, then keys that are equal might be stored in different buckets, and the hashmap would not be able to find key-value pairs (because it's going to look in the same bucket).
  • If two keys are different, then it doesn't matter if their hash codes are the same or not. They will be stored in the same bucket, but the hashmap will use equals() to tell them apart.













Reference :

What is the difference between creating a String using the new operator and String intern ?


String s1 = "abcde";

Creating a String in this way is called interning a String.  string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.



String s2 = new String("abcde");
String s3 = "abcde";



String object is an individual instance of the java.lang.String class. s2 will be a new String object.


Hence, 

(s1 == s2) is false
(s1 == s3) is true
(s1.equals(s2)) is true



Why is the String class immutable ? 
String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.


References :


public class StringConstruction {
static String str1 = "You cannot change me!"; // Interned
public static void main(String[] args) {
String emptyStr = new String(); // ""
System.out.println("emptyStr: \"" + emptyStr + "\"");
String str2 = "You cannot change me!"; // Interned
String str3 = "You cannot" + " change me!"; // Interned
String str4 = new String("You cannot change me!"); // New String object
String words = " change me!";
String str5 = "You cannot" + words; // New String object
System.out.println("str1 == str2: " + (str1 == str2)); // (1) true
System.out.println("str1.equals(str2): " + str1.equals(str2)); // (2) true
System.out.println("str1 == str3: " + (str1 == str3)); // (3) true
System.out.println("str1.equals(str3): " + str1.equals(str3)); // (4) true
System.out.println("str1 == str4: " + (str1 == str4)); // (5) false
System.out.println("str1.equals(str4): " + str1.equals(str4)); // (6) true
System.out.println("str1 == str5: " + (str1 == str5)); // (7) false
System.out.println("str1.equals(str5): " + str1.equals(str5)); // (8) true
System.out.println("str1 == Auxiliary.str1: " +
(str1 == Auxiliary.str1)); // (9) true
System.out.println("str1.equals(Auxiliary.str1): " +
str1.equals(Auxiliary.str1)); // (10) true
System.out.println("\"You cannot change me!\".length(): " +
"You cannot change me!".length());// (11) 21
}


Tuesday, 3 July 2012

Immutable vs Mutable Objects in Java - the question answer approach



  1. What is an immutable object ? 
An object is considered immutable if its state cannot change after it is constructed. 


     2.  What is happenning to immutable object myString in the example below ? 

	String myString = new String( "old String" );
	String myCache = myString;
	System.out.println( "equal: " + myString.equals( myCache ) );
	System.out.println( "same:  " + ( myString == myCache ) );

	myString = "not " + myString;
	System.out.println( "equal: " + myString.equals( myCache ) );
	System.out.println( "same:  " + ( myString == myCache ) );
Result : 
        equal: true
	same:  true
	equal: false
	same:  false
The contents of myString is not changing here. We are discarding the instance and changed our reference to a new one with new contents. 

     3.  How can you change the values of a variable ? 
  • You can always change the value of a variable by getting your variable to reference a new object. 
  • Sometimes you can change the value of a variable by keeping a reference to the same instance, but change the contents of the instance.
    4.  What are the uses of immutable objects ?

  • They can promote thread safety in your code 
  • You can share them around without being afraid that they will change without your knowledge 
  • They are great for caching and constants
    5.  How can we create a mutable class ? 
  • Make all fields private
  • Don't provide mutators
  • Ensure that methods can't be overridden by either making the class final (Strong Immutability) or making your methods final (Weak Immutability)
  • If a field isn't primitive or immutable, make a deep clone on the way in and the way out.
References :