Você está na página 1de 26

Difference between Stack and Heap?

Stack- memory set aside for a thread of execution. When a function is called, a block is reserved
on the top of the stack for local variables. When that function returns, the block becomes unused
and can be used the next time a function is called. Reserved in a LIFO order; Freeing a block from
the stack is nothing more than adjusting one pointer. Stack is divided such that every thread has
its own stack. Push and Pop operations on a stack. Stack set to fixed size, cannot grow past its
fixed size. If there is not enough room on the stack to handle the memory being assigned to it, a
stack overflow occurs.
Heap- memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to
the allocation and deallocation of blocks from the heap; Can allocate a block at any time and free
it at any time. Different threads share heap.

Difference between process and thread?

A process has code, data, heap and stack segments. Now, the Instruction Pointer (IP) of a thread OR threads
points to the code segment of the process. The data and heap segments are shared by all the threads. The
stack area is an area created by the process just for its thread to use... because stacks can be used in a much
faster way than heaps etc. The stack area of the process is divided among threads, i.e. if there are 3 threads,
then the stack area of the process is divided into 3 parts and each is given to the 3 threads. When a thread
finishes its execution, the stack of the thread is reclaimed by the process. In fact, not only the stack of a
process is divided among threads, but all the set of registers that a thread uses like StackPointer,
ProgramCounter and state registers are the registers of the process. So when it comes to sharing, the code,
data and heap areas are shared, while the stack area is just divided among threads. Also, threads are a
subset of process.

Difference between JRE and JDK

JRE: Java Runtime Environment. It basically comprises of the libraries, the Java Virtual Machine
where Java programs run on, other components to run applets and applications written in Java. 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) and the Java compiler javac in its bin directory to create
and compile programs.

String and StringBuffer

The String class is used to manipulate character strings that cannot be changed. Objects of type
String are read only and immutable. If we try to alter their values, another object gets created.
Eg of String implementation:String s = ABC; s.toLowerCase();
The method toLowerCase() will not change the data "ABC" that s contains. Instead, a new String
object is instantiated and given the data "abc" during its construction. A reference to this String
object is returned by the toLowerCase() method.
The StringBuffer class is used to represent characters that can be modified. Stringbuffer is
synchronized. Stringbuffer faster than String.

Difference between int and Integer in java

int is a primitive type and not an object and is always passed by value., immutabl That means
that there are no methods associated with it. Integer is an object/wrapper class with
methods (such as parseInt).

Difference between java Applet and java Application

Applet runs under the control of a browser, whereas an application runs stand-alone, with the
support of a virtual machine. An applet can be run by loading the HTML page into our Java
enabled web browser. Running a program as a Java standalone application makes use of the
Java runtime environment and the Java loader, which is usually called java on Unix or either
java or wjava under Microsoft Windows. The Java loader loads the main .class file and all related
classes from the .jar archive(s), which must be either in the same directory, in one of the
directories listed in the CLASSPATH environment variable, or we must specify the path on the
command line.

Difference between break and continue:-

A break statement results in the termination of the statement to which it applies (switch, for,
do, or while)
A continue statement is used to end the current loop iteration and return control to the
loop statement.
When break is encountered inside any loop, control automatically passes to the first statement
after the loop. When continue is encountered inside any loop, control automatically passed to the
beginning of the loop. The break statement breaks out of the loop (the next statement to be
executed is the first one after the closing brace), while continue starts the loop over at the next
iteration. break is used to skip the whole loop and continue is used to skip the current
execution of loop.

Pointers in java

NO pointers in java. Only use of references. Variables for objects are references, when we pass a
variable for an object we are passing a reference which is sort of a pointer. In Java any reference
to a simple type is always by value and any reference to an object is always a pointer.

Java is machine independent-yes? JVM is machine dependent.

Yes, In Java, the compiled code is an exact set of instructions for a "virtual CPU" which is required
to work the same on every physical machine. Since all the JVMs work exactly the same, the same
code works exactly the same everywhere without recompiling. The Java programmer does not (in
theory) need to know machine or OS details. These details do exist and the JVM and class libraries
handle them. The JVM is a "simulated machine" that can be installed on different systems. In this
way, the same Java code can run on different systems, because it relies on the JVM, not on the
operational system itself. Compiler converts the .java files into .class files. JVM runs the .class files.

In java, call by value or call by reference?

Always call by value in Java and C, call by reference in C++. When Java passes an object to
a method, Java copies and passes the reference by value, not the object.

Primitive/wrapper class in Java?

One of eight classes provided in the java.lang package to provide object methods for the eight
primitive types. All of the primitive/wrapper classes in Java are immutable. 8 wrapper classes:Byte, Short, Integer, Long, Float, Double, Character, Boolean.

Abstract Class?

Class that is declared abstractit may or may not include abstract methods. Abstract classes
cannot be instantiated, but they can be subclassed.
public abstract class GraphicObject {
abstract void draw();

Interface?

It is kind of 100% abstract class. Interfaces just specify the method declaration (implicitly public
and abstract) and can contain properties (which are also implicitly public and abstract). Interface
definition begins with the keyword interface. An interface like that of an abstract class cannot be
instantiated. If a class that implements an interface does not define all the methods of
the interface, then it must be declared abstract and the method definitions must be
provided by the subclass that extends the abstract class.
}

