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).