Thursday, December 31, 2015

How To Install And Configure MongoDB on Windows.

1. Download MongoDB

Download .msi installer file from MongoDB download page. 
Choose Windows 32bit or 64bit platform.


Double click the .msi file and follow the set of screens to finish installation process.

2. MongoDB directory structure

In MongoDB, we have required executable files only in bin directory. It doesn't have  any other system dependencies.



We can specify the installation directory if you choose "Custom" installation option.(e.g. F:\mongodb)

 You can add F:\MongoDB\bin  path Windows Environment variable, so that you can access the MongoDB commands from any location in Command Prompt.

3. Configuration

MongoDB requires a data directory to store the data. MongoDB default's data directory is "C:\data\db".

We can create alternative path and specify path in configuration file. We should specify this data directory path with --dbpath option while running MongoDB.

For example:

F:\mongodb\mongo.config
dbpath=F:\mongodb\data\db
logpath=F:\mongodb\log\mongo.log

4. Start/Stop MongoDB Server

We can start MonngoDB server by using mongod.exe file with the option --config F:\mongodb\mongo.config.
F:\MongoDB\bin>mongod --config F:\mongodb\mongo.config

5. Connect to MongoDB Server

We can mongo.exe file to connect the MongoDB server.
F:\MongoDB\bin>mongo.exe
MongoDB shell version: 3.0.6
connecting to: test





Wednesday, December 30, 2015

Joins in SQL with Examples

SQL:   SQL means Structured Query Language.SQL is Primarily use for getting information
into and out of Database. It is communicate with database. It is used to deal with relational database. That means we can querying and editing information in certain database.

Database:

Database is a computer software program is used to store,edit and retrieve data. some of the common databases are Mysql,Oracle etc...

Join in SQL: 

SQL Join is used to retrieve data from  more than one table. We can Write the join condition in the where clause. Joins are used for combining the column from  more than one table by using values common to both tables. For joining two or more tables in SQL Queries we used a keyword as "join" . In my previous i have written  Stored Procedure in SQL Server go through it to understand and learn about it.


Types of Joins: 

There are FIVE types of Joins in SQL. They are as follows

1) Cartesian product or Cross Join
2) Inner Join
3) Outer Join
4) Left Join
5) Right Join

1)Cross Join or Cartesian Product:

Cartesian Product is formed when Join condition is Omitted. To avoid a Cartesian Product ,always include a valid condition in a where clause. Here First Table Employee Rows completely Multiplied by First Row in the Second table Address and so on...

I am going to demonstrate this concept with example using Oracle 10g application using Customers table and Orders Table as shown below.


Customers Table:

create table customers
(
customer_id int,
First_Name varchar2(20),
Last_Name varchar2(20),
address varchar2(20),
city varchar2(20),
state varchar2(20));

Result:







Orders Table:

create table orders
(
order_id int,
amount number,
customer_id int
);

Result:








Syntax for Cross-join:

Select Column-name-list
from table-name1
cross JOIN
table-name2


 The Cartesian Product query will be as follows:

select * from customers
cross JOIN orders;

The Output table will be Like This:



Note:  Here we get No of  Rows * No Columns as Output.

2)Inner Join or Equi Join:

The Relationship Between Employee Table and Address Table is a EQUI-JOIN. That is values in Address table Emp ID and Employee table Emp ID both tables are EQUL.

Syntax for Inner Join:

SELECT column-name-list
from table-name1 
INNER JOIN 
table-name2
on table-name1.column-name = table-name2.column-name;

The Query will Look Like This:

select first_name,last_name,order_id,amount 
from customers c
inner join orders o
on c.customer_id=o.customer_id;

The Output will be as follows:









Outer Join:

Outer Join is used both for Matched and Unmatched data.This is again divided into

  •  Right Join (or)Right Outer Join
  •  Left Join  (or) Left Outer Join
Left Outer Join:

Left Join Performs a Join Starting with a  first table that is (Left most) and then any matching Second(right most)table records.





Syntax for Left Outer Join

SELECT column-name-list
from table-name1 
LEFT OUTER JOIN table-name2
on table-name1.column-name = table-name2.column-name;

