Quantcast
Channel: Interview Questions – Web Development Tutorial
Viewing all 26 articles
Browse latest View live

MUST Have Core Java Interview Questions – Part 2

$
0
0

Let’s continue with Part-2 of MUST Have Core Java Interview Questions and Detailed answers tutorial. Major topics covered in this Java Tutorial are Exception Handling in Java, Threading in Java and Synchronization, Access Modifiers and usage, thread pooling in Java, Complete Collection Framework and Inner Classes.

Java Interview Questions and Answers

Complete Java Interview Questions List

Courses Online

What are different kind of exceptions in java. Explain Runtime and complie time exceptions ? Explain try,catch,throw,throws,finally with example.

Exceptions start from the base class Throwable. Throwable has two hierarchies one is error and other is exceptions. An exception further has its own hierarchy and furthermore divides into Runtime (Unchecked) and all exceptions other than this runtime exception falls into Compile (Checked) exceptions.Exception Handing in Java

As we can see in the diagram above Throwable is the parent class from where all exception propagates. Error is basically an unwanted scenario in the code which will occur and the system will been able to recover from this. Like stack overflow or the heap dump error, which are not recoverable. On the other hand exceptions are the scenarios where in our system will be able to recover from it. I.e. we can handle these types of scenarios in our code.

Lets understand each of them with example.

Runtime (Unchecked) Exception:

Runtime exceptions are basically programming exceptions, which will occur during run of program. Lets say we are writing some mathematical programming code where we are have function which take two parameters , one as dividend and one as divisor.

package com.javatutorial.exceptionhandling;

public class RuntimeExceptionMain
{

    public static void main(String[] args)
    {
        int dividend = Integer.parseInt(args[0]);
        int divisor = Integer.parseInt(args[1]);
        double result = doDivide(dividend,divisor);
        System.out.println("Result is : "+result);
    }

    private static double doDivide(int dividend, int divisor)
    {
        return dividend/divisor;
    }

}

So we are taking parameters form console and passing them to the divide function, which divides and returns the result. By mistake someone has sent the divisor as zero. Ideally one should not send zero as divisor.Runtime Exceptions in Java

So we send two arguments as 12 and zero, lets run and see what we see in output.Output for Exceptions in Java

So we got divide by zero exception, which we got when we try to run the code with the arguments, we got the divide by zero exception, which is a kind of runtime exception in java. So in essence we got runtime exception when we try to run the code with wrong arguments and we don’t have any try/catch block.

Compiletime (Checked) Exception:

Checked exceptions are the exceptions which are occurred during compile time of the code. For example we are writing code where we are dealing with I/O. Some of the methods of File api throws exception which we need to handle in our code, if we don’t add handing for these exception by throws in the method signature or adding try/catch in the code fragment, our code will not compile. Lets take an example where in we will using the File api and we add the code from which we don’t have the handling for the thrown exception.

package com.javatutorial.exceptionhandling;

import java.io.File;

public class CompileTimeMain
{

    public static void main(String[] args)
    {
        File file = new File("c:/text.txt");
        file.createNewFile();
    }

}

Now if we try to compile the code using command prompt, it will not compile. If you are coding using IDE, the IDE will suggest us to handle the exception and mark this line of code as non-compliable. Lets try to compile the code using command prompt and see what happens:Compile Time Exceptions in Java

As we can see when trying to compile the code, compiler is explaining about the exception must be caught or declared to be thrown.

Lets talk about few keywords that are used in exception handling in java.

Try/catch: try/catch is used when there is possible exception in a code block and an exception is been thrown out of it or an exception can be occur out of this code block. In these kind of scenarios we use try/catch block. There can be multiple catch blocks with a try block, but the thumb rule is that exception can not be narrow down in the subsequent catch block. Example of try/catch block is below:

public class CompileTimeMain
{

