Tuesday 28 November 2017

JavaScript Interview Questions and Answers

         I have shared some JavaScript interview questions and answers, please prepare before going for interview.

1) What is JavaScript ?

The JavaScript is a scripting language and it's used for client side web development. 

2) Is JavaScript case sensitive ? 

Yes, it is a case sensitive.

3) What are the data types used in JavaScript ?

JavaScript data types are ,
  • String
  • Number
  •  Boolean
  •  Function
  • Object
  •  Null
  •  Undefined.

4) What are the loops available in JavaScript?

 The following are the loops in JavaScript,
  • for
  • while
  • do-while

5) What are the ways of making comments in JavaScript ?
     There are two ways, single line and block comments.

Single line comment
// - single line comment

Block comment
/*   block comments
*/


6) What are all the types of pop up boxes available in JavaScript ?

There are three pop up boxes,
  1. Alert
  2. Confirm
  3. Prompt 
 

 7) What does isNaN function do ?

 It returns True if the argument is not a number.
Examples,

document.write(isNaN("Hello123")+ "<br>");
document.write(isNaN("2013/06/23")+ "<br>");
document.write(isNaN(123)+ "<br>");

Output would be,

true
true
false



8) What is the difference between undefined and undeclared variable ?
          
         The variable which is not declared in a code, is called undeclared variable and a variable which is declared but not assigned any value is called undefined variable.

Ex:- undefined variable
<script>
   var p;
   alert(p); // This will give error because p is undefined variable.
</script>

Ex:- undeclared variable

<script>
   alert(p); // This will give error because p is undeclared variable.
</script>


 9) What is the data types of variables in JavaScript ?

All variables in JavaScript are of Object data type.

 

10) What is object in JavaScript ? and  How to create the object in JavaScript ?

      JavaScript object is an entity having state and behavior.  JavaScript is an object based language and it treats everything is an object.

    There are three ways to create an object,

1) Object Literal

Syntax:--

object = {property1 : value1, property2 : value2, ......}

the property and value are separated by ':'.

Example:-

<script> 

std={id:1114, name:"Ram Bajaj", subject:"Physics"} 

document.write(std.id+" "+std.name+" "+std.subject); 

</script>


2) Using New Keyword

Syntax:--

var object = new Object();

  
Example:--

<script> 

    var std=new Object(); 

    std.id=10; 

    std.name="Mahesh"; 

    std.subject="Maths"; 

    document.write(std.id+" "+std.name+" "+std.subject); 

</script>

3) Using an Object Constructor
  
    In this case, we can create the function with arguments. The value of each of these arguments can be assigned  to the current object by using this keyword.
Example :--

<script> 

function std(id,name,subject){ 

this.id=id; 

this.name=name; 

this.subject=subject; 

} 

s=new std(10,"Komal","Physics"); 

document.write(s.id+" "+s.name+" "+s.subject); 

</script>

11) What is the use of this keyword in JavaScript ?

            The this keyword behaves differently in JavaScript compared to other language. In Object Oriented languages, the this keyword refers to the current instance of the class. In JavaScript the value of this is determined mostly by the invocation context of function (context.function()) and where it is called

 

12) What is difference between '==' and '===' ?

       These are the operators provided by JavaScript – strict equality and Type converting equality.

Strict equality (===) returns true if the values which it is going to compare have the same data type. 
Taking an example, “2” will not be equal to 2  i.e. (“2″===2) will return false.

Secondly, Type converting equality (==), automatically converts the variable to value irrespective of the data type. Taking an example, here “2” will be equal to 2  i.e. (“2″===2) will return true.

Summarizing it, double equal (==) is an autotype converting equality operator while three equals (===) is a strict equality operator, i.e. it will not convert values automatically.
 
Other Examples :-- 

0==false   // true, because false is equivalent of 0
0===false  // false, because both operands are of different type
2=="2"     // true, auto type coercion, string converted into number
2==="2"    // false, since both operands are not of same type


13) What are the different objects used in  JavaScript?

    The following are the objects used in JavaScript that shows the relationship of one object to another.

1)  Window Object  

       It's the topmost object in the hierarchy . It refers to the content area of the browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.

2) Document Object 
    
     The Document object represents the  HTML documents that window will display.  It has various properties that refer to other objects, which allow access to and modification of content in the document.

3) Form Object  
     
      A form object is used to take user data as input for processing. It corresponds to an HTML input form constructed with the <form> ..</form> tag.

  

