Java Interview Questions – Part 2

Java Interview Questions – Part 2

String is Immutable. (String Details with Example Here)

  1. What is meant by Immutable?
    In Java, Strings are treated as Objects. Immutable means once the object has been created it cannot be changed.
  2. What are the advantages of String being Immutable?
    • It helps in Multi-threading, We can be sure that no one will change the string
    • Reduction in Memory usage
  3. Two ways of Creating Strings:
    • String s1 = “StringValue”;
    • String S2 = new String(“StringValue2”);
  4. What is the difference between creating Strings?
    Consider an example,

    • We are creating 2 strings with S1 and S2,
    • String S1 = “Java”
    • String S2 = “Java”
    • This will create a single reference in string pool and S1 and S2 will point to that Reference
    • String S1 = new String(“Java”)
    • String S2 = new String(“Java”)
    • This will create two separate objects in string pool
    • String s1 = “Java”, String S2 = “Java”
    • String S1 = new String(“Java”), String S2 = new String(“Java”)
  5. Difference Between StringBuilder and StringBuffer:
    StringBuilder StringBuffer
    StringBuilder is mutable StringBuffer is mutable
    StringBuilder is unsynchronized StringBuffer is Synchronized
    StringBuilder is faster StringBuffer is slower when compared to StringBuilder

    NOTE: StringBuffer and StringBuilder does not Override equals() and hashcode()

  6. When to use String, StringBuffer and StringBuilder?
    If our string is not going change, We use String.
    If our string can change and accessed only from single thread, We can use StringBuilder.
    If our string can change and can be accessed from multiple threads, We can use StringBuffer.
  7. Difference between == and Equals()
    • == : Will check if the address of the values are same and NOT the values itself
    • Equals(): Will check if both the values are equals
    • Example:
      • String S1 = “Java”, String S2 = “Java”
        S1==S2 will be True
      • String S1 = new String(“Java”), String S2 = new String(“Java”)
        Here S1 == S2 will be false, But S1.equals(S2) will be true
  8. Important Points:
    • Strings are Thread Safe
    • String Pool is stored in Heap Memory

(For Detailed Example of Strings, StringBuffer and StringBuilder, Click Here)

Arrays:

  1. What is an Array?
    Arrays are objects in Java that store multiple Variables of Same Type
  2. Declaring an Array?
    int[] array1;
  3. Can we declare an Array without its Size?
    Consider, We are constructing and array without mentioning the Size,

    • int[] Array1 = new int[];
      This line will not get Compiled, As the size of array is required.
  4. How does array store the values in memory?
  5. How to declare array with values in single line?
    • int array1 = {4,5,6};
  6. Arrays Holding Objects?
    • A[][] a = {{new A(“value1”), new A(“value2”)}, {new A(“value3”), new A(“value4”)}}

 

 

Read More

Java Interview Questions Part – 1

.1. What is JVM?
Java Virtual Machine, which provides JRE in which byte codes can be executed.

2. What is JRE?
Java run time environment, which is implemented by JVM. This has minimum requirements for executing java byte code. Like supporting files, core classes etc.

3. What is JDK?
It is Java development kit, Which has JRE and developing tools.

4. What is JIT?
JIT is just in time compiler, which compiles the code at run time. Compiler is the one which translates programming code to object code. Machine understandable code

5. What is an object?
Object is the one which has state and behaviour

6. What is a class?
Class is a blueprint that describes the behaviour that object of its type supports

7. What is a method?
Collection of statements grouped together to perform an operation

8. Inheritance: When one class acquires the properties of another class, it is known as inheritance. It uses extends keyword. In java multiple inheritance is not possible. Once class and extend only one class

9. Encapsulation: Process of hiding irrelevant information to other part of the program in known as encapsulation

10. Abstraction: Process of proving relevant information to other part of the program is known as Abstraction

11. Polymorphism: Object taking different forms based on substances.
Method Overloading: When same method name is used more than one time in same class but with different argument it is knows as method Overloading
Method Overriding: Same method name with same arguments in base and subclass is known as method overriding

12. Can Main() be overloaded?
Yes

