Monday, 29 August 2011

Array in Java

Java Array

When you need to store same ‘type’ of data that can be logically grouped together, then you can go for java array.
For example, imagine if you had to store the list of countries in individual java variables and manipulate them. You will have more than hundred variables to manage. Can’t imagine, it would be tedious in any language. Have you ever seen a decent size application programmed without arrays?
In this article you will not find nothing new about java array. Just the same old theory to refresh and I will try to be comprehensive. If you expect some surprise or hidden thing from java, please ALT-F4.
java array logical view
Array is one among the many beautiful things you have in a programming language. Easy to iterate, easy to store and retrieve using their integer index. In java, nobody can deny using an array I challenge. I know you all started with public static void main(?). The argument for the main method is an array.
In java arrays are objects. All methods of an Object can be invoked on an array. Arrays are stored in heap memory.
java array - physical view
Though you view the array as cells of values, internally they are cells of variables. A java array is a group of variables referenced by a common name. Those variables are just references to a address and will not have a name. These are called the ‘components’ of a java array. All the components must be of same type and that is called as ‘component type’ of that java array.

Java Array Declaration

int []marks;
or
int marks[];

Java Array Instantiation

marks = new int[5];
5 inside the square bracket says that you are going to store five values and is the size of the array ‘n’. When you refer the array values, the index starts from 0 ‘zero’ to ‘n-1′. An array index is always a whole number and it can be a int, short, byte, or char.
Once an array is instantiated, it size cannot be changed. Its size can be accessed by using the length field like .length Its a java final instance field.
All java arrays implements Cloneable and Serializable.

Java array initialization and instantiation together

int marks[] = {98, 95, 91, 93, 97};

ArrayIndexOutOfBoundsException

One popular exception for java beginners is ArrayIndexOutOfBoundsException. You get ArrayIndexOutOfBoundsException when you access an array with an illegal index, that is with a negative number or with a number greater than or equal to its size. This stands second next to NullPointerException in java for popularity.

Java Array Default Values

After you instantiate an array, default values are automatically assigned to it in the following manner.
  • byte – default value is zero
  • short – default value is zero
  • int – default value is zero
  • long – default value is zero, 0L.
  • float – default value is zero, 0.0f.
  • double – default value is zero, 0.0d.
  • char – default value is null, ‘\u0000′.
  • boolean – default value is false.
  • reference types – default value is null.
Notice in the above list, the primitives and reference types are treated differently. One popular cause of NullPointerException is accessing a null from a java array.

Iterating a Java Array

public class IterateJavaArray {
  public static void main(String args[]) {
    int marks[] = {98, 95, 91, 93, 97};
    //java array iteration using enhanced for loop
    for (int value : marks){
      System.out.println(value);
    }
  }
}
In language C, array of characters is a String but this is not the case in java arrays. But the same behaviour is implemented as a StringBuffer wherein the contents are mutable.
ArrayStoreException – When you try to store a non-compatible value in a java array you get a ArrayStoreException.

Multidimensional Arrays

When a component type itself is a array type, then it is a multidimensional array. Though you can have multiple dimension nested to n level, the final dimension should be a basic type of primitive or an Object.
int[] marks, fruits, matrix[];
In the above code, matrix is a multidimensional array. You have to be careful in this type of java array declaration.
Internally multidimensional java arrays are treated as arrays of arrays. Rows and columns in multidimensional java array are completely logical and depends on the way you interpret it.
Note: A clone of a java multidimensional array will result in a shallow copy.

Iterate a java multidimensional array

Following example source code illustrates on how to assign values and iterate a multidimensional java array.
public class IterateMultiDimensionalJavaArray {
  public static void main(String args[]) {
 
    int sudoku[][] = { { 2, 1, 3 }, { 1, 3, 2 }, { 3, 2, 1 } };
 
    for (int row = 0; row < sudoku.length; row++) {
      for (int col = 0; col < sudoku[row].length; col++) {
        int value = sudoku[row][col];
        System.out.print(value);
      }
      System.out.println();
    }
  }
}

Sort a Java array

java api Arrays contains static methods for sorting. It is a best practice to use them always to sort an array.
import java.util.Arrays;
 
public class ArraySort {
  public static void main(String args[]) {
    int marks[] = { 98, 95, 91, 93, 97 };
    System.out.println("Before sorting: " + Arrays.toString(marks));
    Arrays.sort(marks);
    System.out.println("After sorting: " + Arrays.toString(marks));
  }
}
//Before sorting: [98, 95, 91, 93, 97]
//After sorting: [91, 93, 95, 97, 98]


Core Collection Interfaces
The core interfaces that define common functionality and allow collections to be manipulated independent of their implementation.
The 6 core Interfaces used in the Collection framework are:
  • Collection
  • Set
  • List
  • Iterator (Not a part of the Collections Framework)
  • SortedSet
  • Map
  • SortedMap
Note: Collection and Map are the two top-level interfaces.
Collection Interface


Note: Concrete Classes for the Map is shown in the previous section.
Standard utility methods and algorithms
Standard utility methods and algorithms
that can be used to perform various operations on collections, such as sorting, searching or creating customized collections.
How are Collections Used
  • The collections stores object references, rather than objects themselves. Hence primitive values cannot be stored in a collection directly. They need to be encapsulated (using wrapper classes) into an Object prior to storing them into a Collection (such as HashSet, HashMap etc).
  • The references are always stored as type Object. Thus, when you retrieve an element from a collection, you get an Object rather then the actual type of the collection stored in the database. Hence we need to downcast it to the Actual Type while retrieving an element from a collection.
  • One of the capabilities of the Collection Framework is to create a new Collection object and populate it with the contents of an existing Collection object of a same or different actual type.
Below is an example program showing the storing and retrieving of a few Collection Types
import java.util.*;

public class CollectionsDemo {

        public static void main(String[] args) {
               List a1 = new ArrayList();
               a1.add("Beginner");
               a1.add("Java");
               a1.add("tutorial");
               System.out.println(" ArrayList Elements");
               System.out.print("\t" + a1);
               List l1 = new LinkedList();
               l1.add("Beginner");
               l1.add("Java");
               l1.add("tutorial");
               System.out.println();
               System.out.println(" LinkedList Elements");
               System.out.print("\t" + l1);
               Set s1 = new HashSet(); // or new TreeSet() will order the elements;
               s1.add("Beginner");
               s1.add("Java");
               s1.add("Java");
               s1.add("tutorial");
               System.out.println();
               System.out.println(" Set Elements");
               System.out.print("\t" + s1);
               Map m1 = new HashMap(); // or new TreeMap() will order based on keys
               m1.put("Windows", "98");
               m1.put("Win", "XP");
               m1.put("Beginner", "Java");
               m1.put("Tutorial", "Site");
               System.out.println();
               System.out.println(" Map Elements");
               System.out.print("\t" + m1);
        }
}
Output
ArrayList Elements
[Beginner, Java, tutorial]
LinkedList Elements
[Beginner, Java, tutorial]
Set Elements
[tutorial, Beginner, Java]
Map Elements
{Tutorial=Site, Windows=98, Win=XP, Beginner=Java}
Download CollectionsDemo.java
Java Collections Source Code Examples
On the following pages in this tutorial I have described how elements can be manipulated by different collections namely;
Java Date Utility:

Java Date API

java.util.
Class Date
java.lang.Object
extended by java.util.Date
All Implemented Interfaces:
Cloneable, Comparable, Serializable
Direct Known Subclasses:
Date, Time, Timestamp
public class Date extends Object
implements Serializable, Cloneable, Comparable
The class Date represents a specific instant in time, with millisecond precision.

Java Date Source Code

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class DateUtility {
 
        /* Add Day/Month/Year to a Date
         add() is used to add  values to a Calendar object.
         You specify which Calendar field is to be affected by the operation
         (Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
         */
 
        public static final String DATE_FORMAT = "dd-MM-yyyy";
        //See Java DOCS for different date formats
        //      public static final String DATE_FORMAT = "yyyy-MM-dd";
 
        public static void addToDate() {
               System.out.println("1. Add to a Date Operation\n");
               SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
               //Gets a calendar using the default time zone and locale.
               Calendar c1 = Calendar.getInstance();
               Date d1 = new Date();
               //             System.out.println("Todays date in Calendar Format : "+c1);
&lt;font size=-1&gt;
  
  
 
               System.out.println("c1.getTime() : " + c1.getTime());
               System.out.println("c1.get(Calendar.YEAR): "+ c1.get(Calendar.YEAR));
               System.out.println("Todays date in Date Format : " + d1);
               c1.set(1999, 0, 20); //(year,month,date)
               System.out.println("c1.set(1999,0 ,20) : " + c1.getTime());
               c1.add(Calendar.DATE, 20);
               System.out.println("Date + 20 days is : "+ sdf.format(c1.getTime()));
               System.out.println();
               System.out.println("-------------------------------------");
        }
 
        /*Substract Day/Month/Year to a Date
 
         roll() is used to substract values to a Calendar object.
         You specify which Calendar field is to be affected by the operation
         (Calendar.YEAR, Calendar.MONTH, Calendar.DATE).       
 
         Note: To substract, simply use a negative argument.
         roll() does the same thing except you specify if you want to roll up (add 1)
         or roll down (substract 1) to the specified Calendar field. The operation only
         affects the specified field while add() adjusts other Calendar fields.
         See the following example, roll() makes january rolls to december in the same
         year while add() substract the YEAR field for the correct result. Hence add()
         is preferred even for subtraction by using a negative element.
 
         */
 
        public static void subToDate() {
 
               System.out.println("2. Subtract to a date Operation\n");
               SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
               Calendar c1 = Calendar.getInstance();
               c1.set(1999, 0, 20);
               System.out.println("Date is : " + sdf.format(c1.getTime()));
               // roll down, substract 1 month
               c1.roll(Calendar.MONTH, false);
               System.out.println("Date roll down 1 month : "+ sdf.format(c1.getTime()));
               c1.set(1999, 0, 20);
               System.out.println("Date is : " + sdf.format(c1.getTime()));
               c1.add(Calendar.MONTH, -1);
               // substract 1 month
               System.out.println("Date minus 1 month : "+ sdf.format(c1.getTime()));
               System.out.println();
               System.out.println("-------------------------------------");
        }
 
        public static void daysBetween2Dates() {
 
               System.out.println("3. No of Days between 2 dates\n");
               Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
                Calendar c2 = Calendar.getInstance(); //new GregorianCalendar();
               c1.set(1999, 0, 20);
               c2.set(1999, 0, 22);
               System.out.println("Days Between " + c1.getTime() + " and "
                               + c2.getTime() + " is");
               System.out.println((c2.getTime().getTime() - c1.getTime()
                               .getTime())    / (24 * 3600 * 1000));
               System.out.println();
               System.out.println("-------------------------------------");
        }
 
        public static void daysInMonth() {
 
               System.out.println("4. No of Days in a month for a given date\n");
               Calendar c1 = Calendar.getInstance(); // new GregorianCalendar();
               c1.set(1999, 6, 20);
               int year = c1.get(Calendar.YEAR);
               int month = c1.get(Calendar.MONTH);
               // int days = c1.get(Calendar.DATE);
               int[] daysInMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 };
               daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;
               System.out.println("Days in " + month + "th month for year" + year
                               + "is " + daysInMonths[c1.get(Calendar.MONTH)]);
               System.out.println();
               System.out.println("-------------------------------------");
        }
 
        public static void validateAGivenDate() {
 
               System.out.println("5. Validate a given date\n");
               String dt = "20011223";
               String invalidDt = "20031315";
               String dateformat = "yyyyMMdd";
               Date dt1 = null, dt2 = null;
               try {
                       SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
                       sdf.setLenient(false);
                       dt1 = sdf.parse(dt);
                       dt2 = sdf.parse(invalidDt);
                       System.out.println("Date is ok = " + dt1 + "(" + dt + ")");
               } catch (ParseException e) {
                       System.out.println(e.getMessage());
               } catch (IllegalArgumentException e) {
                       System.out.println("Invalid date");
               }
               System.out.println();
               System.out.println("-------------------------------------");
        }
 
        public static void compare2Dates() {
 
               System.out.println("6. Comparision of 2 dates\n");
               SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy");
               Calendar c1 = Calendar.getInstance();
               Calendar c2 = Calendar.getInstance();
               c1.set(2000, 02, 15);
               c2.set(2001, 02, 15);
               System.out.print(fm.format(c1.getTime()) + " is ");
               if (c1.before(c2)) {
                       System.out.println("less than " + fm.format(c2.getTime()));
               } else if (c1.after(c2)) {
                       System.out.println("greater than " + fm.format(c2.getTime()));
               } else if (c1.equals(c2)) {
                       System.out.println("is equal to " + fm.format(c2.getTime()));
               }
               System.out.println();
               System.out.println("-------------------------------------");
        }
 
        public static void getDayofTheDate() {
 
               System.out.println("7. Get the day for a given date\n");
               Date d1 = new Date();
               String day = null;
               DateFormat f = new SimpleDateFormat("EEEE");
               try {
                       day = f.format(d1);
               } catch (Exception e) {
                       e.printStackTrace();
               }
               System.out.println("The day for " + d1 + " is " + day);
               System.out.println();
               System.out.println("-------------------------------------");
        }
 
        //Utility Method to find whether an Year is a Leap year or Not
        public static boolean isLeapYear(int year) {
 
               if ((year % 100 != 0) || (year % 400 == 0)) {
                       return true;
               }
               return false;
        }
 
        public static void main(String args[]) {
               addToDate(); //Add day, month or year to a date field.
               subToDate(); //Subtract day, month or year to a date field.
               daysBetween2Dates();
               //The "right" way would be to compute the Julian day number of
               //both dates and then do the subtraction.
               daysInMonth();//Find the number of days in a month for a date
               validateAGivenDate();//Check whether the date format is proper
               compare2Dates(); //Compare 2 dates
               getDayofTheDate();
        }
}
Output
1. Add to a Date Operation
c1.getTime() : Sat Mar 31 10:47:54 IST 2007
c1.get(Calendar.YEAR): 2007
Todays date in Date Format : Sat Mar 31 10:47:54 IST 2007
c1.set(1999,0 ,20) : Wed Jan 20 10:47:54 IST 1999
Date + 20 days is : 09-02-1999
——————————————————-
2. Subtract to a date Operation
Date is : 20-01-1999
Date roll down 1 month : 20-12-1999
Date is : 20-01-1999
Date minus 1 month : 20-12-1998
——————————————————-
3. No of Days between 2 dates
Days Between Wed Jan 20 10:47:54 IST 1999 and Fri Jan 22 10:47:54 IST 1999 is
2
——————————————————-
4. No of Days in a month for a given date
Days in 6th month for year 1999 is 31
——————————————————-
5. Validate a given date
Unparseable date: “20031315″
——————————————————-
6. Comparision of 2 dates
15-03-2000 is less than 15-03-2001
——————————————————-
7. Get the day for a given date
The day for Sat Mar 31 10:47:54 IST 2007 is Saturday
——————————————————-
Download Date Utility Source Code
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar
Swing Tutorial:

Java Swings Tutorial

What is Swings in java ?
  • A part of The JFC
  • Swing Java consists of
    Look and feel
    Accessibility
    Java 2D
    Drag and Drop, etc
  • Compiling & running programs
‘javac <program.java>’ && ‘java <program>’
Or JCreator / IDE
  • if you do not explicitly add a GUI component to a container, the GUI component will not be displayed when the container appears on the screen.
Swing, which is an extension library to the AWT, includes new and improved components that enhance the look and functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets. It employs a model/view design architecture. Swing is more portable and more flexible than AWT.
Swing Model/view design: The “view part” of the MV design is implemented with a component object and the UI object. The “model part” of the MV design is implemented by a model object and a change listener object.
&lt;br /&gt;&lt;font size=-1&gt;
Swing is built on top of AWT and is entirely written in Java, using AWT’s lightweight component support. In particular, unlike AWT, t he architecture of Swing components makes it easy to customize both their appearance and behavior. Components from AWT and Swing can be mixed, allowing you to add Swing support to existing AWT-based programs. For example, swing components such as JSlider, JButton and JCheckbox could be used in the same program with standard AWT labels, textfields and scrollbars. You could subclass the existing Swing UI, model, or change listener classes without having to reinvent the entire implementation. Swing also has the ability to replace these objects on-the-fly.
  • 100% Java implementation of components
  • Pluggable Look & Feel
  • Lightweight components
  • Uses MVC Architecture
    Model represents the data
    View as a visual representation of the data
    Controller takes input and translates it to changes in data
  • Three parts
    Component set (subclasses of JComponent)
    Support classes
    Interfaces