14) What is encodeURI() function ? 

           The encodeURI() function is used to encode a URI. This function encodes all special characters, except these < , / ? : @ & = + $ #>.

Example,
 
var uri="http://www.techbeamers.com/how to make a website using javaScript";

var encodedURI = encodeURI(uri);

console.log(encodedURI);
  

Output:--

http://www.somedomain.com/how%20to%20make%20a%20website%20using%20javaScript

        We see that JavaScript encodes the space between the words in the <uri> variable as <%20>. Thus, the encodeURI function is used to encode special reserved characters and other non-ASCII characters in the URI.


 15) What is Closure in JavaScript ?

         Basically Closure is a local variable, which will be executed after the specific function has returned. A Closure provides us a free environment, where the outer function can easily access the inner functions and inner variables without any scope restrictions. 

Example:-  

function create() {
   var counter = 0;
   return {
      increment: function() {
         counter++;
      },
  
      print: function() {
         console.log(counter);
      }
   }
}
var c = create();
c.increment();
c.print();     // ==> 1


16) How to determine the state of a checkbox using JavaScript? 


var checked = window.document.getElementById("myCheckBox").checked;

alert(checked); // will give true or false

 17) How can the style/class of an element be changed?

It can be done in the as follows,

document.getElementById("myText").style.className = "div1"; 


18) What would be the output of below code?  


(function(){
  var a = b = 3;
})();

console.log("a defined? " + (typeof a !== 'undefined'));
console.log("b defined? " + (typeof b !== 'undefined'));

Output :-- a defined? false
          b defined? true
 

19) What would be the output of below code?  


for (var i = 0; i < 5; i++) {
 setTimeout(function() { console.log(i); }, i * 1000 );
}

Output :-- 5 5 5 5 5


20) What would be the output of below code?  


for (var i = 0; i < 5; i++) {
    (function(x) {
        setTimeout(function() { console.log(x); }, x * 1000 );
    })(i);
}

Output : -- 0 1 2 3 4

Saturday 25 November 2017

Internal Implementation of TreeMap in Java

      We learned the internal working of HashMap in post of How HashMap works internally.  In this post, we can discuss about the internal working of TreeMap in Java.

What is TreeMap ? 

    TreeMap class is a like HashMap which stores a key-value pairs. The major difference is that TreeMap sorts the key in ascending order.

   TreeMap is sorted according to the natural ordering of it's keys, or by a Comparator provided at map creation time, depending on which constructor is used. There are mainly two types of
constructor in TreeMap, 

         TreeMap();
         TreeMap(Comparator comp);

How TreeMap works internally ?


         TreeMap is Red-Black tree based NavigableMap implementation. In other words, it sorts the TreeMap object keys using Red-Black tree algorithm.

Red-Black Tree algorithm:--

       Red-Black tree is a self balancing Binary Search Tree(BST) where every node follows some rules,
  • Every node has color either Red or Black.
  • Root of tree is always black.
  • There are no two adjacent red nodes.
  • Every path from root to a null node has same number of black nodes.  

Red-Black Tree
Red-Black Tree

          Time Complexity of TreeMap of search i.e  get, put and remove is O(log n) . 
         Being a self balancing, we keep inserting and deleting entries, tree growing longer on one edge or shorter on the other side.
         This would mean that an operation would take a shorter time on the shorter branch and longer time on the other branch which is furthest from the root, something we would not want to happen. Therefore this is taken care of in the design of Red-Black trees.


TreeMap Examples :


Simple String as key example,

package com.test;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapEx {
    public static void main(String[] args) {
         TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();
         treeMap.put("Mahesh", 1);
         treeMap.put("Anil", 9);
         treeMap.put("John", 3);
         for(Map.Entry<String, Integer> map : treeMap.entrySet()) {
              System.out.println(map.getKey());
         }
    }
}
 
Output :-- Anil
           John
           Mahesh

 

Example to sort keys in TreeMap using Comparator with custom object.


package com.test;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapSorting {
      public static void main(String[] args) {
           TreeMap<Employee, String> treeMap = new TreeMap<Employee, String>(new MyNameComp());
           treeMap.put(new Employee(10,  "Anil"), "one");
           treeMap.put(new Employee(10,  "Mahesh"), "two");
           treeMap.put(new Employee(10,  "John"), "three");
           treeMap.put(new Employee(10,  "Nagesh"), "four");
           for (Map.Entry<Employee, String> map : treeMap.entrySet()) {
                   System.out.println("Key : ("+map.getKey()+ "), Value : "+ map.getValue());
           }
      }
}
 
