mathworks solutions aug23 (1)

29
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 it’s 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();

Upload: gauravmathur

Post on 17-Dec-2015

24 views

Category:

Documents


4 download

DESCRIPTION

Mathwork Interview

TRANSCRIPT

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. 1. 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 processis 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 JDKJRE: 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 StringBufferThe 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 methodtoLowerCase()will not change the data "ABC" thatscontains. Instead, a new String object is instantiated and given the data "abc" during its construction. A reference to this String object is returned by thetoLowerCase()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 javaint 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 ApplicationApplet 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 javaNO 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 NULLShould 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.1. O(f*g) = O(f)*O(g) and O(f-g) = TypedefUsed 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 objectObject- 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(intinitialCapacity) 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 IteratorHashTable:- 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. ConstVariables 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 pointerNum= 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 functionFunction 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 processorsSingle 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 list = new ArrayList(); 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 = ;1for(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 eg- String 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 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}

MyDataGetNetworkResource(){//if(IOSuccess==false)thrownetworkIOException(Unabletoconnect);//if(readError)throwmyDataFormatException(Formaterror); //}

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 .equals1) == is an comparator operator, .equals() is a method2) 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. Eg-

StringBuilderobjSb1 = newStringBuilder("Elias");StringBuilderobjSb2 = newStringBuilder("Elias"); objSb1 == objSb2 >> FalseobjSb1.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 defaultDefault 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 fragmentation- not 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- eg-function Hash(key) return key mod PrimeNumber // primenumber be size of hashTableend 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 ?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}1. 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 definedEg-#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. Format- Envelop, header, body, fault. HTTP Get and HTTP POST? 2 methods for request-response between client server. Issues with floating-point operationsRounding 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 pre-allocating space for future elements, Each element requires the space for the element type and pointers to next and previous element.

Diff between Mutex and SemaphoreMutex: 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 dependentsJava 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 compilerC++ 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 untiedTime 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 2example : 32 is 2 power 5Time complexity and spaced complexity for the same

float n; cin>>n;while(n>1){ r= n%2; n=n/2; if(r!=0) { cout0 [f(x+h,y)-f(x,y)]/hfy (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)1. How calculator finds Sin x and Cos xUsing 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! - 1. 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?1. Finite state machine/ Deterministic finite automaton (DFA)pigeonMathematical 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. 1. 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.

1. 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. 1. 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 1. Epsilon Delta definition?Letfbe a function defined on anopen intervalcontainingc(except possibly atc) and letLbe areal number. Then the statement means for all real> 0 there exists a real> 0 such that for allxwith 0