Programming Questions
Programming Questions
Encapsulation?
Encapsulation is a strategy used as part of abstraction. Encapsulation refers to the state of
objects - objects encapsulate their state and hide it from the outside; outside users of the class
interact with it through its methods, but cannot access the classes state directly. So the class
abstracts away the implementation details related to its state.
Inheritance?
The Inheritance is ability of a new class to be created, from an existing class by extending it.
Inheritance comes from the fact that the subclass (the newly created class) contains the
attributes and methods of the parent class. The main advantage of inheritance is the ability to
define new attributes and new methods for the subclass which are then are used together with
the inherited attributes and methods.
Abstract class?
Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only
be used as a super-class for other classes that extend the abstract class. Abstract class is the
concept and implementation gets completed when it is being realized by a subclass. Subclass
must override all its abstract methods/properties and may override virtual methods/properties.
Interface?
Interfaces are similar to classes but they can not have state or implementation. This means they
can only contain method prototypes (no implementation, just method signature). An interface act
as a contract between a class and the outside world. When a class implements an interface, it
promises to provide the behavior published by that interface (implement interface methods
behaviour).
Polymorphism?
Polymorphism is a concept in object oriented programming in which classes have different
functionality while sharing a common interface. Code working with the different classes does not
need to know which class it is using since they’re all used the same way.
Overloading?
Overloading is a concept where within one class there can be one or more methods with the
same name, that differ only on number or types of their parameters. This way, there can be a
group of methods that have the same name, and similar functionality within one class. Example
of overloading methods can be DrawRectangle(int left, int top, int bottom, int right) and
DrawRectangle(Point topLeft, Point bottomRight).
http://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-
overloading/154939#154939
Virtual functions
A virtual function provides a default implementation and it can exist on either an abstract class
or a non-abstract class. It provides the functionality that may or may not be good enough for the
child class. So if it is good enough, use this method, if not, then override me, and provide your
own functionality.. When calling the function on the instance of the subclass it will call either
function declared in subclass (if it has overridden it) or in the parent class.
Pass by reference means use the actual memory storing the value - so if the function changes
the value then the change is immediate and preserved when the function exits.
Command
Command decouples the object that invokes the operation from the one that knows how to
perform it. It is mostly used to enable undoable operations.
http://sourcemaking.com/design_patterns/command
Bridge
The bridge pattern is a design pattern used in software engineering which is meant to "decouple
an abstraction from its implementation so that the two can vary independently".The bridge uses
encapsulation, aggregation, and can use inheritance to separate responsibilities into different
classes.
When a class varies often, the features of object-oriented programming become very useful
because changes to a program's code can be made easily with minimal prior knowledge about
the program. The bridge pattern is useful when both the class as well as what it does vary often.
The class itself can be thought of as the implementation and what the class can do as the
abstraction. The bridge pattern can also be thought of as two layers of abstraction.
http://sourcemaking.com/design_patterns/bridge
Composite
Composite objects are objects that contain other objects. The Composite pattern composes
objects into tree structures and lets clients treat individual objects and compositions uniformly.
Ie. complex shape object can contain many different shapes inside. Each shape (complex and
simple) will have a draw method. Composite pattern inside ComplexShape will inside its Draw
method call Draw function of all simple shapes contained within.
http://sourcemaking.com/design_patterns/composite
Proxy
Provide a surrogate or placeholder for another object to control access to it.
http://sourcemaking.com/design_patterns/proxy
Mediator
Define an object that encapsulates how a set of objects interact. Mediator promotes loose
coupling by keeping objects from referring to each other explicitly, and it lets you vary their
interaction independently.
http://sourcemaking.com/design_patterns/mediator
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy
lets the algorithm vary independently from clients that use it.
Data Types
Single linked list
Type of list. In a singly linked list each node in the list stores the contents of the node and a
pointer or reference to the next node in the list. It does not store any pointer or reference to the
previous node.
Doubly linked list
Linked data structure that consists of a set of sequentially linked records called nodes. Each
node contains two fields, called links, that are references to the previous and to the next node in
the sequence of nodes. Nodes contain data structures, that is any primitive type or complex
type (object, structure…)
HashMap
Hashed Associative Container that associates objects of type Key with objects of type Data.
Hash_map is a Pair Associative Container, meaning that its value type is pair<const Key,
Data>. It is also a Unique Associative Container, meaning that no two elements have keys that
compare equal using EqualKey.
Set
Abstract data structure that can store certain values, without any particular order, and no
repeated values.
Dictionary
Tuple
Data structure that has a specific number and sequence of elements. An example of a tuple is a
data structure with three elements (known as a 3-tuple or triple) that is used to store an identifier
such as a person's name in the first element, a year in the second element, and the person's
income for that year in the third element.
Stack
Abstract data type or collection in which the principal (or only) operations on the collection are
the addition of an entity to the collection, known as push and removal of an entity.
Dequeue
Abstract data structure that implements a queue for which elements can only be added to or
removed from the front (head) or back (tail).
Queue
Abstract data type or collection in which the entities in the collection are kept in order and the
principal (or only) operations on the collection are the addition of entities to the rear terminal
position.
XML
XSLT
Is a language for transforming XML documents into other XML documents, or other objects
such as HTML for web pages, plain text or other outputs.
xQuery
Query and functional programming language that is designed to query and transform collections
of structured and unstructured data, usually in the form of XML.
xPath
Is a query language for selecting nodes from an XML document. In addition, XPath may be
used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML
document. The XPath is based on a tree representation of the XML document, and provides the
ability to navigate around the tree, selecting nodes by a variety of criteria.
HTML
What is HTML
HTML is a language for describing web pages. HTML is written in the form of HTML elements
consisting of tags enclosed in angle brackets (like <html>). HTML tags most commonly come in
pairs like <h1>and </h1>, although some tags represent empty elements and so are unpaired,
for example <img>. The first tag in a pair is the start tag, and the second tag is the end tag (they
are also called opening tags and closing tags).
The purpose of a web browser is to read HTML documents and compose them into visible or
audible web pages. The browser does not display the HTML tags, but uses the tags to interpret
the content of the page. HTML describes the structure of a website semantically along with cues
for presentation, making it a markup language rather than a programming language.
Regular Expression
http://www.regular-expressions.info/
https://www.debuggex.com/
Positive lookahead
Matches a group after main expression but doesn’t include it in result.
Negative lookahead
Negative lookahead is used if you want to match something not followed by something else.
MySQL
Create database
CREATE DATABASE dbZveen;
Create table
CREATE TABLE tblStaff (id INT, name VARCHAR(15), lastname VARCHAR(30), address
VARCHAR(50), sex CHAR(1), birth DATE);
Aggregate functions
Aggregate functions are used to calculate data based on record grouping
http://www.mysqltutorial.org/mysql-aggregate-functions.aspx
Views
Views are stored queries that when invoked produce a result set. A view acts as a virtual table.
// Creates view
CREATE VIEW MaleStaff AS
SELECT * FROM tblStaff
WHERE sex = ‘m’;
Triggers
A trigger is a special kind of stored procedure that automatically executes when an event occurs
in the database server. Triggers execute when a user tries to modify data through INSERT,
UPDATE, or DELETE statements on a table or view. Triggers also respond to Transact-SQL
CREATE, ALTER, and DROP statements and some other system events like LOGIN.
1. FROM
2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. WITH CUBE or WITH ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10. ORDER BY
11. TOP
Temporary tables
You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible
only to the current session, and is dropped automatically when the session is closed. It behaves
like normal tables.
Table locking
MySQL enables client sessions to acquire table locks explicitly for the purpose of cooperating
with other sessions for access to tables, or to prevent other sessions from modifying tables
during periods when a session requires exclusive access to them.
What is ACID
Consistency
The consistency property ensures that any transaction will bring the database from one valid
state to another. Any data written to the database must be valid according to all defined rules ie.
that string isn’t written into number column.
Isolation
The isolation property ensures that the concurrent execution of transactions results in a system
state that would be obtained if transactions were executed serially, i.e. one after the other.
Durability
Durability means that once a transaction has been committed, it will remain so, even in the
event of power loss, crashes, or errors.
Not *ACID compliant and non- *ACID compliant and hence fully transactional with
transactional ROLLBACK and COMMIT and support for Foreign Keys
Requires full repair/rebuild of Auto recovery from crash via replay of logs
indexes/tables
Changed Db pages written to disk Dirty pages converted from random to sequential before
instantly commit and flush to disk
Transactions
A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order and each unit of work must be successful for
whole transaction to succeed. Transactions usually consists of many SQL commands that need
to be executed together and if everything is successful COMMIT command applies changes to
the database.
Path Disclosure
Path Disclosure (PD) is the revelation of the full operating path of a vulnerable script. the PD
bug is executed by injecting unexpected characters into certain web site parameters. the script
doesn't expect the injected character and returns an error that includes information about the
error along with the script path. Full path disclosure should be prevented by making sure that
the administrators are the only ones who can see error logs, not the page viewers.
Denial of Service
Denial of Service (DoS) attack is an attempt to make machine or network resource disfunctional
(unavailable to its users) usually by sending large amount of packet requests so that target
cannot respond to legitimate traffic. Those attacks usually lead to server overload, which either
consume all server resources or force a server restart. Prevention is to use smart firewalls.
Overposting
In web apps when users submits a form he passes data on the server. Server code can
populate object with this data as a mass assignment which means if data received from the
client matches property of an object then it will assign value of the data to that object. Problem
is when ie. user is creating account he can overpost some fields with form like IsAdmin=true,
Admin=true and mass assignment will apply that to the object and persist it to database giving
that user admin privileges.
Prevention is to use whitelisting of parameters when using mass assignments.
Web development
JRE
Java Runtime Environment. It is basically the Java Virtual Machine where your Java programs
run on. It also includes browser plugins for Applet execution.
JDK
It's the full featured Software Development Kit for Java, including JRE, and the compilers and
tools (like JavaDoc, and Java Debugger) to create and compile programs.
Usually, when you only care about running Java programs on your browser or computer you will
only install JRE. It's all you need. On the other hand, if you are planning to do some Java
programming, you will also need JDK.
Java Servlets
Java Servlet is server side technologies to extend the capability of web servers by providing
support for dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our
own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle
methods. When implementing a generic service, we can extend the GenericServlet class
provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet()
and doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why we mostly
extend HttpServlet class. Servlet API hierarchy is shown in below image.
MVC
MVC is an architectural pattern which separates the representation and user interaction. It’s
divided into three broader sections, Model, View, and Controller. Below is how each one of them
handles the task.
● The View is responsible for the look and feel.
● Model represents the real world object and provides data to the View.
● The Controller is responsible for taking the end user request and loading the appropriate
Model and View.
There are six broader events which occur in MVC application life cycle below diagrams
summarize it.
Any web application has two main execution steps first understanding the request and
depending on the type of the request sending out appropriate response. MVC application life
cycle is not different it has two main phases first creating the request object and second sending
our response to the browser.
Creating the request object: -The request object creation has four major steps. Below is the
detail explanation of the same.
Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which
controller and action to be invoked. So if the request is the first request the first thing is to fill the
route table with routes collection. This filling of route table happens in the global.asax file.
Step 2 Fetch route: - Depending on the URL sent “UrlRoutingModule” searches the route table
to create “RouteData” object which has the details of which controller and action to invoke.
Step 3 Request context created: - The “RouteData” object is used to create the
“RequestContext” object.
Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to
create the controller class instance. Once the controller class object is created it calls the
“Execute” method of the controller class.
Creating Response object: - This phase has two steps executing the action and finally
sending the response as a result to the view.
MVC is an evolution of a three layered traditional architecture. Many components of the three
layered architecture are part of MVC. So below is how the mapping goes:
Functionality Three layered / tiered Model view controller architecture
architecture
HTTP
The standards development of HTTP has been coordinated by the Internet Engineering Task
Force (IETF) and the World Wide Web Consortium, culminating in the publication of a series of
Requests for Comments (RFCs), most notably RFC 2616 (June 1999), which defines HTTP/1.1,
the version of HTTP in common use
HTTP is a stateless protocol. A stateless protocol does not require the server to retain
information or status about each user for the duration of multiple requests. For example, when a
web server is required to customize the content of a web page for a user, the web application
may have to track the user's progress from page to page. A common solution is the use of
HTTP cookies. Other methods include server side sessions, hidden variables (when the current
page is a form), and URL-rewriting using URI-encoded parameters, e.g.,
/index.php?session_id=some_unique_session_code.
Parallel processing
Threads
In computer science, a thread of execution is the smallest unit of processing that can be
scheduled by an operating system. It generally results from a fork of a computer program into
two or more concurrently running tasks. The implementation of threads and processes differs
from one operating system to another, but in most cases, a thread is contained inside a
process. Multiple threads can exist within the same process and share resources such as
memory, while different processes do not share these resources. In particular, the threads of a
process share the latter's instructions (its code) and its context (the values that its variables
reference at any given moment).
To give an analogy, multiple threads in a process are like multiple cooks reading off the
same cookbook and following its instructions, not necessarily from the same page.
https://www.princeton.edu/~achaney/tmve/wiki100k/docs/Thread_%28computer_science%29.ht
ml
Thread synchronization
When we have multiple threads that share data, we need to provide synchronized access to the
data. We have to deal with synchronization issues related to concurrent access to variables and
objects accessible by multiple threads at the same time. This is controlled by giving one thread
a chance to acquire a lock on the shared resource at a time.
Thread can be synchronized through the usage of Critical Section, MUTEX, Semaphore or
Event objects
Treads can be, through the usage of following methods put in a certain states that are
mentioned in States of a Thread section.
Methods
● Suspend() -> Suspends the execution of a thread till Resume() is called on that.
● Resume() -> Resumes a suspended thread. Can throw exceptions for bad state of the
thread.
● Sleep() -> A thread can suspend itself by calling Sleep(). Takes parameter in form of
milliseconds. We can use a special timeout 0 to terminate the current time slice and give
other thread a chance to use CPU time
● Join()-> Called on a thread makes other threads wait for it till it finishes its task.
States of a Thread
States of a thread can be checked using ThreadState enumerated property of the Thread object
which contains a different value for different states.
● Aborted -> Aborted already.
● AbortRequested -> Responding to an Abort() request.
● Background -> Running in background. Same as IsBackground property.
● Running -> Running after another thread has called the start()
● Stopped -> After finishing run() or Abort() stopped it.
● Suspended -> Suspended after Suspend() is called.
● Unstarted -> Created but start() has not been called.
● WaitSleepJoin -> Sleep()/Wait() on itself and join() on another thread. If a thread
Thread1 calls sleep() on itself and calls join() on the thread Thread2 then it enters
WaitSleepJoin state. The thread exists in this state till the timeout expires or another
thread invokes Interrupt() on it.
It is wise to check the state of a thread before calling methods on it to avoid
ThreadStateException.
This picture describes in detail about the states of the thread [ Collected from “Thinking in C#”
by Bruce Eckel ]
Properties of a Thread
● Thread.CurrentThread -> Static method gives the reference of the thread object which is
executing the current code.
● Name -> Read/Write Property used to get and set the name of a thread
● ThreadState -> Property used to check the state of a thread.
● Priority -> Property used to check for the priority level of a thread.
● IsAlive -> Returns a Boolean value stating whether the thread is alive or not.
● IsBackground -> Returns a Boolean value stating the running in background or
foreground.
PriorityLevels of Thread
Priority levels of thread is set or checked by using an enumeration i.e. ThreadPriority. The valid
values are for this enumeration are;
● Highest
● AboveNormal
● Normal
● BelowNormal
● Lowest
Thread Pool
A thread pool is a group of pre-instantiated, idle threads which stand ready to be given work.
These are preferred over instantiating new threads for each task when there is a large number
of short tasks to be done rather than a small number of long ones. This prevents having to incur
the overhead of creating a thread a large number of times.
Implementation will vary by environment, but in simplified terms, you need the following:
● A way to create threads and hold them in an idle state. This can be accomplished by
having each thread wait at a barrier until the pool hands it work. (This could be done with
mutexes as well.)
● A container to store the created threads, such as a queue or any other structure that has
a way to add a thread to the pool and pull one out.
● A standard interface or abstract class for the threads to use in doing work. This might be
an abstract class called Task with an execute() method that does the work and then
returns.
When the thread pool is created, it will either instantiate a certain number of threads to make
available or create new ones as needed depending on the needs of the implementation.
When the pool is handed a Task, it takes a thread from the container (or waits for one to
become available if the container is empty), hands it a Task, and meets the barrier. This causes
the idle thread to resume execution, invoking the execute() method of the Task it was given.
Once execution is complete, the thread hands itself back to the pool to be put into the container
for re-use and then meets its barrier, putting itself to sleep until the cycle repeats.
Hibernate
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that
allows you to map plain old Java objects to relational database tables using (XML) configuration
files.Its purpose is to relieve the developer from a significant amount of relational data
persistence-related programming tasks.
http://www.javabeat.net/hibernate-interview-questions/
ORM
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a
Java application to the tables in a relational database.
ORM parts and levels
Hibernate mapping file tells Hibernate which tables and columns to use to load and store
objects. Typical mapping file look as follows:
Hibernate configuration
Session Interface
The Session interface is the primary interface used by Hibernate applications. It is a single-
threaded, short-lived object representing a conversation between the application and the
persistent store. It allows you to create query objects to retrieve persistent objects.
Session Factory
The Session interface is the primary interface used by Hibernate applications. It is a single-
threaded, short-lived object representing a conversation between the application and the
persistent store. It allows you to create query objects to retrieve persistent objects.
HQL
Hibernate offers a query language that embodies a very powerful and flexible mechanism to
query, store, update, and retrieve objects from a database. This language, the Hibernate query
Language (HQL), is an object-oriented extension to SQL.
http://www.tutorialspoint.com/hibernate/hibernate_query_language.htm
● First we need to write Java domain objects (beans with setter and getter).
● Write hbm.xml, where we map java class to table and database columns to Java class
variables.
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>
jQuery
jQuery is not a language, but it is a well written JavaScript code. As quoted on official jQuery
website, "it is a fast and concise JavaScript Library that simplifies HTML document traversing,
event handling, animating, and Ajax interactions for rapid web development."
In order to work with jQuery, you should be aware of the basics of JavaScript, HTML and CSS.
It was released in January 2006 at BarCamp NYC by John Resig.
jQuery is very compact and well written JavaScript code that increases the productivity of the
developer by enabling them to achieve critical UI functionality by writing very small amount of
code.
● It helps to improve the performance of the application
● It helps to develop most browser compatible web page
● It helps to implement UI related critical functionality without writing hundreds of lines of
codes
● It is fast
● It is extensible – jQuery can be extended to implement customized behavior
Other advantages of jQuery are:
● No need to learn fresh new syntaxes to use jQuery, knowing simple JavaScript syntax is
enough
● Simple and cleaner code, no need to write several lines of codes to achieve complex
functionality
Closure in JS
Classes in JS
Select by element id
$( "#myDiv" ) //expand
Relationship selectors
$("div span:nth-child(2)") // expand or merge with nTH selecor
nTH selector
The document ready event executes already when the HTML-Document is loaded and the DOM
is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for
certain elements before the window loads, then $(document).ready is the right place.
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready");
});
The window load event executes a bit later when the complete page is fully loaded, including all
frames, objects and images. Therefore functions which concern images or other page contents
should be placed in the load event for the window or the content tag itself.
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
alert("window is loaded");
});
Sorting by custom function
C#
Data Types
In C#, variables are categorized into the following types:
● Value types (bool, byte, char, decimal, double, float, int, long, short, ulong, ushort, uint
etc…).
● Reference types (object, string, dynamic)
● Pointer types (*)
Delegates
Delegates are similar to pointers to functions. Delegates are used to pass methods as
arguments to other methods. Syntax for delegate declaration is:
Lambda Expressions
A lambda expression is an anonymous function that you can use to create delegates or
expression tree types. By using lambda expressions, you can write local functions that can be
passed as arguments or returned as the value of function calls.
Event handlers
To respond to an event, you define an event handler method in the event receiver. This method
must match the signature of the delegate for the event you are handling. In the event handler,
you perform the actions that are required when the event is raised, such as collecting user input
after the user clicks a button. To receive notifications when the event occurs, your event handler
method must subscribe to the event.
There are two types of event handlers:Static and Dynamic.
Static event handlers are in effect for the entire life of the class whose events they handle.
Dynamic event handlers are explicitly activated and deactivated during program execution,
usually in response to some conditional program logic. For example, they can be used if event
notifications are needed only under certain conditions or if an application provides multiple event
handlers and run-time conditions define the appropriate one to use.
Declaring an event To declare an event inside a class, first a delegate type for the event must
be declared, if none is already declared.
The delegate type defines the set of arguments that are passed to the method that handles the
event. Multiple events can share the same delegate type, so this step is only necessary if no
suitable delegate type has already been declared.
Next, the event itself is declared.
Invoking an event Once a class has declared an event, it can treat that event just like a field
of the indicated delegate type. The field will either be null, if no client has hooked up a delegate
to the event, or else it refers to a delegate that should be called when the event is invoked.
Thus, invoking an event is generally done by first checking for null and then calling the event.
if (Changed != null)
Changed(this, e);
Hooking up to an event From outside the class that declared it, an event looks like a field, but
access to that field is very restricted. The only things that can be done are:
● Compose a new delegate onto that field.
● Remove a delegate from a (possibly composite) field.
This is done with the += and -= operators. To begin receiving event invocations, client code first
creates a delegate of the event type that refers to the method that should be invoked from the
event. Then it composes that delegate onto any other delegates that the event might be
connected to using +=.
more on
http://www.codeproject.com/Articles/20550/C-Event-Implementation-Fundamentals-Best-
Practices