Interview Q&A


 PHP Interview Questions - PHP Interview Questions and Answers

PHP Interview Questions - Here are some of the best PHP Interview Questions with Answers. This is a
platform where you can get everything about PHP Interview Questions & Answers.


1) What is the difference between strstr & stristr?
For strstr, the syntax is: string strstr(string $string,string $str ); The function strstr will search $str in $string. If
it finds the string means it will return string from where it finds the $str upto end of $string.
For Example:
$string = "http://yahoomail.com";
$str="yahoomail";
The output is "yahoomail.com". The main difference between strstr and stristr is of case sensitivity. The
former consider the case difference and later ignore the case difference.

2) What is the difference between explode and split?
Split function splits string into array by regular expression. Explode splits a string into array by string.
For Example:
explode(" and", "India and Pakistan and Srilanka");
split(" :", "India : Pakistan : Srilanka");
Both of these functions will return an array that contains India, Pakistan, and Srilanka.

3) How can you avoid execution time out error while fetching record from MySQL?
set_time_limit -- Limits the maximum execution time
For Example:
set_time_limit(0);
If you set to 0 you say that there is not limit.

4) Write a SQL query that displays the difference between the highest and lowest salaries of a database table
"employees". Label the column as DIFFERENCE.
Select max(sal)-min(sal) as Difference from employees;

5) What is the difference between require() and include()?
Both of these constructs includes and evaluates the specific file. The two functions are identical in every way
except how they handle failure. If filepath not found, require() terminates the program and gives fatal error,
but include() does not terminate the program; It gives warning message and continues to program.
include() produces a Warning while require() results in a Fatal Error if the filepath is not correct.

6) What is the difference between echo and print?
Main difference between echo() and print() is that echo is just an statement not a function and doesn't return's
value or it just prints a value whereas print() is an function which prints a value and also it returns value.
We cannot pass arguments to echo since it is just a statement whereas print is a function and we can pass
arguments to it and it returns true or false. print can be used as part of a more complex expression whereas
echo cannot. echo is marginally faster since it doesn't set a return value.

7) An examiner awards the highest mark 75 and the lowest mark 25, the pass marks being 40. The
moderator wants to change the highest mark to 250 and the lowest marks to 100 using the linear formula
y=ax+b. The revised pass marks will be:
A. 145
B. 150
C. 160
D. 400/3
Give the correct option.
y=ax+b
100=25a+b
250=75a+b
Solve it get and b and then put
y=40a+b
Answer: 145

8) A and B are shooters and having their exam. A and B fall short of 10 and 2 shots respectively to the
qualifying mark. If each of them fired at least one shot and even by adding their total score together, they fall
short of the qualifying mark, what is the qualifying mark?
Answer: 11
As A is short by 10 - he has shot 1
As B is short by 2 - he has shot 9
9+1=10 and 10 < 11

9) In objective test a correct answer score 4 marks and on a wrong answer 2 marks. A student scores 480
marks from 150 questions. How many answers were correct?
A. 120
B. 130
C. 110
D. 150
Answer: B i.e. 130
4x-2y=480
x+y=150
Then X is 130 so 130 is correct answer.

10) An INK bug starts jumping 1 meter to each direction north, south, east and west respectively. It marks a
point in the new locations. It comes back to its original point after jumping in all directions. It again starts the
same process from the newly drawn unique points. Totally how many points did the bug mark?

11) A guy walks at 4kmph from a point. After 4hrs a cyclist starts from the same point at 10kmph. At what
distance will they meet from the starting point?
Answer: 26.66km
Explanation: We have, s=vt where s=distance. Since both meet at same point, both travels same distance=s
km. Now, equating, 10(t+4) = 4t ------> t=20/3
sub. t=20/3 in s=4t---------> s = 26.66km

12) What's the difference between COPY OF A FILE & MOVE_UPLOAD_FILE in file uploading?
Move: This function checks to ensure that the file designated by filename is a valid upload file (meaning that it
was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename
given by destination.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
Copy: Makes a copy of a file. Returns TRUE if the copy succeeded, FALSE otherwise.

13) How do you insert single & double quotes in MySQL db without using PHP?
&amp; / &quote;
Alternately, escape single quote using forward slash \' . In double quote you don't need to escape quotes.
Insert double quotes as "".

