Thursday, September 25, 2014

JavaScript DOM & BOM questions and answers

1. How to add JavaScript to an HTML page?

Keyword:
<script> tag,
external js file

Answer:
a. Use <script> tag in the HTML page:
In the following example, a JavaScript function is placed between the <script> and </script> tags. The function is invoked when a button is clicked.
<!DOCTYPE html>
<html>
<head>
<script>
function showHello() {
    alert("hello");
}
</script>
</head>
<body>
    <button type="button" onclick="showHello()">Show Hello</button>
</body>
</html>

b. Use external JavaScript file:
To use an external script, put the name of the script file in the source (src) attribute of the <script> tag.
<!DOCTYPE html>
<html>
<head>
<script src="hello.js"></script>
</head>
<body>
    <button type="button" onclick="showHello()">Show Hello</button>
</body>
</html>

2. What is element, nodeList, attribute and namedNodeMap in HTML DOM?

Answer:
Element refers to an HTML element in the DOM. Element objects can have child nodes of type element nodes, text nodes, or comment nodes. Element objects implement the DOM Element interface and also the more basic Node interface.

NodeList is an array of elements. Items in a nodeList are accessed by index in either of two ways: list.item(1) or list[1].

Attribute refers to an HTML attribute. An attribute belongs to an HTML element.

NamedNodeMap is an unordered collection of an elements attribute nodes. Items in a namedNodeMap are accessed by name or index.

3. How to find HTML element in an HTML page using DOM API?

Keyword:
document.getElementById(),
Element.getElementsByTagName(),
document.getElementsByClassName()

Answer:
There are several ways to do this:
a. Find by id
Example: finds the element with id="add":
var e = document.getElementById("add");

b. Find by Tag Name
Example: finds the element with id="nav", and then finds all <p> elements inside "nav":
var navElement = document.getElementById("nav");
var elements = navElement.getElementsByTagName("p");

c. Find by Class Name
Example: find all HTML elements with class="category":
var elements = document.getElementsByClassName("category");

4. What is innerHTML?

Answer:
The innerHTML is a property of HTML element object. It refers to the HTML code and the text that occurs between the element's opening and closing tag.
We can use innerHTML either to retrieve the current content of the element or to insert new content into that element.

The following example uses innerHTML to insert new elements to a HTML page:
<!DOCTYPE html>
<html>
<head>
<script>
function updateDiv(){
    document.getElementById("div1").innerHTML = "<p>New title</p><p>New Text...</p>";
}
</script>
</head>
<body>
<div id="div1">Default Text</div>
    <button type="button" onclick="updateDiv()">Update</button>
</body>
</html>

5. What is BOM?

Keyword:
Browser Object Model,
window, navigator, location, document, history, screen, frames collection

Answer:
The Browser Object Model (BOM) is the part of JavaScript that allows JavaScript to interface and interact with the web browser. There are no official standards for the BOM.

At the top of the BOM is the window object. It represents the entire browser, with its toolbars, menus, status bar and the page itself. Under the window object, there are the following objects: navigator, location, document (DOM), history, screen, frames collection.

Using BOM, we can modify, move the window or can change the text in status bar, read the current URL, go back or forward of the current page which otherwise not possible with DOM.

6. What is the window object?

Keyword:
window = web browser,
global variables/methods belong to window

Answer:
The window object represents the web browser itself. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object. The document property points to the DOM document loaded in that window.

7. How to get web browser window size?

Keyword:
use window object

Answer:
Use the window object innerWidth and innerHeight property.
var w = window.innerWidth; //return the width of browser window including the vertical scrollbar.
var h = window.innerHeight; //return the height of browser window including the horizontal scrollbar.

The innerWidth and innerHeight is not supported by in Internet Explorer < 9. To get the size of window in IE 6, 7, 8:
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;

8. How to detect web browser information?

Keyword:
use navigator object

Answer:
The navigator object contains information about the browser:
var browserName = navigator.appName; //returns the name of the browser.
var browserVersion = navigator.appVersion; //returns the version of the browser.
var userAgent = navigator.userAgent //returns the user agent string for the browser.
var cookieEnabled = navigator.cookieEnabled; //returns whether cookies are enabled in the browser.

9. What is DOM level 0 event handling model and DOM level 2 event handling model?

Keyword:
DOM level 0: onclick="...", single event handler,
DOM level 2: addEventListener, removeEventListener, allow multiple event handlers

