*Q. How could Java classes direct program messages to the system console, but error messages, say to a file?
A. The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);
*Q. What's the difference between an interface and an abstract class?
A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.
*Q. Why would you use a synchronized block vs. synchronized method?
A. Synchronized blocks place locks for shorter periods than synchronized methods.
*Q. Explain the usage of the keyword transient?
A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
*Q. How can you force garbage collection?
A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
*Q. How do you know if an explicit object casting is needed?
A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.
*Q. What's the difference between the methods sleep() and wait()
A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
*Q. Can you write a Java class that could be used both as an applet as well as an application?
A. Yes. Add a main() method to the applet.
*Q. What's the difference between constructors and other methods?
A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.
*Q. Can you call one constructor from another if a class has multiple constructors
A. Yes. Use this() syntax.
*Q. Explain the usage of Java packages.
A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
*Q. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee
*Q. What's the difference between J2SDK 1.5 and J2SDK 5.0?
A.There's no difference, Sun Microsystems just re-branded this version.
*Q. What would you use to compare two String variables - the operator == or the method equals()?
A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.
*Q. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
*Q. Can an inner class declared inside of a method access local variables of this method?
A. It's possible if these variables are final.
*Q. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A. A single ampersand here would lead to a NullPointerException.
*Q. What's the main difference between a Vector and an ArrayList
A. Java Vector class is internally synchronized and ArrayList is not.
*Q. When should the method invokeLater()be used?
A. This method is used to ensure that Swing components are updated through the event-dispatching thread.
*Q. How can a subclass call a method or a constructor defined in a superclass?
A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor
For senior-level developers:
**Q. What's the difference between a queue and a stack?
A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
**Q. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
**Q. What comes to mind when you hear about a young generation in Java?
A. Garbage collection.
**Q. What comes to mind when someone mentions a shallow copy in Java?
A. Object cloning.
**Q. If you're overriding the method equals() of an object, which other method you might also consider?
A. hashCode()
**Q. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?
A. ArrayList
**Q. How would you make a copy of an entire Java object with its state?
A. Have this class implement Cloneable interface and call its method clone().
**Q. How can you minimize the need of garbage collection and make the memory use more effective?
A. Use object pooling and weak object references.
**Q. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.
*Q. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
A. You do not need to specify any access level, and Java will use a default package access level.
SOME MORE QUESTIONS:
- What is garbage collection? What is the process that is responsible for doing that in java? - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
- What kind of thread is the Garbage collector thread? - It is a daemon thread.
- What is a daemon thread? - These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
- How will you invoke any external process in Java? - Runtime.getRuntime().exec(….)
- What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
- What is mutable object and immutable object? - If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
- What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object.
- What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
- What is reflection? - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
- What is the base class for Error and Exception? - Throwable
- What is the byte range? -128 to 127
- What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented.
- What is a package? - To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
- What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
- What is a DatabaseMetaData? - Comprehensive information about the database as a whole.
- What is Locale? - A Locale object represents a specific geographical, political, or cultural region
- How will you load a specific locale? - Using ResourceBundle.getBundle(…);
- What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.
- Is JVM a compiler or an interpreter? - Interpreter
- When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler
- What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.
- How will you get the platform dependent values like line separator, path separator, etc., ? - Using Sytem.getProperty(…) (line.separator, path.separator, …)
- What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.
- What is the final keyword denotes? - final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.
- What is the significance of ListIterator? - You can iterate back and forth.
- What is the major difference between LinkedList and ArrayList? - LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
- What is nested class? - If all the methods of a inner class is static then it is a nested class.
- What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
- What is composition? - Holding the reference of the other class within some other class is known as composition.
- What is aggregation? - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.
- What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
- Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public.
- What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }
- What is DriverManager? - The basic service to manage set of JDBC drivers.
- What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).
- Inq adds a question: Expain the reason for each keyword of
public static void main(String args[])
PHP INTERVIEW QUESTIONS AND ANSWERS:
- What does a special set of tags <?= and ?> do in PHP? - The output is displayed directly to the browser.
- What’s the difference between include and require? - It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
- I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem? - PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.
- 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.
- How do you define a constant? - Via define() directive, like define ("MYCONSTANT", 100);
- How do you pass a variable by value? - Just like in C++, put an ampersand in front of it, like $a = &$b
- 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.
- 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.
- 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.
- How do I find out the number of parameters passed into function? - func_num_args() function returns the number of parameters passed in.
- 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.
- 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.
- Are objects passed by value or by reference? - Everything is passed by value.
- How do you call a constructor for a parent class? - parent::constructor($value)
- 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.
- 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. - 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.
- How come the code <?php print "Contents: $arr[1]"; ?> works, but <?php print "Contents: $arr[1][2]"; ?> 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.
- What is the difference between characters 23 and x23? - The first one is octal 23, the second is hex 23.
- With a heredoc syntax, do I get variable substitution inside the heredoc contents? - Yes.
- I want to combine two variables together:
22. $var1 = 'Welcome to ';
23. $var2 = 'TechInterviews.com';
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 TechInterviews.com". 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.
- For printing out strings, there are echo, print 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.
- 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().
- What’s the output of the ucwords function in this example?
27. $formatted = ucwords("TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS");
print $formatted;
What will be printed is TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS.
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.
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.
- 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.
- 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.
- 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.
No comments:
Post a Comment