Wednesday, March 26, 2008

Java Interview Questions

 
What if the main method is declared as private?

The program compiles properly but at runtime it will give "Main method not public." message.

What is meant by pass by reference and pass by value in Java?

Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.

If you’re overriding the method equals() of an object, which other method you might also consider?

hashCode()

What is Byte Code?

Or

What gives java it’s “write once and run anywhere” nature?

All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

Expain the reason for each keyword of public static void main(String args[])?

public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.

void: main does not return anything so the return type must be void

The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

What are the differences between == and .equals() ?

Or

what is difference between == and equals

Or

Difference between == and equals method

Or

What would you use to compare two String variables - the operator == or the method equals()?

Or

How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.

 public class EqualsTest { 	 	public static void main(String[] args) {  		String s1 = "abc"; 		String s2 = s1; 		String s5 = "abc"; 		String s3 = new String("abc"); 		String s4 = new String("abc"); 		System.out.println("== comparison : " + (s1 == s5)); 		System.out.println("== comparison : " + (s1 == s2)); 		System.out.println("Using equals method : " + s1.equals(s2)); 		System.out.println("== comparison : " + s3 == s4); 		System.out.println("Using equals method : " + s3.equals(s4)); 	} }


Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

What if the static modifier is removed from the signature of the main method?

Or

What if I do not provide the String array as the argument to the method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

What does it mean that a class or member is final?

o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

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.

Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
  • The global variables breaks the referential transparency
  • Global variables creates collisions in namespace.

How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

What is the difference between a while statement and a do statement?

A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.

What is the Locale class?

The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.

Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places

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 is a native method?

A native method is a method that is implemented in a language other than Java.

In System.out.println(), what is System, out and println?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

What are Encapsulation, Inheritance and Polymorphism

Or

Explain the Polymorphism principle. Explain the different forms of Polymorphism.

Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.

Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting

What is the Java Virtual Machine (JVM)?

The Java Virtual Machine is software that can be ported onto various hardware-based platforms

What do you understand by downcasting?

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy

What are Java Access Specifiers?

Or

What is the difference between public, private, protected and default Access Specifiers?

Or

What are different types of access modifiers?

Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
Public : accessible to all classes
Protected : accessible to the classes within the same package and any subclasses.
Private : accessible only to the class to which they belong
Default : accessible to the class to which they belong and to subclasses within the same package

Which class is the superclass of every class?

Object.

Name primitive Java types.

The 8 primitive types are byte, char, short, int, long, float, double, and boolean.

What is the difference between static and non-static variables?

Or

What are class variables?

Or

What is static in java?

Or

What is a static method?

A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.
     Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a non-static method. In other words, you can't change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.

What is the difference between the boolean & operator and the && operator?

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What if I write static public void instead of public static void?

Program compiles and runs properly.

What is the difference between declaring a variable and defining a variable?

In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String ("bob"); Or String s = "bob"; are both definitions.

What type of parameter passing does Java support?

In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

What do you understand by a variable?

Variable is a named memory location that can be easily referred in the program. The variable is used to hold the data and it can be changed during the course of the execution of the program.

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.

What do you understand by casting in java language? What are the types of casting?

The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.

What is the first argument of the String array in main method?

The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null.

How can one prove that the array is not null but empty?

Print array.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print array.length.

Can an application have multiple classes having main method?

Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?

Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.

Can I have multiple main methods in the same class?

We can have multiple overloaded main methods but there can be only one main method with the following signature :

public static void main(String[] args) {}

No the program fails to compile. The compiler says that the main method is already defined in the class.

Explain working of Java Virtual Machine (JVM)?

JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.

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;

What is data encapsulation?

Encapsulation may be used by creating 'get' and 'set' methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding.

What is reflection API? How are they implemented?

Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.

Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why

Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.

What is phantom memory?

Phantom memory is false memory. Memory that does not exist in reality.

Can a method be static and synchronized?

A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:

           synchronized(XYZ.class) {

           }

What is difference between String and StringTokenizer?

A StringTokenizer is utility class used to break up string.

Example:

StringTokenizer st = new StringTokenizer("Hello World");

   while (st.hasMoreTokens()) {

     System.out.println(st.nextToken());

     }

Output:

Hello

World

 

Monday, March 17, 2008

Core Java Interview Questions

