Archive for the ‘Interview Question’ Category


  1. Would I use print “$a dollars” or “{$a} dollars” to print out the amount of dollars in this example? – In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like “{$a},000,000 mln dollars”, then you definitely need to use the braces.
  2. How do you define a constant? – Via define() directive, like define (“MYCONSTANT”, 100);
  3. How do you pass a variable by value? – Just like in C++, put an ampersand in front of it, like $a = &$b
  4. Will comparison of string “10” and integer 11 work in PHP? – Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.
  5. When are you supposed to use endif to end the conditional statement? – When the original if was followed by : and then the code block without braces.
  6. Explain the ternary conditional operator in PHP? – Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.
  7. How do I find out the number of parameters passed into function? – func_num_args() function returns the number of parameters passed in.
  8. If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? – 100, it’s a reference to existing variable.
  9. What’s the difference between accessing a class method via -> and via ::? – :: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.
  10. Are objects passed by value or by reference? – Everything is passed by value.
  11. How do you call a constructor for a parent class? – parent::constructor($value)
  12. What’s the special meaning of __sleep and __wakeup? – __sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.
  13. Why doesn’t the following code print the newline properly?    <!–?php
    $str = ‘Hello, there.nHow are you?nThanks for visiting TechInterviews’;
    print $str;
    Because inside the single quotes the n character is not interpreted as newline, just as a sequence of two characters – and n.
  14. Would you initialize your strings with single quotes or double quotes? – Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.
  15. How come the code <!–?php print “Contents: $arr[1]”; ?> works, but doesn’t for two-dimensional array of mine? – Any time you have an array with more than one dimension, complex parsing syntax is required. print “Contents: {$arr[1][2]}” would’ve worked.
  16. What is the difference between characters 23 and x23? – The first one is octal 23, the second is hex 23.
  17. With a heredoc syntax, do I get variable substitution inside the heredoc contents? – Yes.
  18. I want to combine two variables together:
     $var1 = 'Welcome to ';
     $var2 = '';

    What will work faster? Code sample 1:

    $var 3 = $var1.$var2;

    Or code sample 2:

    $var3 = "$var1$var2";

    Both examples would provide the same result – $var3 equal to “Welcome to”. However, Code Sample 1 will work significantly faster. Try it out with large sets of data (or via concatenating small sets a million times or so), and you will see that concatenation works significantly faster than variable substitution.

  19. For printing out strings, there are echoprint and printf. Explain the differences. – echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:
     <!--?php echo 'Welcome ', 'to', ' ', 'TechInterviews!'; ?>

    and it will output the string “Welcome to TechInterviews!” print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf  is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

  20. I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP? – On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().
  21. What’s the output of the ucwords function in this example?
    	print $formatted;

    ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth usingstrtolower() first.

  22. What’s the difference between htmlentities() and htmlspecialchars()? – htmlspecialchars only takes care of <, >, single quote ‘, double quote ” and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.
  23. What’s the difference between md5(), crc32() and sha1() crypto on PHP? – The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.
  24. So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()? – Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.


  1. Given a Binary Search Tree, write a program to print the kth smallest element without using any static/global variable. You can’t pass the value k to any function also.
  2. What are the 4 basics of OOP?
  3. Define Data Abstraction. What is its importance?
  4. Given an array of size n. It contains numbers in the range 1 to n. Each number is present at least once except for 2 numbers. Find the missing numbers.
  5. Given an array of size n. It contains numbers in the range 1 to n. Find the numbers which aren’t present.
  6. Given a string,find the first un-repeated character in it? Give some test cases
  7. You are given a dictionary of all valid words. You have the following 3 operations permitted on a word: delete a character, insert a character, replace a character. Now given two words – word1 and word2 – find the minimum number of steps required to convert word1 to word2. (one operation counts as 1 step.)
  8. Given a cube of size n*n*n (i.e made up of n^3 smaller cubes), find the number of smaller cubes on the surface. Extend this to k-dimension.
  9. What is a C array and illustrate the how is it different from a list.
  10. What is the time and space complexities of merge sort and when is it preferred over quick sort?
  11. Write a function which takes as parameters one regular expression(only ? and * are the special characters) and a string and returns whether the string matched the regular expression.
  12. Given n red balls and m blue balls and some containers, how would you distribute those balls among the containers such that the probability of picking a red ball is maximized, assuming that the user randomly chooses a container and then randomly picks a ball from that.
  13. Find the second largest element in an array with minimum no of comparisons and give the minimum no of comparisons needed on an array of size N to do the same.
  14. Given an array of size n, containing every element from 1 to n+1, except one. Find the missing element.
  15. How do you convert a decimal number to its hexa-decimal equivalent.Give a C code to do the same
  16. Explain polymorphism. Provide an example.
  17. Given an array all of whose elements are positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return 15 (sum of 3, 5 and 7)
  18. You are given some denominations of coins in an array (int denom[])and infinite supply of all of them. Given an amount (int amount), find the minimum number of coins required to get the exact amount. What is the method called?
  19. Given an array of size n. It contains numbers in the range 1 to n. Each number is present at least once except for 1 number. Find the missing number.

    1. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
  1. Can you store multiple data types in System.Array? No.
  2. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
  3. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
  4. What’s the .NET datatype that allows the retrieval of data by a unique key?HashTable.
  5. What’s class SortedList underneath? A sorted HashTable.
  6. Will finally block get executed if the exception had not occurred? Yes.
  7. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
  8. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
  9. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
  10. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
  11. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.
  12. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
  13. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
  14. What’s a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
  15. What namespaces are necessary to create a localized application?System.Globalization, System.Resources.
  16. What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
  17. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.
  18. What’s the difference between <c> and <code> XML documentation tag? Single line code example and multiple-line code example.
  19. Is XML case-sensitive? Yes, so <Student> and <student> are different elements.
  20. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
  21. What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.
  22. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
  23. What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
  24. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
  25. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.
  26. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
  27. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
  28. Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
  29. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
  30. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
  31. What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.
  32. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
  33. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
  34. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
  35. Which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
  36. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.
  37. What does the parameter Initial Catalog define inside Connection String?The database name to connect to.
  38. What’s the data provider name to connect to Access database? Microsoft.Access.
  39. What does Dispose method do with the connection object? Deletes it from the memory.
  40. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.