Wednesday, August 28, 2013

How to set value/values(single or multiple) for IN clause in a preparedStatement in JDBC while executing a query.


Suppose we have a table states with following fields

state_id
state_name
country_name

If we want to find the states of india and canada then we will use the prepareStatement as follows

PreparedStatement pstmt = connection.prepareStatement("Select * from states where country_name in (?,?)");
pstmt.setString(1,"india","canada");
result = pstmt.executeQuery();

If we know the number of values which we want to use within in clause then it is very simple as above.
But when we dont know the values which we want to use within in clause then?
when we dont have any idea about the number of values with in IN clause then we will use  prepareStatement as follows.

String queryString = "Select * from states ";

Suppose we have a list of country names(countryNames) which is coming at run time.

StringBuffer sb = new StringBuffer();
for(int i = 0;i<countryNames.size();i++){
sb.append("?,");
}

queryString = queryString + " where country_name IN("+sb.deleteCharAt( sb.length() -1 ).toString()+") ";

pstmt = con.prepareStatement(queryString);
int index = 1;
for( String country : countryNames ) {
   pstmt.setString(  index++, country ); // or whatever it applies
}
result = pstmt.executeQuery();

Thursday, August 1, 2013

class and interface typecasting gotcha!!


 Suppose there are two classes First and Second

 class First{

 }

 class Second{

 }

 class First and Second has no relation(inheritance) and If we write the following statement.

 First obj =  (First)new Second(); // will give error at compile time.

 As all know it will give compile time error.

 But If First(which is class in above case) would be an interface then what would happen?

 Interface First{

 }

 class Second{

 }

 Now If we write the following statement

 First objNew =  (First)new Second(); // will not give compile time error.

 This statement does not give us the compile time error.
 Why this happens in case of interface?

 Reason - In case of Interface there may be a situation that any subclass of Second implements the First interface.Thats why in java type casting of interface is allowed(Because compile is not sure at compile time).

 If we make the class Second final then compiler is sure at compile time that there can't be any subclass of Second the it will give compile time error

 interface First{

 }

 final class Second{

 }

 First objNewer =  (First)new Second(); // will give compile time error 

Thursday, March 14, 2013

What is String Pooling in Java?

When we create string literals jvm maintains all of them in pool known as String pooling.
 for exapmle,

    String str1 = "Hello"; //case 1
    String str2 = "Hello"; //case 2
   
    In case 1, iteral str1 is created newly and kept in the pool. But in case 2, literal str2 refer the str1, it will not create new one instead.
    
       if(str1 == str2) System.out.println("equal"); //Prints equal.
      
       // case 3
      String newString1 = new String("Hello");
      String newString2 = new String("Hello");
      if(newString1 == newString2) System.out.println("equlal"); //No output.
     
      Pooling is done for only string literals. In case 3 it gives no output because both string has a different reference.

Wednesday, March 6, 2013

What is Auto Boxing in Java?

Autoboxing is a new feature offered in the Java SDK 1.5 . In short auto boxing is a capability to convert or cast between object wrapper and it's primitive type.Previously when placing a primitive data into one of the Java Collection Framework we have to wrap it to an object because the collection cannot work with primitive data. Also when calling a method that requires an instance of object than an int or long, than we have to convert it too.

But now, starting from version 1.5 we were offered a new feature in the Java Language, which automate this process, this is call the Autoboxing. When we place an int value into a collection it will be converted into an Integer object behind the scene, on the other we can read the Integer value as an int type. In most way this simplify the way we code, no need to do an explisit object casting.

Here an example how it will look like using the Autoboxing feature:

Conversion of int into Integer and Integer into int

int inative = 0;

inative = new Integer(5); // auto-unboxing

Integer intObject = 5; // autoboxing

Monday, February 11, 2013

What is final class in java?

In Java, a class organization such as:

        class A {}

        class B extends A {}

results in a superclass (A) and a subclass (B). References to B objects may be assigned to A references, and if an A reference "really" refers to a B, then B's methods will be called in preference to A's. All of this is a standard part of the object-oriented programming paradigm offered by Java.

But there is a way to modify this type of organization, by declaring a class to be final. If I say:

        final class A {}

then that means that A cannot be further extended or subclassed.