(From http://www.roseindia.net/interviewquestions/corejava.shtml)
 
Question: What is transient variable?
Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.
 

Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.
    

Question: What do you understand by Synchronization?
Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
     // Appropriate method-related code. 
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
    synchronized (this) { 
            // Synchronized code here.
         }
}
  

Question: What is Collection API?
Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. 
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
  

Question: Is Iterator a Class or Interface? What is its use?
Answer: Iterator is an interface which is used to step through the elements of a Collection. 
   

Question: What is similarities/difference between an Abstract class and Interface?
Answer:  Differences are as follows:

  • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  • Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 

Similarities:

  • Neither Abstract classes or Interface can be instantiated.
      
Question: How to define an Abstract class?
Answer: A class containing abstract method is called Abstract class. An Abstract class can't be instantiated. 
Example of Abstract class:
abstract class testAbstractClass { 
    protected String myString; 
    public String getMyString() { 
        return myString; 
        } 
    public abstract string anyAbstractFunction();
}
     

Question: How to define an Interface?
Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Emaple of Interface:

public interface sampleInterface {
    public void functionOne();

    public long CONSTANT_ONE = 1000;
}
   

Question: Explain the user defined Exceptions?
Answer: User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
     // The class simply has to exist to be an exception
}
  

Question: Explain the new Features of JDBC 2.0 Core API?
Answer: The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities.
New Features in JDBC 2.0 Core API:

  • Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position
  • JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
  • Java applications can now use the ResultSet.updateXXX methods.
  • New data types - interfaces mapping the SQL3 data types
  • Custom  mapping of user-defined types (UTDs)
  • Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values. 

    

Question: Explain garbage collection?
Answer: Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(),  JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. 
   

Question: How you can force the garbage collection?
Answer: Garbage collection automatic process and can't be forced.  
 

Question: What is OOPS?
Answer: OOP is the common abbreviation for Object-Oriented Programming.  
 

Question: Describe the principles of OOPS.
Answer: There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.  
 

Question: Explain the Encapsulation principle.
Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.  
 

Question: Explain the Inheritance principle.
Answer: Inheritance is the process by which one object acquires the properties of another object.  
 

Question: Explain the Polymorphism principle.
Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".  
 

Question: Explain the different forms of Polymorphism.
Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface
 
 

Question: What are Access Specifiers available in Java?
Answer: Access specifiers are keywords that determines the type of access to the member of a class. These are:

  • Public
  • Protected
  • Private
  • Defaults
 
 

Question: Describe the wrapper classes in Java.
Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper
boolean   java.lang.Boolean
byte   java.lang.Byte
char   java.lang.Character
double   java.lang.Double
float   java.lang.Float
int   java.lang.Integer
long   java.lang.Long
short   java.lang.Short
void   java.lang.Void
 
 

Question: Read the following program:

public class test {
public static void main(String [] args) {
    int x = 3;
    int y = 1;
   if (x = y)
     System.out.println("Not equal");
  else
    System.out.println("Equal");
 }
}

What is the result?
   A. The output is “Equal”
   B. The output in “Not Equal”
   C. An error at " if (x = y)" causes compilation to fall.
   D. The program executes but no output is show on console.
Answer: C

Question:
what is the class variables ?
Answer: When we create a number of objects of the same class, then each object will share a common copy of variables. That means that there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class, but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it's initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object. 

Question: What is the difference between the instanceof and getclass, these two are same or not ?
Answer: instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use 
if(o.getClass().getName().equals("java.lang.Math")){ }
This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can't compare their names. It can only gives the implementing class but can't compare a interface, but instanceof operator can. 
The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two. 
Interface one{
}

Class Two implements one {
}
Class Three implements one {
}

public class Test {
public static void main(String args[]) {
one test1 = new Two();
one test2 = new Three();
System.out.println(test1 instanceof one); //true
System.out.println(test2 instanceof one); //true
System.out.println(Test.getClass().equals(test2.getClass())); //false
}
}

8 Simple Rules for Designing Threaded Applications

http://www.devx.com/go-parallel/Article/37034 gives 8 Simple Rules of threading design methods.
 
1. Be sure you identify truly independent computations
2. Implement concurrency at highest level possible
3. Plan early for scalability to take advantage of increasing numbers of cores
4. Make use of thread-safe libraries wherever possible
5. Use the right threading model
6. Never assume a particular order of execution
7. Use thread-local storage whenever possible; associate locks to specific data, if needed
8. Don’t be afraid to change the algorithm for a better chance of concurrency