The Query for Left Join:
select first_name,last_name,order_id,amount 
from customers c
left join orders o
on c.customer_id=o.customer_id;

The Output will be Like This:









Right Outer Join:

Left Join Performs a Join Starting with a  Second table that is (Right most) and then any matching First (Left most)table records.


                











Syntax for Right Outer Join

SELECT column-name-list
from table-name1 
RIGHT  OUTER JOIN table-name2
on table-name1.column-name = table-name2.column-name;


The Query For Right Join:
select first_name,last_name,order_id,amount 
from customers c
right join orders o
on c.customer_id=o.customer_id;


The Output will be Like This:









Also read this post: HR Interview Questions for Experienced Candidate

I hope you people enjoy this post and share on social websites and give your comments on this topic.Keep follow me for my latest updates

Sunday, December 27, 2015

JAVA Collection Framework Interview Questions

In this Article i am trying to explore some of the frequently asked Java Collection Framework interview questions. I am sure without Collection Framework  topic in Technical Interview questions there is no Technical Round for java developer. Because as a java developer should have efficient knowledge on Collection Framework to develop software project efficiently.I also have post Top 10 Exceptions in java  Before attending Technical Round just brush these questions to clear your Technical Round.


1) Can  you  Define Collection? why we use collection in java? Tell me                 some benefits of  Collections?


Ans:  

Collection is an interface available in java.util.*; package for representing group of objects into a single entity. In this interface defines the most common general methods which can be applicable for any collection object. 

Note:  There is no Concrete class which implements collection interface directly.

Collection Framework is group of classes and interfaces which can be used to representing collection of  Objects as single entity.

Some of the benefits of Collection in java:

1. By using collection framework we can improve the code quality and speed while developing programs.

2. With Collection Framework code and software reusability is possible therefore we can reduce the programming effort.

3. Java has Provide rich set of Core collection classes by using these classes we can develop programs easily instead of  implementing our own classes.

2. Can you tell me difference between Collection and Collections?

Ans: Collection is an interface available in java.util package for representing a group of objects as single entity.
Collections is an utility class available in java.util package and defines several utility methods for collection implemented class object

3. Tell me basic interfaces of collection framework in java?

Ans: There are mainly four types of Interfaces are there , they are

a)Collection
b)Set
c)List
d)Map

a)Collection: This interface can be used for representing a group of objects as single entity. It is root of the collection framework hierarchy.

b)Set : This can be used for representing a group of individual objects where duplicate objects are not allowed and insertion operation is not preserved. This is the child interface of collection.

c) List: This can be used for representing a group of individual objects as a single entity where insertion order is preserved and duplicate objects allowed. This is child interface of collection.

d)Map:  This can be used for representing a group of objects as key value pairs. Both key and value are objects only.

Ex:   Studentname --> StudentRollno
           phoneno       --> contact details

Map interface is not child interface of collection

4) can extend collection interface through Map Interface?If not Why?

Ans: No. Map Interface does not extend Collection and vice versa. Even though Map is the part of collection framework  but their designation were different. Map Interface defines key-value pairs and it provides some rich methods like to retrieve list of keys or values as collection but it can not store as group of elements as single entity. Therefore Map interface does not extend Collection interface.

5) Why we use Iterator in java? Explain with example?

 Ans:  Iterator was Introduced in java 1.2 version. Iterator interface has methods to  iterate  over   any collection.  we can get iterator()method from collection class.By iterating the elements we can perform remove operation also in addition to read operation.

This interface contains the following 3 methods.

boolean hasNext();
Object next();
void remove();

Ex:

import java.util.*;
class IteratorDemo
{
public static void main(String arg[])
{
ArrayList al = new ArrayList();
for (int i =0;i<=10 ;i++ )
{
al.add(i);
}
System.out.println(al);
Iterator itr = al.iterator();
while (itr.hasNext())
{
Integer i = (Integer)itr.next();
if((i%2) == 0)
{
System.out.println(i);
}
else
{
itr.remove();
}
}
System.out.println(al );
}
}

Output:    











6) can you tell me where we use enumeration in java with example?