14) What do you need to do to improve the performance (speedy execution) for the script you have written?
If your script is to retrieve data from Database, you should use "Limit" syntax. Break down the non dynamic
sections of website which need not be repeated over a period of time as include files.

15) How do you capture audio/video in PHP?
You need a module installed - FFMPEG. FFmpeg is a complete solution to record, convert and stream audio
and video. It includes libavcodec, the leading audio/video codec library. FFmpeg is developed under Linux,
but it can be compiled under most operating systems, including Windows.

16) How do you know (status) whether the recipient of your mail had opened the mail i.e. read the mail?
Embed an URL in a say 0-byte image tag may be the better way to go. In other word, you embed an invisible
image on you html email and when the src URL is being rendered by the server, you can track whether your
recipients have view the emails or not.

17) What is random number?
A random number is a number generated by a process, whose outcome is unpredictable, and which cannot
be sub sequentially reliably reproduced.

18) What is difference between srand & shuffle?
The srand function seeds the random number generator with seed and shuffle is used for shuffling the array
values.
shuffle - This function shuffles (randomizes the order of the elements in) an array. This function assigns new
keys for the elements in array. It will remove any existing keys you may have assigned, rather than just
reordering the keys.
srand - Seed the random number generator

19) How can we remove duplicate values from an array?
array_unique() funciton can be used for the purpose.

20) How do I find out weather a number is odd or even?
if (number%2==0 ) then even else odd.

21) How can we get the ID generated from the previous insert operation?
SELECT MAX(ID) from tablename;

22) How to limit the number of rows to 5 that I get out of my database?
Select * from tablename LIMIT 0, 5;

23) How to store binary data in MySQL?
 Use BLOB data type for the database field.

24) How can we submit a form without a submit button?
We can submit a form using the JavaScript. Example: document.formname.submit();

25) How can I maintain the count of how many persons have hit my site?

26) What is difference between mysql_fetch_array(), mysql_fetch_row() and mysql_fetch_object()?
mysql_fetch_array - Fetch the all matching records of results.
mysql_fetch_object - Fetch the first single matching record of results. mysql_fetch_row - fetches a result row as array.

27) How to make a download page in own site, where I can know that how many file has been loaded by
particular user or particular IP address?
We can log the IP addresses in one database table while downloading the file. This way we can count and
check the no. of rows inserted for a particular download.

28) What is difference between mysql_connect and mysql_pconnect?
mysql_connect opens up a database connection every time a page is loaded. mysql_pconnect opens up a
connection, and keeps it open across multiple requests.
mysql_pconnect uses less resources, because it does not need to establish a database connection every
time a page is loaded.

29) What is the difference between “Insert”, “Update” and “Modify” events?
INSERT - Add a new record into the database table.
MODIFY - If record is available it modifies otherwise it wont modify.
UPDATE - If record is available it updates the record otherwise it creates a new record.

30) How I can get IP address?
getenv("REMOTE_ADDR");

31) How to make a login page where once the user has logged in will go back to the page it came from to
login page?

32) How do we know properties of the browser?
You can gather a lot of information about a person's computer by using $_SERVER['HTTP_USER_AGENT'].
This can tell us more about the user's operating system, as well as their browser. For example I am revealed
to be Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/418 (KHTML, like Gecko) Safari/417.9.3
when visiting a PHP page.
This can be useful to programmers if they are using special features that may not work for everyone, or if
they want to get an idea of their target audience. This also is important when using the get_browser() function
for finding out more information about the browser's capabilities. By having this information the user can be
directed to a version of your site best suited to their browser.
get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the
browser's information in the browscap.ini file.
echo $_SERVER['HTTP_USER_AGENT'] . "<hr />\n";
$browser = get_browser();
foreach ($browser as $name => $value)
{
echo "<b>$name</b> $value <br />\n";
}