This feature has a couple of big implications. One is that it allows control over a class, so that no one can subclass the class and possibly introduce anomalous behavior. For example, java.lang.String is a final class. This means, for example, that I can't subclass String and provide my own length() method that does something very different from returning the string length.

There is also a big performance issue with final classes. If a class is final, then all of its methods are implicitly final as well, that is, the method is guaranteed not be overridden in any subclass. A Java compiler may be able to inline a final method. For example, this program:

        final class A {
                private int type;
                public int getType() {return type;}
        }

        public class test {
                public static void main(String args[])
                {
                        int N = 5000000;
                        int i = N;
                        int t = 0;
                        A aref = new A();
                        while (i-- > 0)
                                t = aref.getType();
                }
        }

runs about twice as fast when the class is declared final.

Of course, much of the time it's desirable to use the superclass / subclass paradigm to the full, and not worry about wringing out the last bit of speed. But sometimes you have heavily used methods that you'd like to have expanded inline, and a final class is one way of achieving that.

Friday, February 8, 2013

What is abstract class in Java?

What is abstract class in Java?

There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. This is the case with the class Figure used in the preceding example. The definition of area( ) is simply a placeholder. It will not compute and display the area of any type of object.

As you will see as you create your own class libraries, it is not uncommon for a method to have no meaningful definition in the context of its superclass. You can handle this situation two ways. One way, as shown in the previous example, is to simply have it report a warning message. While this approach can be useful in certain situations—such as debugging—it is not usually appropriate. You may have methods which must be overridden by the subclass in order for the subclass to have any meaning. Consider the class Triangle. It has no meaning if area( ) is not defined. In this case, you want some way to ensure that a subclass does, indeed, override all necessary methods. Java's solution to this problem is the abstract method.

You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a subclass must override them—it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form:
abstract type name(parameter-list);

As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.
Here is a simple example of a class with an abstract method, followed by a class which implements that method:
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}

class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}

class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}

Notice that no objects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract class. One other point: class A implements a concrete method called callmetoo( ). This is perfectly acceptable. Abstract classes can include as much implementation as they see fit.

Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature put to use in the next example. Using an abstract class, you can improve the Figure class shown earlier. Since there is no meaningful concept of area for an undefined two-dimensional figure, the following version of the program declares area( ) as abstract inside Figure. This, of course, means that all classes derived from Figure must override area( ).
// Using abstract methods and classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}

class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}

class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}

As the comment inside main( ) indicates, it is no longer possible to declare objects of type Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To prove this to yourself, try creating a subclass that does not override area( ). You will receive a compile-time error.

Although it is not possible to create an object of type Figure, you can create a reference variable of type Figure. The variable figref is declared as a reference to Figure, which means that it can be used to refer to an object of any class derived from Figure. As explained, it is through superclass reference variables that overridden methods are resolved at run time.

Wednesday, February 6, 2013

Access Modifiers in Java



Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

 Visible to the package. the default. No modifiers are needed.

 Visible to the class only (private).

 Visible to the world (public).

 Visible to the package and all subclasses (protected).
               
Default Access Modifier - No keyword:

Default Access Modifier - No keyword:

Default access modifier means we do not explicitly declare an access modifier for a class, field, method etc.
A variable or method declared without any access control modifier is available to any other class in the same package. The default modifier cannot be used for methods, fields in an interface.

Example:

Variables and methods can be declared without any modifiers, as in the following examples:
String version = "1.5.1";

boolean processOrder() {
   return true;
}

Private Access Modifier - private:

Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world.

Example:

The following class uses private access control:
public class Logger {
   private String format;
   public String getFormat() {
      return this.format;
   }
   public void setFormat(String format) {
      this.format = format;
   }
}
Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly.
So to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.

Public Access Modifier - public:

A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Example:

The following function uses public access control:
public static void main(String[] arguments) {
   // ...
}
The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.

Protected Access Modifier - protected:

Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Example:

The following parent class uses protected access control, to allow its child class override openSpeaker() method:
class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}
 
class StreamingAudioPlayer {
   boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}
Here if we define openSpeaker() method as private then it would not be accessible from any other class other than AudioPlayer. If we define it as public then it would become accessible to all the outside world. But our intension is to expose this method to its subclass only, thats why we used protected modifier.

Access Control and Inheritance:

The following rules for inherited methods are enforced:
·         Methods declared public in a superclass also must be public in all subclasses.
·         Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
·         Methods declared without access control (no modifier was used) can be declared more private in subclasses.
·         Methods declared private are not inherited at all, so there is no rule for them.