Final keyword in Java?

final is used in several different contexts to define an entity which cannot later be changed.
Final class: Cannot be subclassed. This is done for reasons of security and efficiency.
public final class MyFinalClass {...}
Final method: Cannot be overridden/hidden by subclassses.
public class Base
{
public
void m1()
public final void m2() {...} }
Final variable: Can only be initialized once, either via an initializer or an assignment statement.
To make a variable immutable.
public final double radius;

Precautionary measures while using pointers?

Shouldnt access illegal memory using pointers.


Cannot do arithmetic operations on void pointers.
Dont dereference null pointers.
Check that the value of a pointer is not equal to NULL

Should never use the pointer to a local variable in a manner which could cause it to be accessed
after the function in which it was declared terminates.

Big O notation?

In mathematics=> describes the limiting behavior of a function when the argument tends towards
a particular value or infinity.
In computer science=> Used to classify algorithms by how they respond (e.g., in their processing
time or working space requirements) to changes in input size. Worst case complexity. Big O
specifically describes the worst-case scenario, and can be used to describe the execution time
required or the space used (e.g. in memory or on disk) by an algorithm.

O(f*g) = O(f)*O(g) and O(f-g) =

Typedef

Used in C and C++. Form complex types from more-basic machine types and assign
simpler names to such combinations. Used when a standard declaration is cumbersome,
potentially confusing, or likely to vary from one implementation to another.
typedef int distance ;
distance boston2nyc ; //"distance" is synonymous with "int" here,
typedef int speed ;
speed bullettrain ;

//and thus, the compiler treats our new variables as integers.

The two variables, distance and speed, while represented by the same data type (int), represent
different and incompatible things.

Pointer in C++?

Variable whose value is the address of another variable. Eg- type *var-name; // pointer to type

Class and object

Object- instance of a class. Class- Data structure which can hold data and functions

HashTable?

Class implements a hashtable, which maps keys to values. Data structure used to implement an
associative array, a structure that can map keys to values. A hash table uses a hash function to
compute an index into an array of buckets or slots, from which the correct value can be found. An
instance of Hashtable has two parameters that affect its efficiency: its capacity and its load
factor. Load factor= Always 75%
Eg- Hashtable numbers = new Hashtable(); // public Hashtable(int initialCapacity)
numbers.put("one", new Integer(1));
If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may
allow the entries to be inserted more efficiently than letting it perform automatic rehashing as
needed to grow the table. Usage of get() and put():- Returns the value to which the specified

key is mapped in this hashtable AND Maps the specified key to the specified value in this
hashtable respectively.
A hash function hashes the key to a unused index into the array. the value is then placed into the
array at that particular index.
Data retrieval is easy, as the index into the array can be calculated via the hash function, thus look
up is ~ O(1).

Difference between hash map and hash table?

HashMap:- Non synchronized and hence not thread safe, faster, Iterator is fail-fast Iterator
HashTable:- Synchronized and hence thread safe, slower, enumerator is not fail-fast

Weak Hash Map?


A WeakHashMap is a special Map implementation where the keys of the map are stored in
java.lang.ref.WeakReference. By storing the keys in a weak reference, key-value pairs can
dynamically be dropped from the map when the only reference to the key is from the weak
reference. This makes the WeakHashMap an excellent implementation for a weakly referenced
list, where entries that aren't used elsewhere may be dropped with no side effects. Also, just
because a key may be dropped, doesn't mean it will immediately be dropped. If the system
has sufficient resources, the weak key reference that isn't externally referenced could stay
around for a long time.

Searching of an element faster in Array than a LinkedList.

#define pi 3.142.....

Substitute into the program text by the preprocessor before reaching the main compiler. Value
might change after compilation while using #define. #define doesnt take any memory space
as its replacing some text with literal value. Doesnt have type, so can be used for any
integer value without getting warnings.

Const

Variables declared with const added become constants and cannot be altered by the program.
Eg- const int Constant1=96; Const declaration takes memory space. They can be scoped, so
can be used when we pass pointer to an object.

Diff between Null pointer and void pointer? Where is it used?

Null pointer points nowhere; it is not the address of any object or function. Used to denote the end
of a memory search or processing event. Malloc does return a null pointer when it fails. Eg. char *p
= NULL; Its the value of a pointer.
Integer num; //num is a variable declared which has a pointer but doesnt point anywhere and
hence is null pointer
Num= new Integer(10); // new keyword is used to instantiate (or create) an object of type Integer
and the pointer variable num is assigned this object.

Void pointer points to some data which doesnt have any specific type. Its a type of pointer. Void*
p; Cannot do arithmetic operations on void pointer.
Significance of null pointer:- To ensure that the address to which ptr points is valid its explicitly
initialized to the null pointer.

Recursive function

Function definition has one or more base cases and one or more recursive cases where the
program recurs (calls itself). Eg- factorial fnc- 0! = 1 and, for all n > 0, n! = n(n 1)!

Multicore processors

Single computing component with two or more independent actual CPUs

#include?

#include statement is basically like a copy/paste operation. The compiler will replace the
#include line with the actual contents of the file were including when it compiles the file. We use
#include to include diff. Header files for:- 1) Speed up compile time 2) Keep code more organized
3) Separate interface from implementation.