jMetal

jMetal stands for Metaheuristic Algorithms in Java, and it is an object-oriented Java-based framework aimed at facilitating the development, experimentation, and study of metaheuristics for solving multi-objective optimization problems (MOPs). jMetal provides a rich set of classes which can be used as the building blocks of multi-objective metaheuristics; thus, taking advantage of code-reusing, the algorithms share the same base components, such as implementations of genetic operators and density estimators, thus facilitating the development of new multi-objective algorithms.

 

Friday, March 14, 2008

10 Ways to Improve Your Programming Productivity

(Original article at - http://www.matthewpaulmoore.com/articles/443-10-ways-to-improve-your-programming-productivity)

Having worked at Google and now working in my own business, I've noticed that some days I'm just a rockstar at getting everything done, and others I can barely get a few lines of code out, or accomplish anything on my todo list.  Of course, now that I'm in a really small business, every single day counts, for each person in the business. 

After looking back and trying to figure out what separates one day from the next, here are some commonalities I've noticed.  All of these are obvious with a little bit of thought, and I'm certainly not the first one to come up with these ideas.  But a reminder of them can go a long way. Also, some of these only apply when you're in Marathon mode (like when you're trying to be effective over the course of a year or two), and not in Sprint mode (like when you have a major, major deadline in 2 weeks).

1. Limit News Intake to twice a day, Including Google Reader & News Sites

Straight from the four hour workweek.  Let's be real: Your minute-to-minute life isn't affected by anything you read in your blogs unless you're a news reporter.  Reading the news is an enjoyable way to procrastinate under the veil of being important.  I have 2 times of the day when I read news: google reader in the morning, and news in the evening.  Anything more is a distraction which lowers my effectiveness.

2. Leave Yourself a Place to Start (or: Leave work with something small broken)

Programming effectively (at least, for me) requires me to have a lot in my brain at one time - which I 'load' when I start, and which rapidly dissipates when I get distracted or stop.  That means that getting started and 'into the zone' is the hardest part.  What makes it easier to get started is if I have a simple task to complete that gets me in the zone.  

So, any time I stop (lunch, or in the evening), I intentionally break something so I can get right back and fix it - when I get back to work, I'm not only anxious to fix it, but I'm in the zone after I'm done fixing it.  

There was a famous sculptor (or ten) who, before he'd leave for the night, would smash a sizable dent into his sculpture - so in the morning, he'd know where to start.  Many programmers I know have a problem with this - but seriously.  Try it a few times, and see if it gets you up and running faster, more consistently.

3. Draw it Out & Research First

I can't really explain it, but I'm so much more productive whenever I use a pen and paper to draw out what I need to do.  I don't know if it gives me time to sort out all the details in my mind, or if it's just giving me a road map so I don't get distracted.  But paper and pen is my favorite, whether it's a flow chart or a UI mockup.  I know others love their whiteboards.  But for some reason, doing it in OmniGraffle or PPT just doesn't have the same effect.

Also, if I know I'm going to need some algorithms that require knowledge I don't currently have, I spend 30 minutes researching the answers to them.  That way I don't get distracted or have to redo anything.

4. Architect Your Perfect Distraction-Eliminating Work Environment

Unfortunately in big companies, you don't necessarily have control over your designated workspace.  However, you can probably control your home work environment, or find an area at the office building that you can make your own.  My work environment includes:

  • Big computer monitor, big desk (for when I want to work at a desk)
  • A recliner chair (for when I want to work in a relaxing posture)
  • Conducive Work Music (my mood is a bit different each day, but I have to know the song well, otherwise I end up listening to the words!)
  • Good sound system
  • Well-Lit with natural light
  • Wide-open space
  • Very few people (or no one) walking by
  • Well ventilated, preferably with outside air
  • Modern feel
  • Calm pets I get along with

5. Eliminate IM during productive hours

Other people don't usually spend the time to think whether or not something is urgent AND important when they IM you.  Chances are if they think about it for 15 seconds after their initial impulse to IM you, most IMs can be done over email, and can be answered in non-productive hours.

The same goes for you.  Before you ask someone on IM for something, see if it's actually urgent and important.  If it's not, send them an email and ask for the answer by the end of the day, or week.  Then you won't get distracted, either.