Monday, February 4, 2013

what is final keyword in java?

When you use the keyword ‘final’ with a variable declaration, the value stored inside that variable cannot be changed come what may!!

So suppose you do this :

final int i =10;

After this, nowhere in your code can you change the value of ‘i’ i.e. ‘i’ will always have a value ’10' .

So i = 11; //will give you a compile time error.

Now, suppose you did not initialize the final integer ‘i’ while declaring it.

final int i;

Can you assign any value to this variable now?

Yes, you definitely can. But only once!

So,

final int i;

i = 10; //This is fine

i = 11; //Compiler error

Now that was the core stuff about ‘final’ . Let’s learn a bit more in detail about it.

The ‘final’ keyword can be used for a class declaration or method declaration.

What happens when you use ‘final’ for a class declaration?

A: You cannot have a sub class of a class declared final i.e. No other class can extend this class.

What happens when you declare a method as final?

A: Simply put, the method cannot be overridden.

Can you override a method(Not declared as ‘final’) present inside a final class?

A: Obviously Not. Since there’s no way to extend a class declared final there’s no way of overriding its methods!

What happens when I declare a method inside a class as both ‘private’ and ‘final’ ?

A: Making a class both ‘private’ and ‘final’ makes the ‘final’ keyword redundant as a private method cannot be accessed in its sub class. But hey, you’ll be able to declare a method of the same name as in the base class if the method has been made private in the base class. But then that doesn’t mean you’re overriding the method. You’re simply declaring a new method in the sub class.

Note: You cannot make an ‘abstract’ class or method as ‘final’ because an ‘abstract’ class needs to be extended which will not be possible if you mark it as ‘final’!

What is static keyword in java?

static variable

    It is a variable which belongs to the class. 
    Static variables are initialized only once , at the start of the execution .
   These variables will be initialized first, before the initialization of any instance variables
    A single copy of static variable is shared  by all instances of the class
    A static variable can be accessed directly by the class name and does not  need any object
    Syntax : ClassName.StaticVariableName
  
   static method

    It is a method which belongs to the class and not to the object(instance)
    A static method can access only static data. It can not access non-static data (instance variables)
    A static method can call only other static methods and can not call a non-static method from it.
    A static method can be accessed directly by the class name and doesn’t need any object
    Syntax : ClassName.StaticMethodName
    A static method cannot refer to “this” or “super” keywords in anyway

    Side Note:

    main method is static , since it must be be accessible for an application to run , before any instantiation takes place.

static block

The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM
   
class Test{
 static {
 //Code goes here
 }
}

A static block helps to initialize the static data members, just like constructors help to initialize instance members


Friday, February 1, 2013

What is jvm.dll,java.exe and javaw.exe?

jvm.dll is the actual Windows implementation of the JVM (or better, the main entry point). C or C++ applications can use this DLL to run an embedded Java runtime, and that would allow the application to interface directly with the JVM, e.g. if they want to use Java for its GUI.

    java.exe is a wrapper around the DLL so that people can actually run Java classes without the need for a custom launcher application. It is a Win32 Console application, so Windows will open a fresh Command Prompt window if the exe is not run from a batch file.

    javaw.exe is a wrapper like java.exe, but it is a Win32 GUI application. Windows doesn't have to open a Command Prompt window, which is exactly what you want to run a GUI application which opens its own windows.

Why main method in java is static?

This is just convention. In fact, even the name main(), and the arguments passed in are purely convention.