Ans: This interface has introduced in 1.0 version it contains the following 2 methods

boolean hasMoreElements();
Object nextElement();

Ex:

import java.util.*;
class EnumaretionDemo
{
public static void main(String arg[])
{
Vector v = new Vector();
for (int i =0;i<=10 ;i++ )
{
v.addElement(i);
}
System.out.println(v);
Enumeration e = v.elements();
while (e.hasMoreElements())
{
Integer i = (Integer)e.nextElement();
if((i%2) == 0)
System.out.println(i);
}
System.out.println(v);
}
}
Output:











Limitations of Enumeration :

  1. It is applicable only for legacy classes and it is not a universal cursor.
  2.  While iterating the elements by using enumeration we can perform only read operation and we can’t perform any modify/removal operations.
  3. To overcome these problems we should go for Iterator interface
7) Why we use UnsupportedOperationException in collection framework?

Ans:  It is an exception is used to indicate that the operations is not supported. It is mainly used in JDK classes. java.util.Collections.unmodifiablecollection when we using operations like  add or remove  thorws this type of exception.







8) what is difference between HashMap and HashTable in java?

Ans: HashMap: 

HashMap is not sorted or ordered. If you just need a Map, and you don’t care about the order of the elements while iterating through it, you can use a HashMap. That keeps it simple. The values can be null. But the key should ne unique, so you can have one null value for key. (Allows only one null key).


HashTable:


Hashtable is almost the same as HashMap. The main differences are:

1. Hashtable does not let you have null value for key.

2. The key methods of Hashtable are synchronized. So, they may take a longer time to execute, compared to HashMap’s methods.

9) Explain TreeSet and TreeMap in java?



Ans: The underlying Data structure for the TreeSet is Balanced tree.

Duplicate objects are not allowed. If we are trying to insert duplicate object we won’t get any
compile time error or Run time error, add method simply returns false.
Insertion order is not preserved but all the elements are inserted according to some sorting order.Heterogeneous objects are not allowed, violation leads to Run time error saying class cast.

Ex: 

import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet t = new TreeSet();
t.add("A");
t.add("B");
t.add("Z");
t.add("L");
//t.add(new Integer(10));// ClassCastException.
//t.add(null);// NullPointerException.
t.add("A"); //false.
System.out.println(t);
}
}
null Acceptance

For the empty TreeSet as the first element null insertion is possible. But after inserting null if we are trying to insert any other element we will get NullPointerException.
If the TreeSet already contains some elements if we are trying to insert null we will get
NullPointerException.

Ex:

import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet t = new TreeSet();
t.add(new StringBuffer("A"));
t.add(new StringBuffer("B"));
t.add(new StringBuffer("T"));
t.add(new StringBuffer("Z"));
System.out.println(t);
}
}

Output: Runtime Exception: ClassCastException

TreeMap:


TreeMap is a sorted Map and will be sorted by the natural order of the elements. If you want, you can define a custom sort order by means of a Comparator passed to the constructor. So, when you need a custom sort order, it is clear which class you should be using!

Saturday, December 26, 2015

How To Create JAR File in Java and in Ecclipse

JAR files means the output of the Java Archive Tool.
Java Archive Tool:  It is a program that is a part of the J2SE Kit. We must set the path before using Jar command. Here Path means where OS looks to run Programs. so we can created jar files using JAR.EXE utility program from JDK. So to make jar files runnable we first need to create manifest file. Here manifest file is one line text file with a "main-class" directive.

For Example:
main-class: luckyprogramclass


Here is step by step process to create Jar files from command prompt:

Step 1: Start Command Prompt
Step 2: Navigate to the folder that holds to your class files

          c:\cd\luckyprogram

Step 3: set path to include JDK bin.

For Example: c:\luckyprogram>c:\program files\java\jdk 1.5\bin;%path%

step 4:  Compile your class(es):

               c:\luckyprogram>javac*.java

Step 5: create manifest file:

                 c:\luckyprogram>echo Main-class:luckyprogramclass>manifest:txt

Step 6: crate jar file:

                  c:\luckyprogram>jar cvfm luckyprogramclass.jar manifest.txt*.class