6. Only Respond to Emergency Emails during productive hours

This goes hand in hand with the tip above.  You can lose a few hours just in the context switching between programming and doing other things.  If you can, make a label, with a rule to filter out emergency emails and bring them to your attention.  Otherwise, answer all other types of emails after productive hours.

7. Limit Meetings to once a week (or less)!

I saw this at the big company I worked at the most, but if your team runs effectively, and is an effective size, you should only have to have meetings once a week, to get everyone back on the same track.  If you have meetings more than once a week, there's most likely a serious problem with how your project is managed, or how your team is structured.

In our small team, we meet once a week to prioritize the next 3 features being built - mostly because each feature takes a week to build (or two).

8. Get out, and be social every 2 weeks

It might just be me, but I think it's universal - I need human contact other than my work friends at least every two weeks, and go somewhere other than home and work.  Otherwise something inside me starts to get distracted easily.  I have a need to talk about myself to friends, and listen to my friends; and doing so regularly keeps me from getting too antsy & feeing couped up.  I'm sure the rest of you experience some similar phenomenon, perhaps on a different timescale.  Tailor your routine to your own emotional needs!

And on a related note, even playing video games on weekends doesn't really keep me from feeling antsy - I really have to leave my normal environment and interact with other people.

9. Take evenings off most days

This is worse at a startup - the inertia of working 24x7, as well as anxiety (or being anxious and excited) can keep you glued to doing work for far too long.  I've found that if I take evenings off, I'm more likely to need less sleep, and less likely to get caught up in reading the news or getting distracted on IM.  Each evening, unless there's a problem, I'll take at least a few hours to enjoy the companionship of my girlfriend, pets, some TV, or a book - and just let my brain unwind and refresh.  I think you'll find your creativity improve, too.

10. Get 20 minutes of exercise in the morning, 3 times a week - but use that time!

I don't know about you, but I used to think exercise was a complete waste of time - but I knew it was important.  However, what I've found is that when I exercise regularly, I need less sleep - which is crucial in a startup!  I also bring along a great podcast I can listen to on an iPod.  Typically they're a perfect length - 30-40 minutes, and I can get in my exercise while I'm getting a new perspective on things.

I suggest:
Stanford Technology Ventures Podcasts (my favorite),  Ruby on Rails Envy (and other technical podcasts)

Bonus. Make/Use Better Tools

This isn't concrete enough to be an actual method (plus, 11 just isn't a good number), but I've found it incredibly valuable. 

The best time savers from a coding perspective for ThriveSmart is when we've made plugins out of repetitive code - or when we've found plugins for things we thought we'd have to do ourselves.   Take a look: can you write any tools that would automate parts of your life or drudge tasks?  Perhaps you can even outsource parts of your life, like in 4 hour workweek.  Just something to revisit every few months, to see if you can work smarter, instead of harder!

 

Generics 101

­          -- With generics, we can create type-safe collections where more problems are caught at compile-time instead of runtime

­          -- With generics, we are prevented at compile time from putting the wrong type of object into a container

­          -- Without generics, the compiler would let us put any type of object into a collection

­          -- There are three important places where generics are used

o        Creating instances of generified classes

new ArrayList<String>()

o        Declaring and assigning variables of generic types

List<String> names = new ArrayList<String>()

o        Declaring and invoking methods that take generic types

void foo(List<String> list) {

      //method code

}

x.foo(names)

­          -- The java documentation defines the ArrayList as

public class ArrayList<E> extends AbstractList<E>

implements List<E> {

            public boolean add(E o) {

                  //method code

            }

            //other ArrayList methods

}

­          -- In the above definition "E" represents the type used to create an instance of ArrayList

­          -- "E" is just a stand-in for the type of element we want this collection to hold and return

­          -- For instance, if we declare the ArrayList as

ArrayList<String> thisList = new ArrayList<String>();

­          -- The compiler interprets it as

public class ArrarList<String> extends AbstractList<String>

                                    implements List<String> {

      public Boolean add(String o) {

      }

}

­          -- In other words, the "E" is replaced by the real type that is used when the ArrayList is created

­          -- A generic class means that the class declaration includes a type parameter

­          -- A generic method means that the method declaration uses a type parameter in its signature