When you run java.exe (or javaw.exe on Windows), what is really happening is a couple of Java Native Interface (JNI) calls. These calls load the DLL that is really the JVM (that's right - java.exe is NOT the JVM). JNI is the tool that we use when we have to bridge between the virtual machine world, and the world of C, C++, etc... The reverse is also true - it is not possible  to actually get a JVM running without using JNI.

Basically, java.exe is a super simple C application that parses the command line, creates a new String array in the JVM to hold those arguments, parses out the class name that you specified as containing main(), uses JNI calls to find the main() method itself, then invokes the main() method, passing in the newly created string array as a parameter. This is very, very much like what you do when you use reflection from Java - it just uses confusingly named native function calls instead.

It would be perfectly legal for you to write your own version of java.exe (the source is distributed with the JDK), and have it do something entirely different. In fact, that's exactly what we do with all of our Java based apps.

Each of our Java apps has its own launcher. We primarily do this so we get our own icon and process name, but it has come in handy in other situations where we want to do something besides the regular main() call to get things going (For example, in one case we are doing COM interoperability, and we actually pass a COM handle into main() instead of a string array).

So, long and short: the reason it is static is b/c that's convenient. The reason it's called 'main' is because it had to be something, and main() is what they did in the old days of C (and in those days, the name of the function was important). I suppose that java.exe could have allowed you to just specify a fully qualified main method name, instead of just the class (java com.myompany.Foo.someSpecialMain) - but that just makes it harder on IDEs to auto-detect the 'launchable' classes in a project.

Tuesday, January 29, 2013

Difference between JVM , JRE and JIT

Java Virtual Machine (JVM) is an abstract computing machine. Java Runtime Environment (JRE) is an implementation of the JVM. Java Development Kit (JDK) contains JRE along with various development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools.

JVM becomes an instance of JRE at runtime of a java program. It is widely known as a runtime interpreter. The Java virtual machine (JVM) is the cornerstone on top of which the Java technology is built upon. It is the component of the Java technology responsible for its hardware and platform independence. JVM largely helps in the abstraction of inner implementation from the programmers who make use of libraries for their programmes from JDK.

Like a real computing machine, JVM has an instruction set and manipulates various memory areas at run time. Thus for different hardware platforms one has corresponding implementation of JVM available as vendor supplied JREs. It is common to implement a programming language using a virtual machine. Historicaly the best-known virtual machine may be the P-Code machine of UCSD Pascal.

A Java virtual machine instruction consists of an opcode specifying the operation to be performed, followed by zero or more operands embodying values to be operated upon. From the point of view of a compiler, the Java Virtual Machine (JVM)is just another processor with an instruction set, Java bytecode, for which code can be generated. Life cycle is as follows, source code to byte code to be interpreted by the JRE and gets converted to the platform specific executable ones.

Sun’s JVM

Sun’s implementations of the Java virtual machine (JVM) is itself called as JRE. Sun’s JRE is availabe as a separate application and also available as part of JDK. Sun’s Java Development Tool Kit (JDK) comes with utility tools for byte code compilation “javac”. Then execution of the byte codes through java programmes using “java” and many more utilities found in the binary directory of JDK. ‘java’ tools forks the JRE. Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.
JVM for other languages

A JVM can also be used to implement programming languages other than Java. For example, Ada source code can be compiled to Java bytecode, which may then be executed by a Java virtual machine (JVM). That is, any language with functionality that can be expressed in terms of a valid class file can be hosted by the Java virtual machine (JVM). Attracted by a generally available, machine-independent platform, implementors of other languages are turning to the Java virtual machine (JVM) as a delivery vehicle for their languages. PHP with Quercus is such an example.
Just-in-time Compiler (JIT)

JIT is the part of the Java Virtual Machine (JVM) that is used to speed up the execution time. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Sunday, January 27, 2013

What is Java Virtual Machine?


The Java Virtual Machine (JVM) is a real name dropper when you’re programming in Java. When your Java project builds, it translates the source code (contained in *.java source files) to Java bytecode (most often contained in *.class files). This takes your high-level code one step closer to machine code, but not quite there yet. This bytecode is a collection of compact instructions; easier for a machine to interpret, but less readable.
When you run a Java application on your computer, cellphone, or any other Java-enabled platform, you essentially pass this Java bytecode to the Java Virtual Machine. The interpreter in the Java Virtual Machine usually starts compiling the entire bytecode at runtime, following the principles of so-called just-in-time compilation. This makes for the typical, albeit often slight delay when opening a Java application, but generally enhances the program performance compared to interpreted compilation. The main advantage of this system is the increased compatibility. Since your applications run in a virtual machine instead of directly on your hardware, the developer can program and build their application once, which can then be executed on every device with an implementation of the Java Virtual Machine. This principle has given birth to the Java slogan: “Write once, run everywhere.”


Tuesday, January 22, 2013

Why Java is called secure

There are two things that make Java "more secure" than other language in certain aspects:

    Automatic array bounds checking and the lack of manual memory management make certain classes of programming mistakes that often cause serious security holes (such as buffer overruns) impossible. Most other modern languages share this feature, but C and C++, which were dominant (and still are major) application development languages at the time Java first appeared, do not.
   
    The Security Manager concept makes it relatively easy to run Java applications in a "sandbox" that prevents them from doing any harm to the system they are running on. This played an important part in promoting Java during its early days, since Applets were envisioned as a ubiquitous, safe way to have client-side web applications.

    In addition, the Java language defines different access modifiers that can be assigned to Java classes, methods, and fields, enabling developers to restrict access to their class implementations as appropriate. Specifically, the language defines four distinct access levels: private, protected, public, and, if unspecified, package. The most open access specifier is public access is allowed to anyone. The most restrictive modifier is private access is not allowed outside the particular class in which the private member (a method, for example) is defined. The protected modifier allows access to any subclass, or to other classes within the same package. Package-level access only allows access to classes within the same package.

    A compiler translates Java programs into a machine-independent bytecode representation. A bytecode verifier is invoked to ensure that only legitimate bytecodes are executed in the Java runtime. It checks that the bytecodes conform to the Java Language Specification and do not violate Java language rules or namespace restrictions. The verifier also checks for memory management violations, stack underflows or overflows, and illegal data typecasts. Once bytecodes have been verified, the Java runtime prepares them for execution.

Monday, January 21, 2013

How Garbage Collection works in Java

1) objects are created on heap in Java  irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of command line tuning.