class Employee {
      private Integer id;
      private String name;
      public Employee(Integer id, String name) {
           this.id = id;
           this.name = name;
      }
      public Integer getId() {
           return id;
      }
      public void setId(Integer id) {
           this.id = id;
      }
      public String getName() {
           return name;
      }
      public void setName(String name) {
           this.name = name;
      }
      public String toString() {
           return this.name+":"+id;
      }
}

class MyNameComp implements Comparator<Employee> {

        public int compare(Employee o1, Employee o2) {
               return o1.getName().compareTo(o2.getName());
        }
 
}
 
Output :--  
Key : (Anil:10), Value : one
Key : (John:10), Value : three
Key : (Mahesh:10), Value : two
Key : (Nagesh:10), Value : four 
 


Related Posts:-- 
1) How HashMap works internally in Java? 
2) Internal implementation of ArrayList in Java  
3) Collection Related Interview Questions and Answers in Java(List,Map & Set)
4) Internal Implementation of LinkedList in Java 
5) Difference between Loose Coupling and Tight Coupling in Java With Examples.
6) String Interview Questions and Answers 
7) Factory Design Pattern in Java

Sunday 19 November 2017

SQL Query Interview Questions and Answers

      In this post, I am giving some examples of SQL queries which are asked in the interview.

1)  What is SQL ?

 SQL  is a Structured Query Language and is designed for managing data in a Relational Database Management System(RDBMS).

2) What are the common aggregate functions in SQL?

 Theses are the common aggregate functions in SQL ,
  • AVG – calculates the average of a set of values
  • COUNT – counts rows in a specified table or view.
  • MIN – gets the minimum value in a set of values.
  • MAX – gets the maximum value in a set of values.
  • SUM – calculates the sum of values.

3)  What  are DDL, DML, DCL Commands ?

Refer : SQL Commands



4) Difference between Primary Key and Unique Key

     Both Primary and Unique key enforce the uniqueness of the column in the database. Primary key creates Clustered index on the column by default but unique column creates Non-Clustered index by default.
     Another difference between Primary and Unique key is that Primary key doesn't allow NULLs but Unique column allow one NULL value.


5) What is difference between DELETE and TRUNCATE Commands?

DELETE DELETE Command is used to remove rows from the table and WHERE command can be used for conditional set of parameters. Commit and Rollback can be performed after delete statement.


TRUNCATE -  Truncate removes all rows from the table. Truncate operation can not be Rollback.


6) What is a Constraint ?

         Constraint can be used to specify the limit on the data type of table. Constraint can be specified while creating or altering the table statement. Following are the some of the constraints,
NOT NULL,
CHECK,
DEFAULT,
UNIQUE,
PRIMARY KEY,
FOREIGN KEY


 
7)  Write a SQL Query to display the total number employees working in the Engineering team.

   Using count() aggregate function, we can write query as follows,

SELECT COUNT(*) FROM employee_details WHERE employee_team = 'ENGINEERING';

 
8) Write a query to find the second highest salary of Employee
   There are two ways to write the above query.  

select MAX(Salary) from Employee WHERE Salary
                                 NOT IN (select MAX(Salary) from Employee );  

Another way i.e to find the nth highest salary from employee,

SELECT * FROM Employee Emp1 
   WHERE (N-1) = ( SELECT COUNT(DISTINCT(Emp2.Salary))
                   FROM Employee Emp2
                   WHERE Emp2.Salary > Emp1.Salary);



 9) Write a SQL query to fetch the duplicate records from the table. 
   
     Using GROUP BY and HAVING Clause,

SELECT empid, project, salary, COUNT(*)
FROM employee_salary
GROUP BY empid, project, palary
HAVING COUNT(*) > 1;


10) Write a SQL query to display the Top  n records.

In MYSQL  & PostgreSQL,
   
SELECT * FROM employee_salary ORDER BY salary DESC LIMIT N
 
In Oracle,

SELECT TOP 10 * FROM employee;


11) Write a query to get the UNIQUE Department from EMPLOYEE Table

Use DISTINCT Clause,

SELECT DISTINCT department FROM employee;


12)  Select first 3 characters of name from employee table

For SQL Server, Use SUBSTR function,

SELECT substr(name, 0,3) FROM employee;

For MYSQL and PostgreSQL, Use SUBSTRING function,

SELECT substring(name, 1,3) FROM employee;