Answer:
DOM level 0 event handling model is based around the concept of using element attributes or named events on DOM elements. There are two model types: inline model and traditional model.
In inline model, event handlers are added as attributes of elements. For example:
<input type="button" onclick="handleButtonClickEvent();" />
In traditional model, event handlers can be added/removed by scripts. The event is added by assigning the handler name to the event property of the element object. For example:
<script>
    document.onclick = function(){
        //......
    }
</script>

DOM level 2 event handling model defines an advanced event-handling API to manage events and subscriptions. With this model, we can add multiple event handlers for a single event.
There are three important methods:
addEventListener: Allows the registration of event listeners on the event target.
removeEventListener: Allows the removal of event listeners from the event target.
dispatchEvent: Allows sending the event to the subscribed event listeners.

10. How to add/remove JavaScript file to a web page at runtime?

Answer:
Use DOM API. For example:

/* Add script to head element */
function addScript(loc) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = loc;
    document.getElementsByTagName('head')[0].appendChild(script);
    return script;  
}

/* Removes script from head element */
function removeScript(script) {
    var head = document.getElementsByTagName('head')[0];
    if (head && script) {
        head.removeChild(script);
        script = null;
    }
}

/* Usage */
var myScript = addScript("http://www.iraylab.com/test/test.js");
......
removeScript(myScript);

More JavaScript DOM & BOM interview questions and answers: JavaScript Interview Notes

  • What is the document object?
  • How to change the style of an HTML element?
  • How to change HTML content dynamically?
  • How to detect the screen resolution?
  • How to detect the operating system on the client machine?
  • How to make web browser go back to previous page?
  • What is DOM event?
  • What is event bubbling and event capture?
  • What are onload event and onunload event?
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


JavaScript Basics questions and answers

1. What is the relationship between JavaScript, JScript and ECMAScript?

Keyword:
ECMAScript: language standard
JavaScript, JScript: different implementations

Answer:
ECMAScript is the name of the language standard developed by ECMA. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript and ActionScript.

JavaScript is the Netscape/Mozilla implementation of the ECMA specification. JScript is the Microsoft implementation of the ECMAScript specification. While both JavaScript and JScript aim to be compatible with ECMAScript, they also provide additional features not described in the ECMA specifications.

2. What is the difference between undefined and null?

Keyword:
undefined: declared,but no value; undefined type
null: a null value; object type

Answer:
a. undefined means a variable has been declared but has not yet been assigned a value. null is an assignment value. It can be assigned to a variable as a representation of no value.

b. For the data type, undefined is a type itself (undefined) while null is an object.

The following example shows their differences:
var a;  //undefined variable
console.log(a); //output undefined
console.log(typeof a); //output undefined
var b = null;
console.log(b); //output null
console.log(typeof b); //output object

3. What is the difference between "===" and "=="?

Keyword:
===: strict equality, no type conversion
==:  try type conversion if not the same type. null == undefined

Answer:
The strict equality (===) returns true if the operands are strictly equal with no type conversion: If the two values have different types, they are not equal.

The equality operator (==) is similar to the strict equality operator, but it is less strict. If the values of the two operands are not the same type, it attempts some type conversions and then tries the comparison. If one value is null and the other is undefined, they are equal.

4. What is the difference between instanceof and typeof?

Keyword:
instanceof: return true/fase,
typeof: return type string representation

Answer:
The instanceof operator returns true if the specified object is of the specified object type.
Usage: obj instanceof type
For example:
var today = new Date(2014, 12, 31);
if (today instanceof Date) {
  //......
}

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned.
Usage: typeof operand   //or: typeof (operand)
For example:
var str = "www.iraylab.com";
var num = 1;
var obj = {};
function hello() {
  console.log("Hello world.");
}
typeof str;   // returns "string"
typeof num;   // returns "number"
typeof obj;   // returns "object"
typeof hello; // returns "function"
typeof true;  // returns "boolean"
typeof null;  // returns “object"

5. How to convert a comma separated string from/to an array?

Keyword:
split()
join()

Answer:
To convert a comma separated string to an array, use split() method:
var str = "a,b,c,d";
var arr = str.split(',');

To convert an array to a comma separated string, use join() method:
var arr = ["Apple", "Orange", "Banana"];
var str = arr.join(","); //the default separator is comma (,)

6. What is the difference between String literal and String object?

Keyword:
String literal: string type
String object: object type

Answer:
String literals (denoted by double or single quotes) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. When a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

String literal is a type of string, while String object is a type of object:
var s1 = "iraylab.com";
var s2 = new String("iraylab.com");
console.log(typeof s1); // output "string"
console.log(typeof s2); // output "object"

7. How to create an array in JavaScript?

Keyword:
array literal
new Array()

Answer:
There are two typical ways to create an array:
a. Using array literal:
var myArray1 = [1,2,5,6];
var myArray2 = ["Apple", "Orange", "Banana"];

b. Using new keyword:
var myArray3 = new Array(1,2,5,6);
var myArray4 = new Array("Apple", "Orange", "Banana");

8. How to add/remove elements from an array?

Keyword:
push()
pop()

Answer:
Use push() and pop method:
var arr = ["Apple", "Orange", "Banana"];
//add element to the end of the array
arr.push("Pear");
//remove element from the end of the array
var element = arr.pop(); //return "Pear", arr is now ["Apple", "Orange", "Banana"]

9. What is associative array in JavaScript?

Keyword:
object is associative array

Answer:
JavaScript doesn't have a specific associative array type, but every object has the ability to act as an associative array.

To create an associative array is to create a JavaScript object:
var obj ={};
obj["someKey"]=3;
obj["someOtherKey"]= someObject;
obj["anotherKey"]="Some text";
Access elements in the associative array:
var someValue = obj["someKey"];
obj["otherKey"]= someValue;

10. How to validate e-mail address using JavaScript?

Answer:
Use regular expression and test() method. For example:

function validateEmail(email){
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (!reg.test(email)) {
        return false;
    }
    return true;
}

More JavaScript Basics interview questions and answers: JavaScript Interview Notes

  • What is delete operator in JavaScript?
  • What is || operator in JavaScript?
  • How to generate a random integer value between two numbers?
  • How to trim leading and trailing spaces from a string?
  • What are the built-in types in JavaScript?
  • What is the difference between slice(), substring() and substr()?
  • How to sort an array of objects?
  • How to create a Regular Expression in JavaScript?
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Wednesday, September 24, 2014

Java JPA & Hibernate interview questions and answers

1. What is ORM?

Keyword:
Object-Relational Mapping.
converting data between relational databases and OOP languages.

Answer:
ORM is Object-Relational Mapping. It is a programming technique for converting data between incompatible type systems in relational databases and object-oriented programming languages. You can use an ORM framework to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states.

2. Explain first-level cache, second-level cache and query cache in Hibernate.

Keyword:
First level cache: associated with session.  enabled by default per transaction.
Second level cache: associated with session factory. disabled by default. Example: EHCache, OSCache, JBoss Cache.
Query cache: cache actual query results. disabled by default.

Answer:
First-level cache is associated with the Session object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications.

Second-level cache is associated with the Session Factory object. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. EHCache, OSCache, JBoss Cache are examples of second-level cache provider.
By default, second-level cache is not enabled, you need to configure it as follows:
<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>

Query cache is used to cache actual query results, rather than just persistent objects. Query cache should always be used in conjunction with the second-level cache.
By default, query cache is not enabled. To enable query cache, the following property should be used:
<property key="hibernate.cache.use_query_cache">true</property>

3. What is lazy loading in Hibernate?

Keyword:
parent-children, doesn’t load the children when loading the parent,
lazy=true/false,
parent.getChildren().size()

Answer:
In a one-to-many relationship, lazy setting decides whether to load child objects while loading the Parent Object.
lazy=true means Hibernate doesn’t load the children when loading the parent. This is the default behavior.
lazy=false makes Hibernate load the children when parent is loaded from the database.

Example:
public class Parent {
    private Set<Child> children;

    public Set<Child> getChildren() {
        return children;
    }
}

public void process() {
    //children contains nothing because of lazy loading.
    Set<Child> children = parent.getChildren();

    // When call one of the following methods,
    // Hibernate will start to actually load and fill the set.
    children.size();
    children.iterator();
}

4. What are the different Cascade: DELETE and DELETE-ORPHAN?

Keyword:
DELETE: delete referenced children when parent entity is deleted.
DELETE-ORPHAN: delete referenced children marked as removed (orphans) when parent entity is saved or updated.

Answer:
Cascade DELETE means if one parent entity is deleted, its referenced children will be deleted automatically.
Example:
Query query = session.create("from Parent where id = :id");
query.setParameter("id", 123);
Parent parent = (Parent)query.list().get(0);
session.delete(parent); //parent’s children will be deleted as well