Diff between malloc() calloc() free() realloc() new()

The malloc() function allocates size bytes and returns a pointer to the allocated memory. The
memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value
that can later be successfully passed to free().
The free() function frees the memory space pointed to by ptr, which must have been returned by
a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called
before, undefined ullityn occurs. If ptr is NULL, no operation is performed.
The calloc() function allocates memory for an array of nmemb elements of size bytes each and
returns a pointer to the allocated memory. The memory is set to zero. If nmemb or size is 0,
then calloc() returns either NULL, or a unique pointer value that can later be successfully passed
to free().
The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The
contents will be unchanged in the range from the start of the region up to the minimum of the old
and new sizes. If the new size is larger than the old size, the added memory will not be initialized.
If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to
zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have
been returned by an earlier call to malloc(), calloc() or realloc(). If the area pointed to was
moved, a free(ptr) is done.
The new() function initializes the allocated memory by calling the constructor (if its an object).
Memory allocated with new should be released with delete (which in turn calls the destructor). It
does not need us to manually specify the size we need and cast it to the appropriate type. Thus,
its more modern and less prone to errors.
Void *malloc(size_t size);

void free(void *ptr);


void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);

Generics in Java

Allow a type or method to operate on objects of various types while providing compile-time
type safety. Code that uses generics has many benefits over non-generic code:
Stronger type checks at compile time.
A Java compiler applies strong type checking to generic code and issues errors if the code violates
type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to
find.
Elimination of casts.
The following code snippet without generics requires casting:
List list = new ArrayList(); list.add(hello); String s = (String) list.get(0);
When re-written to use generics, the code does not require casting:
List<String> list = new ArrayList<String>(); list.add(hello); String s = list.get(0); // no cast
Enabling programmers to implement generic algorithms.
By using generics, programmers can implement generic algorithms that work on collections of
different types, can be customized, and are type safe and easier to read.

String Builder/String Buffer/String Concatenation (Stringbuffer- Synchronized,


Stringbuilder- Unsynchronized)
If we use String Concatenation in a loop, will take very long time. For eg.String s = ;1
for(int i = 0; i < 100; i++) {
s += , + i;
}
We should use a StringBuilder (not StringBuffer) instead of a String, because it is much faster
and consumes less memory. Stringbuilder faster than Stringbuffer because its not
synchronized.
If we have a single statement, for egString s = 1, + 2, + 3, + 4, .;
then we can use Strings, because the compiler will use StringBuilder automatically.
The + operator( string.concat()) uses public String concat(String str) internally. This method copies
the characters of the two strings, so it has memory requirements and runtime complexity
proportional to the length of the two strings. String.concat(+ operator) is slowest. StringBuilder
and StringBuffer works more faster.
StringBuilder- Not thread safe, StringBuffer- Thread safe. If we are concatenating, for example 5
strings in a row, each concat() will create you with a new String object. While using + operator,

compile will translate the statement to one StringBuilder with multiple append operation. It is
definitely saving a lot of ullityng temp object instance.
Why using global variables is a bad practice?
Since every function has access to these, it becomes increasingly hard to figure out which
functions actually read and write these variables.
Accidently we may re-declare an already declared global variable somewhere else and overwrite
the previous declaration
Danger of using pointers?
Dereferencing a pointer which points to invalid memory location will result in shutdown down of OS
with segmentation fault. , Result of dangling pointers.
After freeing dynamically allocated memory, we should set the pointer to null. This should help us
catch some dangling pointer or double-free errors.
Worst case time complexity while searching in a LinkedList- O(n)

Diff between & and * operator in pointers?

& - Address off operator, * - dereferencing operator.


#include<iostream.h> means?
Early in the compiling of a source, a preprocessor takes these # directives. #include basically puts
all of stdio.h into the top of our code during compilation. The .h identifies it as a header.
How can you give a data type a new name? Using typedef.
Rake function?
Software task management tool used to specify tasks and describe dependencies as well as to
group tasks in a namespace. Uses Rubys anonymous function blocks to define various tasks. Has
a library of common tasks: for example, functions to do common file-manipulation tasks and a
library to remove compiled files.
Exception handling mechanisms?
Usage of try, throw, catch and finally.
Try- To indicate which areas in our program that might throw exceptions we want to handle
immediately. To indicate that we want to detect exceptions in the entire body of a function.
Throw- exception is thrown when an unexpected error condition is encountered.
Catch- The exception is then caught by an encompassing clause further up the method stack. All
exception types must extend the Java language class Throwable or one of its subclasses. By
convention, new exception types extend Exception, a subclass of Throwable.
Java exceptions are primarily checked exceptions i.e. the compiler verifies that methods throw only
exceptions that they have declared. Exceptions are caught by enclosing code in try blocks. If an
exception is thrown, each catch clause is examined in turn from first to last to see whether the
type of the exception object is assignable to the type declared in catch. Eg.MyData md;
try {
// code that could throw an exception

md = GetNetworkResource();
}
catch (networkIOException& e) {
// code that executes when an exception of type
// networkIOException is thrown in the try block
}
catch (myDataFormatException& e) {
// code that handles another exception type
}

MyData GetNetworkResource()
{
//
if(IOSuccess == false)
throw networkIOException(Unable to connect);
//
if(readError)
throw myDataFormatException(Format error);
//
}