step 7: Test your jar

            c:\luckyprogram>luckyprogramclass.jar


To create JAR File in the Eclipse Workbench 

 Step 1:   First we have to select Package Explorer, here we can select optionally pre select one or more java elements to export.

Step 2: we need to select Export either from the menu bar's of File menu or from the context menu. 

Step 3:  In the Wizard Page should have expand the java node  and select JAR file.and then click next.

Step 4:  Select the resources that we want to export in the JAR file Specification page.

Step 5:  Select the appropriate check box to specify  whether we want export generated class files and resources.

Note :  here selected resources exported in this case.

Step 6: You need to click Browse to select a location for the JAR file

Step 7: Select or clear the Compress of the contents of the JAR file check box.

Step 8: Select or clear the Overwrite Existing files without warning check box.

Step 9: here we have two options

Step 10: To create JAR files immediately click Finish

Step 11: Click Next to use the JAR Packaging Options page to set advanced options, create a JAR description, or change the default manifest. 

Step 12: If we want to save the JAR file description, select the Save the description of this JAR in the workspace checkbox. A JAR file description can be used to regenerate a JAR file without using the wizard. 

Step 13: The compiler is able to generate CLASS files even when source contains errors. We have the option to exclude CLASS (but not source) files with compile errors. These files will be reported at the end, if reporting is enabled. 

Step 14: We can choose to exclude CLASS (but not source) files that have compile warnings. These files will be reported at the end.

Note: This option does not automatically exclude class files with compile errors. 

Step 15: We can choose to include the source folder path by selecting the Create source folder structure checkbox. 

Step 16:  Select the Build projects if not built automatically checkbox if you want the export to perform a build before creating the JAR file. 

Step 17: Click Finish to create the JAR file immediately or Next if we want to change the default manifest.

Select 18:If it is not already selected, click the Generate the manifest file button. 

Step 19: We can now choose to save the manifest in the workbench. This will save the manifest for later use. Click Save the manifest in the workspace, then click Browse next to the Manifest file field to specify a path and file name for the manifest. 

Step 20: If we decided to save the manifest file in the previous step and you chose to save the JAR description on the previous wizard page, then you can choose to reuse it in the JAR description (by selecting the Reuse and save the manifest in the workspace checkbox). This means that the saved file will be used when the JAR file is recreated from the JAR description.This option is useful if you want to modify or replace the manifest file before recreating the JAR file from the description. 

Step  21: We can choose to seal the JAR and optionally exclude some packages from being sealed or specify a list with sealed packages. By default, nothing is sealed. 

Step 22:Click the Browse button next to the Main class field to specify the entry point for our applications.

Note: If our class is not in the list, then we forgot to select it at the beginning.   Click Finish. This will create the JAR, and optionally a JAR description and a manifest file.

  



Wednesday, December 23, 2015

Java Interview Questions for freshers

In this article we will learn some frequently asked basic java technical interview questions specially for freshers. Every java developer before attending technical interview must brush up these question and answers to clear interview successfully.

1) What is JVM? Why is java called as"Platform Independent Programming Language"?

Ans: JVM Stands for JAVA VIRTUAL MACHINE. It is a process of Virtual Machine that can execute java byte code on different Operating System irrespective of specific Operating System.That means java was designed to allow application programs that could be run on any platform,without having to be rewritten or recompiled by the java programmer for each separate platform.So JVM makes this possible.

2) Can you Override private or  Static method in Java?

Ans: A user can not override static methods in java, method overriding is based upon dynamic binding at runtime and static methods are statically binded  at compile time. A static method is not associated with any instance of a class so we can not override static method in java.

3) What are the Pass by reference and pass by value in java?

Ans: When an Object is passed by reference, this  means that the actual object is not passed,rather a reference of the  object is passed,thus any changes made by the external methods are also reflected in all places.

        When an object is passed by value, this means that a copy of the object is passed,thus even if changes are made to that object it does not effect it's original value.

4) What are differences between process and Threads?

Ans:  A process is self contained execution environment and it can be seen as program whereas Thread is a single task of execution within the process.Thread can be called lightweight process.we can call threads are lightweight process because thread requires less resources to create and exists in the process and thread share process resources.

