Execute Javascript from Java

June 20, 2010 24 comments

After a small gap,I am back to here for share something to you all.A week before i have stuck with execute javascript from java.I google it for this.Finally i found my way to achieve this.

Java provides the way to execute JavaScript also.The solution is come along with ScriptEngineManager.This article deals the same.

The ScriptEngineManager comes along with the package javax.script.

This is a relatively small, simple API. A ScriptEngineManager object can discover script engines through the jar file service discovery mechanism. It can also instantiate ScriptEngine objects that interpret scripts written in a specific scripting language. The simplest way to use the scripting API is as follows:

  • Create a ScriptEngineManager object.
  • Get a ScriptEngine object from the manager.
  • Evaluate script using the ScriptEngine’s eval methods.

Now we look at the sample code.

import javax.script.*;
public class ExecuteScript {
 public static void main(String[] args) throws Exception {
 // create a script engine manager
 ScriptEngineManager factory = new ScriptEngineManager();
 // create a JavaScript engine
 ScriptEngine engine = factory.getEngineByName("JavaScript");
 // evaluate JavaScript code from String
 engine.eval("print('Welocme to java world')");

Executing a Script from .js File:

In this example, we can execute JavaScript which is from .js file.This can be achieved by the eval method of ScriptEngine Class.
The eval method have the FileReader object as argument.

we can create the ScriptEngineManager and get the ScriptEngine from the above code(line 4-7).

Then we add the eval method which is used to execute script from .js file.

// evaluate JavaScript code from given file
 engine.eval(new java.io.FileReader("welcome.js"));

Let us assume that we have the file named “welcome.js” with the following text:

println("Welcome to java world");

If we will run the code,this yields the output as

Welcome to java world.

I hopes this helps.Then Go ahead to execute your JavaScript by using your java code.Before that,if you feel it useful,leave your foot prints here[Comments].

Regular Expression Symbols

April 17, 2010 Leave a comment


“Regular expressions” are combination of special characters and symbols used for pattern matching. i.e., you specify a particular combination of such characters and symbols (= regular expression) and the compiler will search for that string of words through the text data. The following is a very short, and hopefully easy-to-follow, introduction to some of the most useful regular expressions.

1. Common matching symbols

Table 1.

Regular Expression Description
. Matches any sign
^regex regex must match at the beginning of the line
regex$ Finds regex must match at the end of the line
[abc] Set definition, can match the letter a or b or c
[abc[vz]] Set definition, can match a or b or c followed by either v or z
[^abc] When a “^” appears as the first character inside [] when it negates the pattern. This can match any character except a or b or c
[a-d1-7] Ranges, letter between a and d and figures from 1 to 7, will not match d1
X|Z Finds X or Z
XZ Finds X directly followed by Z
$ Checks if a line end follows

2. Metacharacters

The following meta characters have a pre-defined meaning and make certain common pattern easier to use, e.g. \d instead of [0…9].

Table 2.

Regular Expression Description
\d Any digit, short for [0-9]
\D A non-digit, short for [^0-9]
\s A whitespace character, short for [ \t\n\x0b\r\f]
\S A non-whitespace character, for short for [^\s]
\w A word character, short for [a-zA-Z_0-9]
\W A non-word character [^\w]
\S+ Several non-whitespace characters

3. Quantifier

A quantifier defines how often an element can occur. The symbols ?, *, + and {} define the quantity of the regular expressions

Table 3.

Regular Expression Description
* Occurs zero or more times
+ Occurs one or more times
? Occurs no or one times, ? is short for {0,1}
{X} Occurs X number of times, {} describes the order of the preceding liberal
{X,Y} .Occurs between X and Y times,
*? ? after a qualifier makes it a “reluctant quantifier”, it tries to find the smallest match.
Categories: 1

Pattern class of Regular Expression in Java

April 17, 2010 2 comments


This article makes you bit more knowledge in java regular expressions. For manage the regular expressions, the java have the three classes in java.util.regex package. But in this article we focused only Pattern class.

A regular expression is a pattern of characters that describes a set of strings. We use the regular expressions to find, display, or modify some or all of the occurrences of a pattern in an input sequence.

Java.util.regex classes:

The package java.util.regex contains three classes such as,

  • Pattern Class
  • Matcher Class
  • PatternSyntaxExcpetion

Let us take a look at Pattern class.

Pattern Class:

A regular expression which is specified as a string that should be first compiled into an instance of Pattern class. The resulting pattern can be used to create an instance of  Matcher class which contains various in-built methods that helps in performing a match against the regular expression. Many Matcher objects can share the same Pattern object.

Create Pattern using compile():

Pattern class doesn’t have a public constructor. So by using the static method compile we can create the pattern.

Pattern p = Pattern.compile("my regexp");

For Regular expression symbols,click here

Important Note:

The backslash is an escape character in Java Strings. i.e., backslash has a predefine meaning in Java. You have to use “\\” instead of “\”.

If you want to define “\w” then you must be using “\\w” in your regex like this.

Pattern r = Pattern.compile(“\\w+”); //Place your pattern here

“\w“ represents a word character, i.e., short for [a-zA-Z_0-9]

We can create the Pattern with flags.


Pattern pattern=Pattern.compile(regex,flags);

For ex, If we want to neglect the case sensitive we can achieve by using below one,

Pattern pattern = Pattern.compile(“\\w+”,Pattern.CASE_INSENSITIVE);

Validate pattern using matches():

The matches() method is used to check whether the given input is match with the pattern. This method returns true only if the entire input text matches the pattern.

boolean isMatch = Pattern.matches(“\\w+”,”Welcome to java world”);

Get the Pattern using pattern():

The pattern() method is used for find out the pattern of the given string. This method returns the regular expression as a string from which this pattern was compiled.

Pattern p=input.pattern();

Split input using split():

The split() method is used to split the given input text based on the given pattern. It returns a String array. There are two forms of split() method,

  • split(String input)
  • split(String input, int limit)

In the second form, we have an argument called limit which is used to specify the limit i.e. the number of resultant strings that have to be obtained by split() method.

String[] str = pattern.split(input,3);

Sample code for Pattern class and methods:

MailID Validation.java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

 * @author Home
class MailIDValidation
 public static void main(String args[])
 //Input the string for validation
 String email = "mymail@gmail.com";

 //Set the email pattern string
 Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

 //Match the given string with the pattern
 Matcher m = p.matcher(email);

 //check whether match is found
 boolean matchFound = m.matches();

 if (matchFound)
 System.out.println("Valid Email Id.");
 System.out.println("Invalid Email Id.");

I hope it offer bit more knowledge in Regular Expressions. The next article makes you clear in Matcher class in regular expression.Please leave your footprints (comments) here.

10 Fixes that solve IE Issues

April 3, 2010 6 comments


Whenever i designed my web page i have found out some issues that issues make my design is  not compatible with a wide range of browsers.So in this article i add some tips for making your website compatible with a wide range of browsers .

1. Solve invisibility problems:

If you face any problems like the image,text component are invisible sometimes, you add the property position:relative for the components to avoid the invisibility problems.

2. Use display: inline for floated elements

Floated elements with a margin can fire the famous IE6 double-margin bug, e.g. you specify a left margin of 5px and actually get 10px. Display:inline will fix the problem and, although it should not be required, your CSS remains valid.

3.  Alternative for colon in components ID:

The IE does not support colon for represents the components ID.If you want to refer the components ID which has colon you

replace the colon with the value \003A

For ex,

<h1 id="formID:titleID">Welcome to My world</h1>

Css for Mozilla:

//some properties

For IE:

//Some properties

4. Internet Explorer hacks

While conditional comments are better, you can also target some versions of Internet Explorer using the following syntax:

Width: 200px; /* All browsers */
*width: 250px; /* IE */
_width:300px; /* IE6 */
.width:200px; /* IE7 */

This technique is not W3C compliant (this is why you should use conditional comments instead) but sometimes, it is a real time saver.

5. Avoid percentage dimensions

Percentages confuse IE. Unless you can carefully size every parent element, they are probably best avoided. You can still use percentage values in other browsers with !important, e.g.

height: 2%; !important
height: 20px; /*IE6 only*/

6. Another box model hack alternative

Box model hack is used to fix a rendering problem in pre-IE 6 browsers on PC, where by the border and padding are included in the width of an element, as opposed to added on. Number of CSS-based solutions has been put forward to remedy this, so here’s another one which we really like:

padding: 2em;
border: 1em solid green;
width: 20em;
width/**/:/**/ 14em;

The first width command is read by all browsers; the second by all browsers except IE5.x on PC. Because the second command comes second it takes precedence over the first – any command that comes second will always override a preceding command. So, how does all this work?

By placing empty comment tags (/**/) before the colons, IE5.0 will ignore the command. Likewise, by placing these empty comment tags after the colon, IE5.5 will ignore the command. By using these two rules in conjunction with each other, we can hide the command from all of IE5.x.

7.  Class

The class selector allows you to set multiple styles to the same element or tag in a document. For example, you might want to have certain sections of your text called out in different colors from the rest of the text in the document. You would assign your paragraphs with classes like this:

background-color: #0000ff;
background-color: #ff0000;

Then, when you want to call the various classes you would use the CLASS attribute within the paragraph tag. Any tag that did not have a class attribute would be given the default style for that tag. For example:

<p>Welcome in blue background</p>
<p>Hello world in red background</p>

8. ID

The ID selector allows you to give a name to a specific style without associating it with a tag or other HTML element. You write an ID code like this

h3#indent1 {text-indent: 10px ;}

You associate an ID tag the same way you associate classes, within the element that should have that style:

<h3 id="indent1">This test for ID CSS</h3>

You can give your ID tags any grouping of letters and numbers that you would like.Keep in mind that HTML standards require that the ID must be unique.


One of the trickiest things about CSS is that it requires the use of formerly optional ending tags (as does XML). For example, if you have a style applied to a paragraph tag <p>, the browser may not know where to end that style if you do not include the ending tag </p>.

9.  Class and ID together

If we need to assign the same style class or id we can assign different style for each one with using classes and ID together. For ex,

<h1 id="blueheaderId" class="blue">Welcome to CSS</h1>
h1#blueheaderId.blue {color: blue ;}

10. Refractor your code

Often, it can take longer to fix than re-think a layout problem. Minor alterations to the HTML and simpler CSS are often more effective. This may mean you abandon perfectly legitimate code, but fewer long-term issues will arise and you know how to handle the problem in future.

Have I missed your favorites IE fix? Comments and suggestions welcome.

Java Code to Receive Mail using JavaMailAPI

March 21, 2010 35 comments


In the previous article, we have looked at sending mail with Java Mail API.Sending e-mail was relatively simple with only one protocol (SMTP) to handle. But Reception involves two protocols, POP3 and IMAP. POP3 is the older protocol, which offers a single queue of mail messages as a single inbox. IMAP is the more modern protocol, which presents mail messages as entries in a hierarchy of folders, one of which will be an inbox.

Java Mail comes with Provider implementations for POP3 and IMAP, and the secure versions of those as POP3S and IMAPS.


JDK 1.5 and Above

Jar: Mail. jar

Steps involved in receive mail:

Step 1: Define the mail properties (i.e.) Define the protocol, mail server by using the properties class.

Step 2: Create the session for read the mail with the properties which we already defined.

Step 3: Create and connect the store for read the mail.

Step 4: Define and open the folder which we need to read. Open the folder in read-only mode.

Step 5: Search the unread contents in the specified folder and stored it into messages array.

Step 6: Display the messages.

Description of classes and methods :


An abstract class that models a message store and its access protocol, for storing and retrieving messages.


connect -> It is used to connect the store with the mail server store.

getFolder-> It is used to define the folder which will be read. Return Folder class.


Folder is an abstract class that represents a folder for mail messages. Folders can contain Messages, other Folders


open   -> Method for open the foder.We must define the mode of open.

search -> Method for get the messages. Return type: Message[].

fetch  -> Method for Fetch the details which is represented by FetchProfile.

close  -> Method for close the folder.


List the Message attributes that it wishes to prefetch from the server for a range of messages.


add  ->  Method for add the attributes which we wish to prefetch.


This class models an email message. This is an abstract class. Message implements the Part interface

A Message object obtained from a folder is just a lightweight reference to the actual message.


getContent  ->  Method for get the content of the message.


 *  This is the code for read the unread mails from your mail account.
 *  Requirements:
 *      JDK 1.5 and above
 *      Jar:mail.jar
package com.info.mail;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;

public class MailReader
 Folder inbox;

 //Constructor of the calss.
 public MailReader()
 /*  Set the mail properties  */
 Properties props = System.getProperties();
 props.setProperty("mail.store.protocol", "imaps");
 /*  Create the session and get the store for read the mail. */
 Session session = Session.getDefaultInstance(props, null);
 Store store = session.getStore("imaps");
 store.connect("imap.gmail.com","<mail ID> ", "<Password>");

 /*  Mention the folder name which you want to read. */
 inbox = store.getFolder("Inbox");
 System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());

 /*Open the inbox using store.*/

 /*  Get the messages which is unread in the Inbox*/
 Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));

 /* Use a suitable FetchProfile    */
 FetchProfile fp = new FetchProfile();
 inbox.fetch(messages, fp);

 catch (Exception ex)
 System.out.println("Exception arise at the time of read mail");
 catch (NoSuchProviderException e)
 catch (MessagingException e)

 public void printAllMessages(Message[] msgs) throws Exception
 for (int i = 0; i < msgs.length; i++)
 System.out.println("MESSAGE #" + (i + 1) + ":");

 /*  Print the envelope(FromAddress,ReceivedDate,Subject)  */
 public void printEnvelope(Message message) throws Exception
 Address[] a;
 // FROM
 if ((a = message.getFrom()) != null)
 for (int j = 0; j < a.length; j++)
 System.out.println("FROM: " + a[j].toString());
 // TO
 if ((a = message.getRecipients(Message.RecipientType.TO)) != null)
 for (int j = 0; j < a.length; j++)
 System.out.println("TO: " + a[j].toString());
 String subject = message.getSubject();
 Date receivedDate = message.getReceivedDate();
 String content = message.getContent().toString();
 System.out.println("Subject : " + subject);
 System.out.println("Received Date : " + receivedDate.toString());
 System.out.println("Content : " + content);

 public void getContent(Message msg)
 String contentType = msg.getContentType();
 System.out.println("Content Type : " + contentType);
 Multipart mp = (Multipart) msg.getContent();
 int count = mp.getCount();
 for (int i = 0; i < count; i++)
 catch (Exception ex)
 System.out.println("Exception arise at get Content");

 public void dumpPart(Part p) throws Exception
 // Dump input stream ..
 InputStream is = p.getInputStream();
 // If "is" is not already buffered, wrap a BufferedInputStream
 // around it.
 if (!(is instanceof BufferedInputStream))
 is = new BufferedInputStream(is);
 int c;
 System.out.println("Message : ");
 while ((c = is.read()) != -1)

 public static void main(String args[])
 new MailReader();

