Saturday, 30 August 2014

To getting the json from URL and converting the json in MAP Object

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;

public class ParseJson1 {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
        try {
            HashMap<String, String> map=new HashMap<String,String>();
            String genreJson = IOUtils.toString(url.openStream());
            JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
           Iterator i= genreJsonObject.entrySet().iterator();
            while(i.hasNext())
            {
           Entry ee=(Entry) i.next();
           System.out.println(ee.getKey());
           System.out.println(ee.getValue());
                }
          
      
           /*
            // get the title
            System.out.println(genreJsonObject.get("title"));
            // get the data
            JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
            // get the first genre
            JSONObject firstGenre = (JSONObject) genreArray.get(0);
            System.out.println(firstGenre.get("genre_title"));
        */
        
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }
}

Note - Required jars commons-io-1.4.jar , json-simple.jar

Friday, 29 August 2014

To Reading data from given URL by using URL class and openStream() then Write in file

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class OpenStr {

    public int add(int a,int b)
    {
        return(a+b);
    }
   
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws IOException {
        String str="";
        BufferedWriter out=new BufferedWriter(new FileWriter("google.html"));
        // TODO Auto-generated method stub
try{
   
        URL u=new URL("http://www.w3schools.com/");
        DataInputStream in=new DataInputStream(u.openStream());
        while(in.readLine()!=null)
        {
           
            //System.out.println(in.readLine());
            str+=in.readLine();
           
        }
        in.close();
}catch (Exception e) {
    // TODO: handle exception
}   
       
        System.out.println(str);
        out.write(str);
        out.close();
    }

}

JAVAChat: Fiter The Collection of String From number of File...

JAVAChat: Fiter The Collection of String From number of File...: import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStr...

Fiter The Collection of String From number of Files

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class FilterText {

    public static void main(String s[]) throws IOException {
        String line = null;
        List<String> modelsList = new ArrayList<String>();
        File directory = new File("C:\\Users\\vp0c42452\\Desktop\\texts\\text");
        if (directory.isDirectory()) {
            for (int x = 0; x < directory.listFiles().length; x++) {

                FileInputStream in = new FileInputStream(
                        directory.listFiles()[x]);

                InputStreamReader inputStreamReader = new InputStreamReader(in);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String[] splitArray = null;

                while (((line = reader.readLine()) != null)) {
                    splitArray = line.split(",");
                    String sss = null;
                    for (int i = 0; i < splitArray.length; i++) {
                        if (splitArray[i].contains("modelNum")) {
                            String[] ss = splitArray[i].split(":");
                            // for (int j = 0; j < ss.length; j++) {
                            sss = ss[1].substring(ss[1].indexOf("\"") + 1,
                                    ss[1].lastIndexOf("\""));
                            // }
                            if (sss != null && !modelsList.contains(sss))
                                modelsList.add(sss);
                        }
                    }

                }
            }
        }
        System.out.println(modelsList);

    }
}

Send Mails Using JAVA MAIL API

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main {

 
    private static String RECIPIENT = "UserName1@gmail.com";

    public static void main(String[] args) {
        String from = "UserName1@gmail.com";
        String pass = "PassWord1";
        String[] to = { RECIPIENT }; // list of recipient email addresses
        String subject = "Java send mail example";
        String body = "Welcome to vijay java mail Api!";

        sendFromGMail(from, pass, to, subject, body);
    }

    private static void sendFromGMail(final String from, final String pass, String[] to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        //props.put("mail.smtp.user", from);
        //props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("smtp.EnableSsl", "true");
       
    

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // TODO Auto-generated method stub
                return new PasswordAuthentication("UserName@gmail.com", "Password");
            }
        });
       
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
          
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            System.out.println("Message delevered.");
        }
        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }
    }
   
    public static Authenticator getAuthentication(final String userName, final String password){
        Authenticator authenticator = null;
        authenticator = new Authenticator() {
            private PasswordAuthentication passwordAuthentication = new PasswordAuthentication(userName, password);
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // TODO Auto-generated method stub
                return passwordAuthentication;
            }
        };
       
         return authenticator;
    }
}

Fetch the Inbox Mails with Attachments sepratly

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMultipart;

public class AttachmentReader {

    public static void parsemessage(Message message) throws MessagingException, IOException {
          System.out.println( "<"+message.getFrom()[0] + "> " + message.getSubject());
          Multipart multipart = (Multipart)message.getContent();
          System.out.println("     > Message has "+multipart.getCount()+" multipart elements");
            for (int j = 0; j < multipart.getCount(); j++) {
                BodyPart bodyPart = multipart.getBodyPart(j);
                if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                    if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) {
                        MimeMultipart mimemultipart = (MimeMultipart)bodyPart.getContent();
                        System.out.println("Number of embedded multiparts "+mimemultipart.getCount());
                        for (int k=0;k<mimemultipart.getCount();k++) {
                            if (mimemultipart.getBodyPart(k).getFileName() != null) {
                                System.out.println("     > Creating file with name : "+mimemultipart.getBodyPart(k).getFileName());
                                savefile(mimemultipart.getBodyPart(k).getFileName(), mimemultipart.getBodyPart(k).getInputStream());
                            }
                        }
                    }
                  continue;
                }
                System.out.println("     > Creating file with name : "+bodyPart.getFileName());
                savefile(bodyPart.getFileName(), bodyPart.getInputStream());
            }
        }
   
   
    public static void savefile(String FileName, InputStream is) throws IOException {
        File f = new File("Attachment/" + FileName);
        FileOutputStream fos = new FileOutputStream(f);
        byte[] buf = new byte[4096];
        int bytesRead;
        while((bytesRead = is.read(buf))!=-1) {
            fos.write(buf, 0, bytesRead);
        }
        fos.close();
    }
   
    
   
public static void main(String[] args) {
 try {
final String user="userName1@gmail.com";
final    String password="Password1";
String host="pop.gmail.com";
Properties props = new Properties();
props.put("mail.pop3.host", "pop.gmail.com");

props.put("mail.pop3.user", user);

props.put("mail.pop3.socketFactory", 995);

props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

props.put("mail.pop3.port", 995);
    Session session = Session.getInstance(props,
                 new javax.mail.Authenticator() {
                   
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
   
 
Store store = session.getStore("pop3");
 store.connect("pop.gmail.com",user,password);
 System.out.println("Connected");
 Folder folder = store.getFolder("inbox"); 
        folder.open(Folder.READ_WRITE); 
    
        Message[] message = folder.getMessages(); 
       
        System.out.println("Connected");
        System.out.println(message.length);
      //  for (int a = message.length; a>0; a--) {
        for (int a = 0; a < message.length; a++) { 
            System.out.println("-------------" + (a + 1) + "-----------"); 
            System.out.println(message[a].getSentDate()); 
            System.out.println(message[a].getSubject()); 
           
           // String pp=message[a].getSentDate().toString();
         //   System.out.println(pp+"       Ye hai date ");
           //String tt=message[a].getSubject();
           //String det=pp.substring(0, 20);
            message[a].writeTo(new FileOutputStream("Inbox/"+message[a].getFrom().toString()+".txt",true));
           // message[a].getFrom().toString()
           parsemessage(message[a]);
      
       
        }
       

 } catch (Exception e) {

e.printStackTrace();

}    
}

}

PDF TO DOC Converion with itext api in JAVA

 import java.io.File;
import java.io.FileOutputStream;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

import com.lowagie.text.Document; import com.lowagie.text.Paragraph;

import com.lowagie.text.rtf.RtfWriter2;
public class App {

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

        Document document = new Document();

        File  file = new File("Target/file.doc");
        if(!file.exists())
            file.createNewFile();

        RtfWriter2.getInstance(document, new FileOutputStream("Target/file.doc"));
        System.out.println("file created");
        document.open();

    PdfReader reader = new PdfReader("Source/recommendation.pdf");
    int n = reader.getNumberOfPages();
    System.out.println("total no of pages:::"+n);
    String s="";
    for(int i=1;i<=n;i++)
    {

        s=PdfTextExtractor.getTextFromPage(reader, i);


        System.out.println("string:::"+s);
        System.out.println("====================");

        document.add(new Paragraph(s));
        document.newPage();
    }
    document.close();
    System.out.println("completed");
    } catch (Exception de) {}
    }

}