­          -- When you declare a type parameter for the class, you can simply use that type any place that you'd use a real class or interface type

public class MyClass<E> extends MySuperClass<E> {

      //in the following method declaration "E" simply

//represents the type parameter defined in the

//class declaration above

      public void myMethod(E o) {

}

}

­          -- We can also define a type parameter as part of method definition, even if the type parameter was defined in the class declaration

public <T extends Animal> void takeThing(ArrayList<T> list) {

}

­          -- In the above example, "T" used as the type for argument ArrayList is the type defined in the method signature

­          -- When we say "extends" in the above code, it really means "extends or implements"

­          -- In generics, the keyword "extends" really means is-a and works for both classes and interfaces

­          -- The type specified to the right of "extends" can either be a class or an interface

­          -- If the class itself doesn't use a type parameter, we can still specify one for a method, by declaring it before the return type

public void takeThing(ArrayList<Animal> list) {

}

­          -- The above code is really different from the earlier one

­          -- In the first case, the type can be "Animal" or any subclass of "Animal"

­          -- In the second case, the type has to be strictly "Animal", using a subclass of "Animal" will cause a compiler error

­          -- If the compiler does allow an ArrayList of subclass – say Cat, of Animal to be passed in the second case, then it will cause problems if we try to add a Dog object – another subclass of Animal, to the ArrayList passed as parameter

­          -- If the parameter were an array of "Animal" objects, then we can very well pass an array of "Cat" objects to the method

­          -- This is because Array types are checked again at runtime, but collection type checks happen only at compile time

­          -- Hence if we try to add a Dog object to a Cat Array passed as parameter, the compiler will throw a runtime error

­           

­          -- If we do need to make the method argument accept a subclass of the given type, we can use a wildcard

public void takeThing(ArrayList<? extends Animal> animals) {

}

­          -- Now we can very well pass an ArrayList of Cat to the method

­          -- But when we use a wildcard in the method argument, the compiler will not let us add any element to the list

­          -- We can call other methods on the argument but we can't add a new element to the ArrayList

public void takeThing(ArrayList<? extends Animal> animals) {

      for(Animal a : animals)

            a.eat();          à this works

      a.add(new Cat());       à this won't work

}

­          -- Using the wildcard is the same as using the following

public <T extends Animal> void takeThing(ArrayList<T> list) {

}

Wednesday, March 12, 2008

10 ways to improve your code

Neil Ford's Software Development West presentation, 10 Ways to Improve Your Code, was aimed at Java programmers, but Ford's "advanced code hygiene" discussion had wisdom for coders of many stripes.

Ford is a senior application architect and "meme wrangler" at ThoughtWorks, an IT consultant that specializes in development and delivery of software, and that is home to object-oriented development, refactoring and agile authority Martin Fowler. Ford's talk covered a lot of territory, from test-driven development to advice on "good citizenship."

Ford advised attendees to:

1. Write the tests before writing the code. TDD stands for "test-driven development," but Ford believes it's more useful to think of it as "test driven design." "If you're rigorous about doing it, it has beneficial side effects on the design of your code that has nothing to do with testing," he said. Among those benefits: it discourages embedded object creation, forces mocking of dependent objects, and forces the earliest possible object interaction decisions.

2. Use static analysis tools. "If you're paying the static-typing tax in Java and C# anyway, you should take advantage of that in static analysis tools," Ford said. He cited two categories of these tools: byte-code analysis tools, such as the FindBugs open source tool; and source-analysis tools, such as PMD.

3. Practice "good citizenship" by paying attention to how well your objects interact with the outside world. "Never let them exist in an invalid state," Ford advised. "Mutations should always move from one known good state to another known good state." He also advised you should avoid the singletons, because they mix responsibilities by mixing static and state.

4. Avoid indulging in speculative software development. "The goal should be to build the simplest thing we need right now," he said. The practice increases software entropy, he added, which is a measure of code complexity.

5. Simplify essential complexity and kill accidental complexity. "It's the difference between, 'the problem we have is hard,' and 'we've made the problem we have hard,'" he said.

6. Challenge programming conventions, such as writing long, unreadable test names, and blindly following the JavaBean specification to the detriment of your code.

7. Embrace single level of abstraction principle (SLAP). The idea is based on advice from Kent Beck's book Smalltalk Best Practices and Patterns, Ford explained, which states that every public method should be as short as possible, and should consist of steps, each one of which is a private method. "Don't make abstraction leaps in your code," he said.

8. Leverage existing platforms with languages targeted at specific problems and applications. "This notion that there's this one true language that you should write everything in is melting away," Ford said. Coders should think in terms of "polyglot programming," because it takes advantage of "looming opportunities/ problems," such as massively parallel threading.

9. Learn every nuance of the languages you're using. If you're using Java as your everyday language, Ford said, there are a lot of "back alleys" worth investigating. For example: Java's reflection mechanism and regular expressions, which are widely misunderstood.

10. Change your perspective and consider "antiobjects." An antiobject is a kind of object that appears to do the opposite of what we think it should do, Ford explained. The object metaphor sometimes impedes the solution "by making us try to create objects that are too inspired by the real world."®

(From: http://www.regdeveloper.co.uk/2008/03/10/ten_ways_to_improve_code/)

Data Structure Interview Questions

  • A list is ordered from smaller to largest when sort is called. Which sort would take longest time to execute?
  • A list is ordered from smaller to largest when sort is called. Which sort would take shortest time to execute?
  • Convert following infix _expression to post fix notation ((a+2)*(b+4)) -1 (Similar types can be asked)
  • Evaluate following prefix _expression ” ++ + - (Similar types can be asked)
  • Explain about types of linked lists
  • Explain binary searching, Fibinocci search.
  • Explain quick sort and merge sort algorithms and derive time-constraint relation for these.
  • How is it possible to insert different type of elements in stack?
  • How many different binary trees and binary search trees can be made from three nodes that contain key values 2 & 3?
  • How will inorder, preorder and postorder traversals print elements of tree?
  • How would you sort linked list?
  • In which data structure, elements can be added or removed at either end, but not in middle?
  • Parenthesis are never needed in prefix or postfix expressions. Why?
  • Stack can be described as pointer. Explain.
  • The element being searched for is not found in array of elements. What is average number of comparisons needed in sequential search to determine that element is not there, if elements are completely unordered?
  • What data structure would you mostly likely see in non recursive implementation of recursive algorithm?
  • What do you mean by Base case, Recursive case, Binding Time, Run-Time Stack and Tail Recursion?
  • What do you mean by: * Syntax Error * Logical Error * Runtime Error How can you correct these errors?
  • What does abstract data type means?
  • What is average number of comparisons in sequential search?
  • What is average number of comparisons needed in sequential search to determine position of element in array of elements, if elements are ordered from largest to smallest?
  • What is data structure?
  • What is maximum total number of nodes in tree that has N levels? Note that root is level (zero)
  • When will you sort array of pointers to list elements, rather than sorting elements themselves?
  • Which data structure is needed to convert infix notations to post fix notations?
  • Which one is faster? binary search of orderd set of elements in array or sequential search of elements.
  • Which sort show best average behavior?
  • Write Binary Search program
  • Write programs for Bubble Sort, Quick sort
  • Write programs for Linked List (Insertion and Deletion) operations
(http://www.sharpprogrammer.com/data-structures/data-structure-interview-questions/)

Tuesday, March 11, 2008

On-Demand JavaScript

When we load a lot of JavaScript code during initial page load, it can immensely slowdown the page display. The user will be staring at a blank page until all the JavaScript code gets downloaded and executed, which isn't going to exactly help your PR.
 
One workaround is to load the JS code in stages. This way it is possible to initially display a bare-bones page, and we keep building on it, as the JS modules pour in.
 
How to do this
 
Following is a DOM based approach, which appends a <script> tag to the <head> tag of the document. Now there are other methods to do this, which we will look into in later posts.
 
function getCode() {
  if (self.graphScript) { // Already exists
   return;
  }
  var head = document.getElementsByTagName("head")[0];
  script = document.createElement('script');
  script.id = 'graphScript';
  script.type = 'text/javascript';
  script.src = "dash.js";
  head.appendChild(script);
}
 
The code in this case is downloaded asynchronously, hence immediately using the script after loading it might not work. In most cases, using the script will actually fail the first time, because the download function will return before the script's been downloaded.
 
We can add a timeout function which periodically checks for the script load. Or if its your own code add a function call to the loading page at the end of the script being loaded, which tells the loading page that it has arrived safe and secure.