The code block after the catch clause is the exception handler, and catches (handles)
the exception thrown by the throw expression if the type in the throw and catch
expressions are compatible.
The only time a finally block will not be executed is when we call exit() before finally is reached.
The exit() call will shutdown the JVM, so no subsequent line of code will be run. Putting cleanup
code in a finally block is good practice.

Diff between == and .equals


1) == is an comparator operator, .equals() is a method
2) The operator, ==, tests to see if two object reference variables refer to the exact same
instance of an object. Compares the two objects by reference and not just by value. .equals() is
diff from == when we override the method. The method, .equals(), tests to see if the two

objects being compared to each other are just equivalent, compares by value and not
by reference but they need not be the exact same instance of the same object. EgStringBuilder objSb1 = new StringBuilder("Elias");
StringBuilder objSb2 = new StringBuilder("Elias");
objSb1 == objSb2 >> False
objSb1.Equals(objSb2) >> True

Which operators cannot be overloaded?


. (Member Access or Dot operator)
?: (Ternary or Conditional Operator )
:: (Scope Resolution Operator)
.* (Pointer-to-member Operator )
sizeof (Object size Operator)
typeid (Object type Operator)

Diff between struct and class in C++?

Members and base classes of struct- public by default, members and base classes of class- private
by default
Default inheritance in struct- public, default inheritance in class- private

Difference between struct and union in C?

A structure allocates the total size of all elements in it. A union only allocates as much memory as
its largest member requires. In union, we are only supposed to use one of the elements, because
they're all stored at the same spot.

Bitfields in struct?
Struct
{
type [member_name] : width ;
};

Type- An integer type that determines how the bit-fields value is interpreted. The type may be int,
signed int, unsigned int. Member_name- name of bitfield, Width- The number of bits in the bit-field.
The width must be less than or equal to the bit width of the specified type.

Memory management in Java/ Garbage collection in java?

Garbage collection relieves programmers from the burden of freeing allocated memory.
Automatically freeing objects that are no longer referenced by the program. Heap fragmentationnot enough contiguous free heap space available into which the new object will fit.
Call System.gc() or Runtime.gc() anytime to fire off a garbage collection, it tells JVM for gc but
doesnt happen immediately. Call gc.collect()
Reference counting collectors- garbage collecting strategy.

Hash function?

Primarily used in hash tables, to quickly locate a data record. Used to map search key to an index,
index gives the place in the hash table where corresponding record should be stored. Domain of
hash function is larger than its range, several diff keys map to same index. Hash table has buckets
and each bucket has multiple bucket values. Hash function only hints at the records location. Also
used to build caches,
Good hash function to avoid collisions and a fast one- egfunction Hash(key)
return key mod PrimeNumber
end

// primenumber be size of hashTable

Classpath?

Parameter set either on the command-line, or through an environment variablethat tells the JVM
or the java compiler where to look for user-defined classes and packages. CLASSPATH variable is
one way to tell applications, including the JDK tools, where to look for user classes. Specify the
class path is by using the cp command line switch.
The virtual machine searches for and loads classes in this order: bootstrap classes, extension
classes and then user-defined packages and libraries,

stdio.h and not <stdio.h> ?

Preprocessor looks in current directory and then in parent directories. When used angular brackets,
preprocessor directly looks into the standard include directory in the system.

What is the difference between import java.lang.* and import java.lang.String?

Java.lang is default package for java. Neednt do java.lang.* explicitly as this is automatically
imported in every java program. * indicates all classes within that package. Import java.lang.String
imports the String package.

Fibbonacci sequence program:-

F(n)= F(n-1) + F(n-2); F(0)= 0, F(1)= 1

Destructor?

Used to deallocate memory and do other cleanup for a class object and its class members when
the object is destroyed. No arguments and has no return type. Can be declared virtual or pure
virtual. Notation:- ~ Classname();

Virtual function?

Function whose behavior can be overridden within an inheriting class by a function with the same
signature. Application of polymorphism. If a method is virtual, then calling the method on an
object always invokes the method as implemented by the most heavily derived class.
In OOP when a derived class inherits from a base class, an object of the derived class may be
referred to via a pointer or reference of either the base class type or the derived class type. If
there are base class methods overridden by the derived class, the method actually called by such

a reference or pointer can be bound either early (by the compiler), according to the declared type
of the pointer or reference, or late (i.e. by the runtime system of the language), according to the
actual type of the object referred to. All functions in java are virtual by default. Can make them
non-virtual by adding final.
Virtual functions are resolved late. If the function in question is virtual in the base class, the
most-derived classs implementation of the function is called according to the actual type of the
object referred to, regardless of the declared type of the pointer or reference. If it is not virtual,
the method is resolved early and the function called is selected according to the declared type of
the pointer or reference.
Virtual void eat();
class Sample {
public:
void f();
virtual void vf();
};
class Derived : public Sample {
public:
void f();
void vf();
}
void function()
{
Derived d;
Sample* p = &d;
p->f(); // will call void f() of Sample p and not void f() of Derived d
p->vf(); // will call void vf() of Derived d as its virtual function
}

Pure virtual function? Virtual function without any implementation in base class and
implementation in derived class. In base class, virtual func()=0; // pure virtual function.