5) How do you ensures that N threads can access N resources without deadlock?

Ans:  A simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to fallow that ordering. Thus, if all threads lock and unlock the mutexes in the same order no deadlock can raise.

6) When will we use Arrays over ArrayList?

Ans: Arrays can contains Primitives and Objects, while an arraylist can contain only Objects.Arrays have fixed size whereas arraylist is dynamic.An arraylist provides more features than Arrays such as addAll, removeAll,iterator,etc..For list of Primitive data types,the collections use autoboxing to reduce the coding effort.

7) Why wait(), notify(),notifyall() methods have to be called from Synchronized method or block?

Ans:  when a Thread calls wait() method on any object it must have the monitor on the object that it will leave and goes in wait state until any other thread call notify() method on this object. similarly when a Thread calls notify() on any object it leaves the monitor on the object and other waiting threads can get the monitor on the object. so all these methods needs Thread to have Object monitor that can be achieved only by synchronization, this should by called from synchronized method or block.

8) How can we achieve Thread Safety in java?

Ans:  We can achieve Thread Safety in java by using several ways such as synchronization,using volatile keyword,using immutable classes and implementing concurrent Lock Interface.

9) What is Executors class in java?

Ans: Executors class provides utility methods for executor, ExecutorService,scheduledExecutorService,ThreadFactory and Callable classes.

Executor class is used to easily create ThreadPool in java and also this is the only class to supporting execution of Callable implementations.

10) How to create Demon Threads in java?

Ans:  This is very simple to create Daemon threads in java . 
Thread class setDaemon(true) can be used to create Daemon Threads in java.

Note:  we need to call this method before calling start() method otherwise it will throw IlleagalThreadStateException.




Life Cycle Of Thread in java With Example

In this post we will know and understand life cycle of Thread in java. This is one of the important concept in Core Java. A Thread can be any one of the five states. The Life Cycle of Thread in java is controlled by JVM. The Thread States are given below:

a) New or born State                                          
b) Ready or Runnable State
c) Running State
d) Blocked State
e) Dead State















a) New State:

    When we write new MyThread() of  the Thread() class  the Thread has born

b) Ready State:  When we call start() method then the thread enter into Runnable State
                                   Ex: t.start();

Note:  After Starting a Thread we can not restart same thread once again, it violation leads to Runtime Error  saying"IlleagalThreadStateException"

Ex:  MyThread t=new MyThread();
           t.start();
           t.start();//IllegalThreadStateException;


Yield():

The thread which is called yield() method temporarily pause the execution to give the chance for remaining threads of same priority. If there is no waiting thread or all waiting threads having low priority. Then the same thread will get the chance immediately for the execution.

public static native void yield();

Ex:
class MyThread extends Thread
{
public void run()
{
for (int i=0; i< 10 ; i++ )
{
System.out.println("Child Thread");
Thread.yield();
}
}
}
class YieldDemo
{
public static void main(String arg[])
{
MyThread t = new MyThread();
t.start();
for(int i =0;i<10;i++)
{
System.out.println("Main Thread");
}
}
}

In this case main thread will get chance more no of times for execution. Because child thread
intentionally calling “yield()” method. As the yield method is native method some Operating system may not provide the support for this.

Sleep():

If a method has to wait some predefined amount of time with out execution then we should go for sleep() method.

public static void sleep(long ms)throws InterruptedException

public static void sleep(long m, int m)throws InterruptedException

Ex:
class MyThread extends Thread
{
public void run()
{
try
{
for (int i = 0;i<10;i++)
{
System.out.println("This is Lazy Method");
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(e);
}
}
}
class SleepDemo
{
public static void main(String arg[])throws InterruptedException
{
MyThread t = new MyThread();
t.start();
System.out.println("Main Thread");
}
}

Output:  












Running State:

The Thread is Running state if Thread Scheduler selected it.

Blocked State:

In this state The Thread might be in sleeping state,waiting state,yield state that means Thread is still alive but not eligible to run.

Dead State:

A Thread is in Dead state or terminate when the Thread is successfully completed run() method.

Read also : MultiThreading In Java



High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...