Friday, January 18, 2013

Why Java is called Portable?

Portability isn't a black and white, yes or no kind of thing. Portability is how easily one can I take a program and run it on all of the platforms one cares about.

There are a few things that affect this. One is the language itself. The Java language spec generally leaves much less up to "the implementation". For example, "i = i++" is undefined in C and C++, but has a defined meaning in Java. More practically speaking, types like "int" have a specific size in Java (eg: int is always 32-bits), while in C and C++ the size varies depending on platform and compiler. These differences alone don't prevent you from writing portable code in C and C++, but you need to be a lot more diligent.

Finally, there's the whole question of whether you can just take an executable and drop it on the other platform and have it work there. This generally works with Java, assuming there's a JVM for the target platform. (and there are JVMs for many/most platforms people care about) This is generally not true with C and C++. You're typically going to at least need a recompile, and that's assuming you've already taken care of the previous two points.

Why did they decide to call it Java?

Sun Microsystems' chief Scott McNealy will tell you at the drop of a hat that "Java is probably a bigger brand name than Sun itself." And, of course, he is right. When Time magazine called Java one of the Ten Best Products of 1995 (the only computer-related entry on the list), a new American marketing legend was born. Who's to say whether Sun's prized technology would have fared so well if its name had remained "Oak" or "Greentalk"?

We all know the story: Give away an elegant, open programming environment and the world will beat a path to your door. No sweat, no matter what you decide to call it. The people charged with establishing a brand identity for Sun's lingua franca for next-generation application developers, though, decided upon a coffee metaphor for their trademark. Oak, the previous name, was taken. Why they did so, by their own accounts, is still something of a mystery.

To find out the true story behind the Java name, JavaWorld interviewed several of the key people at Sun involved in the naming process. Their accounts appear below. Feel free to draw your own conclusions.
Brainstorming a trademark -- seven perspectives

"The lawyers had told us that we couldn't use the name 'OAK' because [it was already trademarked by] Oak Technologies," said Frank Yellin, a senior engineer at Sun. "So a brainstorming session was held to come up with ideas for a new name. The session was attended by all members of what was then called the Live Oak group, those of us actively working on the new language. The end result was that about ten possible names were chosen. They were then submitted to the legal department. Three of them came back clean: Java, DNA, and Silk. No one remembers who first came up with the name 'Java.' Only one person, to the best of my knowledge, has ever suggested in public to being the creator of the name."

Frank Yellin's complete remarks

"I named Java," said Kim Polese, then the Oak product manager and now CEO of Marimba Inc. "I spent a lot of time and energy on naming Java because I wanted to get precisely the right name. I wanted something that reflected the essence of the technology: dynamic, revolutionary, lively, fun. Because this programming language was so unique, I was determined to avoid nerdy names. I also didn't want anything with 'Net' or 'Web' in it, because I find those names very forgettable. I wanted something that was cool, unique, and easy to spell and fun to say.

"I gathered the team together in a room, wrote up on the whiteboard words like 'dynamic,' 'alive,' 'jolt,' 'impact,' 'revolutionary,' et cetera, and led the group in brainstorming," Polese said. "The name [Java] emerged during that session. Other names included DNA, Silk, Ruby, and WRL, for WebRunner Language -- yuck!"

Kim Polese's complete remarks.

"I believe the [brainstorming] meeting was held around January of 1995," said Sami Shaio, a Sun engineer at the time, who has since become a founding partner of Marimba. "It's actually hard to say where 'Java' first came from, but it ended up on the list of candidates we chose ... along with Silk, Lyric, Pepper, NetProse, Neon, and a host of others too embarrassing to mention."

Sami Shaio's complete remarks.

"Some other candidates were WebDancer and WebSpinner," said Chris Warth, an engineer on the project from its inception and currently a consultant at JavaSoft. "Although marketing wanted a name that implied an association with the Web or the Net, I think we did very well to pick a name that wasn't associated with either one. Java is likely to find a true home in applications far from the Internet, so it's best that it wasn't pigeonholed early."

Chris Warth's complete remarks.

"The name 'Java' originated in a meeting where about a dozen people got together to brainstorm," said James Gosling, a vice president and fellow of Sun, and the author of Oak. "The meeting, arranged by Kim Polese, was fundamentally continuous wild craziness. Lots of people just yelled out words. Who yelled out what first is unknowable and unimportant. It felt like half of the words in the dictionary were yelled out at one time or another. There was a lot of: 'I like this because...' and 'I don't like that because...' And in the end we whittled it down to a list of about a dozen names and handed it off to the lawyers."

James Gosling's complete remarks.

"We were really disgusted and tired from all the marathon hacking we'd been doing at the time, and we still hadn't found a name that we could use," said Sun engineer Timothy Lindholm. "We were pressed for time, as adopting a new name meant a lot of work, and we had releases coming up. So we set up a meeting to thrash out a list of names.... The meeting went on for quite a while, and I remember there wasn't anything that jumped out as obviously the right thing to do. We were talking in despair about dumb names like Rover. We ended up with a final list, and Java was one of the top choices along with Silk, as in what you spin webs with. I do not remember there being a particular champion of Java.... Among the people of the original group that I've talked to about this, most deny any memory of Java being anything but something that bubbled out of the group dynamic."

Timothy Lindholm's complete remarks.

"I believe the name was first suggested by Chris Warth," said Arthur van Hoff, a senior engineer on the project and now CTO of Marimba Inc. "We had been in the meeting for hours and, while he was drinking a cup of Peet's Java, he picked 'Java' as an example of yet another name that would never work. The initial reaction was mixed. I believe the final candidates were Silk, DNA, and Java, however. I suggested Lingua Java, but that didn't make it.... We could not trademark the other names, so Java ended up being the name of choice. In the end, our marketing person, Kim Polese, finally decided to go ahead with it."

Arthur van Hoff's complete remarks.
Deciding to go for coffee

"I test-marketed the names at parties, and on my friends and family members," Polese recalled. "And Java got the most positive reactions of all the candidates. Because it wasn't certain that we would get any of the names cleared through trademark, I selected about three or four and worked with the lawyers on clearing them. Java passed, and it was my favorite, so I named the language Java and subsequently named the browser HotJava, a much better name than WebRunner. The engineers had a hard time parting with Oak, but they finally got used to it.... I felt that branding was very important, because I wanted Java to be a standard. So I focused on building a very strong brand for Java."
"We held a final meeting to vote on the name," said Yellin. "Every person got to rank Java, DNA, and Silk in order of their preference. The same name that got the most 'most-favorite votes' also got the most 'least-favorite' votes. So it was dropped. And of the remaining two, Java got the most votes. So it became the preferred name."

"It came down to Silk or Java, and Java won out," Shaio remembered. "James Gosling seemed to favor Java over Silk. Kim Polese had the final say over the name, since she was the product manager. But most decisions back then were done by everyone kind of agreeing, and then someone would just say, 'OK, this is what we're doing.'"

"I can tell you precisely about the decision to choose the name," said Eric Schmidt, Sun's chief technology officer. "We met in early 1995 at 100 Hamilton in one of our standard operating reviews for little businesses like Oak. Bert Sutherland was the senior manager at the time -- he worked for me -- and he and Kim and a few others including James were there. Kim presented that: one, we had to choose a new name now, and two, Oak -- which we were all used to -- was taken. As I recall, she proposed two names, Java and Silk. Of the two, she strongly preferred Java and represented that the [Live Oak] team was in agreement. Bert and I decided to approve her recommendation, and the decision was made. For those reasons I believe it is correct to give Kim the credit for the name. She presented it and sold it, and then made it happen in marketing."

Eric Schmidt's complete remarks.

"I do seem to recall that Kim [Polese] was initially lukewarm on the name 'Java,'" recalled Warth. "At the time we were also trying to rename our browser from WebRunner -- which had been already taken by Taligent -- to something that wasn't already trademarked. Kim wanted things like WebSpinner or even WebDancer, something that would make it clear that this was a World Wide Web product. The trademark search was done, and after several weeks a short list of cleared names came back.... There seemed to be an endless series of meetings and approvals that were necessary -- as if the name were actually meaningful.

"At the time Kim wanted us to hold up the release so we could find a better name than Java, but she was overruled by the engineers, especially James and Arthur [van Hoff] and myself," Warth said. "At one point James said we were going to go with Java and HotJava, and Kim sent some e-mail asking us to wait for other names that might clear. James wrote back and said 'no,' we were going with what we had. And we just did a very quick set of renames in the source code and put the release out.... In the end, I think the marketeers and vice presidents had far less to say about the name than the engineers who were dying to get something out the door."

"I think Kim is rewriting history a bit when she suggests that she picked this name for some savvy marketing reason," Warth said. "We ended up with this name because we ran out of options and we wanted to get our product out. The marketing justifications came later."

"If Arthur's recollections are accurate (and I have no reason to doubt them) then Chris named the language Java," said Bob Weisblatt, the Java group's self-described "technical writer and margarita master" who now works at Active Software. "I don't remember who first yelled out the name Java -- Chris always had a cup of coffee handy so it makes sense that he'd be the one. Of one thing I am certain: Kim did not name the language Java."

Incidentally, Warth noted that Java was actually the third name for the language. "When we were working on the Green project, James first called it "Greentalk" and the file extension was ".gt"," Warth said. "Then it became "Oak" for several years and only relatively recently was it called "Java."
Sleepless in Palo Alto

"I don't claim to be the one who first suggested the name," said Warth when questioned about van Hoff's statement. "It definitely was Peet's Java [we were drinking], but it might have been me or James [Gosling] or someone else. I just don't recall exactly who said it.

"The feeling amongst myself and James and the other engineers was that we could call it 'xyzzy' and it would still be popular," Warth added. "In the end it doesn't matter who originally suggested the name, because it ultimately was a group decision -- perhaps helped along by a handful of caffeinated people."

"I think that the extent to which the people involved have considered the history of Java's name without arriving at any generally agreed-upon resolution shows that the naming of Java was not done by some heroic individual, but was a by-product of a creative and driven group trying very hard to achieve their goals, of which this name was a part," concluded Lindholm. "I would encourage you not to strive beyond what is reasonable in ascribing the naming of Java to an individual. That is simply not the way things worked in those days. Don't be fooled by how individuals and the media have subsequently filtered many elements of Java's creation to fit their own ends."

Why Java is called Distributed?

Java's pretty solid in this respect. Support for TCP, UDP, and basic Socket communication is excellent and getting better. The class libraries allov IPv6 to be plugged in easily. A varioty of high-level abstractions for network communication and distributed processing are available including applets, servlets, aglets, remote method invocation (RMI), and more. The only missing piece is raw IP or ICMP.

Distributed computing and Java go together naturally. As the first language designed from the bottom up with networking in mind, Java makes it very easy for computers to cooperate. Even the simplest applet running in a browser is a distributed application, if you think about it. The client running the browser downloads and executes code that is delivered by some other system. But even this simple applet wouldn't be possible without Java's guarantees of portability and security: the applet can run on any platform, and can't sabotage its host.

Of course, when we think of distributed computing, we usually think of applications more complex than a client and server communicating with the same protocol. We usually think in terms of programs that make remote procedure calls, access remote databases, and collaborate with others to produce a single result. Java Distributed Computing discusses how to design and write such applications. It covers Java's RMI (Remote Method Invocation) facility and CORBA, but it doesn't stop there; it tells you how to design your own protocols to build message passing systems and discusses how to use Java's security facilities, how to write multithreaded servers, and more. It pays special attention to distributed data systems, collaboration, and applications that have high bandwidth requirements.

In the future, distributed computing can only become more important.Java Distributed Computing provides a broad introduction to the problems you'll face and the solutions you'll find as you write distributed computing applications.

Why java is called robust?

Robust means reliable and no programming language can really assure reliability. Java puts a lot of emphasis on early checking for possible errors, as Java compilers are able to detect many problems that would first show up during execution time in other languages.

Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.

 Java example of "robust" code:

if (var == true) {
    ...
} else if (var == false) {
    ...
} else {
    ...
}

 "robust code" means that your program takes into account all possibilities, and that there is no such thing as an error - all situations are handled by the code and result in valid state, hence the "else".

I am doubtful, however. If the variable is a boolean, what is the point of checking a third state when a third state is logically impossible?

"Having no such thing as an error" seems ridiculous as well; even Google applications show errors directly to the user instead of swallowing them up silently or somehow considering them as valid state. And it's good - I like knowing when something goes wrong. And it seems quite the claim to say an application would never have any errors.

Thursday, January 17, 2013

Why Java is Plateform Independent

Typically, the compiled code is the exact set of instructions the CPU requires to "execute" the program. In Java, the compiled code is an exact set of instructions for a "virtual CPU" which is required to work the same on every physical machine.

So, in a sense, the designers of the Java language decided that the language and the compiled code was going to be platform independent, but since the code eventually has to run on a physical platform, they opted to put all the platform dependent code in the JVM.

This requirement for a JVM is in contrast to your Turbo C example. With Turbo C, the compiler will produce platform dependent code, and there is no need for a JVM work-alike because the compiled Turbo C program can be executed by the CPU directly.

With Java, the CPU executes the JVM, which is platform dependent. This running JVM then executes the Java bytecode which is platform independent, provided that you have a JVM availble for it to execute upon. You might say that writing Java code, you don't program for the code to be executed on the physical machine, you write the code to be executed on the Java Virtual Machine.

The only way that all this Java bytecode works on all Java virtual machines is that a rather strict standard has been written for how Java virtual machines work. This means that no matter what physical platform you are using, the part where the Java bytecode interfaces with the JVM is guaranteed to work only one way. Since all the JVMs work exactly the same, the same code works exactly the same everywhere without recompiling. If you can't pass the tests to make sure it's the same, you're not allowed to call your virtual machine a "Java virtual machine".

Of course, there are ways that you can break the portability of a Java program. You could write a program that looks for files only found on one operating system (cmd.exe for example). You could use JNI, which effectively allows you to put compiled C or C++ code into a class. You could use conventions that only work for a certain operating system (like assuming ":" separates directories). But you are guaranteed to never have to recompile your program for a different machine unless you're doing something really special (like JNI).

The virtual machine is not independent, you have to install one that is specifically made for your type of system. The virtual machine creates an independent platform on top of the operating system.

In case of C or C++(language that are not platform indepedent) compiler generate the .exe file that is OS depedent so when we run this .exe file on another OS it will not run because this file is OS depedent so is not compatible with the another OS.

With Java, you can compile source code on Windows and the compiled code (bytecode to be precise) can be executed (interpreted) on any platform running a JVM. So yes you need a JVM but the JVM can run any compiled code, the compiled code is platform independent.

Like, for example, we need to have Turbo C Compiler in order to compile C/C++ source code and then execute it.. The machine has to have the C compiler.

The machine doesn't have to have a C compiler, the machine has to use a platform specific binary. With C or C++, the compiled code is specific to each architecture, it is platform independent.

In other words, with C / C++ you have portability of source code (with some discipline) but not portability of compiled code: you need to recompile for each architecture into platform specific binaries.

Wednesday, January 16, 2013

Objects in Java:

Objects in Java:

As the name object-oriented implies, objects are key to understanding object-oriented technology. You can look around you now and see many examples of real-world objects: your dog, your desk, your television set, your bicycle. 
 These real-world objects share two characteristics: they all have state and they all have behavior. For example, dogs have state (name, color, breed, hungry) and dogs have behavior (barking, fetching, and slobbering on your newly cleaned slacks). Bicycles have state (current gear, current pedal cadence, two wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears).