Java Concepts

Substring:
Substring function of string has 2 versions:

  1. BeginIndex
  2. BeginIndex, endIndex++


String is immutable & calling substring creates a new string in the memory


If beginIndex is the length of the string then it will return emptyString and not IndexOutOfBoundException


IndexOutOfBound Exception only occurs when BeginIndex is -ve OR greater than startIndex OR greater than string length


Internal implementation
constructor(offset, count, value[]); //value is the original string


II) Contract between equals & hashCode
If 2 objects are equal then their hashCode should be equal.
If 2 objects are not equal than their hashCode can or cannot be equal






String:
Why String is immutable
Strings are created in a string pool. If anyone of them changes then it will change all others that are referring that string.
String s1 = "Test";
String s2 = "Test";


If we change any of the string then the change will be reflected in other. Now "Test" is created once in the pool and different variables point to it.


Usage & Security

  1. DB Connections, Files, etc are created as Strings. If they are allowed to be mutable then DB connection or files will be overwritten.
  2. Class load is immutable. If it can be changed then it will be easy to load any other class.


Will its hashCode be same?
Yes it will be same since the strings are immutable


Advantage:
Helps in thread safety.





What char array is better than string for storing password in java?

  1. Strings are immutable so if we encrypt/change it, it will create a new string.
  2. This way old string will still be placed in same memory location.
  3. It will be available till it is Garbage Collected or else it will be available for a long time in the pool.
  4. Also strings might appear easily in the logs with character array. Also their location can be easily identified.






Why Java doesn’t support multiple inheritance?
To have a cleaner design, less ambiguity, no need of typecasting, and no confusion in which constructor to call.






What is Error in Java?
If an application throws some error and it can’t be recovered and it can’t be caught. It is called as an Error.






What is an Exception?

  1. It is different from an error in the sense that it can be caught.
  2. It can be of 2 types: Checked and Unchecked.
  3. Checked exception includes: FileNotFound, ParseException.
  4. Unchecked exception includes: NullPointer, ArrayOutOfBounds.
try {
.
.
}
catch(Exception e)
{
}


OR
public void doSomething() throws Exception.






What is difference between hash map and hash table?
Hashtable is synchronized and hash map is not.
If you want to use synchronized hash map then use concurrenthashmap.






Java Interfaces:
It can be divided into 3 types:

  1. Set
  2. Map
  3. List


Set:

  1. It cannot contain duplicates.
  2. Inherit the properties of the collection.
  3. 3 types include: HashSet, LinkedHashSet, TreeSet
  4. HashSet has hash table implementation,
  5. treeset has red-black tree implementation
  6. Linked hashset: Linked list in value of the hashtable.
  7. It common functions include: size(), isEmpty(), add(Object), remove(Object), contains(Object), addAll, removeAll, Clear


List:

  1. It is inherit from collection
  2. It can contain duplicates.
  3. Provides positional access to the elements.
  4. Common Access functions include: get(i), add(i), add(i,e), contains(i), remove(i)
  5. Common Search functions include: indexOf(0), lastIndex(0)
  6. Its 2 types include: ArrayList(lookup is easy), LinkedList(Addition and deletion are easy)


Map:

  1. Cannot contain duplicates.
  2. It is implemented as key-value pairs.
  3. Basic operations: put(key, value), get(key), containsKey(object), containsValue(Object), size(), isEmpty(), clear()
  4. 3 types include: LinkedMap, HashMap, TreeMap(Balanced Tree implementation).


TreeMap:

  1. Key value pairs are stored in the tree form. Keys are stored in the sorted form. It is useful to find the elements in ascending order or to find the max element, sorting will be easier, finding parent is easier.
  2. Lookup will be O(logn), and insertion will be O(logn)
  3. TreeSet: There are only values. All the elements are stored in the sorted form on the values. It is basically tree data structure.


LinkedHashMap:

  1. The order of insertion is maintained. Lookup: O(n), insertion: O(1), Deletion O(n)
  2. LinkedHashSet: A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.
  3. Use this class instead of HashSet when you care about the iteration order.
    1. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.






Java advantages:

  1. Portability: Only one version of the code is useful on all the environments and platforms
  2. Class library: Java class library is available on any machine with a Java runtime system.         
  3. Byte Code: Doesn’t compile the source code to the machine code. It compiles it to the byte code. JRE interprets the machine code and executes it.
    1. Hence we need Java compiler to convert it to the Byte code.
    2. We need the JRE to convert the byte code to the m/c level.
  4. Security:
    1. No pointer arithmetic
    2. No array out of bounds – Array bounds checking.
    3. Garbage collection
    4. No illegal data conversion
    5. No jumping to bad address since the pointer arithmetic is absent.
    6. Interfaces and exceptions
    7. The byte code is placed in a separate file where the JRE could find it.
    8. If the program instantiate the object of a class, the class loader searches the CLASSPATH environment for the *.class file. The class file will contain the byte code and class definition for the file A.
    9. All linking is done dynamically.
  5. JRE will first search for the .class and then the public static void main method.
  6. Document comment:
    1. /** Doc comment */ : These comments are processed by the javadoc program  to generate the documentation of the source code.






Allocation:

  1. Nothing is allocated on stack. All java objects are allocated on heap.
  2. Because of garbage collection, storing of the object doesn’t cause the memory leakage issues.






Strings:

  1. Strings are pointers to the memory. They are objects. Could or couldn’t be null terminated.
  2. Constant in length.
  3. For variable length, use the StringBuffer
  4. Operators +, .length
  5. Int to a string : String.valueOf(4)
  6. String to an int Integer.parseInt(“5”);






Array:

  1. Objects that know the number and type of the elements.
  2. To allocate the array use the new operator.
  3. Array allocation will not allocate any memory and will not do any assignment.
  4. Creating multi-dimensional array: T[][]t = new T[10][5]
  5. ArrayIndexOutOfBoundsException: Runtime exception while accessing an undefined array element.
  6. NullPointerException: Assessing an array element that has not been assigned to an object






Other data:

  1. Constant in java: Static final int I;
  2. Break and continue statement might have a label.
  3. Objects are passed by reference and not value.
  4. Primitive types are passed by value
  5. Shallow comparision: if(a==b)
  6. Deep comparision(a.equals(b))
  7. S->method: dereference in C++. S.method(). Dereference automatically.
  8. Garbage collector de-allocated memory that is not in use anymore. Hence, the java object is either null or valid. There is no other state(invalid or stale)
  9. However the memory de-allocation doesn’t happen all the time. It happens at a scheduled time.
  10. Primitive data types: Boolean, int, byte, char, short, long, float, double.

You might also like:
Java String concepts
Immutable classes in Java
Remove duplicates from the array
Telephonic phone technical interview questions
Telephonic phone technical interview questions - Part 2
Serialization & Deserialization
Jersey Package Dependencies
Observable and Observer Interface
Servlet Filter
Servlet Client Request
Spring dependencies for Maven
Java String Operations

No comments:

Post a Comment

NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...