Java code sending Mail with Attachment using Java Mail API

March 3, 2010 39 comments


In a day-to-day life the emails are occupied our life.If we can send our mails by using our java code without help of browser how we feel?

This article do this.By using the JavaMail API send our mail with attachment without help of browser.This code need a mail.jar file.You can download this at http://www.java2s.com/Code/Jar/JKL/Downloadmailjar.htm


/ * This code is only for design the frame
 * @author muneeswaran
package com.mail;

import javax.mail.MessagingException;
import javax.swing.*;

public class MailSender extends JFileChooser

    private JTextField attachmentTextField;
    private JLabel jLabel1, jLabel2, jLabel3, jLabel4, jLabel5, jLabel6;
    private JScrollPane jScrollPane1;
    private JTextArea messageTextArea;
    private JButton sendButton, cancelButton, browseButton;
    private JTextField ccTextField, subjectTextField, toTextField;
    String toAddress = null, ccAddress = null, message = null,
            receipientsList[] = null, attachments[] = null, receipients, subject;
    String fromAddress = "put your full mail id"; //Place your mail id here.
    String authenticationPassword = "your password";//Place your password here

    public MailSender()

    private void initComponents()

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel("To");
        toTextField = new javax.swing.JTextField(20);
        jLabel3 = new javax.swing.JLabel("CC");
        ccTextField = new javax.swing.JTextField(20);
        jLabel4 = new javax.swing.JLabel("Subject");
        subjectTextField = new javax.swing.JTextField(20);
        jLabel5 = new javax.swing.JLabel("Attachemnet");
        attachmentTextField = new javax.swing.JTextField(20);
        browseButton = new javax.swing.JButton("Browse");
        jLabel6 = new javax.swing.JLabel("Message");
        jScrollPane1 = new javax.swing.JScrollPane();
        messageTextArea = new javax.swing.JTextArea(20, 10);
        sendButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();


        jLabel1.setFont(new java.awt.Font("AlMateen-Bold", 3, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(1, 203, 221));
        jLabel1.setText("Mail Sender");
        sendButton.addActionListener(new java.awt.event.ActionListener()

            public void actionPerformed(java.awt.event.ActionEvent evt)

        cancelButton.addActionListener(new java.awt.event.ActionListener()

            public void actionPerformed(java.awt.event.ActionEvent evt)

        browseButton.addActionListener(new java.awt.event.ActionListener()

            public void actionPerformed(java.awt.event.ActionEvent evt)

        jLabel1.setBounds(100, 50, 200, 50);
        jLabel2.setBounds(50, 100, 100, 50);
        toTextField.setBounds(150, 100, 300, 40);

        jLabel3.setBounds(50, 150, 100, 50);
        ccTextField.setBounds(150, 150, 300, 40);

        jLabel4.setBounds(50, 200, 100, 50);
        subjectTextField.setBounds(150, 200, 300, 40);

        jLabel5.setBounds(50, 250, 100, 50);
        attachmentTextField.setBounds(150, 250, 200, 40);
        browseButton.setBounds(375, 250, 100, 20);

        jLabel6.setBounds(50, 300, 100, 50);
        messageTextArea.setBounds(150, 300, 300, 40);

        sendButton.setBounds(100, 400, 75, 20);
        cancelButton.setBounds(200, 400, 75, 20);
        JFrame mailFrame = new JFrame("Mail Sender");

        mailFrame.setSize(500, 500);

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)
        // TODO add your handling code here:

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt)
        JFileChooser selectFile = new JFileChooser();

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt)

        toAddress = toTextField.getText().trim();
        ccAddress = ccTextField.getText().trim();
        subject = subjectTextField.getText().trim();
        message = messageTextArea.getText().trim();
        String attachment = attachmentTextField.getText() + " ";

        attachments = attachment.split(" ");

        receipients = toAddress + "," + ccAddress;
        receipientsList = receipients.split(",");

        SendMailUsingAuthentication mailUsingAuthentication =
                new SendMailUsingAuthentication();
        try {
                    subject, message, fromAddress, authenticationPassword, attachments);
        } catch (MessagingException messagingException) {

    void login(String userName, String password)
        fromAddress = userName;
        authenticationPassword = password;
        System.out.println("User name : " + fromAddress);

    public static void main(String[] args)
        new MailSender();

This is the Code for send Mail with attachment

/* This code is used for send the mail to the any users.</div>
 * It is done by Java Mail Api.
 * By using this code we can send mail with out enter into your mail Account.
 * @author muneeswaran
package com.mail;

import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMailUsingAuthentication {

    private String HOST_NAME = "gmail-smtp.l.google.com";
    String messageBody;

    public void postMail(String recipients[], String subject, String message,
            String from, String emailPassword, String[] files) throws MessagingException {
        boolean debug = false;
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator authenticator = new SMTPAuthenticator(from, emailPassword);
        Session session = Session.getDefaultInstance(props, authenticator);


        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setContent(message, "text/plain");

        BodyPart messageBodyPart = new MimeBodyPart();

        Multipart multipart = new MimeMultipart();

        //add the message body to the mime message

        // add any file attachments to the message
        addAtachments(files, multipart);
        //Put all message parts in the message
        System.out.println("Sucessfully Sent mail to All Users");

    protected void addAtachments(String[] attachments, Multipart multipart)
            throws MessagingException, AddressException {
        for (int i = 0; i <= attachments.length - 1; i++) {
            String filename = attachments[i];
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            //use a JAF FileDataSource as it does MIME type detection
            DataSource source = new FileDataSource(filename);
            attachmentBodyPart.setDataHandler(new DataHandler(source));
            //add the attachment

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        String username;
        String password;

        private SMTPAuthenticator(String authenticationUser, String authenticationPassword) {
            username = authenticationUser;
            password = authenticationPassword;

        public PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(username, password);

Java Code to View System Task List

February 20, 2010 19 comments


In our day-to-day life, lots of process are running in our system.  For windows machine we use Task Manager and for linux machine we use terminal to view the current tasks running in the system. In this article let us see the tasks which are running in our system using a java code. Our sample code will store the current tasks in a file and store it in a desired location.


 * This code get the process list which are currently running(shows in your task manager) in your system and
 * stored at the file named as "process.txt"
 * Remarks:
 * The file is stored at where this java file is available.
 * Chache the file path which you need
package com.sample.javaapplication;

import java.io.*;
import java.util.StringTokenizer;

 * @author Muneeswaran
public class GetProcessList

 private String GetProcessListData()
 Process p;
 Runtime runTime;
 String process = null;
 try {
 System.out.println("Processes Reading is started...");

 //Get Runtime environment of System
 runTime = Runtime.getRuntime();

 //Execute command thru Runtime
 p = runTime.exec("tasklist");      // For Windows
 //p=r.exec("ps ux");              //For Linux

 //Create Inputstream for Read Processes
 InputStream inputStream = p.getInputStream();
 InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

 //Read the processes from sysrtem and add & as delimeter for tokenize the output
 String line = bufferedReader.readLine();
 process = "&";
 while (line != null) {
 line = bufferedReader.readLine();
 process += line + "&";

 //Close the Streams

 System.out.println("Processes are read.");
 } catch (IOException e) {
 System.out.println("Exception arise during the read Processes");
 return process;

 private void showProcessData()
 try {

 //Call the method For Read the process
 String proc = GetProcessListData();

 //Create Streams for write processes
 //Given the filepath which you need.Its store the file at where your java file.
 OutputStreamWriter outputStreamWriter =
 new OutputStreamWriter(new FileOutputStream("ProcessList.txt"));
 BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

 //Tokenize the output for write the processes
 StringTokenizer st = new StringTokenizer(proc, "&");

 while (st.hasMoreTokens()) {
 bufferedWriter.write(st.nextToken());  //Write the data in file
 bufferedWriter.newLine();               //Allocate new line for next line

 //Close the outputStreams

 } catch (IOException ioe) {


 public static void main(String[] args)
 GetProcessList gpl = new GetProcessList();


Now let us execute our sample program, the output would be the following

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         24 K
System                           4 Services                   0      3,056 K
smss.exe                       412 Services                   0        732 K
csrss.exe                      548 Services                   0      6,076 K
wininit.exe                    592 Services                   0      3,940 K
csrss.exe                      604 Console                    1      8,088 K
services.exe                   636 Services                   0      6,668 K
lsass.exe                      648 Services                   0      2,496 K
lsm.exe                        660 Services                   0      4,016 K
winlogon.exe                   760 Console                    1      5,612 K
svchost.exe                    836 Services                   0      6,328 K
svchost.exe                    924 Services                   0      7,240 K
svchost.exe                    964 Services                   0     40,584 K
svchost.exe                   1032 Services                   0     14,628 K
svchost.exe                   1084 Services                   0     70,888 K
svchost.exe                   1100 Services                   0     28,736 K
audiodg.exe                   1228 Services                   0     14,368 K
svchost.exe                   1264 Services                   0      4,760 K
SLsvc.exe                     1280 Services                   0     10,936 K
svchost.exe                   1324 Services                   0     13,552 K
svchost.exe                   1452 Services                   0     16,036 K
upeksvr.exe                   1568 Console                    1      9,496 K
WLTRYSVC.EXE                  1656 Services                   0      2,700 K
BCMWLTRY.EXE                  1704 Services                   0     20,668 K
aswUpdSv.exe                  1720 Services                   0        388 K
wlanext.exe                   1736 Services                   0      5,108 K
ashServ.exe                   1788 Services                   0     22,492 K
spoolsv.exe                   1628 Services                   0      9,484 K
svchost.exe                   1732 Services                   0     17,292 K
AERTSrv.exe                   2008 Services                   0      1,620 K
httpd.exe                     1888 Services                   0     50,016 K
AppleMobileDeviceService.     2056 Services                   0      3,536 K
mDNSResponder.exe             2068 Services                   0      4,448 K
mysqld-nt.exe                 2140 Services                   0     53,444 K
o2flash.exe                   2180 Services                   0      2,480 K
svchost.exe                   2200 Services                   0      5,192 K
sprtsvc.exe                   2372 Services                   0      1,140 K
svchost.exe                   2432 Services                   0      6,232 K
svchost.exe                   2460 Services                   0      2,156 K
SearchIndexer.exe             2480 Services                   0     32,016 K
ACFXAU32.exe                  2508 Services                   0      2,492 K
httpd.exe                     2876 Services                   0     51,208 K
taskeng.exe                   3524 Services                   0      5,736 K
ashMaiSv.exe                  3572 Services                   0      1,632 K
ashWebSv.exe                  3596 Services                   0     16,152 K
taskeng.exe                   2148 Console                    1     10,556 K
dwm.exe                        804 Console                    1     65,228 K
explorer.exe                  3936 Console                    1     65,360 K
MSASCui.exe                   2176 Console                    1      8,884 K
Apoint.exe                    3996 Console                    1      5,784 K
OEM13Mon.exe                  3640 Console                    1      4,444 K
hkcmd.exe                     1992 Console                    1      4,908 K
igfxpers.exe                  4100 Console                    1      4,024 K
DellWMgr.exe                  4116 Console                    1     10,812 K
igfxsrvc.exe                  4124 Console                    1      5,560 K
WLTRAY.EXE                    4148 Console                    1     20,620 K
PDVDDXSrv.exe                 4180 Console                    1      7,984 K
sprtcmd.exe                   4188 Console                    1      1,692 K
ashDisp.exe                   4196 Console                    1      1,784 K
jusched.exe                   4212 Console                    1      8,408 K
sidebar.exe                   4232 Console                    1     28,612 K
googletalk.exe                4256 Console                    1     29,780 K
YahooMessenger.exe            4272 Console                    1     51,152 K
wmpnscfg.exe                  4288 Console                    1      5,100 K
SSScheduler.exe               4336 Console                    1      3,084 K
quickset.exe                  4344 Console                    1     10,548 K
wweb32.exe                    4352 Console                    1      8,036 K
psqltray.exe                  4560 Console                    1     16,380 K
unsecapp.exe                  4676 Console                    1      4,768 K
ApMsgFwd.exe                  4748 Console                    1      2,816 K
WmiPrvSE.exe                  4804 Services                   0      6,824 K
wmpnetwk.exe                  4904 Services                   0     11,144 K
ApntEx.exe                    4976 Console                    1      3,744 K
hidfind.exe                   5024 Console                    1      3,404 K
WmiPrvSE.exe                  5900 Services                   0      9,488 K
firefox.exe                   5176 Console                    1    197,884 K
netbeans.exe                  3896 Console                    1    223,788 K
googletalkplugin.exe          4740 Console                    1     10,216 K
WinRAR.exe                    5576 Console                    1     15,628 K
SearchProtocolHost.exe        4636 Services                   0      8,364 K
SearchFilterHost.exe          3952 Services                   0      6,636 K
java.exe                      5360 Console                    1     10,308 K
tasklist.exe                  4832 Console                    1      4,644 K

I hope this article helps to view the task list of a Windows or a Linux machine using Java code. If you find this article is useful to you. Don’t forget to leave your valuable comments.