Cascade DELETE-ORPHAN means when save or update one parent entity, only those children that have been marked removed will be deleted automatically. DELETE-ORPHAN allows parent table to delete few records (orphans) in child table.
Example:
Child c1 = (Child)session.get(Child.class, new Integer(10));
Child c2 = (Child)session.get(Child.class, new Integer(20));
Set<Child> children = parent.getChildren();
children.remove(c1); //c1 mark as removed
children.remove(c2); //c2 mark as removed
session.saveOrUpdate(parent);  //c1 and c2 will be deleted from table as well.

5. What is the difference between JPA and Hibernate?

Answer:
JPA is a specification for implementing ORM. It provides a set of guidelines that JPA implementation vendors should follow to create an ORM implementation.

Hibernate is an popular provider of JPA specification.

6. How to define a JPA entity class?

Answer:
The following is an example to define a typical JPA entity class

@Entity  //annotate entity class
@Table(name = "user")  //table mapping
public class User implements Serializable {
    //property declaration
    private Integer id;
    private String firstName;

    public User() {
       //default constructor
    }

    //primary key
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id")
    public Integer getId() {
        return this.id;
    }
   
    public void setId(Integer id) {
        this.id = id;
    }

    //column mapping
    @Column(name = "first_name")
    public String getFirstName() {
        return this.firstName;
    }
   
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

7. Describe JPA Annotations for relationship definition.

Keyword:
@OneToOne, @OneToMany, @ManyToOne, @ManyToMany

Answer:
JPA use the following annotations to specify the relationships between entity classes:

@OneToOne defines a single-valued association to another entity that has one-to-one multiplicity.
Example:
    // On Customer class:
    @OneToOne
    @JoinColumn(name="custom_information_id")
    public CustomerInformation getCustomerInformation() { return customerInformation; }

    // On CustomerInformation class:
    @OneToOne(mappedBy="customerInformation")
    public Customer getCustomer() { return customer; }

@OneToMany defines a many-valued association with one-to-many multiplicity.
Example:
    // In Customer class:
    @OneToMany(cascade=ALL, mappedBy="customer")
    public Set<Order> getOrders() { return orders; }

    // In Order class:
    @ManyToOne
    @JoinColumn(name="customer_id", nullable=false)
    public Customer getCustomer() { return customer; }

@ManyToOne defines a single-valued association to another entity class that has many-to-one multiplicity.
Example:
    @ManyToOne(optional=false)
    @JoinColumn(name="customer_id", nullable=false, updatable=false)
    public Customer getCustomer() { return customer; }

@ManyToMany defines a many-valued association with many-to-many multiplicity.
Example:
    // In Customer class:
    @ManyToMany
    @JoinTable(name="customer_product")
    public Set<Product> getProducts() { return products; }

    // In Product class:
    @ManyToMany(mappedBy="products")
    public Set<Customer> getCustomers() { return customers; }

8. What is the difference between @JoinColumn and mappedBy attribute?

Answer:
@JoinColumn annotation indicates that this entity is the owner of the relationship, the corresponding table has a column with a foreign key to the referenced table.
mappedBy attribute indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity.

An example:
@Entity
public class Company {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
    private Set<Department> departments;
}

@Entity
public class Department {
    @ManyToOne
    @JoinColumn(name = "companyId")
    private Company company;
}

9. What is @Temporal in JPA?

Answer:
@Temporal annotation is used to convert the date and time values between Java object and compatible database type. @Temporal must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.

@Temporal has three type of values:
TemporalType.DATE
TemporalType.TIME
TemporalType.TIMESTAMP

An example:
@Temporal(TemporalType.DATE)
@Column(name = "register_date")
private java.util.Date registerDate;

10. What is the difference between JPQL and Criteria API?

Answer:
JPQL queries are defined as strings, similarly to SQL. JPA criteria queries, on the other hand, are defined by instantiation of Java objects that represent query elements.

A major advantage of using the criteria API is that errors can be detected earlier, during compilation rather than at runtime. On the other hand, for many developers string based JPQL queries, which are very similar to SQL queries, are easier to use and understand.

For simple static queries - string based JPQL queries may be preferred. For dynamic queries that are built at runtime - the criteria API may be preferred.

More Java JPA & Hibernate interview questions and answers: Java Interview Notes

  • What is SessionFactory in Hibernate?
  • Explain Hibernate object states.
  • What is the difference between merge method and update method in Hibernate?
  • What is Transaction in Hibernate?
  • What are the advantages of using JPA?
  • What is Entity in JPA?
  • What is Persistence Unit?
  • What is Entity Manager
  • What is FetchType in JPA?
  • What is the difference between JPQL and HQL?
  • ......

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.



JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

 SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play