import javax.swing.*;
import javax.swing.event.*;
public class HelloWorldSwing {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Monday, December 22, 2008
How to create a executable Jar
Posted by sathish at 12/22/2008 08:45:00 AM 0 comments
Labels: java
Thursday, December 18, 2008
Fifteen Exercises for Learning a new Programming Language
First of all, get familiar with Compiler, compiler option, editor shortcuts or integrated development environment (IDE). Start with a simple 'Hello World' program. Compile it. Use basic functionalities of debugger like setting break points, printing variable values, moving to the next or specific position, stopping debugger etc.
To grasp basics of a new language quickly, here are the exercises I use. Remember some programs may not good for beginners.
1. Display series of numbers (1,2,3,4, 5....etc) in an infinite loop. The program should quit if someone hits a specific key (Say ESCAPE key).
2. Fibonacci series, swapping two variables, finding maximum/minimum among a list of numbers.
3. Accepting series of numbers, strings from keyboard and sorting them ascending, descending order.
4. Reynolds number is calculated using formula (D*v*rho)/mu Where D = Diameter, V= velocity, rho = density mu = viscosity
Write a program that will accept all values in appropriate units (Don't worry about unit conversion)
If number is < 2100, display Laminar flow,
If it’s between 2100 and 4000 display 'Transient flow' and
if more than '4000', display 'Turbulent Flow' (If, else, then...)
5. Modify the above program such that it will ask for 'Do you want to calculate again (y/n),
if you say 'y', it'll again ask the parameters. If 'n', it'll exit. (Do while loop)
While running the program give value mu = 0. See what happens. Does it give 'DIVIDE BY ZERO' error?
Does it give 'Segmentation fault..core dump?'. How to handle this situation. Is there something built
in the language itself? (Exception Handling)
6. Scientific calculator supporting addition, subtraction, multiplication, division, square-root, square, cube,
sin, cos, tan, Factorial, inverse, modulus
7. Printing output in different formats (say rounding up to 5 decimal places, truncating after 4 decimal places,
padding zeros to the right and left, right and left justification)(Input output operations)
8. Open a text file and convert it into HTML file. (File operations/Strings)
9. Time and Date : Get system time and convert it in different formats 'DD-MON-YYYY', 'mm-dd-yyyy', 'dd/mm/yy' etc.
10. Create files with date and time stamp appended to the name
11. Input is HTML table, Remove all tags and put data in a comma/tab separated file.
12. Extract uppercase words from a file, extract unique words
13. Implement word wrapping feature (Observe how word wrap works in windows 'notepad')
14. Adding/removing items in the beginning, middle and end of the array.
15. Are these features supported by your language: Operator overloading, virtual functions, references, pointers etc.
Is there something called 'namespace / package / module' supported by your language? (Name mangling) - Read More on this.
Article written by Prashant N Mhatre.
Posted by sathish at 12/18/2008 08:25:00 AM 0 comments
Wednesday, November 19, 2008
Friday, October 31, 2008
Dojo
Posted by sathish at 10/31/2008 09:03:00 AM 0 comments
Monday, September 22, 2008
How to validate e-mail?
function validateEmail(email) {
return (email.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/ig) != null) ? true : false;
}
try {
InteretAddress address = new InternetAddress(emailstring);
address.validate();
return true;
}
catch(AddressException e) {
return false;
}
Posted by sathish at 9/22/2008 10:23:00 AM 0 comments
Wednesday, September 17, 2008
Outlook: Saving Embedded Images
Posted by sathish at 9/17/2008 06:09:00 AM 0 comments
Tuesday, September 02, 2008
Ruby on Rails - Part 1: Hello World
Posted by sathish at 9/02/2008 05:32:00 AM 0 comments
Labels: Ruby, Ruby on Rails
Introduction to Ruby on Rails
Posted by sathish at 9/02/2008 05:31:00 AM 0 comments
Labels: Ruby, Ruby on Rails
Ruby on Rails Demo
Posted by sathish at 9/02/2008 05:31:00 AM 0 comments
Labels: Ruby, Ruby on Rails
Ruby on Rails vs Java
Posted by sathish at 9/02/2008 05:30:00 AM 0 comments
Labels: Ruby, Ruby on Rails
Monday, September 01, 2008
Façade Pattern
- A facade hides all the complexity of one or more classes
- Similar to Adapter pattern, it alters an interface, but for a different reason to simplify the interface
- Façades and adapters may wrap multiple classes, but a façade's intent is to simplify, while an adapter's is to convert the interface to something different
- A façade not only simplifies an interface, it decouples a client from a subsystem of components
- It provides a simplified interface while still exposing the full functionality of the system to those who may need it
- Façades don't encapsulate the subsystem classes they merely provide a simplified interface to their functionality
- The subsystem classes still remain available for direct use by clients that need to use more specific interfaces
- The façade can also add additional functionality in addition to making use of the subsystem
- It is not necessary that each subsystem should have only one façade, any number of façades can be created for a given subsystem
- Following is an example of a façade for a home theater system
public class HomeTheaterFacade {
Amplifier amp;
DvdPlayer dvd;
Projector projector;
Screen screen;
Tuner tuner;
public HomeTheaterFacade(Amplifier amp,
DvdPlayer dvd,
Projector projector,
Screen screen,
Tuner tuner) {
this.amp = amp;
this.dvd = dvd;
this.projector = projector;
this.screen = screen;
this.tuner = tuner;
}
public void watchMovie() {
}
public void endMovie() {
}
}
- The Façade Pattern provides a unified interface to a set of interfaces in a subsystem
- Façade defines a higher-level interface that makes the subsystem easier to user
- To use the façade pattern, we create a class that simplifies and unifies a set of more complex classes that belong to some subsystem
- It allows us to avoid tight coupling between clients and subsystems
Posted by sathish at 9/01/2008 10:34:00 AM 0 comments
Labels: design, design pattern
Friday, August 22, 2008
Composition vs. Aggregation
Composition
- Composition allows us to use behavior from a family of other classes, and to change that behavior at runtime
- Composition is most powerful when we want to use behavior defined in an interface, and then choose from a variety of implementations of that interface, at both compile time and run time
- Composition is like a string "has a" relationship - the components that make up the parent cannot existing without the parent
- When an object is composed of other objects, and the owning object is destroyed, the objects that are part of the composition goes away too
- A real world example may be - a human body is composed of different parts hands, legs etc. But without the body, the parts cannot exist alone
- A code example using a car example
Car car = new Car();
car.setProperty("engine", new Engine()); - When the "car" object is destroyed, so is the Engine object created in the second line. It is destroyed along with the owning object
- Simply there is no reference for the component object outside the owning object
- In composition, the object composed of other behaviors owns those behaviors
- When the object is destroyed, so are all of its behaviors
- The behaviors in a composition do not exist outside of the composition
- The main object owns the composed behavior, so if that object goes away, all the behavior does too
- The UML diagram for composition uses a darkened diamond - signifying the strong relationship
Aggregation
- Aggregation is when one class is used as part of another class, but still exists outside of that other class
- Aggregation is a kind of association that specifies a whole/part relationship between the aggregate(whole) and component part
- This relationship between the aggregate and component is a weak "has a" relationship as the component may survive the aggregate object
- Unlike composition, here, the component object may outlive the aggregate object
- A code example using a Course/Student example
course.addStudent(student);
- The student object has its own behavior, and its state can influence the state of the course object (for instance, the aggregate mark for the course etc.)
- Even if the course object is destroyed, student object will live on
- The UML diagram for aggregation uses an empty diamond
Aggregation vs. Composition
- The easiest way to figure out when to use what is to ask - does the object whose behavior I want to use exist outside of the object that uses its behavior?
- If the object does make sense existing on its own, then we should use aggregation, if not use composition
Posted by sathish at 8/22/2008 09:02:00 AM 0 comments
Labels: design
Saturday, August 16, 2008
Thursday, July 10, 2008
ThreadLocal
ThreadLocal class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
For example, in the class below, the private static ThreadLocal instance (serialNum) maintains a "serial number" for each thread that invokes the class's static SerialNum.get() method, which returns the current thread's serial number. (A thread's serial number is assigned the first time it invokes SerialNum.get(), and remains unchanged on subsequent calls.)
public class SerialNum { // The next serial number to be assigned private static int nextSerialNum = 0; private static ThreadLocal serialNum = new ThreadLocal() { protected synchronized Object initialValue() { return new Integer(nextSerialNum++); } }; public static int get() { return ((Integer) (serialNum.get())).intValue(); } } Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).
Posted by sathish at 7/10/2008 11:11:00 AM 0 comments
Thursday, June 05, 2008
Java Preferences API
This Java Preferences API is not indented to save application data. The Java Preference API removes the burden from the individual programmer to write code to save configuration values on the different platforms his program may be running.
The Preferences API provides a systematic way to handle program preference configurations, e.g. to save user settings, remember the last value of a field etc.
Preferences are key / values pairs where the key is an arbitrary name for the preference. The value can be a boolean, string, int of another primitive type. Preferences are received and saved by get and put methods while the get methods also supply a default value in case the preferences is not yet set.
The actual storage of the data is dependent on the platform, e.g. under Windows the Windows Registry is used while under Linux a hidden file in the home directory of the user is used.
java.util.prefs.Preferences can be easily used. You have to define a node in which the data is stored. Then you can call the getter and setter methods. The second value is the default value, e.g. if the preference value is not set yet, then this value will be used.
Create the following program.
import java.util.prefs.Preferences;
public class PreferenceTest {
private Preferences prefs;
public void setPreference() {
// This will define a node in which the preferences can be stored
prefs = Preferences.userRoot().node(this.getClass().getName());
String ID1 = "Test1";
String ID2 = "Test2";
String ID3 = "Test3";
// First we will get the values
// Define a boolean value
System.out.println(prefs.getBoolean(ID1, true));
// Define a string with default "Hello World
System.out.println(prefs.get(ID2, "Hello World"));
// Define a integer with default 50
System.out.println(prefs.getInt(ID3, 50));
// Now set the values
prefs.putBoolean(ID1, false);
prefs.put(ID2, "Hello Europa");
prefs.putInt(ID3, 45);
// Delete the preference settings for the first value
prefs.remove(ID1);
}
public static void main(String[] args) {
PreferenceTest test = new PreferenceTest();
test.setPreference();
}
}
Run the program twice. The value of "ID1" should be still true as we delete it. The value of "ID2" and "ID2" should have changed after the first call.
Posted by sathish at 6/05/2008 10:45:00 AM 0 comments
Friday, May 23, 2008
The 7 Habits of Highly Effective Developers
If you want to achieve your highest aspirations and overcome your greatest challenges, identify and apply the principle or natural law that governs the results you seek. How we apply a principle will vary greatly and will be determined by our unique strengths, talents, and creativity, but, ultimately, success in any endeavor is always derived from acting in harmony with principles to which the success is tied. This advice comes from Steven Covey in his best-selling book, The 7 Habits of Highly Effective People. If you haven't read this book yet, you must. It's about effecting change from the inside out for success in both your personal and professional life by aligning your values with principles through practicing seven habits. Before reading this book, I felt like a passenger on a career freight-train. like something put in motion that I was powerless to control. What I was practicing in my career, my habits, was misaligned with my values, and my values were misaligned with unmovable principles. Although I was powerless over the career train, I came to realize I had the power to choose which train I was on. So here I am at a company that allows me to follow my passion: developing software.
The 7 Habits book is broadly focused, and it made me think about habits specific to my profession. What do those software developers that I consider effective (if not brilliant) have in common? What values drive their decisions and what habits do they practice that make them successful? Here are the seven habits that I think effective developers practice:
Passionate
The most brilliant people I've worked with are passionate about what they do. They aren't driven by money and fame and, I say this with tongue in cheek, if they didn't have families to feed, would develop software without compensation. If I had two candidates for a development position, I'd rather hire a less-experienced person with passion than a more experienced person without. If you aren't passionate about software development, find what you are passionate about and follow that path.
Able to Learn, Unlearn and Re-learn
I believe that learning is an extension of passion, and effective developers operate in a continuum of improvement and innovation. They learn from their and others' mistakes and don't apply old solutions to new problems just because they worked before. Effective developers follow technology, but are careful to not let new approaches become solutions looking for a problem.
Balance Principle and Practice
Principle and practice are the Yin and Yang of software development. Effective developers don't design impractical solutions for the sake of principle and don't implement solutions without overarching values. They are willing to compromise based on time, cost, scope and quality constraints, but can also obtain compromise from others based on sound principles.
Keep It Simple Software (KISS)
Effective developers implement the simplest possible thing that will work while not painting themselves into a corner. They don't implement anything more than is needed right now, remaining mindful about what might be needed in the future. Effective developers know that the less moving parts there are, the less likely it will break and favor elegance and simplicity over convoluted cleverness.
If You Don't Know the Answer, Know Someone Who Does
Software developers aren't renown for their social prowess, but some of the most effective developers I know are excellent at networking. If you give a random 100 question test to a group of people, no one individual will score 100%, but collectively, with few exceptions, the group can answer all the questions correctly. There is so much technology, so many areas of speciality, you can only be an expert on one, maybe two subject areas. Effective developers know the limit of their knowledge, aren't afraid to admit when they don't know something and have many friends and colleagues in their network they can reach out to for help.
Focus on Value
Effective developers understand the forces driving the project, its stakeholders and their goals. Using this knowledge to guide their decision making, they focus on delivering tangible value to their customers over anything else. Effective developers prioritize work based on its value--the so called "bang for the buck," and avoid projects and features they don't believe in.
Puts the Needs of the Many Before the Needs of the One
I've seen small teams accomplish extraordinary things; it's amazing what "two guys and a laptop" can accomplish. Call it teamwork or synergy or whatever you like, when a group of people put common goals before their own, they converge like light into a laser beam. Contrast this with the arrogant, rogue and cowboy developers who go against team standards or design intents because "that's how I do it" or "that's how you should do it." The message they are really sending is "I am smarter than the team."
Conclusion
These seven habits give me something to work towards and keep me focused. I only had room for seven habits in this article, and I'm sure you can think of many more or define effective in your own way. The important thing is to take a value-driven approach to your software development career and do intentional things that move you towards your definition of success.
Posted by sathish at 5/23/2008 06:28:00 AM 0 comments

