Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 152

Q. When to use a tuple vs list vs dictionary in Python?

Entry

 Use a tuple to store a sequence of items that will not change.

 Use a list to store a sequence of items that may change.

 Use a dictionary when you want to associate pairs of two items.

Q. Explain some benefits of PythonEntry

 Python is a dynamic-typed language. It means that you don’t need to mention


the data type of variables during their declaration.

 Python supports object-orientated programming as you can define classes


along with the composition and inheritance.

 Functions in Python are like first-class objects. It suggests you can assign
them to variables, return from other methods and pass them as arguments.

 Developing using Python is quick but running it is often slower than compiled
languages.

 Python has several usages like web-based applications, test automation, data
modeling, big data analytics, and much more.

Q. What are local variables and global variables in Python?Entry

 Global Variables: Variables declared outside a function or in a global space


are called global variables. These variables can be accessed by any function in
the program.

 Local Variables: Any variable declared inside a function is known as a local


variable. This variable is present in the local space and not in the global space.

Q. What is Lambda Functions in Python?Junior


A Lambda Function is a small anonymous function. A lambda function can
take any number of arguments, but can only have one expression.

Consider:
x = lambda a : a + 10

print(x(5)) # Output: 15

Q. How do I modify a string in python?Junior


You can’t because strings are immutable in python. In most situations, you should
simply construct a new string from the various parts you want to assemble it from.
Work with them as lists; turn them into strings only when needed.

>>> s = list("Hello zorld")

>>> s

['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']

>>> s[6] = 'W'

>>> s

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

>>> "".join(s)

'Hello World'

Q. What is a Negative Index in Python?Junior


Negative numbers mean that you count from the right instead of the left. So, list[-
1] refers to the last element, list[-2] is the second-last, and so on.
Q. How the string does get converted to a number?Junior

 To convert the string into a number the built-in functions are used like int() a
constructor. It is a data type that is used like int (‘1’) == 1 .

 float() is also used to show the number in the format as float(‘1’) = 1 .

 The number by default are interpreted as a decimal and if it is represented


by int(‘0x1’) then it gives an error as ValueError. In this
the int(string,base) the function takes the parameter to convert string to
number in this the process will be like int(‘0x1’,16) == 16 . If the base
parameter is defined as 0 then it is indicated by octal and 0x indicates it as a
hexadecimal number.

 There is function eval() that can be used to convert a string into number but it
is a bit slower and present many security risks

Q. What is docstring in Python?Junior

 A documentation string or docstring is a multiline string used to document a


specific code segment.

 The docstring should describe what the function or method does.

Q. Does Python have a switch-case statement?Junior


In Python before 3.10, we do not have a switch-case statement. Here, you may write
a switch function to use. Else, you may use a set of if-elif-else statements. To
implement a function for this, we may use a dictionary.

def switch_demo(argument):

switcher = {

1: "January",

2: "February",

3: "March",

4: "April",

5: "May",

6: "June",

7: "July",

8: "August",
9: "September",

10: "October",

11: "November",

12: "December"

print switcher.get(argument, "Invalid month")

Python 3.10 (2021) introduced the match-case a statement that provides a first-class
implementation of a "switch" for Python. For example:

For example:

def f(x):

match x:

case 'a':

return 1

case 'b':

return 2

The match-case the statement is considerably more powerful than this simple
example.
Q. What are descriptors ?Junior
Descriptors were introduced to Python way back in version 2.2. They provide the
developer with the ability to add managed attributes to objects. The methods needed
to create a descriptor are __get__, __set__ and __delete__. If you define any of
these methods, then you have created a descriptor.
Descriptors power a lot of the magic of Python’s internals. They are what make
properties, methods and even the super function work. They are also used to
implement the new style classes that were also introduced in Python 2.2.
Q. What are Virtualenvs ?Mid

 A virtualenv is what Python developers call an isolated environment for


development, running, debugging Python code.

 It is used to isolate a Python interpreter together with a set of libraries and


settings.

 Together with pip, it allows developing, deploy and run of multiple


applications on a single host, each with its own version of the Python
interpreter, and a separate set of libraries.

Q. What is Monkey PatchingMid


In Python, the term monkey patch only refers to dynamic modifications of a class or
module at runtime, which means a monkey patch is a piece of Python code that
extends or modifies other code at runtime.

Monkey patching can only be done in dynamic languages, of which python is a good
example. In Monkey patching, we reopen the existing classes or methods in class at
runtime and alter the behavior, which should be used cautiously, or you should use it
only when you really need to. As Python is a dynamic programming language,
Classes are mutable so you can reopen them and modify or even replace them.

For example:

import datetime

datetime.datetime.now = lambda: datetime.datetime(2012, 12, 12)

Most of the time it's a pretty terrible idea - it is usually best if things act in a well-
defined way. One reason to monkey patch would be in testing. The mock package is
very useful to this end.
Q. What is Pickling and Unpickling?Mid
The pickle the module implements a fundamental, but powerful algorithm for
serializing and de-serializing a Python object structure.
 Pickling - is the process whereby a Python object hierarchy is converted into a
byte stream,

 Unpickling - is the inverse operation, whereby a byte stream is converted back


into an object hierarchy.

>>> import random

>>> import pickle

>>> num_list = [random.random() for _ in range(10_000)]

>>> len(num_list)

10000

>>> num_list[:3]

[0.4877162104023087, 0.23514961430367143, 0.683895941250586]

>>> with open('nums.out', 'wb') as f:

... pickle.dump(num_list, f)

...

>>> with open('nums.out', 'rb') as f:

... copy_of_nums_list = pickle.load(f)

...

>>> copy_of_nums_list[:3]

[0.4877162104023087, 0.23514961430367143, 0.683895941250586]

>>> num_list == copy_of_nums_list


True

Q. What is a None value in Python?Mid


None is just a value that commonly is used to signify 'empty', or 'no value here.

If you write a function, and that function doesn't use an explicit return
statement, None is returned instead, for example.

Another example is to use None default values. it is good programming practice to not
use mutable objects as default values. Instead, use None it as the default value and
inside the function, check if the parameter is None and create a new
list/dictionary/whatever if it is.

Consider:

def foo(mydict=None):

if mydict is None:

mydict = {} # create a new dict for local namespace

Q. Explain Decorators in Python?Mid


In Python, functions are the first-class objects, which means that:

 Functions are objects; they can be referenced to, passed to a variable, and
returned from other functions as well.

 Functions can be defined inside another function and can also be passed as
arguments to another function.

Now:

 Decorators allow us to wrap another function in order to extend the


behavior of the wrapped function, without permanently modifying it.

 Decorators are a very powerful and useful tool in Python since it allows
programmers to modify the behavior of a function or class.
@gfg_decorator

def hello_decorator():

print("Gfg")

'''Above code is equivalent to:

def hello_decorator():

print("Gfg")

hello_decorator = gfg_decorator(hello_decorator)'''

Q. Explain the difference between lists and tuples ?Mid

 The key difference is that tuples are immutable. This means that you cannot
change the values in a tuple once you have created it.

 If you're going to need to change the values using a List.

Apart from tuples being immutable, there is also a semantic distinction that should
guide their usage. Tuples are heterogeneous data structures (i.e., their entries have
different meanings), while lists are homogeneous sequences. Tuples have structure,
and lists have been ordered.

One example of a tuple is pairs of the page and line number to reference locations in a
book, e.g.:

my_location = (42, 11) # page number, line number


You can then use this as a key in a dictionary to store notes on locations. A list on the
other hand could be used to store multiple locations. Naturally one might want to add
or remove locations from the list, so it makes sense that lists are mutable. On the other
hand, it doesn't make sense to add or remove items from an existing location - hence
tuples are immutable.
Q. Why would you use the pass statement ?Mid
Python has the syntactical requirement that code blocks cannot be empty. Empty code
blocks are however useful in a variety of different contexts, for example, if you are
designing a new class with some methods that you don't want to implement:

class MyClass(object):

def meth_a(self):

pass

def meth_b(self):

print "I'm meth_b"

If you were to leave out the pass, the code wouldn't run and you'll get an error:

IndentationError: expected an indented block

Other examples when we could use pass:

 Ignoring (all or) a certain type of Exception

 Deriving an exception class that does not add new behavior

 Testing that code runs properly for a few test values, without caring about the
results

Q. What's the difference between the list methods append() and extend()?Mid

 append adds an element to a list, and


 extend concatenates the first list with another list (or another iterable, not
necessarily a list).

Consider:

x = [1, 2, 3]

x.append([4, 5])

print (x)

# [1, 2, 3, [4, 5]]

x = [1, 2, 3]

x.extend([4, 5])

print (x)

# [1, 2, 3, 4, 5]

Q. How to define static methods in pythonMid


To define a static method, you use the @staticmethod decorator:

class className: @staticmethod def static_method_name(param_list):


pass

Code language: Python (python)

To call a static method, you use this syntax:

className.static_method_name()
Q. How does Python memory management work?Mid
Python - like C#, Java, and many other languages -- uses garbage collection rather
than manual memory management. You just freely create objects and the language's
memory manager periodically (or when you specifically direct it to) looks for any
objects that are no longer referenced by your program.
If you want to hold on to an object, just hold a reference to it. If you want the object to
be freed (eventually) remove any references to it.

def foo(names):

for name in names:

print name

foo(["Eric", "Ernie", "Bert"])

foo(["Guthtrie", "Eddie", "Al"])

Each of these calls to foo creates a Python list object initialized with three values.
For the duration of the foo call they are referenced by the variable names, but as soon
as that function exits no variable is holding a reference to them and they are fair game
for the garbage collector to delete.

Q. What is a Callable?Mid

 A callable is anything that can be called.

 A callable object allows you to use round parenthesis ( ) and eventually pass
some parameters, just like functions.

Every time you define a function python creates a callable object. In the example, you
could define the function func in these ways (it's the same):

class a(object):

def __call__(self, *args):

print 'Hello'
func = a()

# or ...

def func(*args):

print 'Hello'

Q. How to make a flat list out of list of lists?Mid


Given a list of lists l consider:

flat_list = []

for sublist in l:

for item in sublist:

flat_list.append(item)

Or using the lambda function:

flatten = lambda l: [item for sublist in l for item in sublist]

print(flatten([[1],[2],[3],[4,5]]))

# Output: [1, 2, 3, 4, 5]

Q. How to use Slicing in Python?Mid


It's pretty simple really:

a[start:stop] # items start through stop-1

a[start:] # items start through the rest of the array


a[:stop] # items from the beginning through stop-1

a[:] # a copy of the whole array

There is also the step value, which can be used with any of the above:

a[start:stop:step] # start through not past stop, by step

The key point to remember is that the :stop the value represents the first value that
is not in the selected slice. So, the difference between stop and start is the number
of elements selected (if step is 1, the default).

The ASCII art diagram is helpful too for remembering how slices work:

+---+---+---+---+---+---+

|P|y|t|h|o|n|

+---+---+---+---+---+---+

0 1 2 3 4 5 6

-6 -5 -4 -3 -2 -1

Slicing built-in types return a copy but that's not universal.


Q. What is introspection/reflection and does Python support it?Mid
Introspection is the ability to examine an object at runtime. Python has a dir() the
function that supports examining the attributes of an object, type() to check the
object type, isinstance(), etc.

While introspection is a passive examination of the objects, reflection is a more


powerful tool where we could modify objects at runtime and access them
dynamically. E.g.

 setattr() adds or modifies an object's attribute;

 getattr() gets the value of an attribute of an object.

It can even invoke functions dynamically:


getattr(my_obj, "my_func_name")()

Q. What is the difference between range and xrange? How has this changed over
time?Mid

 xrange returns the xrange object while range returns the list, and uses the same
memory and no matter what the range size is.

 For the most part, xrange and range are the exact same in terms of
functionality. They both provide a way to generate a list of integers for you to
use, however you please.

 The only difference is that range returns a Python list object and x range returns
an xrange object. This means that xrange doesn’t actually generate a static list
at run-time as range does. It creates the values as you need them with a special
technique called yielding. This technique is used with a type of object known as
generators. That means that if you have a really gigantic range you’d like to
generate a list for, say one billion, xrange is the function to use.

 This is especially true if you have a really memory-sensitive system such as a


cell phone that you are working with, as range will use as much memory as it
can to create your array of integers, which can result in a Memory Error and
crash your program. It’s a memory-hungry beast.

Q. What are the Dunder/Magic/Special methods in Python?Mid


Dunder (derived from double underscore) methods are special/magic predefined
methods in Python, with names that start and end with a double underscore. There's
nothing really magical about them. Examples of these include:

 __init__ - constructor

 __str__, __repr__ - object representation (casting to string, printing)

 __len__, __next__... - generators

 __enter__, __exit__ - context managers

 __eq__, __lt__, __gt__ - operator overloading

Q. What are with statment in Python ?Mid


The with statement simplifies exception handling by encapsulating common
preparation and cleanup tasks in so-called context managers.

For instance, the open the statement is a context manager in itself, which lets you
open a file, keep it open as long as the execution is in the context of the with a
statement where you used it, and close it as soon as you leave the context, no matter
whether you have left it because of an exception or during regular control flow.

As a result, you could do something like:

with open("foo.txt") as foo_file:

data = foo_file.read()

OR

from contextlib import nested

with nested(A(), B(), C()) as(X, Y, Z):

do_something()

OR (Python 3.1)

with open('data') as input_file, open('result', 'w') as output_file:

for line in input_file:

output_file.write(parse(line))

OR

lock = threading.Lock()

with lock: #Critical section of code

Q. How can I create a copy of an object in Python?Mid


 To get a fully independent copy (deep copy) of an object you can use
the copy.deepcopy() function. Deep copies are recursive copies of each
interior object.

 For shallow copy use copy.copy(). Shallow copies are just copies of the
outermost container.

Q. What does this stuff mean: *args, **kwargs? Why would we use it?Mid

 Use *args when we aren't sure how many arguments are going to be passed to
a function, or if we want to pass a stored list or tuple of arguments to a
function.

>>> def print_everything(*args):

for count, thing in enumerate(args):

... print( '{0}. {1}'.format(count, thing))

...

>>> print_everything('apple', 'banana', 'cabbage')

0. apple

1. banana

2. cabbage

 **kwargs is used when we don't know how many keyword arguments will be
passed to a function, or it can be used to pass the values of a dictionary as
keyword arguments.

>>> def table_things(**kwargs):

... for name, value in kwargs.items():


... print( '{0} = {1}'.format(name, value))

...

>>> table_things(apple = 'fruit', cabbage = 'vegetable')

cabbage = vegetable

apple = fruit

Q. What does an x = y or z assignment do in Python?Mid


x = a or b

If bool(a) returns False, then x is assigned the value of b.


Q. What is the function of self?Mid
Self is a variable that represents the instance of the object to itself. In most object-
oriented programming languages, this is passed to the methods as a hidden parameter
that is defined by an object. But, in python, it is declared and passed explicitly. It is
the first argument that gets created in the instance of the class A and the parameters to
the methods are passed automatically. It refers to a separate instance of the variable
for individual objects.

Let's say you have a class ClassA which contains a method methodA defined as:

def methodA(self, arg1, arg2): #do something

and ObjectA is an instance of this class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for


you as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself.


Q. What is the most efficient way to concatenate many strings together?Mid
str and bytes objects are immutable, therefore concatenating many strings together
is inefficient as each concatenation creates a new object. In the general case, the total
runtime cost is quadratic in the total string length.
To accumulate many str objects, I would recommend placing them into a list and
call str.join() at the end:

chunks = []

for s in my_strings:

chunks.append(s)

result = ''.join(chunks)

Q. What is the difference between deep and shallow copy ?Senior

 Shallow copy is used when a new instance type gets created and it keeps the
values that are copied in the new instance. Whereas, a deep copy is used to
store the values that are already copied.

 Shallow copy is used to copy the reference pointers just like it copies the
values. These references point to the original objects and the changes made in
any member of the class will also affect the original copy of it. Whereas, deep
copy doesn’t copy the reference pointers to the objects. Deep copy makes the
reference to an object and the new object that is pointed by some other object
gets stored. The changes made in the original copy won’t affect any other copy
that uses the object.

 Shallow copy allows faster execution of the program and it depends on the size
of the data that is used. Whereas, deep copy makes it slower due to making
certain copies for each object that is been called.

Q. Explain the difference between @staticmethod and @classmethod?Senior


A staticmethod is a method that knows nothing about the class or the instance it was
called on. It just gets the arguments that were passed, no implicit first argument. Its
definition is immutable via inheritance.

class C:

@staticmethod
def f(arg1, arg2, ...): ...

A classmethod, on the other hand, is a method that gets passed the class it was called
on, or the class of the instance it was called on, as the first argument. Its definition
follows Sub class, not Parent class, via inheritance.

class C:

@classmethod

def f(cls, arg1, arg2, ...): ...

If your method accesses other variables/methods in your class then


use @classmethod.
Q. Is it a good idea to use multi-thread to speed your Python code?Senior
Python doesn't allow multi-threading in the truest sense of the word. It has a multi-
threading package but if you want to multi-thread to speed your code up, then it's
usually not a good idea to use it.

Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure
that only one of your 'threads' can execute at any one time. A thread acquires the GIL,
does a little work, then passes the GIL onto the next thread. This happens very quickly
so to the human eye it may seem like your threads are executing in parallel, but they
are really just taking turns using the same CPU core. All this GIL passing adds
overhead to execution.
Q. What is MRO in Python? How does it work?Senior
Method Resolution Order (MRO) it denotes the way a programming language
resolves a method or attribute. Python supports classes inheriting from other classes.
The class being inherited is called the Parent or Superclass, while the class that
inherits is called the Child or Subclass.

In Python, method resolution order defines the order in which the base classes are
searched when executing a method. First, the method or attribute is searched within a
class and then it follows the order we specified while inheriting. This order is also
called Linearization of a class and set of rules are called MRO (Method Resolution
Order). While inheriting from another class, the interpreter needs a way to resolve the
methods that are being called via an instance. Thus we need the method resolution
order.
Python resolves method and attribute lookups using the C3 linearisation of the class
and its parents. The C3 linearisation is neither depth-first nor breadth-first in
complex multiple inheritance hierarchies.
Q. Can you explain Closures (as they relate to Python)?Senior
Objects are data with methods attached, closures are functions with data attached.
The method of binding data to a function without actually passing them as parameters
is called closure.

def make_counter():

i=0

def counter(): # counter() is a closure

nonlocal i

i += 1

return i

return counter

c1 = make_counter()

c2 = make_counter()

print (c1(), c1(), c2(), c2())

# -> 1 2 1 2

Q. Explain how you reverse a generator?Senior


You cannot reverse a generator in any generic way except by casting it to a sequence
and creating an iterator from that. Later terms of a generator cannot necessarily be
known until the earlier ones have been calculated.
Even worse, you can't know if your generator will ever hit a StopIteration exception
until you hit it, so there's no way to know that there will even be the first term in your
sequence.

The best you could do would be to write a reversed_iterator function:

def reversed_iterator(iter):

return reversed(list(iter))

Q. What is the purpose of the single underscore _ variable in Python?Senior


_ has 4 main conventional uses in Python:

1. To hold the result of the last executed expression(/statement) in an interactive


interpreter session. This precedent was set by the standard CPython interpreter,
and other interpreters have followed suit

2. For translation lookup in i18n (see the gettext documentation for example), as
in code like: raise forms.ValidationError(_("Please enter a correct
username"))

3. As a general-purpose "throwaway" variable name to indicate that part of a


function result is being deliberately ignored (Conceptually, it is being
discarded.), as in code like: label, has_label, _ = text.partition(':') .

4. As part of a function definition (using either def or lambda), where the


signature is fixed (e.g. by a callback or parent class API), but this particular
function implementation doesn't need all of the parameters, as in code
like: callback = lambda _: True

Q. How to make a chain of function decorators?Senior


Code:

from functools import wraps

def makebold(fn):
@wraps(fn)

def wrapped(*args, **kwargs):

return "<b>" + fn(*args, **kwargs) + "</b>"

return wrapped

def makeitalic(fn):

@wraps(fn)

def wrapped(*args, **kwargs):

return "<i>" + fn(*args, **kwargs) + "</i>"

return wrapped

@makebold

@makeitalic

def hello():

return "hello world"

@makebold

@makeitalic

def log(s):
return s

print hello() # returns "<b><i>hello world</i></b>"

print hello.__name__ # with functools.wraps() this returns "hello"

print log('hello') # returns "<b><i>hello</i></b>"

Q. Why are default values shared between objects?Senior


It is often expected that a function call creates new objects for default values. This is
not what happens. Default values are created exactly once, when the function is
defined. If that object is changed, like the dictionary in this example, subsequent calls
to the function will refer to this changed object.

Consider:

def foo(mydict={}): # Danger: shared reference to one dict for all calls

... compute something ...

mydict[key] = value

return mydict

The first time you call this function, mydict contains a single item. The second time,
mydict contains two items because when foo()begins executing, mydict starts out
with an item already in it.
Q. What is GIL?Expert
Python has a construct called the Global Interpreter Lock (GIL).

The GIL makes sure that only one of your threads can execute at any one time. A
thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
This happens very quickly so to the human eye it may seem like your threads are
executing in parallel, but they are really just taking turns using the same CPU core.
All this GIL passing adds overhead to execution.
Q. Why would you use metaclasses?Expert
The main use case for a metaclass is creating an API. A typical example of this is the
Django ORM.

It allows you to define something like this:

class Person(models.Model):

name = models.CharField(max_length=30)

age = models.IntegerField()

And if you do this:

guy = Person(name='bob', age='35')

print(guy.age)

It won't return an IntegerField object. It will return an int, and can even take it
directly from the database.

This is possible because models.Model defines __metaclass__ and it uses some


magic that will turn the Person you just defined with simple statements into a complex
hook to a database field.

Django makes something complex look simple by exposing a simple API and
using metaclasses, recreating code from this API to do the real job behind the scenes.
Q. Describe Python's Garbage Collection mechanism in briefExpert
A lot can be said here. There are a few main points that you should mention:

 Python maintains a count of the number of references to each object in


memory. If a reference count goes to zero then the associated object is no
longer live and the memory allocated to that object can be freed up for
something else

 occasionally things called "reference cycles" happen. The garbage collector


periodically looks for these and cleans them up. An example would be if you
have two objects o1 and o2 such that o1.x == o2 and o2.x == o1.
If o1 and o2 are not referenced by anything else then they shouldn't be live. But
each of them has a reference count of 1.
 Certain heuristics are used to speed up garbage collection. For example,
recently created objects are more likely to be dead. As objects are created, the
garbage collector assigns them to generations. Each object gets one generation,
and younger generations are dealt with first.

Q. Why isn't all memory freed when Python exits?Expert


Objects referenced from the global namespaces of Python modules are not
always deallocated when Python exits. This may happen if there are circular
references. There are also certain bits of memory that are allocated by the C library
that are impossible to free (e.g. a tool like Purify will complain about these). Python
is, however, aggressive about cleaning up memory on exit and does try to destroy
every single object.

If you want to force Python to delete certain things on deallocation, you can use
the atexit module to register one or more exit functions to handle those deletions.

Q. How do I access a module written in Python from C?Expert


You can get a pointer to the module object by calling PyImport_ImportModule :

module = PyImport_ImportModule("mymodule");

You can then access the module’s attributes (i.e. any name defined in the module) as
follows:

attr = PyObject_GetAttrString(module, "name");

Calling PyObject_SetAttrString to assign to variables in the module also works.


Q. How to read a very large file in Python?Expert
All you need to do is use the file object as an iterator.

for line in open("log.txt"):

do_something_with(line)

Even better is using context manager in recent Python versions.

with open("log.txt") as fileobject:


for line in fileobject:

do_something_with(line)

This will automatically close the file as well.


Q. Is there any downside to the -O flag apart from missing on the built-in
debugging information?Expert
Many python modules assume docstrings are available, and would break if that
optimization level is used, for instance at the company where I work, raw SQL is
placed in docstrings, and executed by way of function decorators (not even
kidding).

Somewhat less frequently, assert is used to perform logic functions, rather than
merely declare the invariant expectations of a point in code, and so any code like that
would also break.

JAVASCRIPT INTERVIEW QUEST

Q. What is equality in JavaScript ?Entry


JavaScript has both strict and type–converting comparisons:

 Strict comparison (e.g., ===) checks for value equality without


allowing coercion

 Abstract comparison (e.g. ==) checks for value equality


with coercion allowed

var a = "42";

var b = 42;

a == b; // true
a === b; // false

Some simple equality rules:

 If either value (aka side) in comparison could be the true or false value,
avoid == and use ===.

 If either value in comparison could be of these specific values ( 0, "", or [] --


empty array), avoid == and use ===.

 In all other cases, you're safe to use ==. Not only is it safe, but in many cases, it
simplifies your code in a way that improves readability.

Q. What is the object type?Entry


The object type refers to a compound value where you can set properties (named
locations) that each holds their own values of any type.

var obj = {

a: "hello world", // property

b: 42,

c: true

};

obj.a; // "hello world", accessed with doted notation

obj.b; // 42

obj.c; // true

obj["a"]; // "hello world", accessed with bracket notation


obj["b"]; // 42

obj["c"]; // true

Bracket notation is also useful if you want to access a property/key but the name is
stored in another variable, such as:

var obj = {

a: "hello world",

b: 42

};

var b = "a";

obj[b]; // "hello world"

obj["b"]; // 42

Q. Explain is Scope in JavaScript?Entry


In JavaScript, each function gets its own scope. The scope is basically a collection of
variables as well as the rules for how those variables are accessed by name. Only code
inside that function can access that function's scoped variables.

A variable name has to be unique within the same scope. A scope can be nested inside
another scope. If one scope is nested inside another, code inside the innermost scope
can access variables from either scope.
Q. Explain arrays in JavaScriptEntry
An array is an object that holds values (of any type) not particularly in named
properties/keys, but rather in numerically indexed positions:

var arr = [
"hello world",

42,

true

];

arr[0]; // "hello world"

arr[1]; // 42

arr[2]; // true

arr.length; // 3

typeof arr; // "object"

Q. What is typeof operator?Entry


JavaScript provides a typeof operator that can examine a value and tell you what type
it is:

var a;

typeof a; // "undefined"

a = "hello world";

typeof a; // "string"

a = 42;
typeof a; // "number"

a = true;

typeof a; // "boolean"

a = null;

typeof a; // "object" -- weird, bug

a = undefined;

typeof a; // "undefined"

a = { b: "c" };

typeof a; // "object"

Q. Explain the same-origin policy with regards to JavaScript.Junior


The same-origin policy prevents JavaScript from making requests across domain
boundaries. An origin is defined as a combination of URI scheme, hostname, and port
number. This policy prevents a malicious script on one page from obtaining access to
sensitive data on another web page through that page's Document Object Model.
Q. What is the let keyword in JavaScript?Junior
In addition to creating declarations for variables at the function level, ES6 lets you
declare variables to belong to individual blocks (pairs of { .. }), using
the let keyword.
Q. Explain Values and Types in JavaScriptJunior
JavaScript has typed values, not typed variables. The following built-in types are
available:
 string

 number

 boolean

 null and undefined

 object

 symbol (new to ES6)

Q. What's the difference between Host objects and Native objects?Junior


Built-in objects: String, Math, RegExp, Object, Function etc. - core predefined
objects are always available in JavaScript. Defined in the ECMAScript spec.

Host objects: objects like window, XmlHttpRequest , DOM nodes, and so on, which
are provided by the browser environment. They are distinct from the built-in objects
because not all environments will have the same host objects. If JavaScript runs
outside of the browser, for example as a server-side scripting language like in Node.js,
different host objects will be available
Q. What is the difference between == and === ?Junior
== is the abstract equality operator while === is the strict equality operator.
The == operator will compare for equality after doing any necessary type conversions.
The === operator will not do type conversion, so if two values are not the same
type === will simply return false. When using ==, funky things can happen, such as:

1 == '1'; // true

1 == [1]; // true

1 == true; // true

0 == ''; // true

0 == '0'; // true

0 == false; // true
My advice is never to use the == operator, except for convenience when comparing
against null or undefined, where a == null will
return true if a is null or undefined.

var a = null;

console.log(a == null); // true

console.log(a == undefined); // true

Q. Explain strict mode?Junior


JavaScript's strict mode, introduced in ECMAScript 5, is a way to opt into a restricted
variant of JavaScript, thereby implicitly opting out of "sloppy mode". Strict mode
isn't just a subset: it intentionally has different semantics from normal code.

Strict mode makes several changes to normal JavaScript semantics:

1. Eliminates some JavaScript silent errors by changing them to throw errors.

2. Fixes mistakes that make it difficult for JavaScript engines to perform


optimizations: strict mode code can sometimes be made to run faster than
identical code that's not strict mode.

3. Prohibits some syntax likely to be defined in future versions of ECMAScript.

Q. What is a Polyfill?Junior
A polyfill is essentially the specific code (or plugin) that would allow you to have
some specific functionality that you expect in current or “modern” browsers to also
work in other browsers that do not have the support for that functionality built-in.

 Polyfills are not part of the HTML5 standard

 Polyfilling is not limited to Javascript

Q. Explain Null and Undefined in JavaScriptJunior


JavaScript (and by extension TypeScript) has two bottom types: null and undefined.
They are intended to mean different things:

 Something hasn't been initialized: undefined.

 Something is currently unavailable: null.


Q. Explain different methods of iteration in JavascriptJunior
For objects:

 for loops - for (var property in obj) { console.log(property); } .


However, this will also iterate through its inherited properties, and you will add
a obj.hasOwnProperty(property) check before using it.

 Object.keys() - Object.keys(obj).forEach(function (property) { ...


}). Object.keys() is a static method that will list all enumerable properties of
the object that you pass it.

 Object.getOwnPropertyNames() - Object.getOwnPropertyNames(obj).for
Each(function (property) { ... }) . Object.getOwnPropertyNames() is
a static method that will list all enumerable and non-enumerable properties of
the object that you pass it.

For arrays:

 for loops - for (var i = 0; i < arr.length; i++) . The common pitfall
here is that var is in the function scope and not the block scope and most of the
time you would want a block-scoped iterator variable. ES2015
introduces let which has block scope and it is recommended to use that
instead. So this becomes: for (let i = 0; i < arr.length; i++) .

 forEach - arr.forEach(function (el, index) { ... }) . This construct


can be more convenient at times because you do not have to use them index if
all you need is an array of elements. There are also
the every and some methods that will allow you to terminate the iteration early.

Q. Remove duplicates of an array and return an array of only unique


elementsJunior
// ES6 Implementation
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];

Array.from(new Set(array)); // [1, 2, 3, 5, 9, 8]

// ES5 Implementation
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];

uniqueArray(array); // [1, 2, 3, 5, 9, 8]
function uniqueArray(array) {
var hashmap = {};
var unique = [];

for(var i = 0; i < array.length; i++) {


// If key returns undefined (unique), it is evaluated as false.
if(!hashmap.hasOwnProperty(array[i])) {
hashmap[array[i]] = 1;
unique.push(array[i]);
}
}

return unique;
}

Q. Given a string, reverse each word in the sentenceJunior


var string = "Welcome to this Javascript Guide!";

// Output becomes !ediuG tpircsavaJ siht ot emocleW


var reverseEntireSentence = reverseBySeparator(string, "");

// Output becomes emocleW ot siht tpircsavaJ !ediuG


var reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");

function reverseBySeparator(string, separator) {


return string.split(separator).reverse().join(separator);
}

Q. Explain what a callback function is and provide a simple exampleJunior


A callback the function is a function that is passed to another function as an
argument and is executed after some operation has been completed. Below is an
example of a simple callback function that logs to the console after some operations
have been completed.

function modifyArray(arr, callback) {

// do something to arr here

arr.push(100);

// then execute the callback function that was passed

callback();

}
var arr = [1, 2, 3, 4, 5];

modifyArray(arr, function() {

console.log("array has been modified", arr);

});

Q. How to compare two objects in JavaScript?Mid


Two non-primitive values, like objects (including function and array) held by
reference, so both == and === comparisons will simply check whether the references
match, not anything about the underlying values.

For example, arrays are by default coerced to strings by simply joining all the values
with commas (,) in between. So two arrays with the same contents would not
be == equal:

var a = [1,2,3];

var b = [1,2,3];

var c = "1,2,3";

a == c; // true

b == c; // true

a == b; // false

For deep object comparison use external libs like deep-equal or implement your own
recursive equality algorithm.
Q. Explain Function.prototype.bindMid
The bind() the method creates a new function that, when called, has its this keyword
set to the provided value, with a given sequence of arguments preceding any provided
when the new function is called.
Q. Explain Closure in JavaScriptMid
Consider:

function makeAdder(x) {

// parameter `x` is an inner variable

// inner function `add()` uses `x`, so

// it has a "closure" over `x`

function add(y) {

return y + x;

};

return add;

Reference to inner add the function returned is able to remember what x value was
passed to makeAdder function call.

var plusOne = makeAdder( 1 ); // x is 1, plusOne has a reference to add(y)

var plusTen = makeAdder( 10 ); // x is 10

plusOne(3); // 1 (x) + 3 (y) = 4


plusTen(13); // 10 (x) + 13 (y) = 23

In C and most other common languages, after a function returns, all the local variables
are no longer accessible because the stack frame is destroyed.

In JavaScript, if you declare a function within another function, then the local
variables can remain accessible after returning from the function you called.

A closure is a stack frame that is allocated when a function starts its execution, and
not freed after the function returns (as if a 'stack frame' were allocated on the heap
rather than the stack!). In JavaScript, you can think of a function reference variable as
having both a pointer to a function as well as a hidden pointer to a closure.
Q. What's the difference between .call and .apply?Mid
Both .call and .apply are used to invoke functions and the first parameter will be
used as the value this within the function. However, .call takes in comma-
separated arguments as the next argument while .apply taking in an array of
arguments as the next argument. An easy way to remember this is C for call comma-
separated and A for apply an array of arguments.

function add(a, b) {

return a + b;

console.log(add.call(null, 1, 2)); // 3

console.log(add.apply(null, [1, 2])); // 3

Q. What is the drawback of creating true private in JavaScript?Mid


One of the drawbacks of creating a true private method in JavaScript is that they are
very memory inefficient because a new copy of the method would be created for each
instance.

var Employee = function (name, company, salary) {


this.name = name || ""; //Public attribute default value is null

this.company = company || ""; //Public attribute default value is null

this.salary = salary || 5000; //Public attribute default value is null

// Private method

var increaseSalary = function () {

this.salary = this.salary + 1000;

};

// Public method

this.dispalyIncreasedSalary = function() {

increaseSalary();

console.log(this.salary);

};

};

// Create Employee class object

var emp1 = new Employee("John","Pluto",3000);

// Create Employee class object


var emp2 = new Employee("Merry","Pluto",2000);

// Create Employee class object

var emp3 = new Employee("Ren","Pluto",2500);

Here each instance variable emp1, emp2, emp3 has own copy of increaseSalary private
method.
Q. Explain the differences on the usage of foo between function foo() {} and var
foo = function() {}Mid
The former is a function declaration while the latter is a function expression. The key
difference is that function declaration have its body hoisted but the bodies of function
expressions are not (they have the same hoisting behavior as variables). If you try to
invoke a function expression before it is defined, you will get an Uncaught
TypeError: XXX is not a function error.

Function Declaration

foo(); // 'FOOOOO'

function foo() {

console.log('FOOOOO');

Function Expression

foo(); // Uncaught TypeError: foo is not a function

var foo = function() {

console.log('FOOOOO');

};

Q. What is the difference between a shim and a polyfill?Mid


 A shim is any piece of code that performs interception of an API call and
provides a layer of abstraction. It isn't necessarily restricted to a web
application or HTML5/CSS3.

 A polyfill is a type of shim that retrofits legacy browsers with modern


HTML5/CSS3 features usually using Javascript or Flash.

A shim is a library that brings a new API to an older environment, using only the
means of that environment. Thus, a polyfill is a shim for a browser API.
Q. What is Coercion in JavaScript?Mid
In JavaScript conversion between different two build-in types called coercion.
Coercion comes in two forms in JavaScript: explicit and implicit.

Here's an example of explicit coercion:

var a = "42";

var b = Number( a );

a; // "42"

b; // 42 -- the number!

And here's an example of implicit coercion:

var a = "42";

var b = a * 1; // "42" implicitly coerced to 42 here

a; // "42"
b; // 42 -- the number!

Q. What is IIFEs (Immediately Invoked Function Expressions)?Mid


It’s an Immediately-Invoked Function Expression or IIFE for short. It executes
immediately after it’s created:

(function IIFE(){

console.log( "Hello!" );

})();

// "Hello!"

This pattern is often used when trying to avoid polluting the global namespace
because all the variables used inside the IIFE (like in any other normal function) are
not visible outside its scope.
Q. What's a typical use case for anonymous functions?Mid
They can be used in IIFEs to encapsulate some code within a local scope so that
variables declared in it do not leak to the global scope.

(function() {

// Some code here.

})();

As a callback that is used once and does not need to be used anywhere else. The code
will seem more self-contained and readable when handlers are defined right inside the
code calling them, rather than having to search elsewhere to find the function body.

setTimeout(function() {

console.log('Hello world!');

}, 1000);
Arguments to functional programming constructs or Lodash (similar to callbacks).

const arr = [1, 2, 3];

const double = arr.map(function(el) {

return el * 2;

});

console.log(double); // [2, 4, 6]

Q. Find Word Positions in TextMid


module.exports = function (text) {
var trie = {},
pos = 0,
active = trie; // Start the active structure as the root trie structure

// Suffix a space after the text to make life easier


text += ' ';

// Loop through the input text adding it to the trie structure


for (var i = 0; i < text.length; i++) {
// When the character is a space, restart
if (text[i] === ' ') {
// If the current active doesn't equal the root, set the position
if (active !== trie) {
(active.positions = active.positions || []).push(pos);
}
// Reset the positions and the active part of the data structure
pos = i;
active = trie;
continue;
}

// Set the next character in the structure up


active[text[i]] = (active[text[i]] || {});
active = active[text[i]];
}

// Return a function that accepts a word and looks it up in the trie structure
return function (word) {
var i = -1,
active = trie;

while (word[++i]) {
if (!active[word[i]]) { return []; }
active = active[word[i]];
}

return active.positions;
};
};

Q. Implement a queue using a linked listMid


We will store a reference to the front and back of the queue in order to make an
enqueuing and dequeuing run in O(1) constant time. Every time we want to insert into
the queue, we add the new element to the end of the linked list and update the back
pointer. When we want to dequeue we return the first node in the linked list and
update the front pointer.

// queue is initially empty

var Queue = {front: null, back: null};

// we will use a node to keep track of the elements

// in the queue which is represented by a linked list

function Node(data, next) {

this.data = data;

this.next = next;

// add elements to queue in O(1) time

function Enqueue(element) {

var N = new Node(element, null);

if (Queue.back === null) {


Queue.front = N;

Queue.back = N;

} else {

Queue.back.next = N;

Queue.back = Queue.back.next;

// remove first element from queue in O(1) time

function Dequeue() {

if (Queue.front !== null) {

var first = Queue.front;

Queue.front = Queue.front.next;

return first.data;

} else {

if (Queue.back !== null) { Queue.back = null; }

return 'Cannot dequeue because queue is empty';

}
Enqueue('a');

Enqueue('b');

Enqueue('c');

Dequeue();

Q. Write a program for all permutations (Anagrams) of a StringMid


Remove the first character and recurse to get all permutations of length N-1, then
insert that first character into N-1 length strings and obtains all permutations of
length N. The complexity is O(N!) because there are N! possible permutations of a
string with length N, so it’s optimal.

module.exports = function (string) {

var result = {};

// Using an immediately invoked named function for recursion.

(function makeWord (word, remaining) {

// If there are no more remaining characters, break and set to true

// in the result object.

if (!remaining) { return result[word] = true; }

// Loop through all the remaining letters and recurse slicing the character

// out of the remaining stack and into the solution word.

for (var i = 0; i < remaining.length; i++) {


makeWord(

word + remaining[i],

remaining.substr(0, i) + remaining.substr(i + 1)

);

})('', string);

// Using the ES5 Object.keys to grab the all the keys as an array.

return Object.keys(result);

};

Q. Find the intersection of two arraysMid


var firstArray = [2, 2, 4, 1];
var secondArray = [1, 2, 0, 2];

intersection(firstArray, secondArray); // [2, 1]

function intersection(firstArray, secondArray) {


// The logic here is to create a hashmap with the elements of the firstArray as the keys.
// After that, you can use the hashmap's O(1) look up time to check if the element exists in the hash
// If it does exist, add that element to the new array.

var hashmap = {};


var intersectionArray = [];

firstArray.forEach(function(element) {
hashmap[element] = 1;
});

// Since we only want to push unique elements in our case... we can implement a counter to keep track of what we
already added
secondArray.forEach(function(element) {
if (hashmap[element] === 1) {
intersectionArray.push(element);
hashmap[element]++;
}
});

return intersectionArray;

// Time complexity O(n), Space complexity O(n)


}

Q. Given an array of integers, find the largest product yielded from three of the
integersMid
var unsortedArray = [-10, 7, 29, 30, 5, -10, -70];

computeProduct(unsortedArray); // 21000

function sortIntegers(a, b) {

return a - b;

// Greatest product is either (min1 * min2 * max1 || max1 * max2 * max3)

function computeProduct(unsorted) {

var sortedArray = unsorted.sort(sortIntegers),

product1 = 1,

product2 = 1,

array_n_element = sortedArray.length - 1;
// Get the product of three largest integers in sorted array

for (var x = array_n_element; x > array_n_element - 3; x--) {

product1 = product1 * sortedArray[x];

product2 = sortedArray[0] * sortedArray[1] * sortedArray[array_n_element];

if (product1 > product2) return product1;

return product2;

Q. Explain the difference between undefined and not defined in JavaScriptMid


In JavaScript if you try to use a variable that doesn't exist and has not been declared,
then JavaScript will throw an error var name is not defined and the script will
stop execute thereafter. But If you use typeof undeclared_variable then it will
return undefined.

Before starting further discussion let's understand the difference between declaration
and definition.

var x is a declaration because you are not defining what value it holds yet, but you
are declaring its existence and the need of memory allocation.

var x; // declaring x

console.log(x); //output: undefined


var x = 1 is both declaration and definition (also we can say we are doing
initialisation), Here declaration and assignment of value happen inline for variable x,
In JavaScript every variable declaration and function declaration brings to the top of
its current scope in which it's declared then assignment happen in order this term is
called hoisting.

A variable that is declared but not define and when we try to access it, It will
result undefined.

var x; // Declaration

if(typeof x === 'undefined') // Will return true

A variable that neither declared nor defined when we try to reference such variable
then It result not defined.

console.log(y); // Output: ReferenceError: y is not defined

Q. What is the definition of a Higher-Order Function?Mid


A higher-order function is any function that takes one or more functions as arguments,
which it uses to operate on some data, and/or returns a function as a result. Higher-
order functions are meant to abstract some operation that is performed repeatedly. The
classic example of this is map, which takes an array and a function as
arguments. map then uses this function to transform each item in the array, returning a
new array with the transformed data. Other popular examples in JavaScript
are forEach, filter, and reduce. A higher-order function doesn't just need to be
manipulating arrays as there are many use cases for returning a function from another
function. Function.prototype.bind is one such example in JavaScript.

Map

Let say we have an array of names which we need to transform each string to
uppercase.

const names = ['irish', 'daisy', 'anna'];

The imperative way will be as such:


const transformNamesToUppercase = function(names) {

const results = [];

for (let i = 0; i < names.length; i++) {

results.push(names[i].toUpperCase());

return results;

};

transformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']

Use .map(transformerFn) makes the code shorter and more declarative.

const transformNamesToUppercase = function(names) {

return names.map(name => name.toUpperCase());

};

transformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']

Q. What is the purpose of setTimeout function?Mid


The setTimeout(cb, ms) the global function is used to run callback cb after at
least ms milliseconds. The actual delay depends on external factors like OS timer
granularity and system load. A timer cannot span more than 24.8 days.
Q. What advantages are using arrow functions?Mid

 Scope safety: Until arrow functions, every new function defined its own value
(a new object in the case of a constructor, undefined in strict mode function
calls, the base object if the function is called as an "object method", etc.). An
arrow function does not create its own this, the this value of the enclosing
execution context is used.
 Compactness: Arrow functions are easier to read and write.

 Clarity: When almost everything is an arrow function, any regular function


immediately sticks out for defining the scope. A developer can always look up
the next-higher function statement to see what this this object is.

Q. What is a generator in JS?Mid


Generators are functions that can be exited and later re-entered. Their context
(variable bindings) will be saved across re-entrances. Generator functions are written
using function* syntax. When called initially, generator functions do not execute
any of their code, instead of returning a type of iterator called a Generator. When a
value is consumed by calling the generator's next method, the Generator function
executes until it encounters the yield keyword.

The function can be called as many times as desired and returns a new Generator each
time, however, each Generator may only be iterated once.

function* makeRangeIterator(start = 0, end = Infinity, step = 1) {

let iterationCount = 0;

for (let i = start; i < end; i += step) {

iterationCount++;

yield i;

return iterationCount;

Q. What is Currying?Mid
Currying is when you break down a function that takes multiple arguments into a
series of functions that take part in the arguments. Here's an example in JavaScript:

function add (a, b) {


return a + b;

add(3, 4); // returns 7

This is a function that takes two arguments, a and b, and returns their sum. We will
now curry this function:

function add (a) {

return function (b) {

return a + b;

In an algebra of functions, dealing with functions that take multiple arguments (or
equivalent one argument that's an N-tuple) is somewhat inelegant. So how do you deal
with something you'd naturally express as, say, f(x,y)? Well, you take that as
equivalent to f(x)(y) - f(x) , call it g, is a function, and you apply that function
to y. In other words, you only have functions that take one argument - but some of
those functions return other functions (which ALSO take one argument).
Q. Explain destructuring an object or an array in ES6?Senior
Destructuring is an expression available in ES6 which enables a succinct and
convenient way to extract values of Objects or Arrays and place them into distinct
variables.

Array destructuring

// Variable assignment.

const foo = ['one', 'two', 'three'];


const [one, two, three] = foo;

console.log(one); // "one"

console.log(two); // "two"

console.log(three); // "three"

// Swapping variables

let a = 1;

let b = 3;

[a, b] = [b, a];

console.log(a); // 3

console.log(b); // 1

Object destructuring

// Variable assignment.

const o = { p: 42, q: true };

const { p, q } = o;

console.log(p); // 42

console.log(q); // true
Q. What is the new keyword in JavaScript?Senior

1. It creates a new object. The type of this object is simply object.

2. It sets this new object's internal, inaccessible, [prototype] (i.e. __proto__)


property to be the constructor function's external, accessible, prototype object
(every function object automatically has a prototype property).

3. It makes the this variable point to the newly created object.

4. It executes the constructor function, using the newly created object whenever
this is mentioned.

5. It returns the newly created object, unless the constructor function returns a
non-null object reference. In this case, that object reference is returned instead.

Consider:

function New(func) {

var res = {};

if (func.prototype !== null) {

res.__proto__ = func.prototype;

var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));

if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {

return ret;

return res;

}
Q. What does the term Transpiling stand for?Senior
There's no way to polyfill new syntax that has been added to the language. So the
better option is to use a tool that converts your newer code into older code
equivalents. This process is commonly called transpiling, a term for transforming +
compiling.

Typically you insert the transpiler into your build process, similar to your code linter
or your minifier. There are quite a few great transpilers for you to choose from:

 Babel: Transpiles ES6+ into ES5

 Traceur: Transpiles ES6, ES7, and beyond into ES5

Q. Explain what is Hoisting in JavascriptSenior


Hoisting is the concept in which Javascript, by default, moves all declarations to the
top of the current scope. As such, a variable can be used before it has been declared.

Note that Javascript only hoists declarations and not initializations.


Q. Check if a given string is a isomorphicSenior
For two strings to be isomorphic, all occurrences of a character in string A can be
replaced with another character to get string B. The order of the characters must be
preserved. There must be one-to-one mapping for every char of string A to every char
of string B.

 paper and title would return true.

 egg and sad would return false.

 dgg and add would return true.

isIsomorphic("egg", 'add'); // true

isIsomorphic("paper", 'title'); // true

isIsomorphic("kick", 'side'); // false


function isIsomorphic(firstString, secondString) {

// Check if the same lenght. If not, they cannot be isomorphic

if (firstString.length !== secondString.length) return false

var letterMap = {};

for (var i = 0; i < firstString.length; i++) {

var letterA = firstString[i],

letterB = secondString[i];

// If the letter does not exist, create a map and map it to the value

// of the second letter

if (letterMap[letterA] === undefined) {

letterMap[letterA] = letterB;

} else if (letterMap[letterA] !== letterB) {

// Eles if letterA already exists in the map, but it does not map to

// letterB, that means that A is mapping to more than one letter.

return false;
}

// If after iterating through and conditions are satisfied, return true.

// They are isomorphic

return true;

Q. When would you use the bind function?Senior


The bind() method creates a new function that, when called, has its this keyword
set to the provided value, with a given sequence of arguments preceding any provided
when the new function is called.

A good use of the bind function is when you have a particular function that you want
to call with a specific this value. You can then use bind to pass a specific object to a
function that uses a this reference.

function fullName() {

return "Hello, this is " + this.first + " " + this.last;

console.log(fullName()); // => Hello this is undefined undefined

// create a person object and pass its values to the fullName function

var person = {first: "Foo", last: "Bar"};


console.log(fullName.bind(person)()); // => Hello this is Foo Bar

Q. Explain how JSONP works (and how it's not really Ajax)Senior
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain
policies in web browsers because Ajax requests from the current page to a cross-
origin domain is not allowed.

JSONP works by making a request to a cross-origin domain via a <script> tag and
usually with a callback query parameter, for example: https://example.com?
callback=printData . The server will then wrap the data within a function
called printData and return it to the client.

<!-- https://mydomain.com -->

<script>

function printData(data) {

console.log(`My name is ${data.name}!`);

</script>

<script src="https://example.com?callback=printData"></script>

// File loaded from https://example.com?callback=printData

printData({ name: 'Yang Shun' });

The client has to have the printData function in its global scope and the function will
be executed by the client when the response from the cross-origin domain is received.

JSONP can be unsafe and has some security implications. As JSONP is really
JavaScript, it can do everything else JavaScript can do, so you need to trust the
provider of the JSONP data.
These days, CORS is the recommended approach and JSONP is seen as a hack.
Q. Explain Prototype Inheritance in JavaScript?Senior
In a language implementing classical inheritance like Java, C# or C++ you start by
creating a class--a blueprint for your objects - and then you can create new objects
from that class or you can extend the class, defining a new class that augments the
original class.

In JavaScript you first create an object (there is no concept of class), then you can
augment your own object or create new objects from it.

Every object in Javascript has a prototype. JavaScript's inheritance system is


prototypical, and not class-based. When a message reaches an object, JavaScript will
attempt to find a property in that object first, if it cannot find it then the message will
be sent to the object’s prototype, and so on. That behavior called prototype
chain of prototype inheritance.

Constructor functions are the most used way in JavaScript to construct prototype
chains. When we use new, JavaScript injects an implicit reference to the new object
being created in the form of the this keyword. It also returns this reference implicitly
at the end of the function.

function Foo() {

this.kind = ‘foo’

var foo = new Foo();

foo.kind //=> ‘foo’

Q. What's the difference between ES6 Map and WeakMap?Expert


They both behave differently when a object referenced by their keys/values gets
deleted. Lets take the below example code:

var map = new Map(); var weakmap = new WeakMap();


(function() {

var a = {

x: 12

};

var b = {

y: 12

};

map.set(a, 1);

weakmap.set(b, 2);

})()

The above IIFE is executed there is no way we can reference {x: 12} and {y:
12} anymore. Garbage collector goes ahead and deletes the key b pointer from
“WeakMap” and also removes {y: 12} from memory. But in case of “Map”, the
garbage collector doesn’t remove a pointer from “Map” and also doesn’t remove {x:
12} from memory.

WeakMap allows the garbage collectors to do its task but not Map. With manually
written maps, the array of keys would keep references to key objects, preventing them
from being garbage collected. In native WeakMaps, references to key objects are held
"weakly", which means that they do not prevent garbage collection in case there
would be no other reference to the object.
Q. Explain difference between the await keyword and the yield keyword?Expert
yield can be considered to be the building block of await. yield takes the value it's
given and passes it to the caller. The caller can then do whatever it wishes with that
value (1). Later the caller may give a value back to the generator
(via generator.next() ) which becomes the result of the yield expression (2), or an
error that will appear to be thrown by the yield expression (3).
async-await can be considered to use yield. At (1) the caller (i.e. the async-
await driver - similar to the function you posted) will wrap the value in a promise
using a similar algorithm to new Promise(r =>
r(value) (note, not Promise.resolve , but that's not a big deal). It then waits for the
promise to resolve. If it fulfills, it passes the fulfilled value back at (2). If it rejects, it
throws the rejection reason as an error at (3).

So the utility of async-await is this machinery that uses yield to unwrap the yielded
value as a promise and pass its resolved value back, repeating until the function
returns its final value.
Q. Is JavaScript a pass-by-reference or pass-by-value language?Expert
It's always pass by value, but for objects, the value of the variable is a reference.
Because of this, when you pass an object and change its members, those changes
persist outside of the function. This makes it look like pass-by reference. But if you
actually change the value of the object variable you will see that the change does not
persist, proving it's really passed by value.

Example:

function changeStuff(a, b, c)

a = a * 10;

b.item = "changed";

c = {item: "changed"};

var num = 10;

var obj1 = {item: "unchanged"};

var obj2 = {item: "unchanged"};


changeStuff(num, obj1, obj2);

console.log(num);

console.log(obj1.item);

console.log(obj2.item);

Output:

10

changed

unchanged

Q. How to deep-freeze objects in JavaScript?Expert


If you want make sure the object is deep-frozen you have to create a recursive
function to freeze each property which is of type object:

Without deep freeze:

let person = {

name: "Leonardo",

profession: {

name: "developer"

};
Object.freeze(person); // make object immutable

person.profession.name = "doctor";

console.log(person); //output { name: 'Leonardo', profession: { name: 'doctor' } }

With deep freeze:

function deepFreeze(object) {

let propNames = Object.getOwnPropertyNames(object);

for (let name of propNames) {

let value = object[name];

object[name] = value && typeof value === "object" ?

deepFreeze(value) : value;

return Object.freeze(object);

let person = {

name: "Leonardo",

profession: {

name: "developer"

};
deepFreeze(person);

person.profession.name = "doctor"; // TypeError: Cannot assign to read only property 'name'

Load More

MYSQL INTERVIEW QUESTIONS

Q. What is the difference between Data Definition Language (DDL) and Data
Manipulation Language (DML)?Entry

 Data definition language (DDL) commands are the commands which are used
to define the database. CREATE, ALTER, DROP and TRUNCATE are
some common DDL commands.

 Data manipulation language (DML) commands are commands which are


used for manipulation or modification of
data. INSERT, UPDATE and DELETE are some common DML commands.

Q. Describe BLOB in MySQL. What is it used for?Entry


BLOB or Binary Large Object can be used to store binary data in MySQL.
Sometimes binary data like images need to be stored in SQL databases. For example,
you might want to store user photos along with other user details in the database table.
Binary data of the user photo can be saved as a BLOB. By using BLOB, we will not
require separate storage for images. BLOB helps in removing complexity and
providing portability in such cases.
Q. Explain the DEFAULT constraint in MySQL.Entry
DEFAULT constraint provides a default value to a column. In case a row is inserted
into the table and no value is provided to the column, the default value is taken.

Consider a table Customer created using the statement below.

CREATE TABLE `Customer`(

`customerid` CHAR(5) NOT NULL,

`name` VARCHAR(25) NOT NULL,


`country` VARCHAR(25) NOT NULL,

PRIMARY KEY(`customerid`));

If we run the INSERT command as below, we will get an error as the country name is
not provided.

INSERT INTO `Customer` (`customerid`, `name`) VALUES ('12345','William Jones');

To fix this problem you can add a DEFAULT constraint using the command below.
Default value USA will be taken on running the INSERT command above.

ALTER TABLE Customer ALTER country SET DEFAULT 'USA';

Q. What is a VIEW in MySQL? How can you create and query a view?Junior
Views are virtual tables that are stored in SQL queries with a certain given
name. VIEW replaces a SELECT query with a given named view.
The SELECT query could be a complex SELECT query across different database
tables or a simple SELECT query. Once invoked, a view gives results using the query
stored in the view.

A view can be created using the below syntax.

CREATE VIEW `name_of_view`

AS SELECT select_statement;

A query can be made on a view similar to the database table below.

SELECT * FROM name_of_view;

Q. What are Primary Key Constraints and Unique Key Constraints?Junior


The primary key is a column or a group of columns in the table which uniquely
identifies a row in the database. A primary key column can not have NULL value.
Values in the primary key column or columns must be unique so that a row or entry
can be uniquely identified using the primary key.

Unique key constraint ensures that values entered in a column are unique. Although
primary key values will be unique, you might want to ensure that some other column
also has non-duplicate entries.
For example, if we have multiple users and want to ensure that no two users with the
same email id are added to the table, we can put a UNIQUE key constraint on
the email_id column. NULL values are ignored in case of Unique key constraint which
means NULL is allowed value for email id in this case.
Q. What is self-referencing foreign key? Give an example.Junior
A foreign key that is stored in a table itself is called to be a self-referencing foreign
key.

For example, consider an Employee database table. It has employee_id as the primary
key as well as a manager_id which is the employee_id of his manager. If we create a
foreign key constraint, as a manager is also an employee, manager_id will refer
to empolyee_id in the same table.

The Employee table with self-referencing foreign key manager_id can be created
using the below statement.

CREATE TABLE `Employee`(

`name` VARCHAR(25) NOT NULL,

`employee_id` CHAR(9) NOT NULL,

`manager_id` CHAR(9) NOT NULL,

`salary` decimal(10,2) NULL,

PRIMARY KEY(`employee_id`),

FOREIGN KEY (manager_id) REFERENCES employee(employee_id) ON DELETE CASCADE

);

Q. Explain foreign key constraints in MySQLJunior


A Foreign key constraint ensures cross-referencing of values between two tables. A
column or group of columns in a child table references a column or group of columns
in another table. The foreign key constraint is defined in the child table telling about
the table and column(s) which are being referred to.

Foreign key constraint ensures referential integrity. Foreign key columns need to be
indexed in MySQL, so an index is automatically created on a foreign key column if
the index is not created on the column while creating a table with a foreign key
constraint.
Q. What are different integer data types in MySQL? How can you use an
unsigned integer in MySQL?Junior
MySQL has different INT data types with different storage requirements including:

 TINYINT (1 byte), *SMALLINT (2 bytes),

 MEDIUMINT (3 bytes),

 INT (4 bytes) and

 BIGINT (8 bytes).

All the INT types can be used as signed or unsigned. You can write UNSIGNED after
data type to tell if it is unsigned.

For example below command will create a Student table which can mark as an
unsigned SMALLINT value.

CREATE TABLE `Student`(

`name` VARCHAR(25) NOT NULL,

`marks` SMALLINT UNSIGNED);

Q. How are VARCHAR and CHAR different? Mention the use case for
both.Junior
Both CHAR and VARCHAR data types store characters up to a specified length.

1. CHAR stores characters of fixed length while VARCHAR can store characters
of variable length.

2. Storage and retrieval of data are different in CHAR and VARCHAR.

3. CHAR internally takes fixed space, and if the stored character length is small,
it is padded by trailing space characters. VARCHAR has 1 or 2-byte prefixes
along with stored characters.

4. CHAR has slightly better performance.


5. CHAR has memory allocation equivalent to the maximum size specified
while VARCHAR has variable length memory allocation.

Q. What is the difference between TRUNCATE and DELETE?Junior

 DELETE is a Data Manipulation Language(DML) command. It can be used


for deleting some specified rows from a table. DELETE command can be used
with the WHERE clause.

 TRUNCATE is a Data Definition Language(DDL) command. It deletes all the


records of a particular table. The TRUNCATE command is faster in
comparison to DELETE. While the DELETE command can be rolled
back, TRUNCATE can not be rolled back in MySQL.

Q. What is an AGGREGATE function? Name a few aggregate functions used in


MySQL.Junior
Aggregate functions are functions that are used to get a single summary value like the
minimum, maximum, or average of a group of values.

COUNT, SUM, AVG, MIN, MAX are examples of MySQL aggregate functions.

COUNT function is used to count the number of entries returned by


the SELECT query. Similarly, SUM, AVG, MIN, and MAX can be used to
calculate the sum, average, minimum, and maximum of a set of values returned by the
database query.
Q. What is the difference between TEXT and VARCHAR?Mid
Different text data types in MySQL include:

 TINYTEXT,

 TEXT,

 MEDIUMTEXT and

 LONGTEXT.

These data types have different maximum sizes. While TINYTEXT can hold strings
up to 255 characters, TEXT can hold up to 65,535 characters, MEDIUMTEXT can
hold up to 16,777,215 characters and LONGTEXT can hold up to 4,294,967,295
characters.
VARCHAR is also a variable text data type with some difference. VARCHAR is
stored inline in the database table while TEXT data types are stored elsewhere in
storage with its pointer stored in the table. A prefix length is a must for creating index
on TEXT data types. TEXT columns do not support default values,
unlike VARCHAR.
Q. What happens, If a parent row which is referenced by child row is being
deleted in case of foreign key constrain.Mid
The behavior of what happens depends upon set referential actions
including CASCADE, SET NULL, RESTRICT, NO ACTION which can be
provided while creating a foreign key constraint using ON UPDATE and ON
DELETE commands. If no such value is provided while creating a foreign key
constraint, RESTRICT will be the default action.

 CASCADE - changes will be cascaded which means rows in the child table
referencing the parent table will be deleted.

 SET NULL - value in the child table will be set to null.

 RESTRICT - deletion of parent row will fail.

 NO ACTION - it works the same as RESTRICT in MySQL.

Q. What are key constraints? What different types of constraints are there in
MySQL?Mid
Key constraints are rules which ensure that correct data is stored in the database. It
ensures the integrity of the data. MySQL constraints include:

 PRIMARY KEY CONSTRAINT - creates an index using a primary key


column or group of columns for faster access to the database table. The primary
key can not have null or duplicate values.

 FOREIGN KEY CONSTRAINT - creates a link between columns of two


different tables, and ensures that a particular value assigned to a column in one
table has a matching entry in another table.

 NOT NULL CONSTRAINT - ensures a particular column cannot have null


values.

 UNIQUE CONSTRAINT - ensures a particular column does not contain


duplicate values. Unlike primary key constraints, there can be more than one
column with unique key constraint in a table.
 CHECK CONSTRAINT - can be used to ensure a certain condition is met
while assigning a value to a column.

 DEFAULT CONSTRAINT - assigns a default value to a column if a value is


not provided.

Q. What is the difference between BLOB and TEXT in MySQL?Mid

 BLOB data types are designed to store binary data like pictures or videos in a
database.

 TEXT data types are designed to store large text data.

BLOB stores binary byte string while TEXT stores character string.
Although BLOB can be used for storing text data, TEXT data types support sorting
and comparison around text which is not supported by BLOB.

There are four TEXT data types


including TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT which can hold
up to 255 characters, 65,535 characters, 16,777,215 characters and 4,294,967,295
characters respectively.

Similarly, four related BLOB types


including TINYBLOB, BLOB, MEDIUMBLOB and LONGBLOB can hold up to
255 bytes, 65,535 bytes, 16,777,215 bytes and 4,294,967,295 bytes respectively.
Q. What is the use of IN and BETWEEN in MySQL queries?Mid
BETWEEN operator can be used to select a value in a certain range. For example
below statement will return a list of students with rollnumber between 12 and 17.

SELECT * FROM `Student` WHERE `rollnumber` BETWEEN 12 AND 17;

IN operator is used to select rows that have a column value in the provided list of
values. Below command lists all students with rollnumber 2, 4, and 7.

SELECT * FROM `student` WHERE `rollnumber` IN ('2', '4', '7');

Q. What is Stored Function in MySQL. How are they different from Stored
Procedure?Mid
Stored function is a stored complex logic which can be executed like a function call
from any other statement. It returns a single value. It can be used to store business
logic and formulas in database. Stored functions can even run SELECT command or
table manipulation commands like INSERT and UPDATE.

The most general difference between procedures and functions is that they are
invoked differently and for different purposes:

1. A procedure does not return a value. Instead, it is invoked with a CALL


statement to perform an operation such as modifying a table or processing
retrieved records.

2. A function is invoked within an expression and returns a single value directly


to the caller to be used in the expression.

3. You cannot invoke a function with a CALL statement, nor can you invoke a
procedure in an expression.

e.g. SELECT get_foo(myColumn) FROM mytable is not valid if get_foo() is a


procedure, but you can do that if get_foo() is a function. The price is that functions
have more limitations than a procedure.

CREATE PROCEDURE proc_name ([parameters])

[characteristics]

routine_body

CREATE FUNCTION func_name ([parameters])

RETURNS data_type // diffrent

[characteristics]

routine_body

Q. What are REPEAT, LOOP, and WHILE statements used for?Mid


REPEAT, LOOP and WHILE are flow control statements which can be used in
MySQL stored functions and stored procedures. They have slightly different syntax.
 LOOP creates a simple loop and LEAVE statement can be used to come out of
LOOP.

 WHILE can be used as WHILE condition_is_met DO which exits when


condition is false.

 REPEAT repeats the loop UNTIL condition is met.

Q. What is the use of DELIMETER command in MySQL?Mid


MySQL workbench or MySQL client use ; as the delimiter to separate different
statements. DELIMITER command can be used to change the delimiter in MySQL
from ; to something else. It is used while writing trigger and stored procedures in
MySQL. The command below makes // as a delimiter.

DELIMITER //

For example in a stored procedure, ";" is part of the actual stored procedure and not a
delimiter. So while writing a stored procedure, we can make something else like // as
a delimiter and afterward revert it back by calling the below command.

DELIMITER ;

Q. What different stored objects are supported in MySQL?Mid


Different stored objects in MySQL include VIEW, STORED PROCEDURE,
STORED FUNCTION, TRIGGER, EVENT.

 VIEW - It is a virtual table based on a result set of a database query.

 STORED PROCEDURE - It is a procedure stored in a database that can be


called using CALL statement. The stored procedure does not return a value.

 STORED FUNCTION - It is like function calls that can contain logic. It


returns a single value and can be called from another statement.

 TRIGGER - Trigger is a program that is associated with a database table that


can be invoked before or after insert, delete or update operations.

 EVENT - Event is used to run a program or set of commands at a defined


schedule.
Q. What is the difference between commands create database and create schema
in MySQL?Mid
Terms database and schema are synonymous in MySQL. Some other enterprise-level
databases like Oracle and Microsoft SQL server make distinctions between database
and schema.

A MySQL developer can interchangeably use both terms. For example, a database
called test can be created by using either of the CREATE statements below.

CREATE DATABASE test;

CREATE SCHEMA test;

Q. What is an index in MySQL? What is the advantage of an index?Mid


While retrieving rows with certain column values like using the WHERE clause, the
database iterates through each entry to search for matching records. The retrieval can
become significantly fast by creating an index on those columns. Most MySQL index
are stored in B Tree with some exceptions. The index can be created in a database by
using the below syntax.

CREATE INDEX index_name ON table_name (`column_name`);

Q. What is a trigger? What are the different types of triggers in MySQL?Mid


Triggers are database objects or programs that are invoked on certain events
automatically. Triggers are invoked before or after insert, update or delete on rows of
associated table.

There are six types of events associated with a database table when a trigger can be
invoked. It includes:

 BEFORE INSERT,

 AFTER INSERT,

 BEFORE UPDATE,

 AFTER UPDATE,

 BEFORE DELETE

 AFTER DELETE.
For example, BEFORE UPDATE trigger will automatically be invoked and run
before the update is called on the table.
Q. What is mysqldump?Mid
mysqldump is a command line utility for backup and restoration of databases. It
can be run easily to generate a dump of stored databases using the command line.

mysqldump is very simple to use and comes with MySQL installation. It generates
statements to create tables as well as update data. As it does logical backup, backup,
and restore process can be very slow for large databases. The dump file generated
by mysqldump is human readable. A simple command like the below will dump the
database using mysqldump to a human-readable file that can be further compressed
or stored.

mysqldump --user root -p databasename > file.sql

Q. How can VIEW be used to provide a security layer for your app?Mid
Views can be used to selectively show limited data to a user.

For example consider a Customer table that has columns


including name, location, and credit card number. As credit card number is sensitive
customer information, it might be required to hide credit card number from a certain
database user. As the user can not be given access to the entire Customer table, a view
with the name and location of the Customer can be created. The database user can be
given access to that view only. This way view provides a security layer ensuring
limited access to the database table.
Q. Explain the difference between TIMESTAMP and DATETIMEMid
Both TIMESTAMP and DATETIME store date time in YYYY-MM-DD
HH:MM:SS format. While DATETIME stores provided date
time, TIMESTAMP first converts provided time to UTC while storing and then
again converts it back to server time zone upon retrieval. So if you need to serve
different users in different countries using the same time
data, TIMESTAMP facilitates it. DATETIME simply stores provided date time
without making any time zone-related conversion.
Q. Explain the use of FEDERATED tables in MySQL.Mid
FEDERATED tables are tables through which MySQL provides a way to access
database tables located in remote database servers. Actual physical data resides in
remote machine but the table can be accessed like a local table. To use a federated
table ENGINE=FEDERATED and a connection string containing user, remote
hostname, port, schema, and table name are provided in CREATE TABLE command
something like below.
CREATE TABLE table_fed (

...

ENGINE=FEDERATED

CONNECTION='mysql://user@remote_hostname:port/federated_schema/table';

Q. Explain the GRANT command in MySQL.Mid


When a new MySQL user is created, he requires certain privileges to perform various
database operations. GRANT command grants certain privileges to the user. For
example below statement grants permission to
run SELECT and INSERT on TABLE customer table to user username@localhost.

GRANT SELECT, INSERT ON customertable TO 'username'@'localhost'

Q. What are Derived Columns? What possible problems can a derived column
pose?Mid
A derived column is a column in a database table whose value depends on one or
more columns.

For example consider a Customer table for a gym in which the date of birth, age,
height, weight, and BMI of a customer are stored. As the age of a person can be
derived from his date of birth, age is a derived variable. Similarly, as BMI can be
derived from the height and weight of the customer, BMI is a derived column.

The issue with derived columns is that it keeps redundant data. Redundant data
might further affect data accuracy and consistency. For example, if an update
changes the date of birth of a user but somehow fails to change his age, the data
stored in the table becomes inaccurate.
Q. What is MySQL Workbench?Mid
MySQL Workbench is a visual tool that database architects, developers, and
administrators can use. It can be used for data modeling, database development,
database administration, improving MySQL performance as well as database
migration.
 Data Modeling - MySQL workbench provides data modeling features like
visual tool for ER modeling, and reverse and forward engineering to and from
SQL scripts.

 MySQL development - Provides SQL editor with features like auto-


completion, syntax highlighting. Object browser is also there.

 Database administration - Provides visual tools for database administration


tasks like database instance start/stop, server configuration, user administration.

 Database migration - Provides migration solution and supports popular


databases like Microsoft Access, Microsoft SQL server, Sybase ASE, SQLite
and PostgresSQL. Also helps in migration from older MySQL versions.

Q. Remove duplicate rows from a table.Senior


One of the techniques which can be used for removing duplicates is by creating an
intermediate table containing distinct values using DISTINCT command. Below
syntax creates the intermediate table.

CREATE TABLE intermediate_table

SELECT DISTINCT column1, column2

FROM table_name;

The intermediate_table created can replace original table. Below statements drop
original table and replace it with the intermediate_table.

DROP TABLE table_name;

ALTER TABLE intermediate_table RENAME table_name;

Q. What is the cursor used in MySQL? What are the properties of MySQL
cursor?Senior
The cursor is used in stored programs like stored procedures and stored
functions. The cursor is a type of loop that can iterate through the result of
a SELECT query inside stored programs. Here are some properties of the cursor in
MySQL.
 Read-only - In MySQL, the cursor is read-only which means data of table
cannot be updated using cursor.

 Non-scrollable - It is non-scrollable which means one can traverse in forward


direction with one entry at a time without skipping entries or moving in reverse
direction.

 Asensitive - It is asensitive which means cursor will not make temporary copy
of the data rather use original data. One issue with cursor being asensitive is
that if some other process changes the data while cursor is using it, result might
not be predictable.

Consider:

CREATE PROCEDURE curdemo()

BEGIN

DECLARE done INT DEFAULT FALSE;

DECLARE a CHAR(16);

DECLARE b, c INT;

DECLARE cur1 CURSOR FOR SELECT id,data FROM test.t1;

DECLARE cur2 CURSOR FOR SELECT i FROM test.t2;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN cur1;

OPEN cur2;

read_loop: LOOP
FETCH cur1 INTO a, b;

FETCH cur2 INTO c;

IF done THEN

LEAVE read_loop;

END IF;

IF b < c THEN

INSERT INTO test.t3 VALUES (a,b);

ELSE

INSERT INTO test.t3 VALUES (a,c);

END IF;

END LOOP;

CLOSE cur1;

CLOSE cur2;

END;

Q. What are some advantages and disadvantages of stored procedures in


MySQL?Senior
Here are some advantages of the stored procedure:

 Stored procedures help in providing security to the database as users can be


provided access just to required stored procedures for limited operations
defined in the stored procedure instead of giving access to tables. It also helps
in logging.
 Stored procedures can be reused across different applications using the
database thus providing reusability. Business logic resides in the database via
stored procedures. Thus even if different applications are written in different
languages, they share same logic via stored procedures.

 As a large query can be saved using stored procedure, it helps reduce network
traffic as there is no need of repeated calls to same large query, instead the
database request will just make a call to stored procedure along with required
arguments.

Here are some disadvantages:

 Stored procedures can not code complex business logic.

 Also stored procedures are difficult to debug and maintain.

 Running stored procedures in database server means more workload on


database server.

Q. What is master-slave replication in MySQL? What are its advantages?Senior


Master slave replication helps keep a live copy of the data from a master database on
another server. All write operations are done on the master server. The updates are
further replicated in the slave server.

 Master slave replication can provide scalability as read operations can easily be
distributed among different servers thus providing load balancing.

 As a slave server keeps a live copy of data. A slave can quickly be made master
in case the master server is down, thus it helps reduce downtime.

 Data stored in slave can act as data backup as well.

 Different experiments and analytics can be run on a slave server without


putting additional load on the master server.

Q. Compare MySQL and PostgresSQLSenior

 MySQL is a RDBMS (relational database) while PostgresSQL is


an ORDBMS (object relational database) which means apart from relational
database, it also supports some object-oriented language features like table
inheritance and functional overloading.
 Both MySQL and PostgresSQL are open source and free.

 MySQL has better performance in the case of simple queries. It gets this
advantage as MySQL has fewer features in comparison
to PostgresSQL. PostgresSQL has better support for complex queries.

 MySQL is more popular than PostgresSQL so developers can get better


support.

 PostgresSQL is fully ACID compliant while MySQL is ACID compliant


while using InnoDB. PostgresSQL is a better choice than MySQL for highly
reliable applications.

 Both PostgresSQL and MySQL have some NoSQL support


but PostgresSQL has better support to NoSQL. For
example, PostgresSQL has better support to Json, XML and geometric types
in comparison to MySQL.

Q. What is the advantage of FULLTEXT over LIKE for performing text


searches in MySQL?Senior
LIKE is used in MySQL for simple partial text matching. FULLTEXT can be used
for performing search like search engines. It uses data indexing which means the
searches are faster unlike LIKE where entire table needs to be scanned. Search index
of table data is updated dynamically on its own.

FULLTEXT performs flexible searching and natural language text search is


supported as well. FULLTEXT also provides a relevant ranking of results.
Q. Which partitioning types does MySQL support?Senior
MySQL supports range partitioning, list partitioning, hash partitioning, and key
partitioning.

 Range partitioning - rows are partitioned based on a certain range of column


value.

 List partitioning - rows are partitioned based on if the column value is same as
value provided in a list.

 Hash partitioning - rows are partitioned based on hash of column value. Hash
partitioning provides a more even partitioning. Hash is computed based on
user-defined hash function.
 Key partitioning - rows are partitioned based on a hashing function provided
by MySQL like MD5 hash.

Q. What does OPTIMIZE TABLE command do in MySQL?Senior


A database table can be defragmented over time. OPTIMIZE TABLE command can be
executed to reorganize table data and index. OPTIMIZE TABLE command might be
useful for tables that are frequently updated. It can help improve the performance of
I/O operations.
Q. What are the differences between MyISAM and InnoDB database engines
commonly used in MySQL?Senior
Row-level locking, foreign key support, and transaction support are the main features
that differentiate InnoDB from MyISAM.

 MyISAM was default storage engine before 5.5 while InnoDB is default
storage engine from 5.5 and later versions.

 InnoDB is ACID compliant ensuring data integrity while MyISAM is not


ACID compliant.

 COMMIT and ROLLBACK are supported by InnoDB.

 InnoDB has row level locking, which makes it faster in highly concurrent cases
in comparison to MyISAM which has locking at table level. With row level
locking multiple sessions can simultaneously write in a table.

 Foreign key constraint is supported only in InnoDB and not MyISAM.


InnoDB is appropriate engine for payment related applications where
transaction support becomes important.

Q. What are some major differences between MySQL and Oracle database?
Senior
Both Oracle and MySQL are relational database management systems supporting
SQL. Here are some major differences between Oracle and MySQL.

 MySQL is open source and free. Oracle provides an express edition for free
but it comes with limited features. Oracle provides enterprise-level tools.

 Oracle is better in terms of scalability. Oracle is suited for large-scale


enterprise-level projects while MySQL is suited for small and medium-scale
projects.
 While MySQL is Relational DBMS, Oracle has features of Object Relational
DBMS. It supports more complex object-relational model in addition to
Relational DBMS supported by MySQL.

 MySQL uses mysqldump or mysqlhotcopy for data backup. Oracle supports


many options including Export and Import, Offline backup, Online backup,
using RMAN utility, Export or Import Data Pump.

 PL/SQL is supported in Oracle while MySQL does not support PL/SQL.

 MySQL uses username, password, and host for security. Apart from the
username, password Oracle database provides features like profile validation
for security.

Overall MySQL is good for small and medium-sized websites and read-only
websites. Oracle is good for highly scalable enterprise-level applications.
Q. What is Memory Storage Engine in MySQL? What are heap tables?Senior
In MySQL, a Memory storage engine is used to store temporary data in memory. As
data is stored in memory, a memory storage engine can be used for high-performance
non-critical data.

A memory storage engine can be used for data which is updated very frequently. It
can be used for caching. Memory storage engine was called heap table in earlier
versions of MySQL, so sometimes both these terms are used interchangeably.

If the server restarts, the temporary data stored in the Memory storage engine is lost.
Some variable length data types like BLOB and TEXT data types are not supported by
the memory storage engine although VARCHAR is supported.
Q. What is autocommit in MySQL? Can you run a transaction without disabling
autocommit?Senior
In MySQL, if autocommit is disabled, any command you run will not be committed
automatically, which means changes made through these commands will become
permanent only if COMMIT is called. By default autocommit is enabled in MySQL,
which means any change we make is part of a single transaction, commit is done
automatically and it can not be rolled back.

If autocommit is enabled you can call START TRANSACTION to start a


transaction. START TRANSACTION command makes the changes temporary until
either COMMIT or ROLLBACK is called to end the transaction.
Q. How many tables can a trigger associate to in MySQL? Can a trigger be
associated to a view?Expert
A trigger in MySQL can be associated to a permanent table. It can not be associated
to more than one table. Also a trigger cannot be associated to temporary
table or view.
Q. What happens to a trigger in MySQL if an operation which trigger is
associated with fails?Expert
A before trigger executes before the operation. So in case, the operation fails the
associated before trigger will execute but the AFTER trigger will not execute. The
order of execution is BEFORE TRIGGER, operation and then AFTER
TRIGGER at last.

If one of them fails, it causes the entire operation to fail and the subsequent operation
or trigger does not run. So say a BEFORE TRIGGER fails, the operation itself will
not execute and fail. If AFTER TRIGGER fails, the entire statement will fail.
Q. Why you should never use GUIDs as part of the clustered index?Expert
GUIDs are not sequential, thus if they are part of the clustered index, every time you
insert a new record, the database would need to rearrange all its memory pages to find
the right place for insertion, in the case with int(bigint) auto-increment, it would be
just last page.
Q. Which is better for JOIN & INSERT - PostgreSQL or MySQL?Expert
In PostgreSQL, all tables are heap tables. In MySQL, all InnoDB tables are btree
indexes with the tuple in the payload. This means that primary key lookups are faster
on MySQL but general queries are faster on PostgreSQL. It also means you typically
need more indexes on MySQL which will slow down writes.

For example, the following query I would expect to perform better on MySQL than
PostgreSQL:

SELECT u.username, p.*

FROM users u

JOIN preferences p ON u.id = p.user_id

WHERE u.id = 123;

Provided that both tables share the same primary key (u.id and p.user_id), there are
thousands of rows in both tables, and so forth.
On the other hand, I would expect the following query to perform better on
PostgreSQL than MySQL in a db too big to fit in memory, non-cached data, proper
indexes, decent-sized tables, etc:

SELECT c.legal_name, a.*

FROM company c

JOIN address a on a.company_id = c.id

WHERE a.zip_code like '95%' and country = 'us';

In this case you are having to utilize other indexes, which means a lot of extra random
disk I/O on MySQL.

The second issue I would expect would be write performance. I would expect
PostgreSQL to generally win here due to the fact that heap tables allow inserts
wherever it is convenient, and fewer indexes maintained would be helpful too.
Q. What is the use of SAVEPOINT in MySQL?Expert
SAVEPOINT is like a bookmark while running statements in transaction mode. I
helps rolling back to a specific location in the transaction. Below command can be
used to create a save point while running MySQL in transaction mode.

SAVEPOINT savepointName;

And current transaction can be rolled back to desired saved save point location by
running below command.

ROLLBACK TO savepointName;

Unlike ROLLBACK or COMMIT commands which end currently running


transaction, ROLLBACK TO savepointName does not end current transaction.
Q. What is difference between horizontal and vertical partitioning?Expert
Partitioning is used in database to split a table data into multiple parts called
partitions and store them separately. It can further be classified into horizontal
partitioning and vertical partitioning.

 Horizontal partitioning - rows which match a partitioning function are stored


in corresponding partition.
 Vertical partitioning - Different columns of a table can be stored in different
physical partitions using vertical partitioning.

MySQL supports horizontal partitioning but does not support vertical partitioning.

----------------------------------------------------------------------------------------------------------------------------------------

django_interview_questions
Difference between Flask and Django?

Comparison
Django Flask
Factor

Project Type Supports Large Projects Built for smaller projects

Templates,Admin,
Built in Needs to be installed
ORM

More flexible as the user can


Allows complete web
select any third-party tools
Flexibility development without the
according to their choice and
need for third-party tools
requirements

Does not support Visual


Visual Debugging Supports Visual Debug
Debug

Type of framework Batteries included Simple, lightweight

Bootstrapping-
Built-it Not available
tool

Nb: Batteries are libraries and tools that are required for common use cases and ORM is
the object relational mapping layer which is used to interact with other relational
databases.

What is Django?

Django is a Python-based free and open-source web framework that follows the model-
template-view architectural pattern.It was also named after Django Reinhardt who was a
jazz guitarist from the 1930s.

Which companies use Django?

Pinterest, Instagram, Coursera, Udemy, Spotify, Youtube, Bitbucket, Mozilla,Eventbrite,


Dropbox others

What are the features of Django?

SEO Optimized -as from the name it means that adding your website to the search
engine such that it appears in the top results. This is because Django maintains the built
website through URLs rather than the IP addresses on the server, which makes it easy
for SEO engineers to add the website to the server while the web-developer doesn’t
have to convert the URL into some numeric code.
Rapid Development -Django was designed with the intention to make a framework
which takes less time to build web application. The project implementation phase is
takes time but Django creates it rapidly.
Fully loaded framework -Django includes various helping task modules and libraries
which can be used to handle common Web development tasks. Django takes care of
user authentication, content administration, site maps, RSS feeds etc.
High security -thereby helping developers avoid common security mistakes such as
cross-site request forgery (csrf), clickjacking, cross-site scripting, etc It is exceptionally
scalable which in turn helps meet the heaviest traffic demands
Versatile -The logical project structure and MVT architecture of Django provides us with
a solid foundation which can then be used to make whichever application we want to
create.
Scalability -Django is scalable in nature and has ability to quickly and flexibly switch
from small to large scale application project.

How do you check the Django version installed in a PC?

Open CMD command prompt and type python -m django --version


You can also try to import Django and use the get_version() method as follows:
import django
print(django.get_version())

What are the advantages of using Django?

Django is called a loosely coupled framework because of its Model View Template
architecture. It helps in separating the server code from the client-related code.
Django’s models and views take care of the code that needs to be run on the server like
getting records from database, etc., and the templates are mostly HTML and CSS that
just need data from models passed in by the views to render them. Since these
components are independent of each other, Django is called a loosely coupled
framework.
Allows rapid development of websites.
Follows the DRY or the Don’t Repeat Yourself Principle which means, one concept or a
piece of data should live in just one place.
Consistent at low as well as high levels.
SQL statements are not executed too many times and are optimized internally.
Can easily drop into raw SQL whenever required.
Flexibility while using URL’s.

Explain Django architecture?

Django follows the MVT (Model View Template architecture) which is based on the MVC
(Model View Controller architecture). The main difference between these two is that
Django itself takes care of the controller part.
MVT separates the code into three parts.
Model, View, and Template.
The Model contains the system responsible for dealing with data and databases;
View deals with the design pattern; that is, it decides what data should be displayed,
Template specifies a structure for output.
Data can be populated in a template using placeholders. It defines how the information
is presented. An example is a Generic list view that we can use to display a set of records
from the database.

Give a brief about "django-admin"?

django-admin is the command-line utility of Django for administrative tasks. Using the
django-admin you can perform a number of tasks as shown below:

Task Command

To display the usage information and the list of the


django-admin help
commands provided by each application

django-admin help –
To display the list of available commands
command
Task Command

To display the description of a given command and the


django-admin help
list of its available options

Determining the version of Django django-admin version

Creating new migrations based on the changes made in django-admin


models makemigrations

Synchronizing the database state with the current set of


django-admin migrate
models and migrations

Starting the development server django-admin runserver

Sending a test email in order to confirm the email django-admin


sending through Django is working sendtestemail

To start the Python interactive interpreter django-admin shell

django-admin
To show all the migrations in your project
showmigrations

How do you connect your django project to the database?

Django comes with a default database which is SQLite.


To connect your project to this database, use the following commands:
python manage.py migrate (migrate command looks at the INSTALLED_APPS settings and
creates database tables accordingly)
python manage.py makemigrations (tells Django you have created/ changed your models)
python manage.py sqlmigrate <name of the app followed by the generated
id> (sqlmigrate takes the migration names and returns their SQL)

What are the various files that are created when you create a Django Project?
Explain briefly.
After you create a project using the startproject command, the following files will be
created:

File Name Description

manage.p A command-line utility that allows you to interact with your Django
y project

An empty file that tells Python that the current directory should be
init.py
considered as a Python package

settings.py Consists of the settings for the current project

urls.py Contains the URL’s for the current project

This is an entry-point for the web servers to serve the project you
wsgi.py
have created

What are ‘Models’?

Models are a single and definitive source for information about your data. It consists of
all the essential fields and behaviors of the data you have stored. Often, each model will
map to a single specific database table.
In Django, models serve as the abstraction layer that is used for structuring and
manipulating your data.
Django models are a subclass of the django.db.models.Model class and the attributes in
the models represent database fields.

What are ‘views’?

Django views serve the purpose of encapsulation.


They encapsulate the logic liable for processing a user’s request and for returning the
response back to the user.
Views in Django either return an HttpResponse or raise an exception such as Http404.
HttpResponse contains the objects that consist of the content that is to be rendered to
the user. Views can also be used to perform tasks such as read records from the
database, delegate to the templates, generate a PDF file, etc.

What are ‘templates’?

Django’s template layer renders the information to be presented to the user in a


designer-friendly format.
Using templates, you can generate HTML dynamically. The HTML consists of both static
as well as dynamic parts of the content. You can have any number of templates
depending on the requirement of your project. It is also fine to have none of them.
Django has its own template system called the Django template language (DTL).
Regardless of the backend, you can also load and render templates using Django’s
standard admin.

What is the difference between a Project and an App?

An app is basically a Web Application that is created to do something for example, a


database of student records. A project, on the other hand, is a collection of apps of
some particular website. Therefore, a single project can consist of ‘n’ number of apps
and a single app can be in multiple projects.

What are the different inheritance styles in Django?

Django has three possible inheritance styles:

Inheritance
Description
style

Used when you want to use the parent class to hold information
Abstract base
that you don’t want to type for each child model. Here, the
classes
parent class is never used in solitude

Multi-table Used when you have to subclass an existing model and want
inheritance each model to have its own database table

Used if you only want to modify the Python-level behavior of a


Proxy models
model, without changing the ‘models’ fields in any way
What are static files?

Static files in Django are those files that serve the purpose of additional files such as the
CSS, images or JavaScript files. These files are managed by django.contrib.staticfiles.
These files are created within the project app directory by creating a subdirectory
named as static.

What are ‘signals’?

Django includes a “signal dispatcher” which helps allow decoupled applications get
notified when actions occur elsewhere in the framework.
Signals allow certain senders to notify a set of receivers that some action has taken
place. They’re especially useful when many pieces of code may be interested in the same
events.
Some of the signals are as follows:

Signal Description

django.db.models.signals.pre_save Sent before or after a model’s


django.db.models.signals.post_save save() method is called

Sent before or after a model’s


django.db.models.signals.pre_delete
delete() method or queryset’s
django.db.models.signals.post_delete
delete() method is called

Sent when a ManyToManyField


django.db.models.signals.m2m_changed
on a model is changed.

django.core.signals.request_started Sent when Django starts or


django.core.signals.request_finished finishes an HTTP request.

Signals

Briefly explain Django Field Class.


‘Field’ is basically an abstract class that actually represents a column in the database
table.
The Field class, is in turn, a subclass of RegisterLookupMixin. In Django, these fields are
used to create database tables (db_type()) which are used to map Python types to the
database using get_prep_value() and vice versa using from_db_value() method.
Therefore, fields are fundamental pieces in different Django APIs such as models and
querysets.

How do you create a Django project?

To create a Django project, cd into the directory where you would like to create your
project and type the following command:
django-admin startproject Vee NOTE: Here, Vee is the name of the project. You can give
any name that you desire.

What is mixin?

Mixin is a type of multiple inheritance wherein you can combine behaviors and
attributes of more than one parent class.
Mixins provide an excellent way to reuse code from multiple classes. For example,
generic class-based views consist of a mixin called TemplateResponseMixin whose
purpose is to define render_to_response() method. When this is combined with a class
present in the View, the result will be a TemplateView class.
One drawback of using these mixins is that it becomes difficult to analyze what a child
class is doing and which methods to override in case of its code being too scattered
between multiple classes.

What are sessions?

The session framework lets you store and retrieve arbitrary data on a per-site-visitor
basis. It stores data on the server side and abstracts the sending and receiving of
cookies. Cookies contain a session ID – not the data itself unless you’re using the cookie
based backend.

What do you mean by context?

When you use a Django Template, it is compiled once (and only once) and stored for
future use, as an optimization. A template can have variable names in double curly
braces, such as {{ myvar1 }} and {{ myvar2 }}.
A Context is a dictionary with variable names as the key and their values as the value.
Hence, if your context for the above template looks like: {myvar1: 101, myvar2: 102},
when you pass this context to the template render method, {{ myvar1 }} would be
replaced with 101 and {{ myvar2 }} with 102 in your template. This is a simplistic
example, but really a Context object is the context in which the template is being
rendered.
As for a ContextProcessor, that is a slightly advanced concept. You can have in your
settings.py file listed a few Context Processors which take in an HttpRequest object and
return a dictionary (similar to the Context object above). The dictionary (context)
returned by the Context Processor is merged into the context passed in by you (the
user) by Django.
A use case for a Context Processor is when you always want to insert certain variables
inside your template (for example the location of the user could be a candidate). Instead
of writing code to insert it in each view, you could simply write a context processor for it
and add it to the TEMPLATE_CONTEXT_PROCESSORS settings in settings.py.

When can you use iterators in Django ORM?

Iterators in Python are basically containers that consist of a countable number of


elements.
Any object that is an iterator implements two methods which are, the init() and
the next() methods.
When you are making use of iterators in Django, the best situation to do it, is when you
have to process results that will require a large amount of memory space.
To do this, you can make use of the iterator() method which evaluates a QuerySet and
returns the corresponding iterator over the results.

Explain the caching strategies of Django?

Caching basically means to save the output of an expensive calculation in order to avoid
performing the same calculation again.
Django provides a robust cache system which in turn helps you save dynamic web
pages so that they don’t have to be evaluated over and over again for each request.
Some of the caching strategies of Django are listed below:

Strategy Description

Memory-based cache server which is the fastest and most


Memcached
efficient

Filesystem Cache values are stored as separate files in a serialized order


Strategy Description

caching

This is actually the default cache in case you have not specified
Local-memory
any other. This type of cache is per-process and thread-safe as
caching
well

Database Cache data will be stored in the database and works very well if
caching you have a fast and well-indexed database server

Explain the use of Middlewares in Django?

Middleware is a framework that is light and low-level plugin system for altering Django’s
input and output globally.
It's a framework of hooks into the request/ response processing of Django.
Each component in middleware has some particular task. For example, the
AuthenticationMiddleware is used to associate users with requests using sessions.
Django provides many other middlewares such as cache middleware to enable site-wide
cache, common middleware that performs many tasks such as forbidding access to user
agents, URL rewriting, etc, GZip middleware which is used to compress the content for
browsers, etc.

What is the significance of manage.py file in Django?

The manage.py file is automatically generated whenever you create a project.


This is basically a command-line utility that helps you to interact with your Django
project in various ways.
It does the same things as django-admin but along with that, it also sets the
DJANGO_SETTINGS_MODULE environment variable in order to point to your project’s
settings. Usually, it is better to make use of manage.py rather than the django-admin in
case you are working on a single project.

Explain the use of ‘migrate’ command in Django?


In Django, migrations are used to propagate changes made to the models.The migrate
command is basically used to apply or unapply migrations changes made to the models.
This command synchronizes the current set of models and migrations with the database
state. You can use this command with or without parameters. In case you do not specify
any parameter, all apps will have all their migrations running.

How to view and filter items from the database?

In order to view all the items from your database, you can make use of the ‘all()’ function
in your interactive shell as follows: XYZ.objects.all() where XYZ is some class that you
have created in your models.
To filter out some element from your database, you either use the get() method or the
filter method as follows:
XYZ.objects.filter(pk=1) XYZ.objects.get(id=1)

Explain how a request is processed in Django?

In case a user requests a page from some Django powered site, the system follows an
algorithm that determines which Python code needs to be executed.
Here are the steps that sum up the algorithm:
-Django first determines which root URLconf or URL configuration module is to be used
-Then, that particular Python module is loaded and then Django looks for the variable
urlpatterns
-These URL patterns are then run by Django, and it stops at the first match of the
requested URL
-Once that is done, the Django then imports and calls the given view
-In case none of the URLs match the requested URL, Django invokes an error-handling
view

How did Django come into existence?

Django basically grew from a very practical need. World Online developers namely
Adrian Holovaty and Simon Willison started using Python to develop its websites. As
they went on building intensive, richly interactive sites, they began to pull out a generic
Web development framework that allowed them to build Web applications more and
more quickly. In summer 2005, World Online decided to open-source the resulting
software, which is, Django.

How to use file-based sessions?


In order to make use of file-based sessions, you will need to set the SESSION_ENGINE
setting to “django.contrib.sessions.backends.file”.

Explain the Django URLs in brief?

Django allows you to design your own URLs however you like. The aim is to maintain a
clean URL scheme without any framework limitations.
In order to create URLs for your app, you will need to create a Python module informally
called the URLconf or URL configuration which is pure Python code and is also a
mapping between the URL path expressions to the Python methods.
The length of this mapping can be as long or short as required and can also reference
other mappings.
When processing a request, the requested URL is matched with the URLs present in the
urls.py file and the corresponding view is retrieved.

Give the exception classes present in Django?

Django uses its own exceptions as well as those present in Python. Django core
exceptions are present in django.core.exceptions class some of which are mentioned in
the below:

Exception Description

Raised when you try to use your models before the app
AppRegistryNotReady
loading process (initializes the ORM) is completed.

ObjectDoesNotExist This is the base class for DoesNotExist exceptions

This exception may be raised if a query won’t return any


EmptyResultSet
result

This is raised by a query if multiple objects are returned


MultipleObjectsReturned
and only one object was expected

This exception is raised by a model’s


FieldDoesNotExist <_meta.get_field()> function in case the requested field
does not exist
Does the Django framework scale?

Yes. Hardware is much cheaper when compared to the development time and this is
why Django is designed to make full use of any amount of hardware that you can
provide it.
Django makes use of a “shared-nothing” architecture meaning you can add hardware at
any level i.e database servers, caching servers or Web/ application servers.

Is Django a CMS?

Django is not a CMS (content-management-system) . It is just a Web framework, a tool


that allows you to build websites.

Does Django support NoSQL?

NoSQL basically stands for “not only SQL”. This is considered as an alternative to the
traditional RDBMS or the relational Databases.
Officially, Django does not support NoSQL databases. However, there are third-party
projects, such as Django non-rel, that allow NoSQL functionality in Django. Currently,
you can use MongoDB and Google App Engine.

How can you customize the functionality of the Django admin interface?

You can piggyback on top of an add/ change form that is automatically generated by
Django, you can add JavaScript modules using the js parameter.
This parameter is basically a list of URLs that point to the JavaScript modules that are to
be included in your project within a <script> tag. In case you want to do more rather
than just playing around with from, you can exclusively write views for the admin.

Give an example of a Django view?

A view in Django either returns an HttpResponse or raises an exception such as Http404.


HttpResponse contains the objects that consist of the content that is to be rendered to
the user.

from django.http import HttpResponse


def hello_world(request):
html = "
<h1>Hello World!</h1>
"
return HttpResponse(html)

#### What should be done in case you get a message saying “Please enter the correct
username and password” even after entering the right details to log in to the admin
section? In case you have entered the right details and still not able to login to the
admin site, cross verify if the user account has is_active and is_staff attributes set to True.

What should be done in case you are not able to log in even after entering the
right details and you get no error message?

In this case, the login cookie is not being set rightly. This happens if the domain of the
cookie sent out by Django does not match the domain in your browser. For this, you
must change the SESSION_COOKIE_DOMAIN setting to match that of your browser.

How can you limit admin access so that the objects can only be edited by those
users who have created them?

Django’s ModelAdmin class provides customization hooks using which, you can control
the visibility and editability of objects in the admin. To do this, you can use the
get_queryset() and has_change_permission().

What to do when you don’t see all objects appearing on the admin site?

Inconsistent row counts are a result of missing Foreign Key values or if the Foreign Key
field is set to null=False. If the ForeignKey points to a record that does not exist and if
that foreign is present in the list_display method, the record will not be shown the
admin changelist.

What do you mean by the csrf_token?

The csrf_token is used for protection against Cross-Site Request Forgeries. This kind of
attack takes place when a malicious website consists of a link, some JavaScript or a form
whose aim is to perform some action on your website by using the login credentials of a
genuine user.

Does Django support multiple-column Primary Keys?

No. Django only supports single-column Primary Keys.


How can you see the raw SQL queries that Django is running?

First, make sure that your DEBUG setting is set to True. Then, type the following
commands:

from django.db import connection


connection.queries

#### Is it mandatory to use the model/ database layer? No. The model/ database layer
is actually decoupled from the rest of the framework.

How to make a variable available to all the templates?

You can make use of the RequestContext in case all your templates require the same
objects, such as, in the case of menus. This method takes an HttpRequest as its first
parameter and it automatically populates the context with a few variables, according to
the engine’s context_processors configuration option.

#Q1. What
is the
differenc
e between
shallow
copy and
deep copy
?

Ans : Shallow copy is used when a new instance type gets created and it keeps
the values that are copied in the new instance.
Shallow copy is used to copy the reference pointers just like it copies the
values. These references point to the original objects
and the changes made in any member of the class will also affect the original
copy of it. Shallow copy allows faster execution of the program
and it depends on the size of the data that is used.
[Shallow copy doesn't copy the admin structure, just copies the top level
references and the original values ]

Deep copy is used to store the values that are already copied. Deep copy
doesn’t copy the reference pointers to the objects.
It makes the reference to an object and the new object that is pointed by some
other object gets stored.
The changes made in the original copy won’t affect any other copy that uses
the object.
Deep copy makes execution of the program slower due to making certain copies
for each object that is been called.
[Deep copy has to copy all the references , all the admin structures , all the
values each and everything]

l1= [1,2,3,4]
l2 = l1
l2.append(10)
l2
[1,2,3,4,10]
l1
[1,2,3,4,10]
import copy
l1
[1,2,3,4,10]
l3 = copy.copy(l1)
l3
[1,2,3,4,10]
l3.append(11)
l1
[1,2,3,4,10]
l2
[1,2,3,4,10]
l3
[1,2,3,4,10,11]

// To check the memory location


id(l1)
id(l2)

l4 = copy.deepcopy(l2)
l4
[1,2,3,4,10]
#Q2. What is the difference between list and tuples?

Ans: Lists are mutable i.e they can be edited. Tuples are immutable (tuples
are lists which can’t be edited).
Lists are slower than tuples.
List Syntax: list_1 = [10, ‘Chelsea’, 20]
Tuple Syntax: tup_1 = (10, ‘Chelsea’ , 20)

l1= [1,2,3,4]
l1.append(40) // is possible
t1= (1,2,3,4)
t1.append(40) // is NOT possible

#Q3. How is Multithreading achieved in Python?


Ans: Python has a multi-threading package but if you want to multi-thread to
speed your code up, then it’s usually not a good idea to use it.
Python has a construct called the Global Interpreter Lock (GIL). The GIL makes
sure that only one of your ‘threads’ can execute at any one time.
A thread acquires the GIL, does a little work, then passes the GIL onto the
next thread.
This happens very quickly so to the human eye it may seem like your threads
are executing in parallel, but they are really just taking turns using the
same CPU core.
All this GIL passing adds overhead to execution. This means that if you want
to make your code run faster then using the threading package often isn’t a
good idea.

import multiprocessing
import threading

#Q4. How can the ternary operators be used in python?

Ans: The Ternary operator is the operator that is used to show the conditional
statements.
This consists of the true or false values with a statement that has to be
evaluated for it.

x,y = 23,50
big = x if x>y else y
big
50
#Q5. What is monkey patching in Python?
Ans: In Python, the term monkey patch only refers to dynamic modifications of
a class or module at run-time.

Consider the below example:

# m.py
class MyClass:
def f(self):
print "f()"

We can then run the monkey-patch testing like this:

import m
def monkey_f(self):
print "monkey_f()"

m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()
The output will be as below:

monkey_f()
As we can see, we did make some changes in the behavior of f() in MyClass
using the function we defined, monkey_f(), outside of the module m.
#Q6. How can you randomize the items of a list in place in Python?

Ans:
from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)
['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']

#Q7. Write a sorting algorithm for a numerical dataset in Python.

Ans:

list = ["1", "4", "0", "6", "9"]


list = [int(i) for i in list]
list.sort()
print (list)

#Q8. Looking at the below code, write down the final values of A0, A1, …An.
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
print(A0,A1,A2,A3,A4,A5,A6)

Ans: The following will be the final outputs of A0, A1, … A6

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary


A1 = range(0, 10)
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8,
64], [9, 81]]

#Q9. Explain split(), sub(), subn() methods of “re” module in Python.

Ans: To modify the strings, Python’s “re” module is providing 3 methods. They
are:

split() – uses a regex pattern to “split” a given string into a list.


sub() – finds all substrings where the regex pattern matches and then replace
them with a different string
subn() – it is similar to sub() and also returns the new string along with the
no. of replacements.
import re
// Example goes here .

# Explain Inheritance in Python with an example.

Ans: Inheritance allows One class to gain all the members(say attributes and
methods) of another class. Inheritance provides code reusability,
makes it easier to create and maintain an application. The class from which we
are inheriting is called super-class and the class
that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:-

Single Inheritance – where a derived class acquires the members of a single


super class.
Multi-level inheritance – a derived class d1 in inherited from base class
base1, and d2 are inherited from base2.
Hierarchical inheritance – from one base class you can inherit any number of
child classes
Multiple inheritance – a derived class is inherited from more than one base
class.
#Q1. Discuss
the Django
architecture.

Ans. The developer provides the Model, the view and the template then just
maps it to a URL and Django does the magic to serve it to the user.
It follows the MTV (Model template view pattern).

#Q2. Explain how you can set up the Database in Django.

Ans: You can use the command edit mysite/setting.py , it is a normal python
module with module level representing Django settings.

Django uses SQLite by default; it is easy for Django users as such it won’t
require any other type of installation.
In the case your database choice is different that you have to the
following keys in the DATABASE ‘default’ item to match your database
connection settings.

Engines: you can change database by using ‘django.db.backends.sqlite3’ ,


‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’,
‘django.db.backends.oracle’ and so on
Name: The name of your database. In the case if you are using SQLite as
your database, in that case database will be a file on your computer,
Name should be a full absolute path, including file name of that file.
If you are not choosing SQLite as your database then settings like
Password, Host, User, etc. must be added.
Django uses SQLite as default database, it stores data as a single file in
the filesystem. If you do have a database server—PostgreSQL, MySQL,
Oracle, MSSQL—and want to use it rather than SQLite, then use your
database’s administration tools to create a new database for your Django
project.
Either way, with your (empty) database in place, all that remains is to
tell Django how to use it. This is where your project’s settings.py file
comes in.

We will add the following lines of code to the setting.py file:

DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

#Q3. Give an example how you can write a VIEW in Django?

Ans: This is how we can use write a view in Django:

from django.http import HttpResponse


import datetime

def Current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s</body></html>" % now
return HttpResponse(html)
Returns the current date and time, as an HTML document

#Q4. Mention what the Django templates consists of.

Ans: The template is a simple text file. It can create any text-based
format like XML, CSV, HTML, etc.
A template contains variables that get replaced with values when the
template is evaluated and tags (% tag %)
that controls the logic of the template.

#Q5. Explain the use of session in Django framework?

Ans: Django provides session that lets you store and retrieve data on a
per-site-visitor basis.
Django abstracts the process of sending and receiving cookies, by placing a
session ID cookie on the client side,
and storing all the related data on the server side.
So the data itself is not stored client side. This is nice from a security
perspective.
#Q6. List out the inheritance styles in Django.

Ans: In Django, there is three possible inheritance styles.

i. Abstract Base Classes: This style is used when you only wants parent’s
class to hold information that you don’t want to type out for each child
model.
ii. Multi-table Inheritance: This style is used If you are sub-classing an
existing model and need each model to have its own database table.
iii. Proxy models: You can use this model, If you only want to modify the
Python level behavior of the model, without changing the model’s fields.

#Q7. How will you define Django ?

Ans: Django is a web framework in python to develop a web application in


python. Django is a free and open source web application framework,
written in Python. Django makes easier to build better web applications
quickly and with less code.
#Q8. Mention what are the features available in Django?

Ans: Features available in Django are-

Admin Interface (CRUD)


Templating
Form handling
Internationalization
Session, user management, role-based permissions
Object-relational mapping (ORM)
Testing Framework
Fantastic Documentation
Security features

#Q9. Mention the architecture of Django architecture?

Ans: Django architecture consists of-

Models: It describes your database schema and your data structure


Views: It controls what a user sees, the view retrieves data from
appropriate models and execute any calculation made to the data and pass it
to the template
Templates: It determines how the user sees it. It describes how the data
received from the views should be changed or formatted for display on the
page
Controller: The Django framework and URL parsing
#Q10. Why Django should be used for web-development?

Ans: It allows you to divide code modules into logical groups to make it
flexible to change
To ease the website administration, it provides auto-generated web admin
It provides pre-packaged API for common user tasks
It gives you template system to define HTML template for your web page to
avoid code duplication
It enables you to define what URL be for a given function
It enables you to separate business logic from the HTML
Everything is in python

#Q11. Explain how you can setup static files in Django?

Ans: There are three main things required to set up static files in Django

Set STATIC_ROOT in settings.py


run manage.py collectsatic
set up a Static Files entry on the PythonAnywhere web tab

#Q12. Explain how you can use file based sessions?


Ans: To use file based session you have to set the SESSION_ENGINE settings
to “django.contrib.sessions.backends.file”

#Q13. Explain the migration in Django and how you can do in SQL?

Migration in Django is to make changes to your models like deleting a


model, adding a field, etc. into your database schema.
There are several commands you use to interact with migrations.

Migrate
Makemigrations
Sqlmigrate
To do the migration in SQL, you have to print the SQL statement for
resetting sequences for a given app name.

django-admin.py sqlsequencreset

Use this command to generate SQL that will fix cases where a sequence is
out sync with its automatically incremented field data.

#Q14. Mention what command line can be used to load data into Django?
Ans: To load data into Django you have to use the command line Django-
admin.py loaddata.
The command line will searches the data and loads the contents of the named
fixtures into the database.

#Q15.Explain what does django-admin.py makemessages command is used for?

This command line executes over the entire source tree of the current
directory and abstracts all the strings marked for translation.
It makes a message file in the locale directory.

#Q16. Mention what does the Django field class types?

Ans: Field class types determines -


The database column type
The default HTML widget to avail while rendering a form field
The minimal validation requirements used in Django admin and in
automatically generated forms
#Q17. What is the usage of middlewares in Django?

Ans:
Below are the usage of middlewares in Django-
•Session management
•Cross-site request forgery protection
•Use authentication
•Content Gzipping

#Q18. What are the roles of receiver and sender in signals?

Ans: The roles of receiver and sender in signals are-


Receiver: It specifies the callback function which will be connected to the
signal.
Sender: It specifies a particular sender to receive a signal from.
#Q19. Is Django Stable?

Ans: Yes, Django is quite stable. Many companies like Disqus, Instagram,
Pinterest, and Mozilla have been using Django for many years.

#Q20. Mention Caching Strategies That You Know In Django?

Ans: Few caching strategies that are available in Django are as follows:-

File sytem caching


In-memory caching
Using Memcached
Database caching

#Q21. Is Django a content management system (CMS)?

Ans: No, Django is not a CMS. Instead, it is a Web framework and a


programming tool that makes you able to build websites.
#Q22. What is the usage of Django-admin.py and manage.py?

Ans: Django-admin.py: It is a Django's command line utility for


administrative tasks.

Manage.py: It is an automatically created file in each Django project. It


is a thin wrapper around the Django-admin.py. It has the following usage:

It puts your project's package on sys.path.


It sets the DJANGO_SETTING_MODULE environment variable to points to your
project's setting.py file.

#Q23. What are the signals in Django?

Ans: Signals are pieces of code which contain information about what is
happening.
A dispatcher is used to sending the signals and listen for those signals.
#Q24. What is the role of Cookie in Django?

Ans: A cookie is a small piece of information which is stored in the client


browser.
It is used to store user's data in a file permanently (or for the specified
time).
Cookie has its expiry date and time and removes automatically when gets
expire. Django provides built-in methods to set and fetch cookie.

The set_cookie() method is used to set a cookie and get() method is used to
get the cookie.

The request.COOKIES['key'] array can also be used to get cookie values.

Django Interview
Basics

Q What is django? What do you like about it (Can be re-phrased as what are the
features of django?)

Ans - Django is a high-level Python web framework that encourages rapid development
and clean, pragmatic design.

Features :

 Admin Interface (CRUD)


 Templating
 Form handling
 Internationalization
 Session, user management, role-based permissions
 Object-relational mapping (ORM)
 Testing Framework
 Fantastic Documentation
 Open Source and huge collection of availbale packages

Benefits :

Speed: Its slogan is ‘The Web framework for perfectionists with deadlines‘, so it is
focused on web-dev tasks made fast. Django was created with the helpful mindset of
allowing devs to realize ideas as quickly as possible, with less code.

Security: Avoid common security mistakes with its user authentication system and secure
password management.

Scalable: Meet heavy traffic demands with its “shared-nothing” architecture. Add
hardware at any level, including database servers.

Out of the box features: Without any extra downloads, Django handles user
authentication, content administration, site maps, RSS feeds, and more.

Q. What is the architecture that django follows?

Ans - Django follows the Model-Template-View (MTV) architecture. There is separation


of concerns between the database interfacing classes (Model), request-processing
classes (View), and a templating language for the final presentation (Template).

Q. What is the latest version of Django and which one you are uisng?

Ans - The latest version of django is, Django - 3.0. I am using Django 2.2 which is LTS
(Long term support) release.

Q. Is django an MVC framework?

Ans - Django follows MVC pattern very closely but it uses slightly different terminology.
Django is essentially an MTV (Model-Template-View) framework. Django uses the term
Templates for Views and Views for Controller. In other words, in Django views are called
templates and controllers are called views. Hence our HTML code will be in templates
and Python code will be in views and models.

Q. What popular websites use django? Can you name some?

Ans Disqus, Instagram, Mozilla, NASA, The Washington Post etc.

Q. How is Django’s code reusability feature different from other frameworks?


Ans. Django framework offers more code-reusability then other frameworks out there.
As Django Project is a collection of different applications like login application, signup
application. These applications can be just copied from one directory to another with
some tweaks to settings.py file and you won’t need to write new signup application
from scratch.

That’s why Django is a rapid development framework and this level of code reusability is
not there in other frameworks.

**Q. Explain the file structure of a typical Django project?

Ans. A Django project is a collection of web-applications which coordinate together to


serve the request of the user. These applications have one assigned feature and shall do
only that.

A typical Django project consists of these four files:

|── manage.py
└─┬ ProjectFolder
├── settings.py
├── init.py
├── urls.py
└─┬ wsgi.py

The last four files are inside a directory, which is at the same level of manage.py.

Here the structure is very logical, and the names of these files and their purpose should
remain intact.

manage.py is the command line utility of your Django project and this file is used to
control your Django project on the server or even to begin one.

When Django server is started, the manage.py file searches for settings.py file, which
contains information of all the applications installed in the project, middleware used,
database connections and path to the main urls config.

The urls.py file is like a map of your whole web-project, this file examines URL and calls
the right view function or transports the URL to another application specific urls-config
file. This is like the main URL linker and any app installed in the settings.py which you
wish to be searched by the URL should have a link here.

The init.py file is an empty file which is there to make the python interpreter understand
that the directory consisting settings.py is a module/ package.
The wsgi.py file is for the server format WSGI, which Django supports natively. We can
customize that for other server formats.

Q. What happens when a typical Django website gets a request? Explain.

Ans. When a user enters a URL in the browser the same request is received by the
Django Server. The server then looks for the match of the requested URL in its URL-
config and if the URL matches, it returns the corresponding view function. It will then
request the data from the Model of that application, if any data is required and pass it
to the corresponding template which is then rendered in the browser, otherwise, a 404
error is returned.

Q. Why is Django called loosely coupled framework?

Ans. Django is called a loosely coupled framework because of the MTV architecture it’s
based on. Django’s architecture is a variant of MVC architecture and MTV is useful
because it completely separates server code from the client’s machine.

Django’s Models and Views are present on the client machine and only templates return
to the client, which are essentially HTML, CSS code and contains the required data from
the models.

These components are totally different from each other and therefore, front-end
developers and backend developers can work simultaneously on the project as these
two parts changing will have little to no effect on each other when changed.

Therefore, Django is called a loosely coupled framework.

Q. Explain the importance of settings.py file and what data/ settings it contains.

Ans. When Django server starts, it first looks for settings.py. As the name settings, it is
the main settings file of your web application. Everything inside your Django project like
databases, backend engines, middlewares, installed applications, main URL
configurations, static file addresses, templating engines, allowed hosts and servers and
security key stores in this file as a list or dictionary.

So, when your Django server starts it executes settings.py file and then loads particular
engines and databases so that when a request is given it can serve the same quickly.

Q. Explain how you can set up the Database in Django?

Ans - You can use the command edit mysite/setting.py , it is a normal python module
with module level representing Django settings.
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# 'OPTIONS': {
# 'timeout': 20,
# }
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'name_of_database',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': 5432,

}
}
Django uses SQLite by default; it is easy for Django users as such it won’t require any
other type of installation. In the case your database choice is different that you have to
the following keys in the DATABASE ‘default’ item to match your database connection
settings

Engines: you can change database by using ‘django.db.backends.sqlite3’ ,


‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’,
‘django.db.backends.oracle’ and so on Name: The name of your database. In the case if
you are using SQLite as your database, in that case database will be a file on your
computer, Name should be a full absolute path, including file name of that file. If you
are not choosing SQLite as your database then setting like Password, Host, User, etc.
must be added.

Q. What is Django ORM?

Ans. Django ORM is one of the special feature-rich tools in Django. ORM is an acronym
for Object-Relational Mapper. This ORM enables a developer to interact with a database
in a pythonic way.

Django ORM is the abstraction between models (web application data-structure) and
the database where the data is stored. It makes possible to retrieve, save, delete and
perform other operations over the database without ever writing any SQL code.

It also covers many loopholes and takes all the field attributes and gives you more
control over your code in Python rather than any database language.

Q. Mention what does the Django templates consists of? How does Django
Templating work?
Ans - The template is a simple text file. It can create any text-based format like XML,
CSV, HTML, etc. A template contains variables that get replaced with values when the
template is evaluated and tags (% tag %) that controls the logic of the template.

Django templating engine handles templating in the Django framework. There are some
template syntaxes which declares variables, control logic, filters, and comments. After
putting these inside the HTML structure, when the web page is requested and called
upon by the view function, the Django Template engine gets two things, the HTML
structure with variables in place and the data to replace with those variables. It replaces
the variables with data while also executing the control logic and generating filters. It
renders the required HTML and sends it to the browser when all the work gets
complete.

Q. Explain the use of session framework in Django?

Ans - In Django, the session framework enables you to store and retrieve arbitrary data
on a per-site-visitor basis. It stores data on the server side and abstracts the receiving
and sending of cookies. Session can be implemented through a piece of middleware.

Q. Explain the migration in Django and how you can do in SQL?

Ans - Migration in Django is to make changes to your models like deleting a model,
adding a field, etc. into your database schema. There are several commands you use to
interact with migrations.

Migrate Makemigrations Sqlmigrate To do the migration in SQL, you have to print the
SQL statement for resetting sequences for a given app name.

./manage.py sqlsequencreset
Use this command to generate SQL that will fix cases where a sequence is out sync with
its automatically incremented field data.

Q. What is Unicode, what is UTF-8 and how do they relate?

Ans - Unicode is an international encoding standard that works with different languages
and scripts. It consists of letters, digits or symbols representing characters from across
the world. UTF-8 is a type of encoding, a way of storing the code points of Unicode in a
byte form, so you can send Unicode strings over the network or store them in files.”

Q. List out the inheritance styles in Django?

Ans - In Django, there is three possible inheritance styles


Abstract base classes: This style is used when you only wants parent’s class to hold
information that you don’t want to type out for each child model.

Concrete/Multi-table Inheritance: Concrete inheritance works by deriving from the base


class just like you normally would in Python classes. However, in Django, this base class
will be mapped into a separate table. Each time you access base fields, an implicit join is
needed. This leads to horrible performance.

Proxy models: You can use this model, If you only want to modify the Python level
behavior of the model, without changing the model’s fields

Intermediate

Q. What is WSGI?

Ans - Django, being a web framework, needs a web server in order to operate. And since
most web servers don’t natively speak Python, we need an interface to make that
communication happen. This is where WSGI comes.

WSGI is the main Python standard for communicating between Web servers and
applications, but it only supports synchronous code.

Example of WSGI servers - uWSGI, Guniocrn etc

Note - Django begins its path towards asynchronous code capability. With djnago 3.0, it
now supports running as an ASGI (Asynchronous Server Gateway Interface) application.
ASGI provides an interface between asynchronous Python web servers and frameworks.

This is major benefit for web programming. Instead of running 10 queries one after the
other and waiting for each one to come back, you can run 10 queries at the same time,
while hitting your cache and making a HTTP request simultaneously on a single thread.

Q. What are fixtures?

Ans - it’s sometimes useful to pre-populate your database with hard-coded data when
you’re first setting up an app. You can provide initial data with fixtures.

As an example, though, here’s what a fixture for a Person model might look like in JSON:

[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon"
}
},
{
"model": "myapp.person",
"pk": 2,
"fields": {
"first_name": "Paul",
"last_name": "McCartney"
}
}
]
You can load data by calling

manage.py loaddata <fixturename>


Q. Middlewares - what they are and how they work?

Ans - Middlewares are hooks to modify Django request or response object. It’s a light,
low-level “plugin” system for globally altering Django’s input or output.

You can use middleware if you want to modify the request i.e HttpRequest object which
is sent to the view. Or you might want to modify the HttpResponse object returned from
the view.

Example - SecurityMiddleware, SessionMiddleware, AuthenticationMiddleware etc...

An example middleware

class BookMiddleware(object):
def process_request(self, request):
print "Middleware executed"
Add this middleware in MIDDLEWARE_CLASSES

MIDDLEWARE_CLASSES = (
'books.middleware.BookMiddleware',
...
)
Make request to any url. This should get printed on runserver console

Middleware executed
**Q. What are decorators? Name some useful built-in django decorators.

Ans - By definition, a decorator is a function that takes another function and extends the
behavior of the latter function without explicitly modifying it.
Example:

from django.core.exceptions import PermissionDenied

def login_required(function):
def wrap(request, *args, **kwargs):
user = request.user
if user.is_authenticated():
return function(request, *args, **kwargs)
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
Some useful built-in decorators

login_required

group_required: allow a certain group of users to access a page.

@group_required(‘admins’, ‘seller’)
def my_view(request, pk)
ajax_required: checks if the request is an AJAX request.

timeit: This decorator is very helpful if you need to improve the response time of one of
then our views or if you just want to know how long it takes to run.

**Q. What are mixins?? Name some useful built-in django mixins.

Ans - Python supports a simple type of multiple inheritence which allows the creation of
Mixins, which are sort of class that is used to mix-in extra properties and methods into a
class.This allows you to create class in a compositional style.

Example:

class Mixin1(object):
def test(self):
print "Mixin1"

class Mixin2(object):
def test(self):
print "Mixin2"

class MyClass(Mixin2, Mixin1, BaseClass):


pass
Note: In Python, the class hierarchy is defined right to left.

Q. What is signals and how to use it? What are two important parameter in
signals?
Ans - Signals allow certain senders to notify a set of receivers that some action has
taken place. They’re especially useful when many pieces of code may be interested in
the same events.

Some of the most used models’ signals are the following:

 pre_save/post_save: This signal is thrown before/after the method save().


 pre_delete/post_delete: Before after delete a model’s instance (method delete())
this signal is thrown.
 pre_init/post_init: This signal works before/after instantiating a model (init()
method)

Connecting Signals

With the @receiver decorator, we can link a signal with a function:

from django.db.models.signals import post_save


from django.dispatch import receiver
from someapp.models import MyModel

@receiver(post_save, sender=MyModel)
def my_function_post_save(sender, **kwargs):
# do the action…
Every time that a MyModel’s instance ends to run its save() method, the
my_function_post_save will start to work.

Q. How will you integrate a legacy database in your django project?

Ans - First, You’ll need to tell Django what your database connection parameters are,
and what the name of the database is. Do that by editing the DATABASES setting and
assigning values to the following keys for the 'default' connection.

Django comes with a utility called inspectdb that can create models by introspecting an
existing database. Create models.py file based on output of same command

$ python manage.py inspectdb > models.py


Q. How you will add extra function/feature in admin part? Ans - To do so, modify
admin.py file in the app directory to include your model and fields that you wnat to
appear inside admin pannel.

Example - models.py

from django.db import models


Rating = [
('b', 'Bad'),
('a', 'Average'),
('e', 'Excellent')
]
#DataFlair
class Product(models.Model):
name = models.CharField(max_length = 200)
description = models.TextField()
mfg_date = models.DateTimeField(auto_now_add = True)
rating = models.CharField(max_length = 1, choices = Rating)
def __str__(self):
return self.name
def show_desc(self):
return self.description[:50]
admin.py

from django.contrib import admin


from django.contrib.auth.models import Group
from .models import Product

# Admin Action Functions


def change_rating(modeladmin, request, queryset):
queryset.update(rating = 'e')

# Action description
change_rating.short_description = "Mark Selected Products as Excellent"

class ProductA(admin.ModelAdmin):
list_display = ('name', 'description', 'mfg_date', 'rating')
list_filter = ('mfg_date', )
actions = [change_rating]

admin.site.register(Product, ProductA)
admin.site.unregister(Group)

# changes the header of admin


admin.site.site_header = "Django Interview Example"
Q Mentions steps to deploy static files on your production server.

Ans - Serving the site and your static files from the same server:

 Push your code up to the deployment server.


 On the server, run collectstatic to copy all the static files into STATIC_ROOT.
 Configure your web server to serve the files in STATIC_ROOT under the URL
STATIC_URL.

Serving the site and your static files from dedicated server

Since your static file server won’t be running Django, you’ll need to modify the
deployment strategy to look something like:

 When your static files change, run collectstatic locally.


 Push your local STATIC_ROOT up to the static file server into the directory that’s being
served. rsync is a common choice for this step since it only needs to transfer the bits of
static files that have changed.

Serving static files from a cloud service or CDN:

There’s any number of ways you might do this, but if the provider has an API, you can
use a custom file storage backend to integrate the CDN with your Django project. If
you’ve written or are using a 3rd party custom storage backend, you can tell collectstatic
to use it by setting STATICFILES_STORAGE to the storage engine.

For example, if you’ve written an S3 storage backend in myproject.storage.S3Storage


you could use it with:

STATICFILES_STORAGE = 'myproject.storage.S3Storage'
Once that’s done, all you have to do is run collectstatic and your static files would be
pushed through your storage package up to S3. If you later needed to switch to a
different storage provider, you may only have to change your STATICFILES_STORAGE
setting.

For detail on writing custom storage system, see

Q. What is Jinja Templating?

Ans. Django supports many popular templating engines and by default, it comes with
one very powerful templating engine. Jinja Templating is a very popular templating
engine for Python, the latest version in the market is Jinja 2. There are some features of
Jinja templating which makes it a better option then the default template system in
Django.

Sandbox Execution – This is like a sandbox or a protected framework for automating the
testing process. HTML Escaping – Jinja 2 provides automatic HTML Escaping, as <, >, &
characters have special values in templates and if used as regular text, these symbols
can lead to XSS Attacks which Jinja deals with automatically. Template Inheritance
Generates HTML templates much faster than default engine Easier to debug, compared
to default engine.

Advanced

Q. How will you get list of logged-in users?

Ans - For this, you can query the Session model for non-expired sessions, then turn the
session data into users.
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.utils import timezone

def get_all_logged_in_users():
# Query all non-expired sessions
# use timezone.now() instead of datetime.now() in latest versions of Django
sessions = Session.objects.filter(expire_date__gte=timezone.now())
uid_list = []

# Build a list of user ids from that query


for session in sessions:
data = session.get_decoded()
uid_list.append(data.get('_auth_user_id', None))

# Query all logged in users based on id list


return User.objects.filter(id__in=uid_list)

Django interview question that I've been asked. ##Django - Interview Questions

Q#1. What do you like about django? Or the same question can be re-phrased as what
are the features of django?

Answer: Django is secure, fast and rapid application development(RAD) framework.. It


offers/features are:

● Admin Interface (CRUD) ● Templating ● Form handling ● Internationalization ●


Session, user management, role-based permissions, messages ● Object-relational
mapping (ORM)

Q#2. What architecture does Django follow? Or Is Django an MVC framework? Answer:
Django follows MTV pattern/architecture. MTV stands for Model, Template, View.

Q#3. How to write views in django? Answer. There are 2 primary methods to write views
in django. First is the django function based views and second is django’s class based
views. Function based views are simple and are better option to go for if you know that
you have to create less than 8-10 views.

Q#4. What’s the current version of Django? Or (What django version are you currently
working with)? Answer. Django 2.2

Q#5. How to create a model in Django? Or Can you name some model fields that you’ve
created before during your projects? Answer. Models in django inherit from the models
class. The class offers multiple fields to work with. Fields that I’ve used and are used
extensively in any project are:

1. CharField(max_length=128)(tell the interviewer that max_length parameter is not


optional)
2. ImageField() - tell them that the ImageField inherits from FileField()
3. BooleanField() - tell them it’s best practise to use default value for boolean field.
4. IntegerField() - Also mention the PositiveIntegerField()
5. DateTimeField() - Tell them that you can pass auto_now_add=True as a
parameter to get current timestamp saved into datetimefield()

Q#6. How would you check your django version? Answer. Python -m django –version

Q#7. Can you use MySQL with Django? Answer. Yes, you can. You can use, mysql, sqlite,
oracle, postgresql etc

Q#9. What does makemigrations command do? Answer. It creates migrations for the
models that you define in models.py file.

Q#10. What popular websites use django? Can you name some? Answer. Disqus,
Instagram, Mozilla, NASA, The Washington Post etc.

Q#11. So you said, django follows MTV pattern. You mean django doesn’t follow MVC
right? Answer. MTV closely resembles MVC. Because, the framework handles the
controller part itself so most things happen only in models, views and templates.

Q#13. Think of this scenario. You’re a django developer here. A big company, take Tesla
as example, wants us to make them a website where the website handles all the
feedback from the clients that are currently using tesla as their primary vehicle of
transport. How would you make that type of website, sometimes, you might get 1000
reviews/feedbacks in an hour. How would you design the database too. Also tell about
the security. If you know about front-end, what front-end technology would you prefer?

Anwer. Start by asking further questions and remove any doubt or question you have.
Tell them how you would make it. When it comes to database design, explain all the
fields that you are going to use. If the feedback is coming from unregistered clients than
you might not know their location. In that case, you will determine the location using ip-
location services and store the ip-address in GenericIPAddressField() field. Continue with
more explanation and if you know any front-end technology than explain why would
you prefer that particular technology instead of certain other technologies available in
the market
FLASK:

Quickstart
Installation
pip install flask

Minimal app

Code Here

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"

if __name__=="__main__":
app.run()

So what did that code do?

1. First we imported the Flask class. An instance of this class will be our WSGI
application.
2. Next we create an instance of this class. The first argument is the name of the
application’s module or package. name is a convenient shortcut for this that is
appropriate for most cases. This is needed so that Flask knows where to look for
resources such as templates and static files.
3. We then use the route() decorator to tell Flask what URL should trigger our
function.
4. The function returns the message we want to display in the user’s browser. The
default content type is HTML, so HTML in the string will be rendered by the
browser.

Debug Mode

Code Here

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"

# debud mode running on 8000 port


if __name__=="__main__":
app.run(debug=True, port=8000)
The flask run command can do more than just start the development server. By enabling
debug mode, the server will automatically reload if code changes, and will show an
interactive debugger in the browser if an error occurs during a request.

Warning The debugger allows executing arbitrary Python code from the browser. It is
protected by a pin, but still represents a major security risk. Do not run the development
server or debugger in a production environment.

Routing

Code Here

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
return 'This is Index Page'
@app.route('/login')
def login():
return 'This is Login Page'

@app.route('/hello')
def hello():
return 'Hello, World'

if __name__=="__main__":
app.run(debug=True)
Modern web applications use meaningful URLs to help users. Users are more likely to
like a page and come back if the page uses a meaningful URL they can remember and
use to directly visit a page.
Use the route() decorator to bind a function to a URL.

Rendering Templates

Code Here

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def index():
return render_template('index.html')

@app.route("/")
def about():
return render_template('about.html')

if __name__=="__main__":
app.run()

In flask, html file are served from the 'templates' folder by default and all the
static file; images, css, js, etc are served from the 'static' folder.

These folders should be present in the root directly of your python application
URL Variables

Code Here

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html')

# string
@app.route('/string/<string:value>')
def string(value):
return f"<p>Hi this is a string value {value}</p>"

# int
@app.route('/int/<int:value>')
def int(value):
return f"<p>Hi this is a int value {value}</p>"

# float
@app.route('/float/<float:value>')
def float(value):
return f"<p>Hi this is a float value {value}</p>"

# path
@app.route('/path/<path:value>')
def path(value):
return f"<p>Hi this is a path value {value}</p>"

# uuid
@app.route('/uuid/<uuid:value>')
def uuid(value):
return f"<p>Hi this is a uuid value {value}</p>"

if __name__=="__main__":
app.run(debug=True)

You can add variable sections to a URL by marking sections with <variable_name>. Your
function then receives the <variable_name> as a keyword argument. Optionally, you can
use a converter to specify the type of the argument like converter:variable_name.
Type Value Use
string (default) accepts any text without a slash string:value

int accepts positive integers int:value

float accepts positive floating point values float:value

path like string but also accepts slashes path:value

uuid accepts UUID strings uuid:value

Redirection

Code Here

from flask import Flask, render_template, request


from werkzeug.utils import redirect

app = Flask(__name__)

@app.route('/', methods = ['GET', 'POST'])


def home():
if request.method == 'POST':
name = request.form.get('name')
age = request.form.get('age')
return redirect(f'/result/{name}/{age}')
return render_template('home.html')

@app.route('/about')
def about():
return "This is about"

@app.route('/result/<name>/<age>')
def result(name, age):
return render_template('result.html', name=name, age=age)

app.run()
The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in
a file system. If you access the URL without a trailing slash (/about), Flask redirects you
to the canonical URL with the trailing slash (/about/).

Message Flashing

Code Here

from flask import Flask, flash, redirect, render_template, request, url_for

app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

@app.route('/')
def index():
return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])


def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] !=
'secret':
error = 'Invalid credentials'
else:
flash('You were successfully logged in')
return redirect('/')
return render_template('login.html', error=error)

if __name__=="__main__":
app.run(debug=True)

Good applications and user interfaces are all about feedback. If the user does not get
enough feedback they will probably end up hating the application. Flask provides a
really simple way to give feedback to a user with the flashing system. The flashing
system basically makes it possible to record a message at the end of a request and
access it next request and only next request. This is usually combined with a layout
template that does this. Note that browsers and sometimes web servers enforce a limit
on cookie sizes. This means that flashing messages that are too large for session cookies
causes message flashing to fail silently.
JAVA INTERVIEW QUESTIONS

Q. What is JVM? Why is Java called the "Platform Independent Programming


Language”?Entry
A Java virtual machine (JVM) is a process virtual machine that can execute Java
bytecode.

Each Java source file is compiled into a bytecode file, which is executed by the JVM.
Java was designed to allow application programs to be built that could be run on any
platform, without having to be rewritten or recompiled by the programmer for each
separate platform.

A Java virtual machine makes this possible because it is aware of the specific
instruction lengths and other particularities of the underlying hardware platform.
Q. What is a Java Applet?Entry
A Java Applet is a program that can be included in an HTML page and be executed in
a java enabled client browser. Applets are used for creating dynamic and interactive
web applications.
Q. What is JDBC?Entry
JDBC is an abstraction layer that allows users to choose between databases. JDBC
enables developers to write database applications in Java without having to concern
themselves with the underlying details of a particular database.
Q. What is a JSP Page?Entry
A Java Server Page (JSP) is a text document that contains two types of text:

 static data and


 JSP elements.

Static data can be expressed in any text-based format, such as HTML or XML. JSP is
a technology that mixes static content with dynamically-generated content.
Q. What is the difference between an Applet and a Java Application?Entry

 Applets are executed within a Java-enabled browser.


 Java application is a standalone Java program that can be executed outside of a
browser.
However, they both require the existence of a Java Virtual Machine (JVM).
Furthermore, a Java application requires a main method with a specific signature, in
order to start its execution. Java applets don’t need such a method to start their
execution. Finally, Java applets typically use a restrictive security policy, while Java
applications usually use more relaxed security policies.
Q. What is the Difference between JDK and JRE?Entry

 The Java Runtime Environment (JRE) is basically the Java Virtual Machine
(JVM) where your Java programs are being executed. It also includes browser
plugins for applet execution.
 The Java Development Kit (JDK) is the full-featured Software Development
Kit for Java, including the JRE, the compilers, and tools (like JavaDoc, and
Java Debugger), in order for a user to develop, compile and execute Java
applications.

Q. What is a Servlet?Entry
The servlet is a Java programming language class used to process client requests and
generate dynamic web content.

Servlets are mostly used to process or store data submitted by an HTML form,
provide dynamic content and manage state information that does not exist in the
stateless HTTP protocol.
Q. What are the two types of Exceptions in Java? Which are the differences
between them?Entry
Java has two types of exceptions: checked exceptions and unchecked exceptions.

1. Unchecked exceptions do not need to be declared in a method or a


constructor’s throws clause if they can be thrown by the execution of the
method or the constructor, and propagate outside the method or constructor
boundary.
2. On the other hand, checked exceptions must be declared in a method or a
constructor’s throws clause.

Q. What are JSP Actions?Junior


JSP actions use constructs in XML syntax to control the behavior of the servlet
engine. JSP actions are executed when a JSP page is requested. They can be
dynamically inserted into a file, re-use JavaBeans components, forward the user to
another page, or generate HTML for the Java plugin. Some of the available actions are
listed below:
 jsp:include – includes a file, when the JSP page is requested.
 jsp:useBean – finds or instantiates a JavaBean.
 jsp:setProperty – sets the property of a JavaBean.
 jsp:getProperty – gets the property of a JavaBean.
 jsp:forward – forwards the requester to a new page.
 jsp:plugin – generates browser-specific code.

Q. Explain the architecture of a Servlet.Junior


The core abstraction that must be implemented by all servlets is
the javax.servlet.Servlet interface.

Each servlet must implement it either directly or indirectly, either by


extending javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet .

Finally, each servlet is able to serve multiple requests in parallel using multithreading.
Q. What’s the difference between sendRedirect and forward methods?Junior
The sendRedirect method creates a new request, while the forward method just
forwards a request to a new target. The previous request scope objects are not
available after a redirect, because it results in a new request.

On the other hand, the previous request scope objects are available after forwarding.
FInally, in general, the sendRedirect method is considered to be slower compared to
the forward method.
Q. What are Declarations?Junior
Declarations are similar to variable declarations in Java. Declarations are used to
declare variables for subsequent use in expressions or scriptlets. To add a declaration,
you must use the sequences to enclose your declarations.
Q. What is the purpose of Garbage Collection in Java, and when is it used?Junior
The purpose of garbage collection is to identify and discard those objects that are no
longer needed by the application, in order for the resources to be reclaimed and
reused.
Q. What is the reflection and why is it useful?Junior
The name reflection is used to describe code which is able to inspect other code in the
same system (or itself) and to make modifications at runtime.

For example, say you have an object of an unknown type in Java, and you would like
to call a 'doSomething' method on it if one exists. Java's static typing system isn't
really designed to support this unless the object conforms to a known interface, but
using reflection, your code can look at the object and find out if it has a method called
'doSomething' and then calls it if you want to.

Method method = foo.getClass().getMethod("doSomething", null);

method.invoke(foo, null);

Q. What is the design pattern that Java uses for all Swing components?Junior
The design pattern used by Java for all Swing components is the Model View
Controller (MVC) pattern.
Q. What is the purpose Class.forName method?Junior
The java.lang.Class.forName(String name, boolean initialize, ClassLoader loader)
the method returns the Class object associated with the class or interfaces with the
given string name, using the given class loader.
Q. What is Function Overriding and Overloading in Java?Junior

 Method overloading in Java occurs when two or more methods in the same
class have the exact same name, but different parameters.

class Dog{

public void bark(){

System.out.println("woof ");

//overloading method

public void bark(int num){

for(int i=0; i<num; i++)

System.out.println("woof ");

}
}

 On the other hand, method overriding is defined as the case when a child class
redefines the same method as a parent class. Overridden methods must have the
same name, argument list, and return type. The overriding method may not
limit the access of the method it overrides.

class Dog{

public void bark(){

System.out.println("woof ");

class Hound extends Dog{

public void sniff(){

System.out.println("sniff ");

public void bark(){

System.out.println("bowl");

}
public class OverridingTest{

public static void main(String [] args){

Dog dog = new Hound();

dog.bark();

Q. How are the JSP requests handled?Junior


On the arrival of a JSP request, the browser first requests a page with a .jsp extension.
Then, the Web server reads the request, and using the JSP compiler, the Web server
converts the JSP page into a servlet class. Notice that the JSP file is compiled only on
the first request of the page, or if the JSP file has changed.

The generated servlet class is invoked, in order to handle the browser’s request. Once
the execution of the request is over, the servlet sends a response back to the client.
Q. What are Expressions?Junior
A JSP expression is used to insert the value of a scripting language expression,
converted into a string, into the data stream returned to the client, by the web server.
Expressions are defined between <% = and %> tags.
Q. How does Garbage Collection prevent a Java application from going out of
memory?Junior
It doesn’t! Garbage Collection simply cleans up unused memory when an object goes
out of scope and is no longer needed. However, an application could create a huge
number of large objects that causes an OutOfMemoryError .
Q. Explain Serialization and Deserialization.Junior
Java provides a mechanism, called object serialization where an object can be
represented as a sequence of bytes and includes the object’s data, as well as
information about the object’s type, and the types of data stored in the object.

Thus, serialization can be seen as a way of flattening objects, in order to be stored on


a disk, and later, read back and reconstituted. Deserialisation is the reverse process of
converting an object from its flattened state to a live object.
Q. How HashMap works in Java?Junior
A HashMap in Java stores key-value pairs. The HashMap requires a hash function and
uses hashCode and equals methods, in order to put and retrieve elements to and from
the collection respectively. When the put method is invoked, the HashMap calculates
the hash value of the key and stores the pair in the appropriate index inside the
collection. If the key exists, its value is updated with the new value. Some important
characteristics of a HashMap are its capacity, its load factor, and the threshold
resizing.
Q. What does System.gc() and Runtime.gc() methods do?Junior
These methods can be used as a hint to the JVM, in order to start a garbage collection.
However, it is up to the Java Virtual Machine (JVM) to start the garbage collection
immediately or later in time.
Q. What are Directives?Junior
What are the different types of Directives available in JSP? Directives are instructions
that are processed by the JSP engine when the page is compiled to a servlet.
Directives are used to set page-level instructions, insert data from external files, and
specify custom tag libraries. Directives are defined between < %@ and % >.The
different types of directives are shown below:

 Include directive: it is used to include a file and merges the content of the file
with the current page.
 Page directive: it is used to define specific attributes in the JSP page, like the
error page and buffer.
 Taglib: it is used to declare a custom tag library that is used on the page.

Q. What differences exist between HashMap and Hashtable?Junior


There are several differences between HashMap and Hashtable in Java:

1. is synchronized, whereas HashMap is not. This makes HashMap better for


Hashtable
non-threaded applications, as unsynchronized Objects typically perform better
than synchronized ones.
2. Hashtable does not allow null keys or values. HashMap allows one null key and
any number of null values.
3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want
predictable iteration order (which is insertion order by default), you could
easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you
were using Hashtable.

Q. What is the difference between an Interface and an Abstract class?Junior


Java provides and supports the creation both of abstract classes and interfaces. Both
implementations share some common characteristics, but they differ in the following
features:

 All methods in an interface are implicitly abstract. On the other hand, an


abstract class may contain both abstract and non-abstract methods.
 A class may implement a number of Interfaces, but can extend only one
abstract class.
 In order for a class to implement an interface, it must implement all its declared
methods. However, a class may not implement all declared methods of an
abstract class. Though, in this case, the sub-class must also be declared as
abstract.
 Abstract classes can implement interfaces without even providing the
implementation of interface methods.
 Variables declared in a Java interface is by default final. An abstract class may
contain non-final variables.
 Members of a Java interface are public by default. A member of an abstract
class can either be private, protected or public.
 An interface is absolutely abstract and cannot be instantiated. An abstract class
also cannot be instantiated, but can be invoked if it contains a main method.

Q. What are the Data Types supported by Java? What are Autoboxing and
Unboxing?Junior
The eight primitive data types supported by the Java programming language are:

 byte
 short
 int
 long
 float
 double
 boolean
 char

Autoboxing is the automatic conversion made by the Java compiler between the
primitive types and their corresponding object wrapper classes. If the conversion goes
the other way, this operation is called unboxing.
Q. What is the difference between processes and threads?Junior
The main difference between them is that
 a Process is a program which is executing some code and
 a Thread is an independent path of execution in the process.

A process can have more than one thread for doing independent task e.g. a thread for
reading data from disk, a thread for processing that data and another thread for
sending that data over the network.
Q. What will happen to the Exception object after exception handling?Junior
The exception object will be garbage collected in the next garbage collection.
Q. What does the static keyword mean? Can you override the private or static
methods in Java?Junior
The static keyword denotes that a member variable or method can be
accessed, without requiring an instantiation of the class to which it belongs.

A user cannot override static methods in Java, because 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 the concept is
not applicable.
Q. What is the difference between Exception and Error in Java?Junior

 An Error "indicates serious problems that a reasonable application should not


try to catch."
 An Exception "indicates conditions that a reasonable application might want to
catch."

Q. What is the importance of finally block in exception handling?Junior


A finally block will always be executed, whether or not an exception is actually
thrown. Even in the case where the catch statement is missing and an exception is
thrown, the finally block will still be executed.

The Last thing to mention is that the finally block is used to release resources like I/O
buffers, database connections, etc.
Q. What is an Iterator?Junior
The Iterator provides a number of methods that are able to iterate over any Collection.
Each Java Collection contains the Iterator method that returns an Iterator instance.
Iterators are capable of removing elements from the underlying collection during the
iteration.
Q. When does an Object become eligible for Garbage Collection in Java?Junior
A Java object is subject to garbage collection when it becomes unreachable to the
program in which it is currently used.
Q. What is pass by reference and pass by value?Junior

 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 doesn’t affect the
original value.
 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 method, are also reflected in all places.

Q. What are the basic interfaces of the Java Collections Framework?Junior


Java Collections Framework provides a well-designed set of interfaces and classes
that support operations on collections of objects. The most basic interfaces that reside
in the Java Collections Framework are:

 Collection, which represents a group of objects known as its elements.


 Set, which is a collection that cannot contain duplicate elements.
 List, which is an ordered collection and can contain duplicate elements.
 Map, which is an object that maps keys to values and cannot contain duplicate
keys.

Q. Explain the role of the Driver in JDBC.Mid


The JDBC Driver provides vendor-specific implementations of the abstract classes
provided by the JDBC API. Each driver must provide implementations for the
following classes of the java.sql package: Connection, Statement, PreparedStatement,
CallableStatement, ResultSet, and Driver.
Q. What is the relationship between an event-listener interface and an event-
adapter class?Mid
An event-listener interface defines the methods that must be implemented by an event
handler for a particular event.

An event adapter provides a default implementation of an event-listener interface.


Q. What is the applet security manager, and what does it provide?Mid
The applet security manager is a mechanism to impose restrictions on Java applets. A
browser may only have one security manager. The security manager is established at
startup, and it cannot thereafter be replaced, overloaded, overridden, or extended.
Q. What is the difference between throws and throws?Mid
The throw keyword is used to explicitly raise an exception within the program. On the
contrary, the throws clause is used to indicate those exceptions that are not handled by
a method.

Each method must explicitly specify which exceptions do not handle, so the callers of
that method can guard against possible exceptions. Finally, multiple exceptions are
separated by a comma.
Q. What happens when an Applet is loaded?Mid
First of all, an instance of the applet’s controlling class is created. Then, the applet
initializes itself and finally, it starts running.
Q. Explain the life cycle of a Servlet.Mid
At every client’s request, the Servlet Engine loads the servlets and invokes its init
methods, in order for the servlet to be initialized.

Then, the Servlet object handles all subsequent requests coming from that client, by
invoking the service method for each request separately.

Finally, the servlet is removed by calling the server’s destroy method.


Q. What is the structure of Java Heap?Mid
The JVM has a heap that is the runtime data area from which memory for all class
instances and arrays is allocated. It is created at the JVM start-up.

Heap memory for objects is reclaimed by an automatic memory management system


which is known as a garbage collector.

Heap memory consists of live and dead objects. Live objects are accessible by the
application and will not be a subject of garbage collection. Dead objects are those
which will never be accessible by the application but have not been collected by the
garbage collector yet. Such objects occupy the heap memory space until they are
eventually collected by the garbage collector.
Q. What differences exist between Iterator and ListIterator?Mid

 An Iterator can be used to traverse the Set and List collections, while
the ListIterator can be used to iterate only over List .
 The Iterator can traverse a collection only in the forward direction, while
the ListIterator can traverse a List in both directions.
 The ListIterator implements the Iterator interface and contains extra
functionality, such as adding an element, replacing an element, getting the
index position for previous and next elements, etc
Q. What is the difference between doGet() and doPost()?Mid

 doGET: The GET method appends the name-value pairs on the request’s URL.
Thus, there is a limit on the number of characters and subsequently on the
number of values that can be used in a client’s request. Furthermore, the values
of the request are made visible and thus, sensitive information must not be
passed in that way.
 doPOST: The POST method overcomes the limit imposed by the GET request,
by sending the values of the request inside its body. Also, there is no limitations
on the number of values to be sent across. Finally, the sensitive information
passed through a POST request is not visible to an external client.

Q. What is the role of stub in RMI?Mid


A stub for a remote object acts as a client’s local representative or proxy for the
remote object. The caller invokes a method on the local stub, which is responsible for
executing the method on the remote object. When a stub’s method is invoked, it
undergoes the following steps:

 It initiates a connection to the remote JVM containing the remote object.


 It marshals the parameters to the remote JVM.
 It waits for the result of the method invocation and execution.
 It unmarshals the return value or an exception if the method has not been
successfully executed.
 It returns the value to the caller.

Q. What is the difference between GenericServlet and HttpServlet?Mid


GenericServlet is a generalized and protocol-independent servlet that implements the
Servlet and ServletConfig interfaces.

Those servlets extending the GenericServlet class shall override the service method.

Finally, in order to develop an HTTP servlet for use on the Web that serves requests
using the HTTP protocol, your servlet must extend the HttpServlet instead.
Q. What is a Constructor, Constructor Overloading, and Copy-Constructor in
Java?Mid
A constructor gets invoked when a new object is created. Every class has a
constructor In case the programmer does not provide a constructor for a class, the Java
compiler (Javac) creates a default constructor for that class.
The constructor overloading is similar to method overloading in Java. Different
constructors can be created for a single class.

Each constructor must have its own unique parameter list. Finally, Java does support
copy constructors like C++, but the difference lies in the fact that Java doesn’t create a
default copy constructor if you don’t write your own.

REACT INTERVIEW QUESTIONS

You might also like