13)  Write an SQL Query to find name of employee whose name Start with ‘M’

SELECT * FROM Employees WHERE EmpName like 'M%';


14)  How do you find all employees which are also manager?

Using Self Join you can write query as follows,

SELECT e.name, m.name FROM Employee e, Employee m WHERE e.mgr_id = m.emp_id;


15) What is GROUP BY Clause ? Explain with examples

  It is a SQL Command used to group rows that have the same values.
Example:-
ID
GENDER
NAME
1
2
3
4
5
MALE
FEMALE
FEMALE
MALE
MALE
Mahesh
Ashwini
Priyanka
Rajesh
Anand












SELECT gender FROM employee GROUP BY gender;

Output :- gender
                MALE
                FEMALE



16) Write a SQL query to create a new empty table from an existing table.

 Example, using SELECT INTO

SELECT * INTO newTable FROM employee_details WHERE 1 = 2;


17) Write a SQL query to create a new table with data and structure copied from another table.

Using SELECT INTO Command, 

SELECT * INTO newTable FROM employee_details;


18) Difference between INNER and OUTER Join with example. 
 

Inner Join :--

        Inner join is the most common type of Join which is used to combine the rows from two tables and create a result set containing only such records that are present in both the tables based on the joining condition (predicate).
 Inner join returns rows when there is at least one match in both tables

      If none of the record matches between two tables, then INNER JOIN will return a NULL set. Below is an example of INNER JOIN and the resulting set.

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE 
FROM DEPT dept, EMPLOYEE emp
WHERE emp.dept_id = dept.id

Outer Join

Outer Join, on the other hand, will return matching rows from both tables as well as any unmatched rows from one or both the tables (based on whether it is single outer or full outer join respectively).

Outer Join can be full outer or single outer

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE 
FROM DEPT dept 
LEFT OUTER JOIN EMPLOYEE emp
ON dept.id = emp.dept_id  


19)  What is a CARTESIAN or CROSS JOIN ? Explain with example.

         The SQL CROSS JOIN produces a result set which is the number of  rows in the first table multiplied by the number of rows in the second table if no WHERE clause is used along with CROSS JOIN.  This kind of result set is as Cartesian Product.

         An alternative way of achieving the same result is to use column names separated by commas after SELECT and mentioning the table names involved, after a FROM clause.

Syntax:
                
SELECT * FROM table1
CROSS JOIN table2
OR

SELECT * FROM table1, table2;

ID
Name
Department
1
2
3
Kiran
Laxmi
Mahesh
IT
Support
Engineering
Designation
Salary
SE
SSE
20000
40000








 For the above table employee and salary,

SELECT id, name, salary FROM employee,salary;

The output as follows, total 3*2 = 6 rows.


ID
NAME
SALARY
1
1
2
2
3
3
Kiran
Kiran
Lakshmi
Lakshmi
Mahesh
Mahesh
20000
40000
20000
40000
20000
40000


20) Difference between Clustered and Non-Clustered Index  

    Clustered Index
  •  Only one per table
  • Faster to read than non clustered as data is physically stored in index order
    Non Clustered Index
  • Can be used many times per table
  • Quicker for insert and update operations than a clustered index
         Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.


21) PostgreSQL Database Case Expression and example.

     The PostgreSQL Case expression is the same as If/else statement in other programing languages.
The following illustrates the syntax of CASE expression.
CASE 
     WHEN condition_1  THEN result_1
     WHEN condition_2  THEN result_2
     [WHEN ...]
     [ELSE result_n]
END

Example:-

SELECT patient_name, 
CASE 
     WHEN gender='M'  THEN 'MALE'
     WHEN gender='F'  THEN 'FEMALE'
     ELSE 'TRANSGENDER'
END as patient_gender from patient_details;


22) What is SQL Injection? Explain with examples

          SQL injection is the technique to extract the database information through web application.
Scenario:
         We have one database server [MySQL] and web application server [Tomcat]. consider that database server is not connected to internet. but its connected with application server. Now we will see using web application how to extract the information using sql-injection method.

Refer this SQL Injection in Java Application


23) What is a Stored Procedure ?

            A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.


24) What are the advantages and disadvantages of Stored Procedure ?

        Advantage - Stored Procedure can be used as modular programming - means create once, store and call for several times whenever required.  This supports faster execution instead of executing multiple queries. This reduces network traffic and provides better security to the data.

       Disadvantage - It can be executed in the only in the database and utilizes more memory in the database server.