Monday, 24 March 2014

Learn Java: Marshaling java code to xml using JaxBContext

Learn Java: Marshaling java code to xml using JaxBContext: try {   File file = new File ( "C: \\ file.xml" ) ;  JAXBContext jaxbContext = JAXBContext. newInstance ( Customer. cl...

Unmarshaling Using JaxBContext


try  
{
 File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
 Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
 System.out.println(customer);    
}
catch (JAXBException e)
 {
 e.printStackTrace();
  }

Marshaling java code to xml using JaxBContext

try {

 File file = new File("C:\\file.xml");
 JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
  Marshaller jaxbMarshaller = jaxbContext.createMarshaller();   // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);   jaxbMarshaller.marshal(customer, file);
 jaxbMarshaller.marshal(customer, System.out);

    } catch (JAXBException e)  
{
e.printStackTrace();
  }    
}

Friday, 17 January 2014

Garbage Collection in Java (Watch Video)





Java Memory Management

Java Memory Management, with its built-in garbage collection, is one of the language’s finest achievements. It allows developers to create new objects without worrying explicitly about memory allocation and deallocation, because the garbage collector automatically reclaims memory for reuse. This enables faster development with less boilerplate code, while eliminating memory leaks and other memory-related problems. At least in theory.
Ironically, Java garbage collection seems to work too well, creating and removing too many objects. Most memory-management issues are solved, but often at the cost of creating serious performance problems. Making garbage collection adaptable to all kinds of situations has led to a complex and hard-to-optimize system. In order to wrap your head around garbage collection, you need first to understand how memory management works in a Java Virtual Machine (JVM).

How Garbage Collection Really Works

Many people think garbage collection collects and discards dead objects. In reality, Java garbage collection is doing the opposite! Live objects are tracked and everything else designated garbage. As you’ll see, this fundamental misunderstanding can lead to many performance problems.
Let's start with the heap, which is the area of memory used for dynamic allocation. In most configurations the operating system allocates the heap in advance to be managed by the JVM while the program is running. This has a couple of important ramifications:
  • Object creation is faster because global synchronization with the operating system is not needed for every single object. An allocation simply claims some portion of a memory array and moves the offset pointer forward (see Figure 2.1). The next allocation starts at this offset and claims the next portion of the array.
  • When an object is no longer used, the garbage collector reclaims the underlying memory and reuses it for future object allocation. This means there is no explicit deletion and no memory is given back to the operating system.
New objects are simply allocated at the end of the used heapFigure 2.1: New objects are simply allocated at the end of the used heap.
All objects are allocated on the heap area managed by the JVM. Every item that the developer uses is treated this way, including class objects, static variables, and even the code itself. As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory. As simple as this sounds, it raises a question: what is the first reference in the tree?

Garbage-Collection Roots — The Source of All Object Trees

Every object tree must have one or more root objects. As long as the application can reach those roots, the whole tree is reachable. But when are those root objects considered reachable? Special objects called garbage-collection roots (GC roots; see Figure 2.2) are always reachable and so is any object that has a garbage-collection root at its own root.
There are four kinds of GC roots in Java:
  1. Local variables are kept alive by the stack of a thread. This is not a real object virtual reference and thus is not visible. For all intents and purposes, local variables are GC roots.
  2. Active Java threads are always considered live objects and are therefore GC roots. This is especially important for thread local variables.
  3. Static variables are referenced by their classes. This fact makes them de facto GC roots. Classes themselves can be garbage-collected, which would remove all referenced static variables. This is of special importance when we use application servers, OSGi containers or class loaders in general. We will discuss the related problems in the Problem Patterns section.
  4. JNI References are Java objects that the native code has created as part of a JNI call. Objects thus created are treated specially because the JVM does not know if it is being referenced by the native code or not. Such objects represent a very special form of GC root, which we will examine in more detail in the Problem Patterns section below.
GC Roots are objects that are themselves referenced by the JVM and thus keep every other object from being garbage collected.Figure 2.2: GC roots are objects that are themselves referenced by the JVM and thus keep every other object from being garbage-collected.
Therefore, a simple Java application has the following GC roots:
  • Local variables in the main method
  • The main thread
  • Static variables of the main class

Marking and Sweeping Away Garbage

To determine which objects are no longer in use, the JVM intermittently runs what is very aptly called a mark-and-sweep algorithm. As you might intuit, it’s a straightforward, two-step process:
  1. The algorithm traverses all object references, starting with the GC roots, and marks every object found as alive.
  2. All of the heap memory that is not occupied by marked objects is reclaimed. It is simply marked as free, essentially swept free of unused objects.
Garbage collection is intended to remove the cause for classic memory leaks: unreachable-but-not-deleted objects in memory. However, this works only for memory leaks in the original sense. It’s possible to have unused objects that are still reachable by an application because the developer simply forgot to dereference them. Such objects cannot be garbage-collected. Even worse, such a logical memory leak cannot be detected by any software (see Figure 2.3). Even the best analysis software can only highlight suspicious objects. We will examine memory leak analysis in the Analyzing the Performance Impact of Memory Utilization and Garbage Collection section, below.
When objects are no longer referenced directly or indirectly by a GC root, they will be removed. There are no classic memory leaks. Analysis cannot really identify memory leaks, it can only hint at suspicious objectsFigure 2.3: When objects are no longer referenced directly or indirectly by a GC root, they will be removed. There are no classic memory leaks. Analysis cannot really identify memory leaks; it can only point out suspicious objects.


Thursday, 16 January 2014

Constructor Chaning in java




Example of Constructor Chaning

class Initemp
{
int x;
{
System.out.println("Init block executed.");
this.x=20;

}
Initemp()
{
this(10);
  this.x=10;
System.out.println("Default"+x);
}
Initemp(int x)
{    
                                     this(10,20);
System.out.println(x);
}

Initemp(int x,int y)
{    
                      
System.out.println("First Execute");
}
      
public static void main(String...s)
{
new Initemp();
System.out.println("Vijay Prakash");
}
}


Design Analog Clock Using AWT Swing in Java



                                               Design Analog Clock Using Swing in Java


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Watch extends JPanel implements Runnable
{
JLabel l,l1;
JPanel p,p1;
JButton b,b1;
double x,y,r=90,q=270,x1,y1,x2,y2;
Watch3()
{

x=150+r*Math.cos((q*Math.PI)/180);
y=138+r*Math.sin((q*Math.PI)/180);
x1=150+r*Math.cos((q*Math.PI)/180);
y1=138+r*Math.sin((q*Math.PI)/180);
x2=150+r*Math.cos((q*Math.PI)/180);
y2=138+r*Math.sin((q*Math.PI)/180);

Thread t=new Thread(this);
t.start();
}
public void paint(Graphics g)
{
setBackground(Color.red);
g.setColor(Color.red);
g.drawOval(25,10,250,250);
g.fillOval(25,10,250,250);
g.setColor(Color.green);
///g.setStroke(new BasicStroke(5));
g.drawLine((int)x,(int)y,150,138);
g.drawLine(150,80,150,138);
g.drawLine(130,70,150,138);                                              
g.setColor(Color.green);
g.fillOval(145,135,10,10);
g.setColor(Color.blue);
g.setFont(new Font("snserif",Font.BOLD,20));
g.drawString("12",150,40);
g.drawString("6",150,245);
g.drawString("9",40,140);
g.drawString("3",250,140);
g.drawString("1",205,60);
g.drawString("2",240,95);
g.drawString("11",90,55);
g.drawString("10",55,95);
g.drawString("8",55,190);
g.drawString("VIJAY",120,190);
g.drawString("4",240,190);
g.drawString("7",90,230);
g.drawString("5",205,230);
g.setColor(Color.black);
//g.drawString("VIJAY",120,190);
}
public void run()
{

for(;;)
{
repaint();
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
x=150+r*Math.cos((q*Math.PI)/180);
y=138+r*Math.sin((q*Math.PI)/180);

q+=6;
if(q==360)
{
q=0;
}
}
}
public static void main(String...s)
{
JFrame f=new JFrame();
f.setSize(315,350);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Watch3());
f.setVisible(true);

}
}

How to Run
1-Copy this code and save as Watch.java
2-Compile it as- javac Watch.java
3-Run it as- java Watch

Design Car Racing Game using AWT Swing in java


                                                      Design a Car Racing Game (Vijay Prakash)





import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyCar extends JPanel implements KeyListener,Runnable
{
Image i;
Toolkit t;
int j=550,n=80,l=210,d,s=0,p=0;



MyCar1()
{

t=Toolkit.getDefaultToolkit();
i=t.getImage("car.png");
setBackground(Color.black);
Thread tt=new Thread(this);

tt.start();

}

public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.green);
g.fillRect(0,0,100,700);
g.setColor(Color.green);
g.fillRect(380,0,500,700);
g.setColor(Color.red);
g.drawRect(130,0,220,700);
g.setColor(Color.white);
g.fillRect(215,0+p,15,50);
g.fillRect(245,0+p,15,50);
g.fillRect(215,100+p,15,50);
g.fillRect(245,100+p,15,50);
g.fillRect(215,200+p,15,50);
g.fillRect(245,200+p,15,50);
g.fillRect(215,300+p,15,50);
g.fillRect(245,300+p,15,50);
g.fillRect(215,400+p,15,50);
g.fillRect(245,400+p,15,50);
g.fillRect(215,500+p,15,50);
g.fillRect(245,500+p,15,50);
g.fillRect(215,600+p,15,50);
g.fillRect(245,600+p,15,50);
g.drawImage(i,l,j,this);
}
public void keyPressed(KeyEvent d )
{
  int code =d.getKeyCode();
            if (code == KeyEvent.VK_UP)
         {

               n=n-2;
           j--;
    
this.repaint();
            }


    if (code == KeyEvent.VK_DOWN)
         {

               n=n+5;
          
    
this.repaint();
            }

    if (code == KeyEvent.VK_LEFT)
         {

               l=l-5;
          
    
this.repaint();
            }

    if (code == KeyEvent.VK_RIGHT)
         {

               l=l+5;
          
    
this.repaint();
            }

    if (code == KeyEvent.VK_B)
         {

               j=j+50;
          
    
this.repaint();
            }

  if (code == KeyEvent.VK_U)
         {

               j=j-5;
          
    
this.repaint();
            }

}

public void keyReleased(KeyEvent d )
{

}
public void keyTyped(KeyEvent d )
{

}
public void run()
{
repaint();
for( p=0;p<=100;p=p+10)
{
repaint();
try
{

Thread.sleep(n);
}
catch(Exception e)
{}
if(p==100)
p=0;
}
}
public static void main(String...s)
{
String ss=" Developed By Vijay Prakash";
JFrame f=new JFrame();
JLabel ll=new JLabel("Scors");
ll.setBounds(400,650,50,20);
ll.setForeground(Color.red);
f.add(ll);
f.setTitle("                                                    Need For Speed Game");
JLabel l=new JLabel(ss);
l.setBounds(20,650,200,20);
l.setForeground(Color.blue);
f.add(l);
f.setLayout(null);
f.setSize(500,700);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyCar1 o=new MyCar1();
o.setBounds(0,0,500,650);
f.add(o);
f.addKeyListener(o);
}
}


How To Run This Programe

1- Create a Folder named as MyCar
2- Save above Car Image as car.png
3-Copy above code and past in notepad and save as MyCar.java
4-Compile This code as-  javac MyCar.java
5-Run Program as-java MyCar

Working of String Constant pool and Heap Memory


here are slight differences between the various methods of creating a String object. String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals/objects to increase performance and decrease memory overhead. To cut down the number of String objects created, JVM maintains a special memory called “String literal pool” or “String constant pool”.

Each time your code creates a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string does not exist in the pool, a new String object is created and placed in the pool. JVM keeps at most one object of any String in this pool. String literals always refer to an object in the string pool.

For example,

Direct Method of creating String object
1
String s1 = "iByteCode";
How this works?

JVM checks the String constant pool first and if the string does not exist, it creates a new String object “iByteCode” and a reference is maintained in the pool. The variable ‘s1′ also refers the same object.
This statement creates one String object “iByteCode”.
Now, let’s see what happens if we have a statement like this:
1
String s2 = "iByteCode";
JVM checks the String constant pool first and since the string already exists, a reference to the pooled instance is returned to s2.
This statement does not create any String object in the memory and ‘s2′ refers the same object as ‘s1′.
To check this, you can compare two String references using == operator to check whether two references are referring to the same String object in the memory.
1
2
3
4
String s1 = "iByteCode";
String s2 = "iByteCode";
if(s1 == s2)
    System.out.println("s1 and s2 referring to the same object.");
s1 and s2 referring to the same object.




Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example, if several reference variables refer to the same String object then it would be bad if any of them changes the String’s value. This is the reason for making String objects as immutable.

Creating String using constructor
1
String s = new String("iByteCode");
In this case, because we used ‘new’ keyword a String object is created in the heap memory even if an equal string object already exists in the pool and ‘s’ will refer to the newly created one.

1
2
3
String str1 = "iByteCode";
String str2 = new String("iByteCode");
System.out.println(str1 == str2);
false

String objects created with the new operator do not refer to objects in the string pool but can be made to using String’s intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String literal pool. If the String is not already in the global String literal pool, then it will be added. For example,

1
2
3
4
String s1 = new String("iByteCode");
String s2 = s1.intern();
String s3 = "iByteCode";
System.out.println(s2 == s3);
true





In the above example, if the change the statement 2 as,

1
String s2 = s1;
Reference variable ‘s2′ will refer to the string object in the heap instead of string literal pool and s1 == s2 will print true.

Note-An object is eligible for garbage collection when it is no longer referenced from an active part of the application. In the case of String literals, they always have a reference to them from the String Literal Pool and are, therefore, not eligible for garbage collection.

Note-All the string literals are created and their references are placed in the pool while JVM loads the class. So, even before a statement like this String s1 = new String(“iByteCode”); is executed, the string literal pool contains a reference to “iByteCode”.


"


According to the Java Virtual Machine Specification, the area for storing string literals is in the runtime constant pool. The runtime constant pool memory area is allocated on a per-class or per-interface basis, so it's not tied to any object instances at all. The runtime constant pool is a subset of the method area which "stores per-class structures such as the runtime constant pool, field and method data, and the code for methods and constructors, including the special methods used in class and instance initialization and interface type initialization". The VM spec says that although the method area is logically part of the heap, it doesn't dictate that memory allocated in the method area be subject to garbage collection or other behaviors that would be associated with normal data structures allocated to the heap.
                                                                                                                      "

Class Loaders in Java


         Java Class Loader

Java ClassLoader loads a java class file into java virtual machine. It is as simple as that. It is not a huge complicated concept to learn and every java developer must know about the java class loaders and how it works.
Like NullPointerException, one exception that is very popular is ClassNotFoundException. At least in your beginner stage you might have got umpteen number of ClassNotFoundException. Java class loader is the culprit that is causing this exception.

Types (Hierarchy) of Java Class Loaders

Java class loaders can be broadly classified into below categories:
  • Bootstrap Class Loader
    Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.
  • Extensions Class Loader
    JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.
  • System Class Loader
    Java classes that are available in the java classpath are loaded using System class loader.
You can see more class loaders like java.net.URLClassLoader, java.security.SecureClassLoader etc. Those are all extended from java.lang.ClassLoader
These class loaders have a hierarchical relationship among them. Class loader can load classes from one level above its hierarchy. First level is bootstrap class loader, second level is extensions class loader and third level is system class loader.









How to Install and Run JDK

How can I get started developing Java programs with the Java Development Kit (JDK)?


OTN logo
Writing Java applets and applications needs development tools like JDK. The JDK includes the Java Runtime Environment, the Java compiler and the Java APIs. It's easy for both new and experienced programmers to get started.

Where can I get JDK download?
To download the latest version of the Java Development Kit (JDK), go to JDK downloads.
Developers can also refer to the Oracle Technology Network for Java Developers for everything you need to know about Java technology, including documentation and training.
What if I am new to Java?
If you are new and interested to get started developing Java programs, please refer to new to Javato find useful information for beginners.
How do I get Java certification?
Earning an Oracle Java technology certification provides a clear demonstration of the technical skills, professional dedication and motivation for which employers are willing to pay a premium. Recognized industry-wide, Oracle's Java technology training and certification options help ensure that you have the necessary skills to efficiently meet the challenges of your IT organization.
» Learn more about Java Certification
Java Developer Conferences
  • JavaOne is the premier Java developer conference where you can learn about the latest Java technologies, deepen your technical understanding, and ask questions directly to your fellow strategists and developers. Oracle runs annual JavaOne conferences, including the flagship JavaOne in San Francisco and regional conferences. Visit www.oracle.com/javaonefor more information on upcoming events and locations.
  • Oracle Technology Network Developer Days are free, hands-on Java developer workshops conducted globally on a regular basis.
  • Oracle also sponsors a variety of third party Java technology conferences and events. Search the Oracle Events catalog for an upcoming event near you.
Java Magazine
Java Magazine, a bimonthly, digital-only publication, is an essential source of knowledge about Java technology, the Java programming language, and Java-based applications for people who rely on them in their professional careers, or who aspire to. It includes profiles of innovative Java applications, Java technical how-to's, Java community news, and Information about new Java books, conferences and events.
Oracle Academy
The Oracle Academy provides a complete portfolio of software, curriculum, hosted technology, faculty training, support, and certification resources to K-12, vocational, and higher education institutions for teaching use. Faculty can flexibly insert these resources into computer science and business programs, ensuring that students gain industry-relevant skills prior to entering the workforce. The Oracle Academy supports over 1.5 million students in 95 countries. Oracle Academy recently expanded its curriculum to include Java. To learn more, visit Oracle Academy Java Programming.

How can I get started developing Java programs with the Java Development Kit (JDK)?


OTN logo
Writing Java applets and applications needs development tools like JDK. The JDK includes the Java Runtime Environment, the Java compiler and the Java APIs. It's easy for both new and experienced programmers to get started.

Where can I get JDK download?
To download the latest version of the Java Development Kit (JDK), go to JDK downloads.
Developers can also refer to the Oracle Technology Network for Java Developers for everything you need to know about Java technology, including documentation and training.
What if I am new to Java?
If you are new and interested to get started developing Java programs, please refer to new to Javato find useful information for beginners.
How do I get Java certification?
Earning an Oracle Java technology certification provides a clear demonstration of the technical skills, professional dedication and motivation for which employers are willing to pay a premium. Recognized industry-wide, Oracle's Java technology training and certification options help ensure that you have the necessary skills to efficiently meet the challenges of your IT organization.
» Learn more about Java Certification
Java Developer Conferences
  • JavaOne is the premier Java developer conference where you can learn about the latest Java technologies, deepen your technical understanding, and ask questions directly to your fellow strategists and developers. Oracle runs annual JavaOne conferences, including the flagship JavaOne in San Francisco and regional conferences. Visit www.oracle.com/javaonefor more information on upcoming events and locations.
  • Oracle Technology Network Developer Days are free, hands-on Java developer workshops conducted globally on a regular basis.
  • Oracle also sponsors a variety of third party Java technology conferences and events. Search the Oracle Events catalog for an upcoming event near you.
Java Magazine
Java Magazine, a bimonthly, digital-only publication, is an essential source of knowledge about Java technology, the Java programming language, and Java-based applications for people who rely on them in their professional careers, or who aspire to. It includes profiles of innovative Java applications, Java technical how-to's, Java community news, and Information about new Java books, conferences and events.
Oracle Academy
The Oracle Academy provides a complete portfolio of software, curriculum, hosted technology, faculty training, support, and certification resources to K-12, vocational, and higher education institutions for teaching use. Faculty can flexibly insert these resources into computer science and business programs, ensuring that students gain industry-relevant skills prior to entering the workforce. The Oracle Academy supports over 1.5 million students in 95 countries. Oracle Academy recently expanded its curriculum to include Java. To learn more, visit Oracle Academy Java Programming.



Watch this video How to install JDK and Run