In Swing, classes that represent GUI components have names beginning with the letter J. Some examples are JButton, JLabel, and JSlider. Altogether there are more than 250 new classes and 75 interfaces in Swing — twice as many as in AWT.
Java Swing class hierarchy
The class JComponent, descended directly from Container, is the root class for most of Swing’s user interface components.
http://www.javabeginner.com/images/java-swing.gif
Swing contains components that you’ll use to build a GUI. I am listing you some of the commonly used Swing components. To learn and understand these swing programs, AWT Programming knowledge is not required.

Java Swing Examples

Below is a java swing code for the traditional Hello World program.
Basically, the idea behind this Hello World program is to learn how to create a java program, compile and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse.
import javax.swing.JFrame;
import javax.swing.JLabel;
 
//import statements
//Check if window closes automatically. Otherwise add suitable code
public class HelloWorldFrame extends JFrame {
 
        public static void main(String args[]) {
               new HelloWorldFrame();
        }
        HelloWorldFrame() {
               JLabel jlbHelloWorld = new JLabel("Hello World");
               add(jlbHelloWorld);
               this.setSize(100, 100);
               // pack();
               setVisible(true);
        }
}
Output
http://www.javabeginner.com/images/java-swing-example.jpg
Note: Below are some links to java swing tutorials that forms a helping hand to get started with java programming swing.
  • JPanel is Swing’s version of the AWT class Panel and uses the same default layout, FlowLayout. JPanel is descended directly from JComponent.
  • JFrame is Swing’s version of Frame and is descended directly from that class. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane instead.
  • JInternalFrame is confined to a visible area of a container it is placed in. It can be iconified , maximized and layered.
  • JWindow is Swing’s version of Window and is descended directly from that class. Like Window, it uses BorderLayout by default.
  • JDialog is Swing’s version of Dialog and is descended directly from that class. Like Dialog, it uses BorderLayout by default. Like JFrame and JWindow,
    JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All dialogs are modal, which means the current
    thread is blocked until user interaction with it has been completed. JDialog class is intended as the basis for creating custom dialogs; however, some
    of the most common dialogs are provided through static methods in the class JOptionPane.
  • JLabel, descended from JComponent, is used to create text labels.
  • The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including
    JButton.
  • JTextField allows editing of a single line of text. New features include the ability to justify the text left, right, or center, and to set the text’s font.
  • JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each character entered can be replaced by an echo character.
    This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *.
  • JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar;
    JButton is a component the user clicks to trigger a specific action.
  • JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio buttons can be associated as a group in which only
    one button at a time can be selected.
  • JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state.
  • JComboBox is like a drop down box. You can click a drop-down arrow and select an option from a list. For example, when the component has focus,
    pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists.
  • JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not
    support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined
    border. JList actions are handled using ListSelectionListener.
  • JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image.
  • JToolbar contains a number of components whose type is usually some kind of button which can also include separators to group related components
    within the toolbar.
  • FlowLayout when used arranges swing components from left to right until there’s no more space available. Then it begins a new row below it and moves
    from left to right again. Each component in a FlowLayout gets as much space as it needs and no more.
  • BorderLayout places swing components in the North, South, East, West and center of a container. You can add horizontal and vertical gaps between
    the areas.
  • GridLayout is a layout manager that lays out a container’s components in a rectangular grid. The container is divided into equal-sized rectangles,
    and one component is placed in each rectangle.
  • GridBagLayout is a layout manager that lays out a container’s components in a grid of cells with each component occupying one or more cells,
    called its display area. The display area aligns components vertically and horizontally, without requiring that the components be of the same size.
  • JMenubar can contain several JMenu’s. Each of the JMenu’s can contain a series of JMenuItem ’s that you can select. Swing provides support for
    pull-down and popup menus.
  • Scrollable JPopupMenu is a scrollable popup menu that can be used whenever we have so many items in a popup menu that exceeds the screen visible height.

Java Swing Projects

  • Java Swing Calculator developed using Java Swing. It is a basic four-function calculator java program source code.
  • Java Swing Address Book demonstrates how to create a simple free address book program using java swing and jdbc. Also you will learn to use
    the following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout).