What is differences between JVM, JDK, JRE

Java Development Kit (JDK)

The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.

Java Runtime Environment (JRE)

The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which deploys standalone applications over a network. It is also the foundation for the technologies in the Java 2 Platform, Enterprise Edition (J2EE) for enterprise software development and deployment. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.

Java Virtual Machine

The Java Virtual Machine is responsible for the hardware- and operating system-independence of the Java SE platform, the small size of compiled code (bytecodes), and platform security.










Reference : Oracle


Does Java Use Pass-By-Value Semantics?

If Java passes objects by passing the reference variable instead, does that mean Java uses pass-by-reference for objects? Not exactly, although you’ll often hear and read that it does. Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-of-the-variable! (There’s that word copy again!)

It makes no difference if you’re passing primitive or reference variables, you are always passing a copy of the bits in the variable. So for a primitive variable, you’re passing a copy of the bits representing the value. For example, if you pass an int variable with the value of 3, you’re passing a copy of the bits representing 3. The called method then gets its own copy of the value, to do with it what it likes.

And if you’re passing an object reference variable, you’re passing a copy of the bits representing the reference to an object. The called method then gets its own copy of the reference variable, to do with it what it likes. But because two identical reference variables refer to the exact same object, if the called method modifies the object (by invoking setter methods, for example), the caller will see that the object the caller’s original variable refers to has also been changed.

The bottom line on pass-by-value: the called method can’t change the caller’s variable, although for object reference variables, the called method can change the object the variable referred to. What’s the difference between changing the variable and changing the object? For object references, it means the called method can’t reassign the caller’s original reference variable and make it refer to a different object, or null. For example, in the following code fragment,
                          void bar() {
                                Foo f = new Foo();
                           void doStuff(Foo g) {
                                 g = new Foo();
reassigning g does not reassign f! At the end of the bar() method, two Foo objects have been created, one referenced by the local variable f and one referenced by the local (argument) variable g. Because the doStuff() method has a copy of the reference variable, it has a way to get to the original Foo object, for instance to call the setName() method. But, the doStuff() method does not have a way to get to the f reference variable. So doStuff() can change values within the object f refers to, but doStuff() can’t change the actual contents (bit pattern) of f. In other words, doStuff() can change the state of the object that f refers to, but it can’t make f refer to a different object! 

Latest News

Java 8

Java SE 8 Developer preview
Java SE 8 Early Access is provided to the community so that they can get feedback on the ongoing progress of the project. Download it at http://jdk8.java.net/download.html. Please try it out and report bugs

NetBeans IDE 7.3 Released

NetBeans IDE 7.3 empowers developers to create and debug rich web and mobile applications using the latest HTML5, JavaScript, and CSS3 standards. Developers can expect state of the art rich web development experience with a page inspector and CSS style editor, completely revamped JavaScript editor, new JavaScript debugger, and more. Additional highlights available in 7.3 include continued enhancements to the IDE’s support for Groovy, PHP, JavaFX and C/C++.

Generic Types – III

Generic Declarations

For example, this is the API declaration for the java.util.List interface:
public interface List<E>
The <E> is a placeholder for the type you pass in. The List interface is behaving as a generic “template” (sort of like C++ templates), and when you write your code, you change it from a generic List to a List<Dog> or List<Integer>, and so on.The E, by the way, is only a convention. Any valid Java identifier would work here, but E stands for “Element,” and it’s used when the template is a collection. The other main convention is T (stands for “type”), used for, well, things that are NOT collections.

Now that you’ve seen the interface declaration for List, what do you think the add() method looks like?
boolean add(E o)
In other words, whatever E is when you declare the List, that’s what you can add to it . So imagine this code:
                 List<Animal> list = new ArrayList<Animal>();

The E in the List API suddenly has its waveform collapsed, and goes from the abstract <your type goes here>, to a List of Animals. And if it’s a List of Animals, then the add() method of List must obviously behave like this:
                   boolean add(Animal a)

Making Your Own Generic Class

Here’s simple class that uses the parameterized type of the class in several ways:
                        public class TestGenerics<T> { // as the class type
                                          T anInstance; // as an instance variable type
                                          T [] anArrayOfTs; // as an array type
                              TestGenerics(T anInstance) { // as an argument type
                                          this.anInstance = anInstance;
                            T getT() { // as a return type
                               return anInstance;

You can use more than one parameterized type in a single class definition:
                    public class UseTwo<T, X> {
                           T one;
                           X two;
                           UseTwo(T one, X two) {
                                        this.one = one;
                                        this.two = two;
                           T getT() { return one; }
                           X getX() { return two; }

                     // test it by creating it with <String, Integer>
                           public static void main (String[] args) {
                                      UseTwo<String, Integer> twos = new UseTwo<String, Integer>(“foo”, 42);
                                      String theT = twos.getT(); // returns a String
                                      int theX = twos.getX(); // returns Integer, unboxes to int



Creating Generic Methods

Using a generic method, we can declare the method without a specific type and then get the type information based on the type of the object passed to the method. For example:
                          import java.util.*;
                          public class CreateAnArrayList {
                                     public <T> void makeArrayList(T t) { // take an object of an
                                                                                              // unknown type and use a
                                                                                              // “T” to represent the type
                                    List<T> list = new ArrayList<T>(); // now we can create the
                                                                                             // list using “T”

In the preceding code, if you invoke the makeArrayList() method with a Dog instance, the method will behave as though it looked like this all along:
                           public void makeArrayList(Dog t) {
                                      List<Dog> list = new ArrayList<Dog>();

The strangest thing about generic methods is that you must declare the type variable BEFORE the return type of the method:
                       public <T> void makeArrayList(T t)
The <T> before void simply defines what T is before you use it as a type in the argument. You MUST declare the type like that unless the type is specified for the class.

You’re also free to put boundaries on the type you declare, for example, if you want to restrict the makeArrayList() method to only Number or its subtypes (Integer, Float, and so on) you would say
                         public <T extends Number> void makeArrayList(T t)

If you REALLY want to get ridiculous, you can declare a class with a name that is the same as the type parameter placeholder:
                           class X { public <X> X(X x) { } }
Yes, this works. The X that is the constructor name has no relationship to the <X> type declaration, which has no relationship to the constructor argument identifier, which is also, of course, X. The compiler is able to parse this and treat each of the different uses of X independently. So there is no naming conflict between class names, type parameter placeholders, and variable identifiers.

Generic Types – II

Polymorphism and Generics

There’s a very simple rule here—the type of the variable declaration must match the type you pass to the actual object type. If you declare List<Foo> foo then whatever you assign to the foo reference MUST be of the generic type <Foo>. Not a subtype of <Foo>. Not a supertype of <Foo>. Just <Foo>. These are wrong:
                       List<Object> myList = new ArrayList<JButton>(); // NO!
                       List<Number> numbers = new ArrayList<Integer>(); // NO!
                       // remember that Integer is a subtype of Number
But these are fine:
                      List<JButton> myList = new ArrayList<JButton>(); // yes
                      List<Object> myList = new ArrayList<Object>(); // yes
                      List<Integer> myList = new ArrayList<Integer>(); // yes

So far so good. Just keep the generic type of the reference and the generic type of the object to which it refers identical. In other words, polymorphism applies here to only the “base” type. And by “base,” we mean the type of the collection class itself—the class that can be customized with a type. In this code,
                                  List<JButton> myList = new ArrayList<JButton>();
List and ArrayList are the base type and JButton is the generic type. So an ArrayList can be assigned to a List, but a collection of <JButton> cannot be assigned to a reference of <Object>, even though JButton is a subtype of Object.

Generic Methods

One of the biggest benefits of polymorphism is that you can declare, say, a method argument of a particular type and at runtime be able to have that argument refer to any subtype-including those you’d never known about at the time you wrote the method with the supertype argument.

For example, imagine a classic (simplified) polymorphism example of a veterinarian (AnimalDoctor) class with a method checkup(). And right now, you have three Animal subtypes—Dog, Cat, and Bird—each implementing the abstract checkup() method from Animal.

imagine what the AnimalDoctor class needs to look like in order to have code that takes any kind of Animal and invokes the Animal checkup() method. Trying to overload the AnimalDoctor class with checkup() methods for every possible kind of animal is ridiculous, and obviously not extensible. You’d have to change the AnimalDoctor class every time someone added a new subtype of Animal. So in the AnimalDoctor class, you’d probably have a polymorphic method:

                         public void checkAnimal(Animal a) {
                                  a.checkup(); // does not matter which animal subtype each
                                   // Animal’s overridden checkup() method runs

And of course we do want the AnimalDoctor to also have code that can take arrays of Dogs, Cats, or Birds, for when the vet comes to the dog, cat, or bird kennel. Again, we don’t want overloaded methods with arrays for each potential Animal subtype, so we use polymorphism in the AnimalDoctor class:
                                public void checkAnimals(Animal[] animals) {
                                           for(Animal a : animals) {

this approach does NOT work the same way with type safe collections! In other words, a method that takes, say, an ArrayList<Animal> will NOT be able to accept a collection of any Animal subtype! That means ArrayList<Dog> cannot be passed into a method with an argument of ArrayList<Animal>, even though we already know that this works just fine with plain old arrays.
Obviously this difference between arrays and ArrayList is consistent with the polymorphism assignment rules we already looked at—the fact that you cannot assign an object of type ArrayList<JButton> to a List<Object>. But this is where you really start to feel the pain of the distinction between typed arrays and typed collections.

We know it won’t work correctly, but let’s try changing the AnimalDoctor code to use generics instead of arrays:
public class AnimalDoctorGeneric {

                      // change the argument from Animal[] to ArrayList<Animal>

                     public void checkAnimals(ArrayList<Animal> animals) {
                     for(Animal a : animals) {
                      public static void main(String[] args) {
                               // make ArrayLists instead of arrays for Dog, Cat, Bird
                              List<Dog> dogs = new ArrayList<Dog>();
                              dogs.add(new Dog());
                              dogs.add(new Dog());
                              List<Cat> cats = new ArrayList<Cat>();
                              cats.add(new Cat());
                              cats.add(new Cat());
                              List<Bird> birds = new ArrayList<Bird>();
                              birds.add(new Bird());
                              // this code is the same as the Array version
                              AnimalDoctorGeneric doc = new AnimalDoctorGeneric();
                              // this worked when we used arrays instead of ArrayLists
                              doc.checkAnimals(dogs); // send a Li st<Dog>
                              doc.checkAnimals(cats); // send a Li st<Cat>
                              doc.checkAnimals(bird s); // send a Li st<Bird>

So what does happen?

javac AnimalDoctorGeneric.java
AnimalDoctorGeneric.java:51: checkAnimals(java.util.
ArrayList<Animal>) in AnimalDoctorGeneric cannot be applied to
AnimalDoctorGeneric.java:52: checkAnimals(java.util.
ArrayList<Animal>) in AnimalDoctorGeneric cannot be applied to
AnimalDoctorGeneric.java:53: checkAnimals(java.util.
ArrayList<Animal>) in AnimalDoctorGeneric cannot be applied to

The compiler stops us with errors, not warnings. You simply CANNOT assign the individual ArrayLists of Animal subtypes (<Dog>, <Cat>, or <Bird>) to an ArrayList of the supertype <Animal>, which is the declared type of the argument.This is one of the biggest gotchas for Java programmers who are so familiar with using polymorphism with arrays, where the same scenario ( Animal[] can refer to Dog[], Cat[], or Bird[]) works as you would expect. So we have two real issues:
1. Why doesn’t this work?
2. How do you get around it?

You can do the with generics:
           List<Animal> animals = new ArrayList<Animal>();
           animals.add(new Cat()); // OK
           animals.add(new Dog()); // OK
So this part works with both arrays and generic collections—we can add an instance of a subtype into an array or collection declared with a supertype. You can add Dogs and Cats to an Animal array ( Animal[] ) or an Animal collection (ArrayList<Animal>).

The reason it is dangerous to pass a collection (array or ArrayList) of a subtype into a method that takes a collection of a supertype, is because you might add something. And that means you might add the WRONG thing!

And that’s a clue! It’s the add() method that is the problem, so what we need is a way to tell the compiler, “Hey, I’m using the collection passed in just to invoke methods on the elements—and I promise not to ADD anything into the collection.” And there IS a mechanism to tell the compiler that you can take any generic subtype of the declared argument type because you won’t be putting anything in the collection. And that mechanism is the wildcard <?> . The method signature would change from
                               public void addAnimal(List<Animal> animals)
public void addAnimal(List<? extends Animal> animals)

By saying <? extends Animal> , we’re saying, “I can be assigned a collection that is a subtype of List and typed for <Animal> or anything that extends Animal. And oh yes, I SWEAR that I will not ADD anything into the collection.”

So of course the addAnimal() method above won’t actually compile even with the wildcard notation, because that method DOES add something.
                                 public void addAnimal(List<? extends Animal> animals) {
                                        animals.add(new Dog()); // NO! Can’t add if we
                                       // use <? extends Animal>
You’ll get a very strange error that might look something like this:
                              javac AnimalDoctorGeneric.java
                              AnimalDoctorGeneric.java:38: cannot find symbol
                              symbol : method add(Dog)
                              location: interface java.util.List<capture of ? extends Animal>
                              animals.add(new Dog());
                              1 error
which basically says, “you can’t add a Dog here.” If we change the method so that it doesn’t add anything, it works. the keyword extends in the context of a wildcard represents BOTH subclasses and interface implementations. There is no <? implements Serializable> syntax. If you want to declare a method that takes anything that is of a type that implements Serializable, you’d still use extends like this:

                               void foo(List<? extends Serializable> list) // odd, but correct
// to use “extends”
This looks strange since you would never say this in a class declaration because Serializable is an interface, not a class. But that’s the syntax, so burn it in!

However, there is another scenario where you can use a wildcard AND still add to the collection, but in a safe way—the keyword super.Imagine, for example, that you declared the method this way:
                                       public void addAnimal(List<? super Dog> animals) {
                                             animals.add(new Dog()); // adding is sometimes OK with super
                                      public static void main(String[] args) {
                                            List<Animal> animals = new ArrayList<Animal>();
                                            animals.add(new Dog());
                                            animals.add(new Dog());
                                            AnimalDoctorGeneric doc = new AnimalDoctorGeneric();
                                            doc.addAnimal(animals); // passing an Animal List
Now what you’ve said in this line public void addAnimal(List<? super Dog> animals) is essentially, “Hey compiler, please accept any List with a generic type that is of type Dog, or a supertype of Dog. Nothing lower in the inheritance tree can come in, but anything higher than Dog is OK.”

When you use the <? super …> syntax, you are telling the compiler that you can accept the type on the right-hand side of super or any of its supertypes, since—and this is the key part that makes it work.

Generic Types – I

before Java 5 there was no syntax for declaring a type safe collection. To make an ArrayList of Strings, you said,
                 ArrayList myList = new ArrayList();
or, the polymorphic equivalent
                List myList = new ArrayList();
There was no syntax that let you specify that myList will take Strings and only Strings.

As of Java 5, we can use generics, and while they aren’t only for making type safe collections, that’s just about all most developers use generics for.

Here’s a review of a pre-Java 5 ArrayList intended to hold Strings. (We say “intended” because that’s about all you had—good intentions—to make sure that the ArrayList would hold only Strings).
                 List myList = new ArrayList(); // can’t declare a type
                 myList.add(“Fred”); // OK, it will hold Strings
                 myList.add(new Dog()); // and it will hold Dogs too
                 myList.add(new Integer(42)); // and Integers…
A non-generic collection can hold any kind of object! A non-generic collection is quite happy to hold anything that is NOT a primitive.

And since a collection could hold anything, the methods that get objects out of the collection could have only one kind of return type—java.lang.Object. That meant that getting a String back out of our only-Strings-intended list required a cast:
                       String s = (String) myList.get(0);
And since you couldn’t guarantee that what was coming out really was a String.

So, generics takes care of both ends (the putting in and getting out) by enforcing the type of your collections. Let’s update the String list:
                     List<String> myList = new ArrayList<String>();
                     myList.add(“Fred”);// OK, it will hold Strings
                     myList.add(new Dog());// compiler error!!

Perfect. That’s exactly what we want. By using generics syntax—which means putting the type in angle brackets <String>, we’re telling the compiler that this collection can hold only String objects. The type in angle brackets is referred to as either the “parameterized type,” “type parameter,” or of course just old-fashioned “type.”

So, now that what you put IN is guaranteed, you can also guarantee what comes OUT, and that means you can get rid of the cast when you get something from the collection. Instead of
                        String s = (String)myList.get(0);// pre-generics, when a String wasn’t guaranteed
we can now just say
String s = myList.get(0);
The compiler already knows that myList contains only things that can be assigned to a String reference, so now there’s no need for a cast.

Java Email

I have used  Java Mail API 1.4.3. I have added mail.jar as dependency.

  • My example program uses yahoo SMTP server.
  • To use Gmail use 587 gmail smtp port
  • “smtp.gmail.com” as gmail smtp host
  • Mail authentication is set to true and need to give sender’s email and password. That is, we cannot send email anonymously.
  • In the program you can modify it to send to multiple To emails.
  • Sample uses HTML email as content type.
  • You can add email attachment to emailMessage.
  • To send email and test the program, just change fromUser and fromUserEmailPassword. Yes it is as simple as that.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMail {

public static void main(String args[]) {
 Properties props = new Properties();

// for gmail

//props.put("mail.smtp.port", "587");
 //props.put("mail.smtp.host", "smtp.gmail.com");

props.put("mail.smtp.host", "smtp.mail.yahoo.com");// remove this for gmail
 props.put("mail.stmp.user", "joshi_dax@yahoo.in");
 //To use TLS
 props.put("mail.smtp.auth", "true");
 props.put("mail.smtp.starttls.enable", "true");
 props.put("mail.smtp.password", "*****");
 Session session = Session.getDefaultInstance(props, new Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
 String username = "joshi_dax@yahoo.in";
 String password = "*****";
 return new PasswordAuthentication(username, password);
 String to = "joshi_dax@yahoo.in";
 String from = "joshi_dax@yahoo.in";
 String subject = "Testing...";
 MimeMessage msg = new MimeMessage(session);
 try {
 msg.setFrom(new InternetAddress(from));
 msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
 msg.setText("yahoo program working...!");
 Transport transport = session.getTransport("smtp");
 } catch (Exception exc) {