Virtual destructor:-

When we delete an instance of a derived class through a pointer to base class, we need virtual
destructor in base class.
If base class destructor is not virtual, the delete operation invokes the destructor of base class and
not the most derived class resulting in resources leak. The base class object gets deleted and not
the derived class object.

#ifdef and #ifndef

#ifdef- if the following is defined


#ifndef- if the following is not defined

Eg#define one 0
#ifdef one
printf(one is defined ); //will excute this as one is defined
#endif
#ifndef one
printf(one is not defined ); //will not execute this as one is defined
#endif
#ifdef will only check if the following symbol has been defined via #define or by command line,
but its value is irrelevant.

Friend function?

It can access private and protected data of a class from outside the class. A friend function is
declared by the class that is granting access, explicitly stating what function from a class is
allowed access. The friend declaration can be placed anywhere in the class declaration. It is not
affected by the access control keywords.

Soap?

Simple Object Access Protocol used for exchanging structured info in the implementation of Web
Services. Relies on XML Info set for message format and HTTP/SNMP for transmission. FormatEnvelop, header, body, fault.

HTTP Get and HTTP POST? 2 methods for request-response between client server.

Issues with floating-point operations

Rounding errors, truncating conversion

Diff between List and vector?

Vector:- synchronized and hence slower than ArrayList, Contiguous memory, Pre-allocates space
for future elements, so extra space required, Each element only requires the space for the element
type itself
ArrayList:- Unsynchronized and hence faster than vector, non contiguous memory, No preallocating space for future elements, Each element requires the space for the element type and
pointers to next and previous element.

Diff between Mutex and Semaphore


Mutex: Used to serialize access to a section of code that cannot be executed concurrently by more
than one thread. A mutex object only allows one thread into a controlled section, forcing other
threads which attempt to gain access to that section to wait until the first thread has exited from
that section Eg: Is a key to a toilet. One person can have the key occupy the toilet at the time.
When finished, the person gives (frees) the key to the next person in the queue. Usage of
acquire() and release(). A mutex can only be released by the thread which has ownership, i.e.
the thread which previously called the Wait function, Locking mechanism.

Semaphore: A semaphore restricts the number of simultaneous users of a shared resource up to a


maximum number. Threads can request access to the resource (decrementing the semaphore),
and can signal that they have finished using the resource (incrementing the semaphore Eg: Is the
number of free identical toilet keys. Say we have four toilets with identical locks and keys. The
semaphore count the count of keys is set to 4 at beginning (all four toilets are free), then the
count value is decremented as people are coming in. If all toilets are full, ie. There are no free keys
left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is
increased to 1 (one free key), and given to the next person in the queue. Usage of signal() and
wait(). A semaphore can be released by any thread. Signaling mechanism.

Difference between C++ and Java


C++ supports pointers whereas Java does not pointers.
At compilation time Java Source code converts into byte code .The interpreter execute this byte
code at run time and gives output .Java is interpreted for the most part and hence platform
independent. C++ run and compile using compiler which converts source code into machine level
languages so c++ is plate from dependents
Java is platform independent language but c++ is depends upon operating system machine etc.
C++ source can be platform independent (and can work on a lot more, especially embedded,
platforms), although the generated objects are generally platform dependent but there is clang for
llvm which doesnt have this restriction.
Java uses compiler and interpreter both and in c++ there is only compiler
C++ supports operator overloading, multiple inheritance but java does not.
C++ is more nearer to hardware then Java.
Everything (except fundamental types) is an object in Java (Single root hierarchy as everything
gets derived from java.lang.Object).
Java does is a similar to C++ but not have all the complicated aspects of C++ (ex: Pointers,
templates, unions, operator overloading, structures etc..) Java does not support conditional
compile (#ifdef/#ifndef type).
Thread support is built-in Java but not in C++. The most recent iteration of the C++ programming
language does have Thread support though.
Internet support is built-in Java but not in C++. However c++ has support for socket programming
which can be used.
Java does not support header file, include library files just like C++ .Java use import to include
different Classes and methods.
Java does not support default arguments like C++.
There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the
namespace they came from.
There is no goto statement in Java.
Exception and Auto Garbage Collector handling in Java is different because there are no
destructors into Java.
Java has method overloading, but no operator overloading just like c++.

The String class does use the + and += operators to concatenate strings and String expressions
use automatic type conversion,
Java is pass-by-value.
Java does not support unsigned integer.

Diff between func overloading and overriding.

Overriding is the concept of having functions of same name and signature in different classes. One
in the super class can be made virtual and other can override the functionality of virtual one. The
method of a sub class takes priority over its counterpart in the super-class.
Overloading is the concept of having functions of same name, but different signature in same
class. They are differentiated by the compiler by their signatures. Have no priority over each other.

Finalize method call in java?

Called by the garbage collector on an object when garbage collection determines that there are no
more references to the object. Called when an object is about to get garbage collected. Finalize
should only be used for cleanup of (usually non-Java) resources.

One of the problems with recursion? Stack overflow might occur.

Algorithm question 1 : How do you find if two strings are anagram.


Anagram definition : two string having the same characters eg : united and untied
Time complexity and space complexity for the same.
(count[str[i]-a]++ || count[str[i]-A]

//decimal value of a=97, A=65

Algorithm question 2 : How do you determine if a number is power of 2


example : 32 is 2 power 5
Time complexity and spaced complexity for the same
float n; cin>>n;
while(n>1)
{ r= n%2; n=n/2;
if(r!=0) { cout<<Not a power of 2; break;}
}
OR
if(n & (n-1) == 0) cout<<power of 2;

//n is converted to binary before AND

Inline function?

Functions used to tell the compiler insert the complete body of the function in every place that the
function is called, rather than generating code to call the function in the one place it is defined.
Inline expansion used to eliminate time and space overhead when a func is called. Used for small
funcs and funcs which execute frequently. Eginline int max(int a, int b)

{
return (a > b) ? a : b;
}

oncreate(),onstop(),onresume()?

Used in Android app developing. Used during an acitivitys lifecycleoncreate()- called when activity is first created.
Onresume()- called when activity will start interacting with the user.
Onstop()-called when activity is no longer visible to user because another activity is resumed.

Diff between tree and directed graphs?

Tree- Minimally connected graph having only 1 path between any 2 nodes. No loops, circuits or
self-loops. Exactly 1 root node and every child has only 1 parent node. Parent-child relationship.
Traversal-pre order, in-order, post-order. They are Directed Acyclic graphs.
Graph- Can be more than 1 path between nodes. Can have loops, circuits and self-loops. No root
node, parent-child relationship. Traversal-DFS or BFS. Can be cyclic/acyclic.

Types of scheduling?

First In First Out/First Come First Serve, Shortest Remaining Time/Shortest Job First, Fixed Priority
Pre-emptive Scheduling, Round Robin Scheduling.

How to define custom memory management in C++? Use malloc() and then overload new()
and delete().

Explain system.out.println() in Java

System is a final class from java.lang package.


out is the reference of PrintStream class and a static member of System class, so accessed by
class name System.
println is a method of PrintStream class.

Type casting?

B = (int) a; // c-like cast notation


b = int (a); // functional notation

Storage classes in C? Auto, Register, Static, Extern, Typedef.

Difference between Foo bar(); and Foo bar;

Foo bar(); prototype to a function named bar which takes no parameters and returns a Foo. Foo
bar; This creates a variable named bar of type Foo, and calls the default constructor.

Design patterns?
Creational Patterns
o

Abstract Factory Creates an instance of several families of classes

Builder Separates object construction from its representation

Factory Method Creates an instance of several derived classes

Prototype A fully initialized instance to be copied or cloned

Singleton A class of which only a single instance can exist

Structural Patterns
o

Adapter Match interfaces of different classes

Bridge Separates an objects interface from its implementation

Composite A tree structure of simple and composite objects

Decorator Add responsibilities to objects dynamically

Facade A single class that represents an entire subsystem

Flyweight A fine-grained instance used for efficient sharing

Proxy An object representing another object

Behavioral Patterns
o

Chain of Resp. A way of passing a request between a chain of objects

Command Encapsulate a command request as an object

Interpreter A way to include language elements in a program

Iterator Sequentially access the elements of a collection

Mediator Defines simplified communication between classes

Memento Capture and restore an objects internal state

Observer A way of notifying change to a number of classes

State Alter an objects behavior when its state changes

Strategy Encapsulates an algorithm inside a class

Template Method Defer the exact steps of an algorithm to a subclass

Visitor Defines a new operation to a class without change

Program for checking palindrome ?

for ( int i = length - 1 ; i >= 0 ; i-- )


reverse = reverse + original.charAt(i);
OR
begin = 0; end = length - 1; middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (inputString.charAt(begin) == inputString.charAt(end)) {
else {

break;

begin++; end--; }

Static?
Static variable- variable is class scoped, not instance scoped. Only one copy shared among all
instances of a class. Accessing static variable is through Classname.variable and not obj.variable.
Static function- Doesnt need an object to call it. Gets called on declaration. Eg- static main();
Extern?
Used to extend visibility of variables/functions through the program. Functions are visible
throughout the program by default. So using extern for functions is meaningless.

Smart pointers?

Abstract data type that simulates a pointer while providing additional features, such as
automatic memory management or bounds checking. Keep track of the memory they point to. Not
required for memory management in Java s garbage collector is there

Recursive string reversal

String lastChar = arg.substring(arg.length()-1,arg.length()); //substring(from,to)


String remainingString = arg.substring(0, arg.length() -1);
tmp = lastChar + reverse(remainingString);
return tmp;

Deadlock?

In an OS, a deadlock is a situation which occurs when a process enters a waiting state because a
resource requested by it is being held by another waiting process, which in turn is waiting for
another resource. If a process is unable to change its state indefinitely because the resources
requested by it are being used by another waiting process, then the system is said to be in a
deadlock. Deadlock arises if all of the following conditions hold simultaneously in a
system:
1.

Mutual Exclusion: At least one resource must be non-shareable. Only one process can use the
resource at any given instant of time.

2.

Hold and Wait or Resource Holding: A process is currently holding at least one resource and
requesting additional resources which are being held by other processes.

3.

No Preemption: The operating system must not de-allocate resources once they have been
allocated; they must be released by the holding process voluntarily.

4.

Circular Wait: A process must be waiting for a resource which is being held by another process,
which in turn is waiting for the first process to release the resource. In general, there is a set of
waiting processes, P = {P1, P2, ..., PN}, such that P1 is waiting for a resource held by P2, P2 is waiting
for a resource held by P3 and so on till PN is waiting for a resource held by P

Race Condition in OS?

A race condition occurs when two threads access a shared variable at the same time. The first
thread reads the variable, and the second thread reads the same value from the variable. Then the
first thread and second thread perform their operations on the value, and they race to see which
thread can write the value last to the shared variable. The value of the thread that writes its value
last is preserved, because the thread is writing over the value that the previous thread wrote.

Serialization?

Serialization is the process of converting a set of object instances that contain references to each
other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or
simply manipulated as a stream of data.

Maths

Eigen vector and eigen value? Their imp?

Eigen vector of sq. matrix A is non-zero vector v such that Matrix multiplied by v yields constant
multiple of v.
The number Lambda is called the eigenvalue of A corresponding to v.
Lambda positive= same direction, negative= opposite direction, magnitude= length of vector
Eigenvectors make understanding linear transformations easy. They are the axes (directions)
along which a linear transformation acts simply by stretching/compressing and/or flipping;
eigenvalues give us the factors by which this compression occurs.

Every vector is eigen vector of I. [Identity matrix A i.e. A i,j is 1 if i=j, and 0 otherwise]
Diagonal matrix- with Ai,j =0 for i=j

Projection of vector a on vector b?

Orthogonal projection of a onto a straight line parallel to b i.e.


a onto b , a1 = (a Cos theta) x unit vector b ={(a.b)/|b|} x unit vector b

where projection of

Orthogonality?

Relation of two lines at right angles to one another. a and b are orthogonal iff a.b = 0 [Cos 90 =
0]

Singular matrix? Sq Matrix which doesnt have a matrix inverse, iff its determinant is 0.

Symmetric matrix? Matrix A such that A= AT.

Rank of a matrix?

No. of linearly independent row/column vectors in a matrix A.


A row or a column is considered independent, if it satisfies the below conditions.
1. A row/column should have atleast one non-zero element for it to be ranked.
2. A row/column should not be identical to another row/column.
3. A row/column should not be proportional (multiples) of another row/column.
4. A row/column should not be a linear combination of another row/column.

How to find rank of a matrix?

Gaussian elimination method by converting matrix into reduced echelon form. Reduced echelon
formThe first element in the first row should be the leading element i.e. 1.
The leading element in the columns should be to the right of the previous rows leading element.
If there are any rows with all zero elements, it should be below the non-zero element rows.
The leading element should be the only non-zero element in every column.

Relation between null space matrix dimensionality and rank of the matrix?

Rank-Nulity theorem: rank(A) + nullity(A) = n //A is m x n matrix.

AA

-1

Inverse of a matrix?
=1

Calculating inverse of 2 x 2 matrix:For a 2-D matrix A= [a , b ; c, d ]


A-1 = (1/det A) Adjoint of A maxtrix= (1/det A) (Cofactor matrix of A)T;
ad bc

Determinant of A =

Calculating inverse of 3 x 3 or bigger matrix:1 Calculating the Matrix of Minors, 2) then turn that into the Matrix of Cofactors, 3) then the
Adjugate, and 4) multiply that by 1/Determinant.
Step 1) Calculating matrix of Minors- For each element of the matrix:- ignore values of current row
and column; calculate the determinant of the remaining values.
Step 2) Matrix of cofactors- Change sign of alternate cells

Step 3) Adjugate- Take transpose


Step 4) Multiply 1/det A
Determinant of A is

OR
Use gauss Jordan elimination to convert [ A | I ] into [ I | A-1 ]

Null space of a matrix A?

Set of all vectors x s.t. Ax = O (Results in O vector); Set of all solutions to the homogeneous
equation Ax = 0.

Null matrix or zero matrix? All entries are 0.

Angle between 2 vectors a and b ?

cos = a.b / |a||b| // Dot product or scalar product of a and b is a1b1 + .anbn

Cross product and dot product of 2 matrix?

Cross product(vector)- Let u = ai + bj + ck and v = di + ej + fk be vectors then we define the


cross product u x v by the determinant of the matrix:

= (bf ce) i + (cd af) j + (ae bd) k = Magnitude is Area of parallelogram formed by the 2
vectors u and v
.
Dot product(scalar)- If v = ai + bj + ck and w = di + ej + fk then v w = ad + be + cf

Correlation, cross- correlation and auto- correlation?

Correlation of vector X = correlation matrix between the scalar elements of X


Cross- correlation(X, Y)= Correlation corr(X, Y)
Auto correlation of X= Cross correlation of X with itself.

Pigeon hole principle?

If n pigeons are randomly put into m pigeonholes (n>m) with uniform probability 1/m, then at least
one pigeonhole will hold more than one pigeon with probability
1 [ (m)n / mn ] where (m)n is the falling factorial m(m 1)(m 2)(m n + 1)
If n items are put into m pigeonholes with n > m, then at least one pigeonhole must contain more
than one item

Four color theorem?

Given any separation of a plane into contiguous regions, producing a figure called a map, no more
than four colors are required to color the regions of the map so that no two adjacent regions have
the same color. Two regions are called adjacent if they share a common boundary.

Integration and differentiation?

Integration- Reverse process to differentiation. Summation of different parts. Operation of finding


integral of a function. Means of finding areas under summation and limits. Area under a curve.
Differentiation- Process of finding a derivative. Basically how a function changes as its input
changes. How much one quantity is changing in response to changes in some other quantity.
Derivative at a point equals the slope of the tangent line to the graph of the function at that point.
Rate of change.

Derivative?

How function changes with as its input changes. Ratio of the infinitesimal change of the output
over the infinitesimal change of the input producing that change of output.

Partial differentiation?

The rate of change of function f with respect to x (holding y constant) is called the partial
derivative of f with respect to x and is denoted by fx(x y). Similarly, the rate of change of f with
respect to y is called the partial derivative of f with respect to y and is denoted by fy(x y).
fx (x,y)= lim h>0 [f(x+h,y)-f(x,y)]/h
fy (x,y)= lim h>0 [f(x,y+h)-f(x,y)]/h

Differential equation?

Mathematical equation for an unknown function of one or several variables that relates the values
of the function itself and its derivatives of various orders.
Partial differential equation- Differential equation in which the unknown function is a function of
multiple independent variables and the equation involves its partial derivatives.
Linear equation- Differential equation of degree 1.

A matrix(n*n) with its elements sorted column wise and row wise. Design an algorithm to
search an element and its time complexity.

Start with top right element. If search element is bigger, then go down. If smaller, go left. Time
complexity O(n)

How calculator finds Sin x and Cos x

Using Taylors or Maclaurin series. Taylors series is representation of a function as an infinite sum
of terms that are calculated from the values of the functions derivatives at a single point.
Maclaurins series is taylors series centered at 0.
Taylors series:- f(a) + [f(a)/1!](x-a) + [f(a)/2!](x-a)2 + [f(a)/3!](x-a)3 +..
Maclaurins series:- Taylors series at a=0= f(0) + [ f(0)/1!](x) + [f(0)/2!](x)2 + [f(0)/3!](x)3 +
..
So, Sin x from Maclaurins series: x x3/3! + x5/5! - ..
Cos x from Maclaurins series: 1 x2/2! + x4/4! -

P complete(deterministic polynomial) and NP complete (non deterministic polynomial)


problems?

Problems for which some algorithm can provide an answer in polynomial time is P.

For some problems, there is no known way to find an answer quickly, but if one is provided with
information showing what the answer is, it may be possible to verify the answer quickly. The class
of questions for which an answer can be verified in polynomial time is NP. Eg- subset sum problem.
Given a set of integers, is there a subset which sums to 0?

Finite state machine/ Deterministic finite automaton (DFA)pigeon

Mathematical model of computation used to design both computer programs and sequential logic
circuits. Abstract machine that can be in one of a finite number of states. Machine is in
only one state at a time. Can change from one state to another when initiated by a triggering
event or condition called transition. FSM is defined by a list of its states, and the triggering
condition for each transition. Use state tables to define FSM.

Non-deterministic finite automaton (NFA)

It is a finite state machine where from each state and a given input symbol, the automaton may
jump into several possible next states. This distinguishes it from the deterministic finite automaton
(DFA), where the next possible state is uniquely determined. Represented formally by a 5-tuple, (Q,
, , q0, F), consisting of:- a finite set of states Q, a finite set of input symbols , a transition
relation : Q P(Q), an initial (or start) state q0 Q, a set of states F distinguished as
accepting (or final) states F Q.

Max flow min cut theorem?

In a flow network, the maximum amount of flow passing from the source to the sink is equal to the
minimum capacity that when removed in a specific way from the network causes the situation that
no flow can pass from the source to the sink. The maximum value of an s-t flow is equal to the
minimum capacity over all s-t cuts where s is source and t is sink.

Characteristics to fully define a linear function?

Linear functions have a constant rate of change and describe a straight line on a graph. Linear
functions can be defined by the equation y = mx + b

Epsilon Delta definition?

Let f be a function defined on an open interval containing c (except possibly at c) and let L be
a real number. Then the statement

means for all real > 0 there exists a real > 0 such that for all x with
0 < |x c | < , we have |f(x) L| <

Summation of Harmonic Progression 1+1/2+1/3+1/4+..?

Infinite. Area under graph plot is infinite. Integral of 1/x (x from 1 to infinity) is also Infinite. [ln
infinity ln 1]

Summation of 1+2+3+4++n

n(n+1)/2 n terms, infinity infinite terms as graph diverges and doesnt converge.

Summation of AP series of n terms?

Summation of GP series (1/7 + 1/72 + 1/73 + ..)

n(a1 + an )/2

a (1- rn )/(1-r)---- n terms,


a/(1-r)-- infinite terms
Exponential decay equation?
=> Exponential decay equation. N(t)= Quantity at time t, N 0 = Quantity at t=0 or
N(0), = decay constant.

LHopital rule?

If

, and

all x in I with x c, then

exists, and

Runge Kutta method for solving ODE?


with

, over the interval

The Runge-Kutta method uses the formulas

for
where

Partial fraction expansion?

.
, and

for

Difference between definite and indefinite integral?

Definite integral- Number. Integration from limits x=a to x=b


Indefinite integral- Function. Integration of a function without specifying the limits.

Você também pode gostar