13. Static Method and Variables

  1. Static variables value is same for all instances of same class
  2. Static method belongs to the class and can be invoked without creating instance of the class
  3. Static method cannot have non-static data member.
  4. This and super cannot be used with static context

14. Class Modifiers

  1. Default:
    1. A class with no modifier is known as Default Modifier
    2. Package level access, can be seen only by classes within same package
  2. Public:
    1. Gives access to all classes from all packages.
    2. But if we need to import public class from another package, we still need to import it to use it.
  3. Private:
    1. Class level access, Can be used in a class where private member is declared.
    2. When extended we wont be able to inherit private member variable
    3. We can see private method/private member in subclass with the same name as Super class. But that don’t mean it is been overridden. That is just a method declared in sub-class.
  4. Protected:
    1. Protected member can be accessed by subclass even if the subclass is in different package (Through Inheritance)
    2. The difference between default and protected is, Default can be accessed in subclass but only within same package. But protected can be accessed by subclass even in different package.
  5. Final:
    1. Final key word can be applied for variables, methods and classes
    2. Variable marked as final cannot change its value.
    3. Final methods cannot be overridden
    4. Final class cannot be extended.
    5. When a final variable is not initialized a value at run time is known as blank final variable
    6. We can declare final method in subclass with same name but with different arguments
    7. We can initialize blank final variable using constructor
  6. Abstract:
    1. Abstract class can never be instantiated, it can only be extended
    2. Abstract class can have both abstract and non-abstract methods
    3. If one method is declared as abstract, the class should be declared as abstract
    4. One abstract class can extend another abstract class but doesn’t necessarily implement all methods
    5. A class cant be marked both as abstract and final. Why?
      1. Final classes cannot be extended, But abstract class can only be Inherited
      2. Methods cannot be both Final and private in abstract class, as both cannot be subclassed.

15. Interface:

  1. Interfaces are similar to class.
  2. Can have abstract methods, default methods and static methods.
  3. One interface can extend another interface and a class can implement interface not extend it
  4. Interface doesn’t have constructors
  5. All the methods in interfaces are abstract

16. Difference between Abstract class and Interface.

Abstract Class Interface
Can have constructor Cannot have constructor
Can have fields that are non-static, final All the fields are public static final
Can have methods with access specifiers like public, protected and private All methods are public

 As from Java 8, Interfaces can also have static and default methods which is not mandatory to be implemented by implementing class.

17. Stack Memory vs Heap Memory:

Stack Memory Heap Memory
Stack memory is static memory, allocated during compile time Heap Memory is dynamic memory allocated during Run time
Directly stored in memory so access to this memory is faster Accessing this memory is slower, and heap size  is limited by size of virtual memory
Local variables are stored in Stack Objects are stored in Heap

 18. Enum:

  1. Enum is a datatype that has contant values.
  2. We should use Enum when a variable needs to use one value from set of values
  3. Increases compile time checking and will help us to parse only valid constants
  4. Enum can have constructors but cannot invoke constructor directly. It is invoked automatically
  5. RULES:
    1. Enum can be declared as separate class or class member
    2. They should not be declared within a method

 

19. Casting

  1. Assigning one object to another or one datatype to another is known as casting
  2. With datatypes, Byte, Short, int, long,  float and double.
    1. Byte can be converted to short, int, long, float, double
    2. Short can be converted to int, long, float, double
    3. Int can be converted to long, float, double
    4. Long can be converted to float and double
    5. Float to double
  1. Upcasting:
    1. When a subclass object is assigned to superClass object is it known as Upcasting
    2. This is done automatically
    3. Example

Subclass s1 = new Subclass();
Superclass super1 = (Superclass) s1;
another way: Superclass super1 = new Subclass();

  1. Downcasting:
    1. When Superclass object is assigned to subclass it is known as Downcasting
    2. This has to be done manually
    3. Advantage is, it is used to get derived type using a reference to a base type
    4. Example:

Superclass s1 = new Subclass();
Subclass sub1 = (Subclass) s1;

  1. String and String.valueOf(): (Casting)
    1. String:
      1. This works when the object really is a string
      2. Object o = “String”
        String str = (String) o;
    2.  valueof():
      1.  Irrespective of object, this converts to string.
      2. Object o = 20;
        String s1 = String.valueof(o)
  2. Can a constructor be private?
    Yes.
  3. Can a Constructor be static or final or abstract. Why?
    1. Static – Belongs to a class and not a object. When we create an object, Constructor gets initialized
    2. Abstract –means method cannot have a body and can be used in subclass. But constructor are called when creating object (new keyword) so it needs to have body
    3. Final– A constructor internally is final, so we cannot declare constructor final again. Also if we make constructor final, we wont be able to create object of the class
    4. A constructor can be private and can be overloaded|
  4. Why is string non-primitive type?
    1. String is an object, array of characters
    2. Int, short, long, char, float and double all have fixed length memory. But string does not have different length
  5. Post Increment and Pre Increment:
    1. i++:
      1. Will increment the value of i in the first iteration but returns the original value of I.
    2. ++i:
      1. Will increment the value of I and returns the incremented value
  6. Bitwise Operators: (Example here)
    1. >>
      1. Division Operation
      2. 3 >> 6 : Output is: 0
      3. ‘-’ or ‘+’ sign is noted
    2. <<
      1. Multiplication Operation
      2. 2 << 5: this works as 2^5 –> Output is 64 (starts from 2^0+2^1 etc)
    3. >>>
      1. This is unsigned right shift
      2. Irrespective of sign it will always returns as positive
      3. Shifts 0 to the left most position irrespective of sign

Read More

Hibernate Interview Questions – Part 6

Hibernate Interview Questions – Part 6
Implementing Concurrency

What is Concurrency?
Each transaction is Hibernate is isolated from another transaction. So one transaction is not aware of another transaction. Which results in high possibility of a same record in database may be accessed by two or more transactions at same time. When multiple transactions access the same record in database and make changes concurrency issue occurs as data becomes inconsistent.

Concurrency Issues:
Dirty Read:
A transaction reads the data that has not been committed by another transaction

Lost Updates:
When two or more transactions try to access same row this issue occurs. Transactions overwrite the data on same row again and again leading to loss of data manipulation

Nonrepeatable Read:
Transaction reads the same row more than once and another transaction changes the data in the row between the successive reads of the transaction

Phantom Read:
A transaction reads a rowset more than once and another transaction inserts or deletes a row between the successive reads.


How to Control Concurrency Issues?
Setting transaction isolation levels
Implementing versioning
Implementing Locks


Setting Transaction Isolation Levels:
Read Uncommitted: 

In this level, a transaction can read the data modified by another transaction. But a transaction can read the data modified by another transaction even before the commit is made. Dirty Reads, Lost Updates, Nonrepeatable Read and Phantom read all issues occur at this level
Isolation Level – 1

Read Committed:
This is the default Isolation level in SQL database. In this level, When a transaction modifies a data other transactions will not be able to read the modified data. This prevents Dirty Reads but Lost Updates, Nonrepeatable Read and Phantom Read occurs at this level
Isolation Level – 2

Repeatable Read:
In this level, When a transaction is modifying a data no other transactions can Read or Update the data until the current transaction completes it process. At this level, Dirty Reads, Lost Updates and Nonrepeatable Read are prevented but Phantom Read may occur
Isolation Level – 4

Serializable:
In this level, When a transaction is modifying a data no other transaction can read, update, modify or insert data until the current transaction completes its process and commits.
Isolation Level – 8

1


Implementing Versioning:
In this method, version information is added to the persistent entities. Each entity has a version that represents the state of that entity. These version information are stored in a column in a database or timestamp that shows the time the data last modified.

How this Works?
When a record is modified in the database, hibernate increments the version number or timestamp of that record. So when another transaction tries to update the data, Hibernate will check for the version number or timestamp with the version or Timestamp of the transaction and throws exception it the transaction carries older version number


Implementing Locks:
We can implement the Locks when data’s are retrieved from database or when updating in database. Session interface provides lock() method.

LockMode.READ:
This acquires  lock when record is read from database

LockMode.UPGRADE:
This acquires database-level lock for persistent objects that are going to update.

LockMode.WRITE:
This acquires  lock when data is updated or inserted


 

Read More

Hibernate Interview Questions – Part 5

Hibernate Interview Questions – Part 5
Part 1, Part 2, Part 3, Part 4
Persistent Objects and Transactions

Different Object States in Hibernate?
Transient
Persistent
Detached


Transient:
An object created using new Operator is known in Transient State. This object is not associated with database.

Persistent:
When a Transient object with values are stored in database, then the object is said to be in Persistent State.

Detached State:
When an object is saved in the database and the hibernate session is closed, The object is said to be in Detached State


What is a Transaction?
Transaction is a sequence of operations performed.


Properties of Transactions?
Every transaction should have the following ACID properties,
Atomic : All the modifications to be performed or none to be performed
Consistency: All data should be consistent once the transaction has been completed
Isolation: Every transaction should be Isolated from another transaction
Durability: Data change in a system after the transaction is completed should remain permanent in the System.


States of Transactions:
Active:
when transaction is created and ready for execution.

Partially Committed:
When all the operations are performed but the transaction is not yet committed.

Failed:
When transaction is failed and cannot proceed further.

Aborted:
Transaction is failed and the operations of transactions are rolled back.

Committed:
Transaction is success and all the changes are committed and saved in database.

Terminated:
When transaction is completed successfully or when transaction is failed this state occurs.


Methods to Configure Transactions:
void begin():
Starts the transaction.

void commit():
Ends the work.

void rollback():
Reverse the changes.

boolean wasCommitted():
checks whether the transaction is committed or not.

boolean wasRolledBack():
checks if transaction is rolledback or not.


 

Read More

Hibernate Interview Questions – Part 4

Hibernate Interview Questions – Part 4

Hibernate Interview Questions (Part 1 – Part 2Part 3)

HQL – Hibernate Query Language:

Why HQL?
Most of the applications use Databases like Oracle, SQL etc. So when writing an application we use specific queries to access database. SQL Query might be different when compared with Oracle Query to access databases. So if database with which the application works changes, We need to change the queries accordingly to access the database. To overcome this we use HQL.


Query:
In hibernate we use,
Query query = session.createQuery();



Commonly used class in HQL:
From:
Query query = session.createQuery(FROM entityname);

SELECT:
Query query = session.createQuery(SELECT empid from Employee);

WHERE:
Query query = session.createQuery(FROM employee WHERE empname = ’employeename’);


How to Bind Parameters in Query?
We can bind parameters in HQL,
Query query = session.createQuery(“FROM employee WHERE ename= :ename”);
Now we have to pass value to that parameter,
String ename = “Alpha”;
query.setString(“ename”,ename); (for integers its query.setInteger)


How to use Iterator?
Query query = session.createQuery(“FROM employee”);
for(Iterator itr = query.iterate(); itr.hasNext(); ;){
Employee emp = (Employee) itr.next();
}


How can we use Native SQL Query in Hibernate?
SQLQuery Session.createSQLQuery(String queryString);


Criteria Queries:
Criteria Queries are used to check multiple conditions and add restrictions in a query.
To create Criteria Queries,
Criteria createCriteria


Adding Restrictions in a Query
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.eq(“columnname”, “condition”));


Criteria Queries with Restrictions:

.add(Restrictions.eq(Propertyname, object value) – This will compare the property name equals to the object value

.add(Restrictions.gt(Propertyname, object value) – This will return the results when the value of that property is greater than the specified value

.add(Restrictions.lt(Propertyname, object value) – This will return the results when the value of that property is lesser than the specified value

.add(Restrictions.ge(Propertyname, object value) – This will return the results when the value of that property is greater than or equal to the specified value

.add(Restrictions.le(Propertyname, object value) – This will return the results when the value of that property is lesser than or equal to the specified value

.add(Restrictions.like(Propertyname, object value) – This will compare the propertywith specified pattern

.add(Restrictions.between(Propertyname, object low, object high) – This method compares the property within the range of low and high

Example here


 

 

 

Read More