33) What is difference between require_once(), require(), include(). Because all these function are used to
call a file in another file.
Difference between require() and require_once(): require() includes and evaluates a specific file, while
require_once() does that only if it has not been included before (on the same page).
So, require_once() is recommended to use when you want to include a file where you have a lot of functions
for example. This way you make sure you don't include the file more times and you will not get the "function
re-declared" error.
Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to
include is not found, while include() only produces a WARNING.
There is also include_once() which is the same as include(), but the difference between them is the same as
the difference between require() and require_once().

34) If you have to work with dates in the following format: "Tuesday, February 14, 2006 @ 10:39 am", how
can you convert them to another format that is easier to use?
The strtotime function can convert a string to a timestamp.
A timestamp can be converted to date format. So it is best to store the dates as timestamp in the database,
and just output them in the format you like.
So let's say we have $date = "Tuesday, February 14, 2006 @ 10:39 am";
In order to convert that to a timestamp, we need to get rid of the "@" sign, and we can use the remaining
string as a parameter for the strtotime function.
So we have
$date = str_replace("@ ","",$date);
$date = strtotime($date);
Now $date is a timestamp and we can say:
echo date("d M Y",$date);

35) What is CAPTCHA?
CAPTCHA stands for Completely Automated Public Turing Test to tell Computers and Humans Apart. To
prevent spammers from using bots to automatically fill out forms, CAPTCHA programmers will generate an
image containing distorted images of a string of numbers and letters. Computers cannot determine what the
numbers and letters are from the image but humans have great pattern recognition abilities and will be able
to fairly accurately determine the string of numbers and letters. By entering the numbers and letters from the
image in the validation field, the application can be fairly assured that there is a human client using it.

36) What is the difference between sessions and cookies?

 37) What is the difference between $x and $$x ?
$x is simple variable. $$x is reference variable or infact a variable of variable. A variable variable allows us to
change the name of a variable dynamically.
<?
$x = "this";
$$x = "is cake";
?>
The $$ is the syntax used in PHP for a variable variable. I can now call the two variables $x and $$x two
ways.
<?
echo "$x ${$x}";
?>
<?
echo "$x $this";
?>
Both of these will return the string "this is cake". Notice that $$x is written as ${$x} in echo. This lets PHP
know that you are using the variable $$x and not $ and $x

38) What is meant by nl2br()?
New line (\n) to Break tag (<BR>) conversion.

39) What are the current versions of apache, PHP, and MySQL?

40) What are the reasons for selecting lamp (Linux, Apache, MySQL, PHP) instead of combination of other
software programs, servers and operating systems?

41) How can we encrypt and decrypt a data present in a MySQL table using MySQL?
AES_ENCRYPT(str,key_str) , AES_DECRYPT(crypt_str,key_str)

42) What are the differences between Get and post methods in form submitting, give the case where we can
use get and we can use post methods?

43) What does PHP stands for and who is the father of PHP? Explain the changes in PHP versions?

44) How can we create a database using PHP and MySQL?

45) What is meant by urlencode() and urldecode()?
string urlencode(str)
When str contains a string like this “hello world” and the return value will be URL encoded and can be use to
append with URLs, normally used to append data for GET like someurl.com?var=hello%world
string urldocode(str)
This will simple decode the GET variable’s value. Example: echo (urldecode($_GET_VARS[var])) will output
“hello world”

46) What is the difference between the functions unlink and unset?
unlink is a function for file system handling. It will simply delete the file in context. unset will set UNSET the
specified variable.
unlink is used to delete a file. unset is used to destroy an earlier declared variable.

47) What are the different types of errors in PHP?
1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example,
accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all
- although you can change this default behavior.
2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist.
By default, these errors are displayed to the user, but they do not result in script termination.
3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling
a non-existent function. These errors cause the immediate termination of the script, and PHP’s default
behavior is to display them to the user when they take place.

48) How can we create a session variable & terminate it?
$_SESSION[’name’] = “Chinmay”;
To destroy a session: unset($_SESSION[’name’]);

49) How to Create a Cookie & destroy it in PHP?
setcookie(”variable”,”value”,”time”);
variable - name of the cookie variable
variable - value of the cookie variable
time - expiry time
Example: setcookie(”test”,$i,time()+3600);
Test - cookie variable name
$i - value of the variable ‘Test’
time()+3600 - denotes that the cookie will expire after an one hour.
Destroy a cookie by specifying expiry time
Example: setcookie(”test”,$i,time()-3600); // already expired time
Reset a cookie by specifying its name only
setcookie(”test”);

50) What is the difference between sizeof($array) and count($array)?
sizeof($array) - This function is an alias of count()
count($array) - If you just pass a simple variable instead of an array it will return 1.




 Java Interview Interview Questions with Answers



Time is changing and so is Java interviews. Gone
are the days, when knowing the difference
between String and StringBuffer can help you to
go till the second round of interview, questions
are becoming more advanced and interviewers are
asking more deep questions.
Since I like to explore interview questions, I have
got this huge list of questions with me, which
contains lots and lots of questions from different
topics. I have been preparing this MEGA list from
quite some time and now It's ready to share with
you guys. It contains interview questions not only
from classic topics like threads, collections,
equals and hashcode, sockets but also from NIO,
array, string, java 8 and many more.
Important Topics for Java Interviews
To give you an
idea, this list of Java interview questions includes
following topics:
1. Multithreading, concurrency and thread basics
2. Date type conversion and fundamentals
3. Garbage Collection
4. Java Collections Framework
5. Array
6. String
7. GOF Design Patterns
8. SOLID design principles
9. Abstract class and interface
10. Java basics e.g. equals() and hashcode
11. Generics and Enum
12. Java IO and NIO
13. Common Networking protocols
14. Data structure and algorithm in Java
15. Regular expressions
16. JVM internals
17. Java Best Practices
18. JDBC
19. Date, Time, and Calendar
20. XML Processing in Java
21. JUnit
22. Programming
Multithreading, Concurrency and Thread
basics Questions
1) Can we make array volatile in Java?
Ans : Yes, you can make an array volatile in
Java but only the reference which is pointing to
an array, not the whole array.
2) What are practical uses of volatile modifier?
Ans :  One of the practical use of the volatile variable is
to make reading double and long atomic. Another
use of the volatile variable is to provide a memory
barrier, just like it is used in Disrupter framework.
3) What guarantee volatile variable provides?
Ans : volatile variables provide the guarantee about
ordering and visibility .
4) Which one would be easy to write?
synchronization code for 10 threads or 2 threads?
Ans : In terms of writing code, both will be of same
complexity because synchronization code is
independent of a number of threads. Choice of
synchronization though depends upon a number
of threads .
5) What is a thread local variable in Java?
Ans : Thread-local variables are variables confined to a
thread, its like thread's own copy which is not
shared between multiple threads. Java provides a
ThreadLocal class to support thread-local
variables. It's one of the many ways to achieve
thread-safety.
6) The difference between sleep and wait in
Java?
Ans : Though both are used to pause currently running
thread, sleep() is actually meant for short pause
because it doesn't release lock, while wait() is
meant for conditional wait and that's why it
release lock which can then be acquired by
another thread to change the condition on which
it is waiting.
Date types and Basic Java Interview Questions
1)What is the right data type to represent a
price in Java?
Ans :  BigDecimal if memory is not a concern and
Performance is not critical, otherwise double with
predefined precision.
2) How do you convert bytes to String?
Ans :  you can convert bytes to the string using string
constructor which accepts byte[], just make
sure that right character encoding otherwise
platform's default character encoding will be used
which may or may not be same.
3) Which class contains clone method?
Cloneable or Object?
Ans : java.lang.Cloneable is marker interface and
doesn't contain any method. clone method is
defined in the object class. It is also knowing that
clone() is a native method means it's
implemented in C or C++ or any other native
language.
4) Is ++ operator is thread-safe in Java?
Ans : No it's not a thread safe operator because its
involve multiple instructions like reading a value,
incriminating it and storing it back into memory
which can be overlapped between multiple
threads.
5) Difference between a = a + b and a += b ?
Ans : The += operator implicitly cast the result of
addition into the type of variable used to hold the
result. When you add two integral variable e.g.
variable of type byte, short, or int then they are
first promoted to int and them addition happens.
If result of addition is more than maximum value
of a then a + b will give compile time error but
a += b will be ok as shown below
byte a = 127;
byte b = 127;
b = a + b; // error : cannot convert
from int to byte
b + = a; // ok
JVM Internals and Garbage Collection
Interview Questions
1) What is the size of int in 64-bit JVM?
Ans : The size of an int variable is constant in Java, it's
always 32-bit irrespective of platform. Which
means the size of primitive int is same in both
32-bit and 64-bit Java virtual machine
2) What is the size of an int variable in 32-bit
and 64-bit JVM?
Ans : The size of int is same in both 32-bit and 64-bit
JVM, it's always 32 bits or 4 bytes.
3) How do you find if JVM is 32-bit or 64-bit
from Java Program?
Ans : You can find that by checking some system
properties like sun.arch.data.model or os.arch.
4) Can you guarantee the garbage collection
process?
Ans :  No, you cannot guarantee the garbage collection,
though you can make a request using System.gc()
or Runtime.gc() method.
5) What is the difference between stack and
heap in Java?
Ans : Stack and heap are different memory areas in the
JVM and they are used for different purposes. The
stack is used to hold method frames and local
variables while objects are always allocated
memory from the heap. The stack is usually much
smaller than heap memory and also didn't shared
between multiple threads, but heap is shared
among all threads in JVM.
Basic Java concepts Interview Questions
1) What's the difference between "a == b" and
"a.equals(b)"?
Ans : The a = b does object reference matching if both a
and b are an object and only return true if both
are pointing to the same object in the heap space,
on the other hand, a.equals(b) is used for logical
mapping and its expected from an object to
override this method to provide logical equality.
2)Difference between final, finalize and
finally?
Ans : The final is a modifier which you can apply to
variable, methods and classes. If you make a
variable final it means its value cannot be
changed once initialized. finalize is a method,
which is called just before an object is a garbage
collected, giving it last chance to resurrect itself,
but the call to finalize is not guaranteed. finally is
a keyword which is used in exception handling
along with try and catch. the finally block is
always executed irrespective of whether an
exception is thrown from try block or not.
3) What is a compile time constant in Java?
Ans : public static final variables are also known as a
compile time constant, the public is optional
there. They are replaced with actual values at
compile time because compiler know their value
up-front and also knows that it cannot be
changed during run-time.
Java Collections Framework Interview Questions
1) Difference between poll() and remove()
method?
Ans : Both poll() and remove() take out the object from
the Queue but if poll() fails then it returns null but
if remove fails it throws Exception.
2) Difference between ArrayList and LinkedList
in Java?
Ans : The obvious difference between them is that
ArrrayList is backed by array data structure,
supprots random access and LinkedList is backed
by linked list data structure and doesn't
supprot random access. Accessing an element
with the index is O(1) in ArrayList but its O(n) in
LinkedList.
3) How do you print Array in Java?
Ans : You can print an array by using the
Arrays.toString() and Arrays.deepToString()
method. Since array doesn't implement toString()
by itself, just passing an array to
System.out.println() will not print its contents but
Arrays.toString() will print each element.
4) LinkedList in Java is doubly or singly linked
list?
Ans : It's a doubly linked list, you can check the code in
JDK. In Eclipse, you can use the shortcut , Ctrl + T
to directly open this class in Editor.
5) Which kind of tree is used to implement
TreeMap in Java?
Ans : A Red Black tree is used to implement TreeMap in
Java.
Recommended Books for Java Interviews
If you are looking for some goods to prepare for
your Java Interviews, You can take a look at
following books to cover both theory and coding
questions:
1. Java Programming Interview Exposed by
Markham
2.Cracking the Coding Interview: 150
Programming Questions and Solutions.
3. Programming Interviews Exposed: Secrets
to Landing Your Next Job.


Post a Comment