    public static void main(String[] args)
    {
        File file = new File("c:/text.txt");
        try
        {
            file.createNewFile();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

throw/throws:

throw/throws is used when in a method we want to indicate the calling method that the code is throwing some exception. Throw used mostly when we want to wrap an exception to a particular kind of user defined exception.

Finally:

Finally keyword is used when we want to do some particular kind of task even after the exception is thrown out of the code. Finally code is always executed, except some particular scenarios where we use System.exit in any of the catch block.

Back to top

How to create thread in java, what are different ways to create a thread? Explain synchronization with example.

To create thread in java, there are two ways:

  • By extending Thread class
  • By implementing runnable interface

Let’s understand the same with example:

package com.javatutorial.multithreading;

public class Main
{

    public static void main(String[] args)
    {
        Thread t1 = new PrintThread();
        Thread t2 = new Thread(new PrintRunnable());

        t1.start();
        t2.start();
    }

}

class PrintThread extends Thread{

    public void run(){
        System.out.println("In there !! Creating thread with extending Thread class");
    }
}

class PrintRunnable implements Runnable{

    @Override
    public void run()
    {
        System.out.println("In there !! Creating thread with implementing Runnable interface !! ");
    }
}

In the example above we are creating thread with both extending Thread class and also implementing Runnable interface. We have created a class PrintThread which is extending the Thread class and in the run method we have printed a string. On the other hand we have also created  class PrintRunnable which is implementing runnable interface and we have overridden the run method of this interface and in the run method we did some dummy text.

If you see the code thoroughly, in the main method where we have instantiated both Thread, the class with is extending the thread class we have created direct object, since it is extending the thread class, where as the class which is implementing the Runnable interface, we have created a Thread object and passed Runnable object to it.

One we are done with the initiation part, all we need to do is to start the threads.

Upon running the code what we got as output is:Threading in Java

Synchronization in Java:

Synchronization is the concept of acquiring lock on an object. In java each object has a lock and to acquire the lock on an object we need to use a keyword that is used for this purpose only, that is synchronized.

By using this keyword we can acquire lock on an object, the scope of lock can be on method or on a particular piece of code.  It is always advisable to lock a particular piece of code instead of locking the entire method. Since if there will be lock on the method level then all objects will be kept on waiting stating until unless the running thread does not completes its task.

A part of synchronized keyword, Lock api does the same task. So we can use Lock api as well instead of synchronized keyword.

Back to top

What are different access modifiers in java, explain with example?

Access modifiers are the modifiers which provides access/visibility to class, method, field.

In java there are four access modifiers :

  • Public
  • Private
  • Protected
  • Default

Public access modifier provides object visibility to anywhere. Any object can access public class, public interface from anywhere. When we are saying anywhere it means from any class from any package. Public access modifier can be applied on class, methods, fields , constructor, interfaces and inner classes.

Private access modifier provides object visibility to no-where, other than the class. It is just reverse of public access modifier. Private access modifier can be applied on methods, fields, and constructor and inner classes.

Protected access modifier provides object visibility to same package or any other package where the class is been sub classed. Protected access modifier can be applied on methods, fields and constructor.

Default access modifier provides object visibility to same package only. Default access modifier can be applied on class, methods, fields, constructor and inner classes.

Lets check the same with some code stuff. We will be creating two packages to check the access, also we will add one class with four methods with four different access modifiers and we try to check how the visibility goes.

Lets start with creating CheckAccess class which has four methods with all four modifiers.

package com.javatutorial.accessmodifiers;

public class CheckAccess
{
    public void doCheckPublicAcccess(){
        System.out.println("Method with public access modifier, Accessed from outer class");
    }

    private void doCheckPrivateAcccess(){
        System.out.println("Method with private access modifier");
    }

    void doCheckDefaultAccess(){
        System.out.println("Method with Default access modifier");
    }

    protected void doCheckProtectedAccess(){
        System.out.println("Method with Protected access modifier");
    }
}

Lets create a Main class and try to access these four methods.

package com.javatutorial.accessmodifiers;

public class MainCheckAccess
{
    public static void main(String[] args)
    {
        CheckAccess access = new CheckAccess();

        access.doCheckDefaultAccess();

        access.doCheckProtectedAccess();

        access.doCheckPublicAcccess();

        access.doCheckPrivateAcccess();

    }
}

So we have added all four methods, lets try and run the code.

Upon running the code what we got is:Private Access Modifier in Java

So we got exception, since doCheckPrivateAccess has the private access modifier and doesnot have visibility to outer class other then the class itself where it is declared.

Lets test the same with other package. So we will be creating the same main class in other package and try to run the code.Main Check Access

So as we can see other than method with public access modifier, no methods can be accessed in this class which is other package. So it is as expected, now check for protected modifier which are accessible from other package where class is sub classed. Let’s modify our code and check:

package com.javatutorial.accessmodifierotherpackage;

import com.javatutorial.accessmodifiers.CheckAccess;

public class MainCheckAccess extends CheckAccess
{
    public void testAccess(){
        doCheckProtectedAccess();

        doCheckPublicAcccess();

        doCheckPrivateAcccess();

        doCheckDefaultAccess();
    }

    public static void main(String[] args)
    {
        new MainCheckAccess().testAccess();
    }
}

Upon compilation of this code what we got is:Java Access Modifiers

Only public and protected modifiers have visibility in this class. Public one because public has visibility all over and protected because protected access modifier has visibility in same package and other package where it sub classed.

Back to top

What is thread pool in java? Explain executor framework with different types of thread pools in java?

Thread pool, as the name suggests, it is a special kind of pool that maintains threads. Thread pool keep threads alive and not let them die. Whenever a task needs a thread, thread pool fetches the thread from thraedpool and allocates to task. Thread does its task and again comes into the pool.

So we are talking about die of thread, what is that special thing in thread that don’t keep threads to die. Or if we take the same in other way, when a thread dies. When we call thread has completed the task and it is no more alive now.

So we are talking about the run() method of thread. This method is responsible for keeping the thread alive, when a thread exits from the run method it is died. What thread pool does specially is that it don’t get the thread exit from the run method. This is so special about the thread pools.

To create thread in java is not an easy task behind the scene for vm. What thread pool does specially for vm is it just removes the extra thing that vm needs to do for creating threads separately. In java there is something called executor framework, which provides some special kind of thread pools. Using the executor framework the same can be achieved.

Let’s talk about the thread pools that executor framework provides. There are four kind of threadpools in java:

  • Fixed Size Thread Pool
  • Cached Thread Pool
  • Single Thread executor
  • Scheduled Thread Pool

Fixed Size Thread Pool

Fixed size thread pool is a thread pool, where a fix number of threads are available. Whenever any task arrives it is been allocated to a thread whichever is free at that point of time. If no thread is free at that point of time the task is kept on waiting until a thread is free. If any thread dies during run, then it’s executor functionality to ensure that the thread will be created.

Signature to create service with this kind of thread pool is:

ExecutorService executorService = Executors.newFixedThreadPool(<number of threads>);

Here 10 is number of threads that we want as part of this service. These can very as per requirement.

Threads in this thread pool dies once shutdown() is called, till then all threads in the threadpool are kept alive and they keep picking tasks.

Cached Thread pool:

Cached thread pool is a thread pool, where threads are kept in cache and they are created as and when needed.  If there are threads available and a task arrives then the threads are reused. Once a thread is done with the task then the same thread is kept into the pool. In order to make is more efficient and less resource consumption, the threads in pool are terminated after every 60 seconds, which are idle.

Signature to create service with this kind of thread pool is:

ExecutorService executorService = Executors.newCachedThreadPool();

This piece of code will create an executor where threads will be created as and when needed and idle threads will be terminated after a minute.

Single Thread Executor :

Single thread  executor is a thread executor  where exactly one thread executes a task. So it is guaranteed that one task will be executed at one point of time. If any task arrives when the executor is executing a task, then the arrived task is kept in a queue and as soon the executor completes the running task, new task got picked and is executed. This kind of thread pool is used when tasks are required to run sequentially.

Signature to create service with this kind of thread pool is:

ExecutorService executorService = Executors.newSingleThreadExecutor();

The above line of code will create an executor with a single thread.

Scheduled Thread Pool :

Scheduled thread pool is a kind of thread pool where threads can be scheduled to run at certain amount of time. Threads can also be triggered to run at certain period. In this case threads will run at a certain period.

Back to top

Continue with Java Interview Questions Preparation

What is collection framework, explain collection hierarchy? Briefly explain List, Set, Map, Comparator and comparable.

Collections in Java

Above is the diagram of collection framework. Collection interface sits on the top of the hierarchy, below this there are interfaces like List, Set, Queue that extends this Collection interface.  Below this in hierarchy are the Classes that implement these interfaces. Like ArrayList, LinkedList etc classes implements List interface. Whereas Hash Set etc classes implements Set interface. LinkedList, PriorityQueue implements Queue interface.

Interesting to see there is no Map interface in this hierarchy, isn’t it ? Map interface has its own hierarchy, and the reason behind it that Map works on key, value pair rest all collection classes works on value part only and not key value.

Let’s see how Map hierarchy goes: Map Heirarchy in Java

As we can see in the diagram, classes like HashMap, HashTable implements Map interface, since Map stores in key, value pair and not only the elements.

Lets start with List interface :

Whenever one wants to store elements in ordered sequence, that can be accessed based on index or based on iteration, List interface is used there. List maintains the insertion order and retrieval on list is also based on the iteration of the list. List store any type of objects and based on the object type if it is primitive List automatically box unbox the primitive data types. One more property of list interface is that list allows the null and duplicate elements that are not allowed in some of the data structures that we will talk later on.

Most common and most used implementation of list interface are LinkedList and ArrayList.List Interface in Java

The above are the methods available in list interface. Implementation of the same can be found in each and every implementation of List interface.

Lets move to set interface:

Generally we use set where we want no duplicate elements, HashSet is most common implementation of Set interface and most widely used.

Set has the property that is does not allows any duplicate elements, one null element is allowed but not more than one null element.

One more important thing to keep in mind is that, whenever we are using any custom object in Set, we must override the equals and hash code methods from object class these are utter important when dealing with the hash based collection.

Let’s now move to Map interface:

Map interface is used when we want some key value kind of relationship. This is the only reason that map does not fall into the standard Collection hierarchy. Since if you can see all the implementation of the Collection interface have only the value part and none of them has the key value mapping. So what if one needs key value mapping, here Map comes to rescue, Map provides key value mapping of the objects.

As we talked in the Set part, while dealing with Maps as well one must override the equals and hash code methods from object class and provide the implementation accordingly.

Whenever one dealing with sorting of collection, Comparable and Comparator are the collection that we needs to use. Both are used for sorting of the underlying collection.

It is all about the collection interface in brief.

Back to top

Explain are Inner classes in Java? When will you use an Inner Class?

Inner classes as the name suggests are the classes within classes. So there will be outer classes and inner classes concept. Inner classes will always be a part of outer class and they will be enclosed in outer classes.

Inner classes behave much more similar to a method in a class or a field in a class. Like there are members of a class same as inner classes will also be part of class within which the inner class in enclosed.

Usually we should avoid to use inner classes because class within a class and to read such kind of code is a bit hard, inner classes are good to write but at the same time they make your code less readable.

Also to maintain the code with such properties is not an easy task, like if there are some modifications in the class than one should have the full knowledge about the class how it was written and what the inner class in is has intended to.

Lets take an example of inner class:

package com.javatutorial.innerclass;

public class Employee
{
    String name;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    static class Department{
        int id;

        public int getId()
        {
            return id;
        }

        public void setId(int id)
        {
            this.id = id;
        }

    }
}

So we have created a class named Employee and there is an inner class called Department. Outer class have one field name and inner class also have one field id that is of type integer.

Lets see how this class can be used.

We will be creating a main class and we will try to use this class:

package com.javatutorial.innerclass;

public class MainInner
{
    public static void main(String[] args)
    {
        Employee emp = new Employee();
        emp.setName("Ahmad");
        Employee.Department department = new Employee.Department();
        department.setId(12);
    }
}

This is how the inner class can be used. As we can see the Department class is property of Employee class then the Department will be accessed can be only accessed with reference of Employee class only.

There is one more concept as well to create anonymous inner classes, let see how to create and use them.

This is how inner classes are created and used in java.

Back to top

This Java Tutorial Series is continued and you can find more Java Interview Questions in next Web Development Tutorial here.

Top Technical Interview Questions and Answers Series:

The post MUST Have Core Java Interview Questions – Part 2 appeared first on Web Development Tutorial.


MUST Have Core Java Interview Questions – Part 3

$
0
0

We are continuing with Part-3 of MUST Have Core Java Interview Questions and Detailed answers tutorial. Major topics covered in this Java Tutorial are Garbage Collection in Java, File Handling and Java I/O, Generics in Java, Hashmap details and performance improvements in it.

Java Interview Questions and Answers

Complete Java Interview Questions List

Udemy

Explain garbage collection with example? What are different parameters to tune GC?

Garbage collection is most important and most critical part of JVM. Whenever we create any object it is created on the heap area. When these objects keep on creating in the heap area, heap gets full and whenever on the full heap VM tries to put a new object, it does not allows and throw error.

This is same in C,C++ as well, where we need to remove the object or clear the space manually and need to create destructor to finalize object.

Java takes this part a step forward and provides garbage collector which automatically collects the unused objects and keeps heap space happy. So programmer while writing program needs not to worry about the object destruction part.

Java provides automatic garbage collection, and it just removes the objects that are not reachable anymore.

There are two kind of object state in Heap :

Reachable, these are the objects that are referenced.

Unreachable, there are the objects that are not referenced from anywhere.

Below is the diagram how the heap is divided:Garbage Collection Java Tutorial

This is how the head is divided into regions.  There are basically two regions in heap, these are Young Generation and Old Genearation.

Lets talk about both of them brief:

Young Generation : As the name suggests, young generation is the space where once the object is formed, it is placed in. Young generation is further divided into two regions that are Eden Space and Survivor Space. Eden space is the space where all the fresh or new objects are placed, once any new object is created with new, it will be placed into Eden space. We will talk about GC strategy afterwards but when GC cycle runs and any object that survives one cycle are moved to Survivor space and in Survivor space these objects are keep moving from one to other from each GC cycle. Some objects that became unreachable are garbage collected and some objects who are still reachable are exists in the survivor space.

Old Generation:  Old generation again as the name suggests where old objects are placed. So we have talked about the survivor space in young generation. Objects that are survived more than a threshold that is max tenuring threshold are moved to old generation.

Below is the GC parameter for this threshold:

-XX:MaxTenuringThreshold

Whenever any object crosses the number that is given in MaxTenuringThreshold, the same object is promoted to Old generation.

There are GC cycles as well, they kicks in when JVM sense low heap memory.

Minor GC Cycle is GC cycle that run periodically and collects the unreachable objects.  Whenever there is memory crunch and there is low memory then GC triggers major GC that runs on whole heap and collects the objects that are unreachable.

If your JVM continuously kicks major GC then there are possible chances of memory leak. In this case one needs to check application and find out the possible memory leak.

There are different kind of Garbage collectors available and we can use any of them with our application.

  • Serial Collector : Serial garbage collector is a garbage collector which runs with single thread and the same can be used for small applications.
  • CMS : CMS stands for concurrent mark sweep garbage collector. In this kind of garbage collector JVM continually does mark and sweep on the objects that are in the heap. This runs along with the application. One more thing about this garbage collector is that it doesnot stops the world, it just stops the world on mark/remark process. When we say stop the world it means that the application will be paused for a small amount of time.
  • Parallel: Parallel garbage collector is a garbage collector which uses multiple CPU’s to garbage collect from heap. Uses multiple CPU’s to mark and sweep. This garbage collector stops the world when it runs.
  • G1 : G1 stands for Garbage First, Introduced in java 7, this garbage collector divides the heap into small small regions. Regions with most garbage will be collected first.

There are different VM arguments to select the respective garbage collector:

For Serial GC:

-XX:+UseSerialGC

For Parallel GC:

-XX:+UseParallelOldGC

For CMS GC:

-XX:+UseConcMarkSweepGC

For G1 GC:

-XX:+UseG1GC

Back to top

Explain file handling in java, explain I/O in java, with example?

To deal with file system, java comes with I/o package, which provides a very rich library to interact with any of the file system. I/O basically stands for input/output. Java provides functions that deal with file system, whether creating a file, reading or deleting.

Lets talk about term Stream, that is very widely used term when we talk about i/o in java. So what is stream in java? Stream is basically a sequence of data that will be either reading by our program or our code will be writing, with is in a way input / output operation.

There are abstract classes present different kinds of stream that are ByteStream and CharacterStream. We will be using these classes when writing our code for input/output handling.

For ByteSteam java comes with InputStream and OutputStream, whereas for CharacterStream java comes with Reader and writer classes. For reading out of file system java comes with InputStream, whereas for writing OutputStream is used. For optimization BufferedInputStream and BufferedOutputStream are used.

Below is the hierarchy diagram of I/O classes:File Handling in Java

So this is how the file system hierarchy goes. Dotted one means there are multiple implementations but we have listed some of them. You can go through the java doc for all specification. But these are the implementations which are most widely used while dealing with file system.

Lets write code for creating file and write some data over it:

package com.javatutorial.file.io;

import java.io.*;

public class MainIO
{
    private static final String FILE_LOCATION="c:\\data\\tempfile.txt";
    private static final String DATA = "This is dummy data";

    public static void main(String[] args) throws IOException
    {
        MainIO main = new MainIO();
        main.writeFile(FILE_LOCATION, DATA);

    }

    void writeFile(String fileLocation, String data)
    {
        BufferedOutputStream outputStream = null;
        try{
            File file = new File(fileLocation);
            file.createNewFile();
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
            outputStream.write(data.getBytes());
        }catch(IOException ioe){
            ioe.printStackTrace();
        }finally{
            if(outputStream != null){
                try
                {
                    outputStream.flush();
                    outputStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

    }
}

Lets understand the code first and then try to run and see what happens. What we have done is we first created File object and created a new file in our system. Once we are done with creating new file, we have to write some data in this. For this purpose we have used BufferedOutputStream, since as we have discussed earlier as well, BufferedOutputStream is optimized way while we deal with file system. After that we just write byte array to output stream which will actually write the data to our file system.

Lets run the code and try to find if it working fine:TempFile in System Path

So as we can see tempfile has been created in the given system path. Lets open and see if it containes the data that we have passed:Java TempFile

Allright, so we got the data what we wanted to write in the file. This was a very simple example of how to write data in a file using I/O library in java. In the same way using FileInputStream we can read the data from file system as well. Apart of these i/o library has a lot of methods to deal with file system. This is all about file handling in java using i/o library.

Back to top

Explain generics in java with example?

From java 1.5 a new concept is emerged that was generics and from then this was used very heavily in all types of applications. What was so special in generics and what does it solved. Lets understand in this section.

Basically generics provide some very useful features like type safety. Type safety is some thing which was not there in java before java1.5, type safety is a concept which says there is only and only one type of object is allowed in collection.

For example:

List<String> list = new ArrayList<>();

In the above example only String type of objects are allowed in this collection. If one tries to enter any object other than String complier will throw the error.

Here one more important thing of generics comes that is check at compile time and not run time. And this is another good thing which is these small types of thigs are detected at compile time and not at run time.

If one tries to add integer or some other object compiler will throw error and it is not allowed to do.

What if one tries to create a Generic class, let’s try to create on:

package com.javatutorial.generics;

public class Generic<T>
{
    T obj;

    void setObj(T obj){
        this.obj = obj;
    }

    T getObj(){
        return obj;
    }
}

So we have created a simple generic class with set and get the object. To create one we need to modify the class signature what we usually writes, and append a generic object term to it, in the example above we used it as T. T is the type of object what we will try to set and get from our main class.

Lets create our main class and test if our Generic class working fine:

package com.javatutorial.generics;

public class MainGenerics
{

    public static void main(String[] args)
    {
        Generic<String> objGeneric = new Generic<>();

        objGeneric.setObj("Test");

        String obj = objGeneric.getObj();

        System.out.println("Object :: "+obj);
    }

}

Executing the above code we got the output as:Generic Classes in Java

So we got what we set with the Generic class’s setObj method.

We can use generics on the method level as well like we used on class level.

Subtyping is not allowed in generics. Like we can not use subtype while declare with generics. Like we can not use Object and String as subtype in generics. For example:

List<Object> objList = new ArrayList<String>();

Writing the above line, compiler will complain and the code will not compile. Lets try to run and see what the above code will throw exception.MainGenerics in Java

Running the code will throw the above exception. Irrespective of String is subtype of Object, but the compiler will not allow to use the sub types in generics.

Back to top

Explain HashMap in detail, what are performance enhancements in HashMap in Java8?

Hashmap is a special kind of collection in java and why we use special kind of collection with HashMap is because unlike other type of collection, HashMap provides key, value pair type of collection which other collection doesnot provides.

HashMap works on concept of hashing. One thumb rule is while working with hash based collection is that when writing custom classes and use them as a key in HashMap, we should always override HashCode and equals methods.

And why these are important is because, based on the hashcode, there is one more method in HashMap class which again calculates hash for the object, just to prevent against poor quality hash code methods.

Below is the implementation of hash method from HashMap class:

final int hash(Object k) {
    int h = hashSeed;
    if (0 != h && k instanceof String) {
        return sun.misc.Hashing.stringHash32((String) k);
    }

    h ^= k.hashCode();

    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}

As we can see, object’s hash code is used again in the HashMap class.

Based on the hash, bucket is defined, on which the object will be placed. So there are buckets which are simply an array. Index of array is calculated based on the hash value and based on the index the values are placed in the bucket.

One more important thing to learn is Entry class, Entry class is an inner class in HashMap, code of Entry class is as follows:

static class Entry<K,V> implements Map.Entry<K,V> {

    final K key;
    V value;
    Entry<K,V> next;
    int hash;

…

So we have just added a glimpse of Entry class to understand what this class does. There is a lot of code in this class, that you can found in the HashMap class itself.

So basically bucket has Entry objects. Entry class is basically a LinkedList, if you see there is a next variable in the class which contains the next pointer. Apart of this there are key and values that HashMap stores.

So why this Entry class is designed as LinkedList?

What we understand earlier is that, based on the hashcode that we have defined in our object, the index is calculated and based on the index the object is placed in HashMap. Now suppose, for two object same index is calculated. If there is same index and if there is already an object is placed in the bucket then will it be overrided ? No, because the Entry class is designed in such a way that if there are more than one object on the same index then these will be added in the Iinked list.

This is because the Entry class is designed as LinkedList.

Now Lets see code for put and get methods in HashMap class.

public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

So as we can see in put method, hash function is used to generate hashcode and the same hash is used to get the index for the bucket. One more thing, there is only one null key allowed in HashMap and the handling for the same can be seen in the method.

Lets see code for get as well:

final Entry<K,V> getEntry(Object key) {
    if (size == 0) {
        return null;
    }

    int hash = (key == null) ? 0 : hash(key);
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k))))
            return e;
    }
    return null;
}

So here we placed code for getEntry, which is been called from get method of HashMap. Here as well same as the put method, hash function is used to calculate the hash and based on hash the bucket is decided and based on bucket the Entry is fetched.

If you see the code of put and get closely then you will find the importance of equals and hashcode methods . And why it is very important to have them in the object that is being used as key in HashMap.

Now lets talk some about performance now, suppose there is very bad hash code designed and that returns the same value each and every time. In this case the bucket location of all objects will be same and the linked list will keep on growing. And once the the linked list grows then to retrieve the element is difficult because the complexity will be O(n) at that time. So what performance improvement being done as part of java8 is that whenever the linked list grows about a threshold the list is converted into a tree, and tree is red black tree, we will not go in the details of redblack tree but certainly the performance improvement will be there. Since the complexity of tree traversal is O(logn) . That is the performance improvement done as part of java8 in HashMap. This is all about HashMap in java.

Back to top

This Java Tutorial Series is continued and you can find more Java Interview Questions and answers in coming Web Development Java Tutorial here.

More Technical Interview Questions and Answers Series:

Udemy

The post MUST Have Core Java Interview Questions – Part 3 appeared first on Web Development Tutorial.

Design your Way Through 2.8 million Android Apps

$
0
0

2.8 Million Android AppsWith a whopping 2.8 million apps in the Android store, we all can wonder how difficult it is for people who are trying to make a mark in the Android app store. The more the number of options users have in front of them, the stiffer the competition grows for these app developers.

Mobile apps have taken a giant leap over a period of past 10 years. They are loaded with a lot of features and they render an alluring tour to the offerings. Thus, helping users to save a lot of their time and energy consumed in doing the task that is just worth few minutes. Now that you have decided to develop your own mobile app, you need to make sure that you are well equipped and versed with the nuances of the craft.

To begin with let’s just divide the making of a mobile app into two parts; say, user experience(UX) and user interface(UI).  Plus, before getting into the intricacies you need to get to know your targeted audience and market you are aiming at. Developing mobile apps is not about spending extravagantly on designing. All that matters is the incredible app interface that brings out the best out of your mobile app.

Moreover, it is expected that the success of a mobile app depends highly on the user experience.  And a ‘bad’ user interface will lead to a bad experience causing the reason of the failure of the app.

I do not advocate that design and interface of an app will completely overshadow the actual essence of the app. However, an intuitive interface packed in an eye-catchy design will surely work as a booster in the conversion.

Interface design is an intermediary between the functionality of interfaces, and it is a key feature in the user experience design. If you are wondering that designing a user interface design needs your full attention then you are absolutely right!

To begin your work you need to set up your Android Studio Layout Editor to the following settings:Android Studio Layout Editor

Move down to app > res > layout > activity_main.xml in your Android Studio’s Project window. To add space to your Layout Editor you can move on to hide the Project window. For this you need to select View > Tool Windows > Project (or you can even click Project option on the left-hand side of your Android Studio).

If there is an XML source depicted on your editor, then click on the Design tab present at the bottom of your monitor screen.

Then you need to click on the Show Blueprint option so as to look at the blueprint layout. Ensure that the Show Constraints option is on. The tooltip available in the toolbar must now read Hide Constraints.

Ensure to disable the Autoconnect. The tooltip available in the toolbar now reads Turn On Autoconnect. There is an option of Default Margins present in the toolbar and then you need to select 16 (it gives the designer to adjust the margin for different view later).

Click Device in Editor available in the toolbar and pick Pixel XL. On the bottom-left side of the window, you will get to see layout’s hierarchy of views known as The Component Tree window. In the picture, we the ConstraintLayout comprises of just one TextView object.

ConstraintLayout has defined the proper positioning for each layout view depending on the constraints applicable on the parent layout and to sibling views.This is the best way to create simple as well as complex layouts with the help of flat view hierarchy. The best part is that with this you do not nested layouts and thus saves a lot of time invested in drawing the UI. Now you can add components such as textbox and button accordingly.

Creating a responsive layout:

In order to make your layout flexible enough to fit into various screen sizes which mean responsive, you will have to stretch the text box stretch in order to fill the horizontal space left. You need to create constraint from the right-hand side corner of the button to the right-hand side of the screen’s parent layout. This will now be the total width available (which can be filled using the text box).

Likewise, you can incorporate constraint from the right-hand side corner of the text box moving on to the left-hand side corner of the button. You might feel that there is no need of the constraint there but this is equivalent to adding a bidirectional constraint between these views. This will constrain both the views to each other. This is known as a chain and it gives you options of some extra layout.

I hope these tips will help you to design a very great user experience and thus will in return work as a sales booster.

Author Bio:

Elley ALoy is a Professional Mobile App Developer works at Mobiers. Mobiers is a leading offshore android app  development company , backed by a strong workforce of 150+ iPhone experts offering high-performance iPhone / iPad app development services to help you surge ahead of the competition.

More Mobile App Development and Related Articles:

The post Design your Way Through 2.8 million Android Apps appeared first on Web Development Tutorial.

MUST Have Python Interview Questions

$
0
0

Here we are starting with a MUST Have Python Interview Questions with detailed answers explaining the concepts with the help of examples and source code. We will start with beginner level basic concepts and further take to  intermediate and advanced topics throughout this Python Interview Questions and Answers Series.
Python Interview Questions

Let’s Move on with Python Interview Questions and Answers

Below is the list of MUST Know Python Interview Questions with detailed answers:

Quick and Easy way to grasp Web, Database, Web Scrapping, Data Science, Web Visualization, Image Processing & More…
  • A Name Generator
  • A Website URL Timed Blocker
  • A Web Map Generator
  • A Portfolio Website with Flask
  • A GUI based desktop Application
  • A Webcam Motion detector
  • A Web Scraper of Property
  • An Interactive web-based Financial Chart
  • A Data Collector Web Application
  • A Geo Coding Web Service

Learn More Now…Click Here

How to Install Python and Prepare Environment?

Python increasingly becoming one of the most popular programming language among developers, especially for Machine Learning and research purpose. This is very easy and straight forward to learn python. The first step of getting started with python, is to install it. In this section we would describe the Installation Process for python in different environment.

How to Install Python:

WINDOWS:

  • Open the download page link on a browser.
    Installing Python on Windows
  • Download the installer package for Windows
    Python Installer Package for Windows Once the download is complete, execute the installer and once the installation s complete, open a terminal and run the following command.
    python -V
  • This will provide the following details.Python Interview Questions

MAC:

  • Open the download page link on a browser.
    Python Installer Package for Mac
  • Download the installer package for Mac OS X
    Python Releases for Mac OS X
  • Once the download is complete, execute the installer and once the installation is complete, open a terminal and run the following command to check if the installation is correct, which will print the version of installed python.
    python -V

LINUX:

  • Python is by default installed.
  • To check if the python is available, open a terminal and run the following command to check if the installation is correct , which will print the version of installed python.
    python -V

Back to top

What are the Key Features/Benefits of using Python?

There are several flexibility and uniqueness in Python that is contributing in order to make this language as one of the most promising language in the world:

  • The community is very large, therefore, there are lots of tutorial and learning material available
  • Easy to learn
  • Comparatively less code is required than any other language
  • Simple and straight forward
  • Machine learning and deep learning community as well as research work are using python extensively.

Benefits using Python:

One of the main argument in favor of python from python developer is that it as for being a dynamic-typed language needs no variable declaration, no explicit type conversion. As a result the same functionality can be implemented in fewer line of code than any other language. Development is quicker in python for this reason.

Python is excellent language for functional programming. Functions are like object, therefore, it is possible to assign them to any other class object or even return from another function as well as can be passed as parameter to other function.

For automation, Python is very popular.

Python is still number one language for big data analytics. Even though R has been designed specifically for data analytics however Python is still number one choice among data scientist for its simplicity and powerful computation tool.

The huge community and lots of opensource tools is another reason for growing popularity of python.

Back to top

Python Specialization from University of Michigan

How does the Ternary Operator work in Python? Explain with the help of a Real-Time example?

One of the most important as well as interesting feature of python is ternary operator. These are conditional expression in Python.

What is Ternary Operator?

These operators are used to evaluate any expression and provide output as either true or false. Some feature of ternary operator are as following:

  • It takes 3 arguments
    [<comparison expression> <result for true statement> <result for false statement>]
  • Example
    $result = ($x==1) ? true: false;
    So If x=1, $result = true otherwise $result = false.
  • This is a common concept across different programming languages. For example,  in Java this is the similar keyword as self.

How does the Ternary Operator work in Python?

In the following example, True and False can be used as the index of the dictionary as True =1 and False = 0.Python Questions

Therefore, True and False can be used as Boolean variable as well. As in the following example:Python Ternary Example

This is the beauty of Python, based on the context the variable can be used as different type.

The if-else block can be defined as following:Python Ternary Example Question

This is the magic of Python.

Back to top

What does the “self” keyword do?

The “self” keyword is a variable that refer to an instance of an object. When a class is created there is not explicit reference of the object of that class type, therefore in python in order to refer the current class or current object, self is used as a reference.

class User:
    def __init__(self):
        self.name = 'Muhammad Ahmad’
        self.age = 16
 
user_obj = User()
user_obj.name    # self.name holds 'Muhammad Ahmad' as value

Back to top

Define the following Items in Python?

Iterator:

Iterator are used for iterating through array:

for k in {"a": 1, "b": 2}:
    print (k)

Function:

Function is very interesting and can be used in so many different ways in python.

Creating a Function: 

The definition of function starts with the keyword “def” and followed by the name of the fucntion and finally it returns a result. In the following example, the name of the function is “square_of_first_ten_number” and it returns the square of 1 to 10.

def square_of_first_ten_number(n):
   return [x**2 for x in range(10)]

This function then can be used in any code segment of the complete program.

Pdb:

Pdb is the debugging module for python, here are some pdb commands for  debugging Python code.

  • To add breakpoint : <b>
  • To resume execution : <c>
  • To go through line by line debugging : <s>
  • To go to next line : <n>
  • To list source code : <l>
  • To print an expression : <p>

Generator:

  • A function that returns inerrable object
  • Used to control iterative behavior of a loop
  • it contains yield expression in the function definition, using yield expression it can iterate, however this can be done only once as the object is not persisted in memory
  • loop can be replaced with generators for efficient iteration over large dataset
    def  customgen(n):
        x = 0
        while x < n:
            x = x + 1
            if x % 4== 0:
                yield x
    
    for i in customgetn(100):
        print i
    The generator in the above example that iterates from 0 to n, and it yields the variable if the loop variable is a multiple of 4.

Lambda:

This is a normal method in python

def square(x):
   return x * 2

This method can be represented as a lambda

square = lambda x: x * 2

lambda can have e a number of arguments but execute a single expression.

Map:

  • Map accepts a function and a list
  • Map is equivalent to for loop
  • However for each iteration, it perform the passed function on each item of the list
  • It returns a list
    list = [1, 2, 3, 4, 5]
    def cube(x): return x ** 3
    list(map(cube, items))
    >>>>[1, 8, 27, 64, 125]

Filter:

  • Accepts a condition and a list
  • Iterate through the list and compute for each item if the condition is true or false
  • Return a subset of given list that matches the condition
list( filter((lambda x: x > 0), range(-5,5)))
>>>>>[1,2,3,4,5]
Reduce:
  • Accepts a function and a list
  • Iterate through the list and compute for each item and perform the operation specified by the function and aggregate the result
reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
24
Static Method:

Static method are method from any python class those can be called from any part of the program without creating a object of the associated class.  From Python 3.6 there is a decorator to define any method as static method and later they can be classed just using the class name such as:

class Fruit(object)
	@staticmethod
	def generaldescription(x):
		print ("This is a static method of Fruit class with argument", x)

Fruit.generaldescription(2) # call static method from Fruit class

The output would be:Static method Output in Python

They can be also called on an object of the class, such as:

class Fruit(object)
	@staticmethod
	def generaldescription(x):
		print ("Fruit class with static method having argument", x)

Fruit().generaldescription(3) # call static method from Fruit class

The output would be as following:Python Static Function Interview Questions

Back to top

Continue with More Advanced Python Interview Questions and Answers

Python 300x250

What is Threading? Explain how multi-threading can be implemented in Python? Give an example of multi-threading using Python?

A thread is a small unit of program that can be scheduled in OS. Usually a program is forked to more than one parallel task and scheduled in OS for the execution of thread. Each process has at least one thread, however it can have more than one thread.

There are two specific kind of thread, such as

  • User- specific
  • kernel

How to Create a Thread in Python?

There are 2 module in python, such as

  1. thread
  2. threading

Using Threading Module:

from threading import Thread

t1 = Thread(target=execute, args=("Thread-1", 1, 5))
t1.start()

Here, target argument in Thread() is a callable function and  args are the argument for the callable function

def execute (name, delay, repeat):
    print("Thread: " + name + " Started")

    while repeat > 0:
        time.sleep(delay)
        print
        name + ": " + str(time.ctime(time.time()))
        repeat -= 1
    print("Thread: " + name + " Completed")

Some Features of Threading in Python:

Multithreading in Python

  • Thread share data and code with main thread
  • Multiple thread can co-exists in the same process and can communicate with each other
  • Multiple thread can execute code faster as they can run concurrently
  • For a single process each thread of its share the global data, therefore it need proper data-lock mechanism while multiple thread is manipulating the same data.

Example of Multi-threading using Python:

Here is an example, when Thread-1 is acquire a lock on particular interval and Thread-2 keep trying to acquire the lock, it can only acquire the lock when the lock has been released by Thread-1.

from threading import Thread
import threading
import time

data=0

def timer(name, delay, repeat, lock):
    print("Timer: " + name + " Started")
    global data
    while repeat > 0:
        time.sleep(delay)
        if(name == 'Thread-1'):
            while True:
                lock.acquire()
                try:
                    print('Locking')
                    time.sleep(1.0)
                finally:
                    print('Releasing Lock')
                    lock.release()
                    time.sleep(1.0)
        if(name == 'Thread-2'):
            num_tries = 0
            num_acquires = 0
            while num_acquires < 3:
                time.sleep(0.5)
                print('Trying to acquire')
                acquired = lock.acquire(0)
                try:
                    num_tries += 1
                    if acquired:
                        print('Try',num_tries, ': Acquired' )
                        num_acquires += 1
                    else:
                        print('Try ',num_tries, ': Not acquired')
                finally:
                    if acquired:
                        lock.release()
            print('Done after',num_tries,' tries' )
        print(name + ": " + str(time.ctime(time.time()))+":",data)

        repeat -= 1
    print("Thread: " + name + " Completed")



def main():
    lock = threading.Lock()
    t1 = Thread(target=timer, args=("Thread-1", 1, 2,lock))
    t2 = Thread(target=timer, args=("Thread-2", 2, 2, lock))
    t1.start()
    t2.start()

    print("Main proogram complete")



if __name__ == '__main__':
   main()

The output would be as following:

Timer: Thread-1 Started
Timer: Thread-2 Started
Main proogram complete
Locking
Releasing Lock
Trying to acquire
Try 1 : Acquired
Locking
Trying to acquire
Try  2 : Not acquired
Trying to acquire
Try  3 : Not acquired
Trying to acquire
Releasing Lock
Try  4 : Not acquired
Trying to acquire
Try 5 : Acquired
Locking
Trying to acquire
Try  6 : Not acquired
Trying to acquire
Try  7 : Not acquired
Releasing Lock
Trying to acquire
Try 8 : Acquired
Done after 8  tries
Thread-2: Sun Jun 25 22:53:53 2017: 0
Locking
Releasing Lock
Trying to acquire
Try 1 : Acquired
Locking
Trying to acquire
Try  2 : Not acquired
Trying to acquire
Try  3 : Not acquired
Releasing Lock
Trying to acquire
Try 4 : Acquired
Trying to acquire
Try 5 : Acquired
Done after 5  tries

  • Thread-2: Sun Jun 25 22:53:57 2017: 0
    Thread: Thread-2 Completed
  • Thread can be interrupted or can totally put into sleep for certain time.
  • Each data can have its own local data and local code
  • Thread run in the same process of the main program, it can run concurrently with main thread, so it is used for quick task or background task.

In the following example, two separate thread is performing two different operation on the same global data:

from threading import Thread
import time

data=0

def timer(name, delay, repeat):
    print("Timer: " + name + " Started")
    global data
    while repeat > 0:
        time.sleep(delay)
        if(name == 'Thread-1'):
            data= data+5
        if(name == 'Thread-2'):
            data = data*5
        print(name + ": " + str(time.ctime(time.time()))+":",data)

        repeat -= 1
    print("Thread: " + name + " Completed")



def main():
    t1 = Thread(target=timer, args=("Thread-1", 1, 5))
    t2 = Thread(target=timer, args=("Thread-2", 2, 5))
    t1.start()
    t2.start()

    print("Main proogram complete")



if __name__ == '__main__':
   main()

The output would be as following

Timer: Thread-1 Started
Timer: Thread-2 Started
Main proogram complete
Thread-1: Sun Jun 25 22:39:59 2017: 5
Thread-2: Sun Jun 25 22:40:00 2017: 25
Thread-1: Sun Jun 25 22:40:00 2017: 30
Thread-1: Sun Jun 25 22:40:01 2017: 35
Thread-2: Sun Jun 25 22:40:02 2017: 175
Thread-1: Sun Jun 25 22:40:02 2017: 180
Thread-1: Sun Jun 25 22:40:03 2017: 185
Thread: Thread-1 Completed
Thread-2: Sun Jun 25 22:40:04 2017: 925
Thread-2: Sun Jun 25 22:40:06 2017: 4625
Thread-2: Sun Jun 25 22:40:08 2017: 23125
Thread: Thread-2 Completed

Back to top

What is __init__.py? How to import class from different directory?

__init__.py is mainly used to initialize Python packages.Initialize Python Packages

the __init__.py file in a lstm_m directory indicates to the Python interpreter that this directory is to be treated like a Python package.

How to Import Class from different Directory?

Usually  __init__.py  is an empty file. Now if we want to use lstm.py in run.py file we simple need to import it as following:

Import Class in Python

And also there must be a __init__.py  inside the module folder that is intended to be imported.

Back to top

Python Certification Training

Explain different ways of Reading and Writing files in Python?

The most popular reason for using Python in order to process file, is that it supports streaming. For example, in order to read huge data set for big data analytics and process the file.

Usercase 1: Read all txt files in a directory

The yield command enables a function to comeback where it left off when it is called again. It took only 4 line to execute this processing.

for root, directories, files in os.walk(given_directory):
        for file in filter(lambda file: file.endswith('.txt'), files):
            # read each document as one big string
            document = open(os.path.join(root, file)).read()
            # returns a generator
            yield document

Usercase 2: Read a huge file using generator

def get_line():
     with open('filename') as file:
         for i in file:
             yield i

lines_required = 100
gen = get_line()
chunk = [next(gen) for i in range(lines_required)]

Back to top

How do we debug a Program in Python? Is it possible to step through Python code?

There is a built-in model ‘pdb’ which provide a interactive python debugger.

python -m pdb mypyscript.py

Run pdb from  interpreter

>>> import pdb_script
>>> import pdb
>>> pdb.run('pdb_script.MyPyObj(6).go()')
> <string>(1)<module>()
(Pdb)

From python script file

import pdb

class MyObj(object):
    count = 5
    def __init__(self):
        self.count= 9

    def go(self):
        for i in range(self.count):
            pdb.set_trace()
            print i
        return

if __name__ == '__main__':
    MyObj(5).go()

Back to top

Describe Python’s Garbage Collection Mechanism?

Garbage Collector:

As like Java, python also has its own built-in garbage collector, it release memory when any memory taken by any object is no longer is being used.  Now when garbage collector know the memory is not being used. Garbage collector use reference counter of object, if the reference counter of any object is 0, it is called dead object and it is ready to be cleared by GC.  However, this mechanism is called as referencing counting.  Referencing counting is easy to implement, however, it is not thread safe. If a object has been referenced so many times that is also stored in memory, therefore, for a single object it need to store name, reference counter and value which needs memory.Python Interview Questions

Another algorithm used by python to manage garbage collection is Mark and Sweep Tracing.

Cyclic Reference:

When two object reference each other. The reference cant not be deleted.  This situation is known as cyclical reference. Under this situation the reference counter for both x and y is ot 0, therefore even if they are not being used, however, it is not collected by garbage as both of them are unreachable.Cyclic Reference in Python

Mark and Sweep Tracing:

Any garbage collection algorithm must perform 2 basic operations. One, it should be able to detect all the unreachable objects and secondly, it must reclaim the heap space used by the garbage objects and make the space available again to the program.

The above operations are performed by Mark and Sweep Algorithm in two phases:

1) Mark phase

2) Sweep phase

Mark

This mechanism follows a depth first search to search each object and check its mark bit, which is assigned to 0 at the time creation, if that object is reachable from current object, that is marked as 1, otherwise the mark bit remains 0.

Sweep

So all the objects whose mark bit is still 0 are considered as unreachable object. And this mechanism clear off all the unreachable objects and thereby clears the heap memory. Now the mark value for all the reachable objects is reset to false for further garbage detection.

Back to top

The course is designed to cover web, database, data science, web scrapping, image processing, web visualization and much more.

Followings are few highlight about this Python Online Course:

  • Best Seller Udemy Online Course
  • 40,016++ students enrolled
  • 6,251 Review available
  • 23 Hours on-demand videos
  • 28 Articles
  • 36 Supplemental Resource
  • Access on Mobile and TV
  • Certificate of Completion
  • Lifetime Access
  • 30 days Money back guarantee
  • You can get the course at Discounted Price here.

Most attractive feature is 30 days Money Back Guarantee means there is NO RISK. If you didn’t like this Python Online Course, you can refund your money back within 30 days of purchase.

Take-This-Course

This was first part in Python Language Interview Questions and details answers.  We will explore more advanced concepts in following parts. Keep in touch.
Step forward in 2017: Build in-demand career skills with Coursera

More Python and Related:

The post MUST Have Python Interview Questions appeared first on Web Development Tutorial.

MUST Have Python Interview Questions – Part 2

$
0
0

Python Interview Questions

Continue with More Advanced Python Interview Questions and Answers

Below is the list of MUST Know Python Interview Questions with detailed answers:

Python 300x250

Explain how to make HTTP request in Python?

There are different ways to make http request:

Get Request using httplib2:

Here is an example session that uses the “GET” method:

>>> import httplib2
>>> http = httplib2.Http()
>>> response = http.request("http://edition.cnn.com")[0]
>>> content = http.request("http://edition.cnn.com")[1]
>>> print (response.status, response.reason)
200 OK
>>> print(content.decode())
<!DOCTYPE html><html class="no-js"><head><meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"> …………..
>>> sport = http.request("http://edition.cnn.com/sport", 
                       method="GET")[1]

Post Request:

Here is an example session that shows how to “POST” requests:

>>> import httplib2, urllib
>>> params = urllib.urlencode({'id': 1, 'name': ‘john’, 'address': ‘dublin’})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "application/json"}
>>> http = httplib2.Http()
>>> request = httplib.request("somehost.com:80",method="POST", ...headers={"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "application/json"}, body=urllib.parse.urlencode(params))
>>> response = request[0]
>>> print response.status, response.reason
200 OK
>>> content = request[1].decode()

Back to top

Describe how to connect to MongoDB. Explain Basic CRUD operation using Python.

Install python driver for mongodb with following command:

pip install pymongo

Create a python script with name dbconnect.py as following:

# import python driver
from pymongo import MongoClient

def dbConnect:
      client = MongoClient()
      client = MongoClient("mongodb://addressbook.net:27017")
      db = client.addressbook # addressbook is the database name
# accessing collection 
     mycollection = db.dataset

  • Insert Data with PyMongo
    There are two method to insert data to database inser_one() and insert_many() to add data to a collection. If dataset is a collection in addressbook database.
    Insert_one:
    >>> result = db.dataset.insert_one({'address': ‘140,summertown,london’})
    >>> result.inserted_id
    ObjectId('54e112cefba822406c9cc208')
    >>> db.dataset.find_one({'address': ‘140,summertown,london’})
    {u'address': ‘140,summertown,london’, u'_id': ObjectId('54e112cefba822406c9cc208')}

    Insert_many:

    >>> result = db.dataset.insert_many([{'address': ‘150,summertown,london’},{'address': ‘9,balnchardstown,dublin’}])
    >>> db.dataset.count()
    3

  • Find Document
    db.dataset.find_one({'address': ‘140,summertown,london’})
    {u'address': ‘140,summertown,london’, u'_id': ObjectId('54e112cefba822406c9cc208')}

    Use cursor to iterate all the address in the dataset collection of addressbook database:

    cursor = db.dataset.find()
    for address in cursor:
        print(address)

    Use cursor to perform logical and operation, this will print all document those have city= london and postcode=10075.

    cursor = db.dataset.find({"address.city": "london", "address.zipcode": "10075"})
     for address in cursor:
      print(address)

    If we want to perform an or operation the cursor would be as following

    cursor = db.dataset.find(
        {"$or": [{"address.city": " london"}, {"address.zipcode": "10075"}]})

  • Update data
    There are update_one and update_many two method  in order to update data:
    update_one:
    result = db.dataset.update_one(
        {"address_id": "101"},
        {"$set": {"address.street": "9 Coolmine,Dublin"}}
    )

    update_many:

    result = db.dataset.update_many(
        {"address.zipcode": "10016", "address.city": "Burlin"},
        {
            "$set": {"address.zipcode": "10016C"},
            "$currentDate": {"lastModified": True}
        }
    )

  • Delete Data
    The following command will delete all the address data where city = london.
    result = db.dataset.delete_many({"city": "london"})

Back to top

Python Specialization from University of Michigan

How does Python handle the memory management?

The different type of memory for python are as following:Different Memory Types in Python

Memory management is very interesting in python. There are 2 types of object which are

  • Primitive object like number or string
  • Container object such as dictionary, list or user defined class

Each object has a value, one or more name and reference count. For example, in the following example.Handling Memory in Python

10 is a python object, it has 2 name x and y and the reference count for the object is 2 as two name is referred to the object.

If we execute print(id(x)), it shows the memory location for x which is also the same memory location for y. Therefore  x and y both are name for same object ‘10’.

Now if we assign x to z , we can see that the memory location for z is exactly same as x and y which is actually the memory location for 10.

If we execute, print (x is y) => it will print ‘True’, as both x and y is referring to the same object which is 300.

If we execute ‘del x’, it will not delete the object, however the reference count for 300 will be decreased by one.

If we create another object w and give it value ‘car’, it would create a string object and will get different memory location.Memory Managment in Python

If we assign w to z, which was earlier assigned with x , which was a number, z would point to the memory location of w instead of x, and x is z => false.

Heap Memory and Stack Memory:

def main():
    x=300
    print(id(x))
    w=sqr(x)
    print(id(w))
def sqr(x):
    print (id(x))
    z=x*x
    print(id(z))
    return z
if __name__ == "__main__":
    main()

In this above example, under main method an object 300 has been referenced with name x.  and there is another function has been defined as sqr. For the above example, the output would be:

1036686092944
1036686092944
1036681129680
1036681129680

So in both function main and sqr, the x is referencing to the same memory location. And z as well as w are referencing to the same memory location. When sqr method is returned the reference z is no longer in scope, therefore the reference count of 90000 is reduced to 0 and the returned value is assigned to w and w also referenced to 90000, the reference count to w in increased by 1. Every function is executed on stack memory and each reference is also created in stack memory. However the object is created in heap memory.Python Memory Management

Back to top

More Python Related Tutorials:

Describe the following Data Structure in Python?

Hashtable:

This is a data structure which stores object as a (key,value) tuple.

hashtable = {}

hashtable[1] = "Summer"
hashtable[2] = "Fall"
hashtable[3] = "Winter"
print(hashtable)

The output would be:

Dictionary in Python

Dictionary:

  • Dictionary is as an un-ordered set of key: value pairs where keys are unique.
  • {} is an empty dictionary.
  • The dict() constructor builds dictionaries directly from sequences of key-value pairs.
    >>> dict([('a', 1), ('b', 2), ('c', 3),(‘d’,4)])
    {'a': 1, 'b': 2, 'c': 3, ‘d’:4}
  • Indexed by keys instead of range of number; keys can be only immutable e.g number, string or tuple with number, string or tuple; if a tuple is of mutable object that can not be key of a dictionary.
  • This can be sorted.

Collections:

Collections module has some subclass of its as following:

  • defaultdict: This is similar as dictionary, however, this is smarter than dictionary as if in case of any missing key in the dictionary, it creates the key and store the value for the key.
  • orderedDict: This data structure keeps all entries sorted by the order of the insertion.
    For example for a general collection as the following example:
    hashtable = {}
    
    hashtable[1] = "Summer"
    hashtable[2] = "Fall"
    hashtable[3] = "Winter"
    
    for key, value in hashtable.items():
        print (key, value)
    The output would be:Collection Output

    Another way of creating ordererdic is as following:

    import collections
    
    hashtable = collections.OrderedDict( [(1, "Summer"), (2, "Fall"), (3, "Winter")] )
    for key, value in hashtable.items():
       print (key, value)

  • Counter: This can count the occurrence of item in a collections. For example for the following code.
    import collections
    
    Fav_seasons = (
       ('John', 'Summer'),
       ('Smith', 'Winter'),
       ('Barak', 'Fall'),
       ('John', 'Fall'),
       ('Smith', 'Summer'),
       ('Ahmed', 'Autumn'),
    )
    
    favseasons = collections.Counter(name for name, season in Fav_seasons)
    print (favseasons)
    
    #hashtable = {}

    John has 2 favorite seasons, Smith has 2 favorite seasons and Barak and Ahmed each has 1 favorite seasons, therefore, the output of this program would be:Python Collections Interview Questions

  • Deque : This is a doubly linked queue. Therefpre , it is possible to add or remove items from the both end of the queue. Once interesting feature of deque is that it can be rotate, for example:
    import collections
    
    d = collections.deque(range(10))
    print('Normal        :', d)
    
    d = collections.deque(range(10))
    d.rotate(2)
    print('Right rotation:', d)
    
    d = collections.deque(range(10))
    d.rotate(-2)
    print('Left rotation:', d)

    The output would be:Python Deque Interview Questions

Back to top

What are Regular Expressions and how to use them in Python?

Regular expression is very important for data analysis and manipulation. Following table would introduce different sign used in python as well as all other programming language for regular expression.

Symbol Definition
^ matches the beginning of a string.
$ matches the end of a string.
\b matches a word boundary.
\d matches any numeric digit.
\D matches any non-numeric character.
(x|y|z) matches exactly one of xy or z.
(x) in general is a remembered group. We can get the value of what matched by using the groups() method of the object returned by re.search.
x? matches an optional x character (in other words, it matches an x zero or one times).
x* matches x zero or more times.
x+ matches x one or more times.
x{m,n} matches an x character at least m times, but not more than n times.
?: matches an expression but do not capture it. Non capturing group.
?=  matches a suffix but exclude it from capture. Positive look ahead.
a(?=b) will match the “a” in “ab”, but not the “a” in “ac”
In other words, a(?=b) matches the “a” which is followed by the string ‘b’, without consuming what follows the a.
?! matches if suffix is absent. Negative look ahead.
a(?!b) will match the “a” in “ac”, but not the “a” in “ab”.
Regular expression flag:
Flag Description
re.I Ignore case.
re.L Matches pattern according to locale.
re.M Enable multi line regular expression.
re.S Make the “.” special character match any character at all, including a newline.
re.U Matches pattern according to Unicode character set.
re.X Ignore whitespace and treats unescaped # as a comment marker.

Example: Validate Email Address

import re
email = abcdefg@gmail.com
email2 = abcdefg#gmail.com

k = false
if(re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email != None):
   k = true
q = false
if(re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email2 != None):
   q = true
print(k)
print(q)

The output would be:Python Regular Expression Questions

Back to top

Python Certification Training

Give some example of Functional programming in Python?

Here is an example of traditional square function in python:

def sqr(x):
    return x*x
 
number = [1, 2, 3, 4]
output = []
for i in number:
    output.append(sqr(i))

Now in functional programming a function take and input and generate output without any intermediate step. If we rewrite the above function as following:

def sqr(x):
    return x*x
 
number = [1, 2, 3, 4]
output = map(sqr, number)

In python map, filter, reduce, lambda are used for functional programming.

Back to top

Describe Python’s Exception Handling mechanism in brief?

Exception Name
Reason
Exception Parent class of all exception.
StopIteration If iterator has no next object to iterate.
SystemExit If system exit abruptly.
StandardError Parent class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError When there is an error in numeric calculation.
OverflowError Raised when a result of any numerical computation is too large.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError When there is a divition by 0 or module by 0 occur.Python Exception Interview Questions
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
ImportError When the module  to be imported is not installed.Python Exception Questions
KeyboardInterrupt Ctrl+C caused this interruption exception.
LookupError Base or parent class for all lookup errors.
IndexError Similar to ArrayIndexOutOfExcerption in Java.
KeyError Dictionary is a container of list of (key,value) air. If the key is not found, this exception is raised.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it.
EnvironmentError Base class for all exceptions which are outside the Python environment.
IOError Raised when there is a file red/write error. Also raised for operating system-related errors.
SyntaxError Raised for any error in Python syntax.
IndentationError Indention is very important in python for each codde block. This error is raised when indentation is not correct.
SystemError If Python interpreter finds an exception. This can be handled in code as the interpreter does not exit.
TypeError Raised when any operation is intended to be executed on a wrong data type.
ValueError Raised when type conversation can not occur due to wrong value.
RuntimeError Raised when an unknown exception occur.
NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

Try-except-finally Block:

try:
 // do some operation
except  Error1:
    // catch exception of type Error1
except  Error2:
    // catch exception of type Error2
else:
   // execute this block when no exception is occurred
finally:
  // the final block excute at the end of try and except either there is an exception or not

Nested Try-except Block:

try:
 // do some operation
     try:
        // this is the nested try block
     except  Error1:
       // catch exception of type Error1 for nested try
    else:
       // execute this block when no exception is occurred
    finally:
       // the final block excute at the end of try and except either there is an exception or not
except  Error2:
    // catch exception of type Error2 for outer try block
else:
   // execute this block when no exception is occurred
finally:
  // the final block excute at the end of try and except either there is an exception or not

Try Block without Except:

Each try block must be followed by either a except of finally block.

try:
   // execute some operation
finally:
  // the final block excute at the end of try and except either there is an exception or not

Different Ways to Handle Exception in Python:

  • Catch exception argument: Exception or can be handled with argument. As in following exception, ‘car’ can not be converted to int and args of error object define the reason for exception.Catch Exception Argument Question
  • Multiple exception in same line.
    try:
       # some operation in thos blcok
    except (Erro1[, Erro2[,...ErroN]]]):
       # if any exception from the list occur , this block would be executed
    else:
       If there is no exception then execute this block

Throw Exception:

Raise command is used to throw an exception either user defined or built-in as following:

  • If the error type is not known, it is possible to catch all kind of exception.Throw Exception Interview Question
  • It is also possible to detect which kind of error has been raised.Detect Error Type
  • It is also possible to pass user defined argument for the thrown exception.User Defined Argument

Back to top

How Object Serialization works in Python?

Object serialization is a simple way to convert an object from format to others and at the same way later this converted form of object can be converted back to the earlier version of object. Python uses a particular mechanism in order to serialize object which is known as ‘pickling’. Using pickling an object can be converted to a binary object.

There are two steps in order to serialize an object:

  • Import the pickling module.
  • Call the dump method with the object as an argument.
    import pickle
    class User:
       def __init__(self, name, age):
           self.name = name
           self.age= age
    class John(User):
       def __init__(self, aget):
           John.__init__(self, “John”, color)
    john = Jhon(18)
    smith = pickle.dumps(john)

Here john and smith are two different type of object. Picling has been used to convert john to smith.

Similarly, way it is also possible to de-serialize the object:

John2 = pickle.loads( smith)

If we only want to convert any python object to json , there are the following two steps need to be executed:

  • Import JSON module.
  • Call dumps function from JSON module and pass the object as an argument.
    import json
    d = [{"name":"John", "age":"10"}, {"name":"Smith", "age":"15"}]
    e = json.dump(d)
    print ("json version", d)

Here, the python object has been serialized to a json variable , the output would be as following:Object Serialization Question in Python

Back to top

Describe Object Oriented feature in Python?

There are two main concept of object oriented programming language. Python also support them.

  • Inheritance
  • Polymorphism

Inheritance:

Any class can be extended from another class. And the child class can access the method of the parent class.Inheritance Question in Python

Following are some example of method access across parent class and child class.

class Fruit:
   def __init__(self, name, color):
        self.__name = name      # __name is private to Fruit class
        self.__color = color
 
    def getColor(self):         # getColor() function is accessible to class Car
        return self.__color
 
    def setColor(self, color):  # setColor is accessible outside the class
        self.__color = color
 
    def getName(self):          # getName() is accessible outside the class
        return self.__name
    
class Apple(Fruit):
 
    def __init__(self, name, color, taste):
        # call parent constructor to set name and color  
        super().__init__(name, color)       
        self.__taste = taste
 
    def getDescription(self):
        return self.getName() +" tastes  "+ self.__taste + " is " + self.getColor() + "in color"
 
c = Apple("Red Apple", "red", "sweet")
print(c.getDescription())
print(c.getName()) # apple has no method getName() but it is accessible through class Fruit

class GreenApple(Apple):
    def __init__(self, name, color, taste, typed):
        # call parent constructor to set name and color  
        super().__init__(name, color, taste)       
        self.__typed = typed
    def getTyped(self):          # getTyped() is accessible outside the class
      return self.__typed    
        
g = GreenApple("Green Apple", "red", "sweet",2)        
print(g.getDescription()) # greenapple has no method getDescription() but it is accessible through class Apple 
print(g.getName()) # greenapple has no method getName() but it is accessible through class Fruit 
print(g.getTyped())

The output would be as following:Inheritance in Python

Polymorphism:

In this following class diagram, both Window and Wall are of Structure type. Therefore, for both of them Structure is the parent class.Polymorphism in Python

So now if we run the following example:Python Structure Questions

The output would be as following:Python Structure Output

As the destroy method has not been implemented in the child classed in Window or Wall therefore, there is an exception has been thrown.  Now if the program is fixed and all the abstract methods are implemented as following the output would be:

class Structure:
    def __init__(self, loadbearing):    
        self.loadbearing = loadbearing
 
    def built(self):             
        raise NotImplementedError("Subclass must implement abstract method")
 
    def destroy(self):             
        raise NotImplementedError("Subclass must implement abstract method")
 
class Window(Structure):
    isOpen=False;
    def close(self):
       self._isOpen =False;
 
    def open(self):
         self._isOpen =True;
    def built(self):
        return 'Wall has been built properly with loadbearing.' 
    def destroy(self):
        return 'Wall has been destroyed properly.'    
 
class Wall(Structure):
    def built(self):
        return 'Wall has been built properly.'
    def destroy(self):
        return 'Wall has been destroyed properly.'    
 
  
structures = [Wall(True),
        Wall(False),
        Window(True)]
 
for structure in structures:
    print (structure.loadbearing)
    print(structure.built())
    print(structure.destroy())
    if isinstance(structure, Window):
     print(structure.isOpen)
     structure.open()
     print(structure.isOpen)

Advanced Python Interview Questions

Back to top

The course is designed to cover web, database, data science, web scrapping, image processing, web visualization and much more.

Followings are few highlight about this Python Online Course:

  • Best Seller Udemy Online Course
  • 40,016++ students enrolled
  • 6,251 Review available
  • 23 Hours on-demand videos
  • 28 Articles
  • 36 Supplemental Resource
  • Access on Mobile and TV
  • Certificate of Completion
  • Lifetime Access
  • 30 days Money back guarantee
  • You can get the course at Discounted Price here.

Most attractive feature is 30 days Money Back Guarantee means there is NO RISK. If you didn’t like this Python Online Course, you can refund your money back within 30 days of purchase.

Take-This-Course

We will soon add a small Online Test to enhance user skills. Keep in touch.
Step forward in 2017: Build in-demand career skills with Coursera

More Python and Related:

The post MUST Have Python Interview Questions – Part 2 appeared first on Web Development Tutorial.

Top 10 Tips to Prepare For a Web Developer Interview

$
0
0

Getting a job in web development today requires you to go through a comprehensive technical interview since employers not only want someone who knows how to code but one who has the ability to solve problems. Your experience and impressive CV can only tell the employer so much which is why you will need to adequately prepare for a web developer interview in order to stand out from other job seekers. It is important to note that just because you are a good developer does not necessarily mean that you will nail your technical interview. It will take you a lot of preparation to effectively demonstrate your coding skills to recruiters. Here are some tips to prepare for a technical interview especially a web developer interview including preparation tips for online technical interviews and related online tests.Top 10 Tips for Web Developer Interview

1. Thorough practice

As a developer, you will need to take time to practice for your technical interview ahead of time. Whether you have been coding for many years, you still need to practice since an interview environment is completely different from the working environment. You can follow here for a complete reference to web developer interview questions with detailed answers.

2. Research

The tech industry is extremely competitive today which means that to be hired as the best technical talent, you will need to master your technical interview. This involves researching the company’s interview process either through their website or published interview tips. The internet can be a good source of information where you can find question types as well as time limits.

3. Ask for help where necessary

A technical interview presents a perfect opportunity for you to show your employer how much you know about web development. You will not be expected to know everything hence being honest about what you do not know is important. You do not want to waste your time or the recruiter’s by pretending to know everything.

4. Over-communicate

Never assume that the recruiter can read your mind in a technical interview especially when working through a problem in a whiteboard style interview. Think out loud as this not only makes you understand the best way to approach a problem, but it will also make it easy for the interviewers to help you.

5. Avoid arguments and confrontation

Never argue with your recruiters even if you feel that they are wrong. Instead, turn the arguments into a conversation. This is important because it will keep you in good terms with the interviewer.

Web Developer Interview Questions with Answers:

6. Let the interviewer know about your best career achievement

During your web development career, there may be something that you consider as your greatest achievement. Be sure to describe it in a way that will make the recruiter feel that it is indeed an extraordinary achievement.

7. Ask “smart” questions

When presented with an opportunity to ask questions at the end of the interview, focus on making yourself look good by asking brilliant questions.

8. Profile yourself

Be sure to have a solid online presence which also involves establishing an active digital footprint. Highlight the most relevant information that includes your experience and education. For more professional communication, create your own profile on networking sites such as LinkedIn and Stack Overflow.

9. Learn how to cope with interview bias

It is normal for job recruiters to subconsciously or unintentionally hold biases or make judgments against you. Find a way to go beyond these biases by portraying your strong skills and attributes.

10. Be up-to-date

The technical industry is experiencing many changes and upgrades hence you must show your interviewers that you are up-to-date with these changes as well as industry trends as this shows your interest in the web development field.

The post Top 10 Tips to Prepare For a Web Developer Interview appeared first on Web Development Tutorial.

Viewing all 26 articles
Browse latest View live




Latest Images