Programming technical questions

Every developer should know to answer

Introduction

Basics first, then the rest. This principle seems natural enough, but it's not always followed. The reason might be impatience to go to the advanced level. And it is particularly important in software development. Because in this area there are always new languages to learn, new libraries and tools to use, new approaches to apply. And if we constantly learning new, it is easy to overlook what is beneath the new stuff, and beneath are the basics.

So, if I am Java programmer with ten years of experience, and want to ask myself, how well do I know Java? The main part of the answer would not be how many java libraries or tools I've use during that course (half of what is obsolete or forgotten). But how well do I know Java language itself and its basic classes. Something that should be applied without using internet queries for usage.

And to know language well, we should test ourselves often against these basic things, and repeat it. Questions in this list are those we came upon during the time, or found on other web pages. We consider them basic, for java, or databases. If you think you are proficient at these areas, have a try at them, and feel free to comment how well you pass it!

Java

What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.
Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
What is implicit casting?
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.
Example

int i = 1000;

long j = i; //Implicit casting
					
Is sizeof a keyword in java?
The sizeof operator is not a keyword
What if I write static public void instead of public static void?
Program compiles and runs properly.
What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:
int a=5,b=10;
a=a+b; 
b=a-b; 
a=a-b;

An other approach to the same question

You use an XOR swap.

for example:

int a = 5; int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
					
How to run a class from a jar file?
java -cp myjar.jar com.mypackage.myClass
Does Map interface extends Collection ?
No. Map instances have methods to return collection, entrySet(), keySet(), values().
Can you write: a) 'p'-'k' and whats the result? b) char c=77?
a) Yes. Both are converted to int and result is int.
b) Yes. Result is 'M'.
How
for (String item : someList) {
    System.out.println(item);
}
				
code works?
It is equivalent to
for(Iterator i = someList.iterator(); i.hasNext(); ) {
    String item = i.next();
    System.out.println(item);
}						
					
In
for(String s : myCollection.expensiveListGeneration()){
      doSomething();
}
how many times is expensiveListGeneration() invoked?
Once. See previous question.
How for statement is executed?
for (initialization; termination;
     increment) {
    statement(s)
}						
					
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
How to remove a character from string?
Cannot be done without creating ne string.
occurrence - str.replace("char","")
from position - str.substring(0, index) + str.substring(index+1)
StringBuilder sb = new StringBuilder(str); sb.deleteCharAt(index); sb.toString();
What are java system properties? How to set one?
Those are properties initially set by JVM. They use dot notation, and some predefined are always set, like "java.version".
They are accessed through System.getProperties() and System.getProperty().
					
New property can be added with -D jvm argument, or with System.setProperty().
				
What are main methods in HttpServlet class to handle requests, and what parameters they receive?
Methods are doGet() and doPost() and they receive HttpServletRequest and HttpServletResponse objects as parameters.
How many times, when, and by who are called servlet's init() and destroy() methods?
They are called exactly once by servlet container. init() indicate to a servlet that the servlet is being placed into service, and destroy() indicate to a servlet that the servlet is being taken out of service.
What happens if object's wait() method is called out of synchronized block?
Program compiles but RuntimeException is thrown. wait() and notify() must be called from synchronized block with that object's monitor.
In public static void main(String[] args) call, does args[0] contain class name or first parameter to program?
First parameter to program.
What levels of web application listeners exist and for what kind of events?
There are two levels: servlet-context (application) and session level. Both can register listeners for life cycle changes and attribute changes (4 listeners all together).
Does sleep() or interrupt() stop the thread?
No for both. sleep() pauses it, but thread does not lose ownership of any monitors. And interrupt() just indicates to it that it should (probably) stop and return from run(). But it's up to thread to decide. Either in catch block if it's in state which throws it, or by checking it's own isInterrupted() status.
If given are three classes, what would every assignment line produce (if run without other lines)?
class A{};
class B extends A {};
class C extends A {};

A a=new A();
B b=new B();
C c=new C();
a=b;	//1
c=a;	//2
b=(B)a;	//3
b=(A)b;	//4				
				
1 - OK. 2 - compile error. 3 - runtime exception. 4 - compile error.
In chained exception, how to get previous exception in chain?
With getCause() method from Throwable.
Why SQLException has getNextException() method in addition to exception chaining?
Because SQL operation can fail for several independent reasons which are on the same level, none caused with another.
What are the differences between a HashMap and a Hashtable?
Hashtable is synchronized, HashMap is not.
Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
If synchronization is needed, which class is better option to use instead of HashMap and why?
ConcurrentHashMap, and not Hashtable or Collections.synchronizedMap(map). Because it avoid read locks and improves performance over other two. Hashtable and Collections.synchronizedMap(Map) use the same simple synchronization, which means that only one thread can access the map at the same time.
Which one (or both) is correct:
public synchronized void metod(){}; public void synchronized metod(){};
Just the first. Second is compile error.
In the following class, are two print statements correct?
class OC {
	int i =12;
	void ocm(){
		int j =11;
		class IC{
			void icm(){
				System.out.println(i);
				System.out.println(j);
			}
		}
	}
}				
				
First one is correct, second is compile error. Which can be changed by adding final to j declaration.

Databases

How to create transaction with JDBC?
First disable auto commit. When a connection is created, it is in auto-commit mode.
con.setAutoCommit(false);
After the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit.
con.commit();
How to call stored procedure from Java?
From Spring - class SimpleJdbcCall.
Map outParams = jdbcCall.execute(inParams);
With JDBC:
cs = this.con.prepareCall("{call PROC_NAME()}");
ResultSet rs = cs.executeQuery();
                            
What are two roles of transaction?
Grouping statements together for execution as a unit, and help preserve the integrity of the data in a table (isolation levels are used for this).
What are transaction's isolation levels?
TRANSACTION_NONE
TRANSACTION_READ_UNCOMMITTED just groups statements
TRANSACTION_READ_COMMITTED prevents dirty reads
TRANSACTION_REPEATABLE_READ prevents non-repeatable reads
TRANSACTION_SERIALIZABLE prevents phantom reads
What does rollback() do? Why is it needed?
Rollback returns database to some previous clean state. It keeps database state consistent.
So why it is needed if without commit no transaction operations will be stored in db?
It ends transaction (like commit). It means it releases locks and leaves everything in clean state. With open transaction, starting new one could first commit all previous actions.

Comments