Posts tagged ‘Java Tutorial’

Java Tutorial – Sorting and Searching Data

We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial CD

.

Java Tutorial – Sorting, Searching and Recursion

Once you start to use data structures in Java, you will inevitably encounter situations in which you need to sort or search through them. For the purposes of this beginners Java tutorial, we will use arrays to illustrate some basic sorting, searching and recursive algorithms.

An algorithm is a procedure, a series of steps that you define to solve a particular problem. In the examples below, our algorithms will be expressed in the Java code that we use in our programs.

Recursion

Some of the techniques we will be using rely on recursive processes, so let’s explore these first. A recursive method in your program is basically one that calls itself, i.e. within the method body, there will be a call to the method itself. Using recursive methods effectively can take a bit of practice, as your program can easily get caught in a loop, so you need to think the procedure in any such method through carefully.

To demonstrate a recursive function in action, let’s create a trivial example. Create a new Java project and enter the following in your main class, after the main method:

//recursive method
public static int doSomething(int someNumber)
{
		//check the value of the input parameter
	if(someNumber<=0)
		return someNumber;
	else
	{
			//decrement and call the method again
		someNumber--;
		System.out.println(someNumber);
		return(doSomething(someNumber));
	}
}

Now call the new method within your main method:

int result = doSomething(10);
System.out.println("done: " + result);

All the program does is count down from the passed int value to zero. Experiment by changing the value of the int parameter passed to the method and observe what effect it has on the output printed to the console. The method manages to avoid getting stuck in a loop (caused by calling itself repeatedly) by having the conditional ‘if’ statement.

This simple recursive method has much the same effect as a loop, but, as you’ll see, recursion can be particularly useful when you have a complex problem that is best solved in stages, each stage taking you a step closer to the solution by simplifying it. A necessary ingredient for recursive methods then is that you specify explicitly how the method should behave with the simplest input, and then with each iteration, you work towards this simplest case. In the example above, the simplest case is when the int parameter is less than or equal to zero.

Try not to worry if this seems an odd practice at first, once you start using sorting methods the recursive approach will become clearer.

Sorting

The main reason for keeping a collection of data in sorted order is that it is far easier to find items within the data and therefore maintain it effectively. Keeping the data in sorted order does, however, involve a certain amount of processing, particularly when adding or deleting items.

When we say, for example, that an array is in sorted order, we mean that the items within the array are arranged according to some understood ordering system. Sometimes this is intuitive, for example if the array contains numbers, sorted order will naturally comprise numbers stored according to ascending (or sometimes descending) numerical value. Similarly, if the array contains String values, sorted order will generally mean alphabetical order.

However, there are cases when sorted order will be less clear – imagine you have created your own class declaration for use within your program, and you wish to store objects of your class in the array. You will have to decide then what constitutes sorted order for these objects. In order to do this you have to think about comparing two objects of the same class. When you compare two objects of the class, it must be that case that either one is ‘greater’ than the other, or they are ‘equal’. This is how your objects will be ordered, and to provide this in your own classes they will need to implement the Comparable interface, which means that your objects provide a compareTo method. Within this method you will need to decide how to measure the objects of your class against one another, for example, you might decide to use the value of some variable in the class.

Note: be careful when using the ‘equals’ method on your objects also, as the default equals method inherited from the Class Object, actually tests the object references, i.e. it tests to see whether the two variable names are pointing to the same object. If you plan to use the equals method, you would be best to provide your own implementation of the method, overriding the default for this reason.

For the purposes of this Java tutorial, we will stick to simple types in order to illustrate the algorithms required.

Selection Sort

Selection sort works by continually finding the next smallest item in the collection and placing it at the front. Create a new program and enter the following code in your main method to create an array with some arbitrary data in it:

	//array with unsorted int data
int [] myData = {3, 1, 9, 5, 7};

Now we will use selection sort to arrange the items in the array in ascending numerical order. The selection sort technique is as follows:

  • Within the section of data that is yet to be sorted (initially the whole structure), find the smallest item
  • Place this item at the first position (of the unsorted section), swapping it with any element that’s already there
  • The unsorted section now contains one less item (the item just deemed smallest and therefore moved)
  • Continue placing the smallest unsorted item in first position until all of the data has been sorted

Enter the following code after declaring the array and compile your program, observing its output:

	//loop through the array
for(int pos=0; pos<myData.length-1; pos++)
{
		/* find and keep track of the smallest
		 * element's position
		 * -start at pos and look through the rest
		 * (pos is at the start of the unsorted section)
		 */
	int minIndex = pos;

		//loop through the unsorted section
	for(int next=pos+1; next<myData.length; next++)
	{
		if(myData[minIndex]>myData[next])
			minIndex=next;
	}

		//swap the item if necessary
	if(minIndex!=pos)
	{
			//keep track of the value currently at pos
		int temp = myData[pos];
			//copy the new smallest value into pos
		myData[pos] = myData[minIndex];
			//copy the swapped value into minIndex
		myData[minIndex] = temp;
	}

		//print the array for demonstration
	for(int p : myData)
	{	System.out.print(p);	}
	System.out.println();
}

When you look at the program output, try to work through which items are being swapped with one another at each stage – experiment by changing the int values (or their order) in the array.

Merge Sort

A more efficient approach to sorting the contents of an array is Merge Sort, which uses a recursive algorithm. This rests on the idea that merging two already sorted arrays is a simpler problem than sorting all of the data in one unsorted array. The algorithm therefore sorts an unsorted array by continually dividing it into two parts and sorting each part, merging the results into a final sorted array.

Add the following method to your program (after the main method):

/* mergeSort method sorts the data in a section of
	 * the array passed
	 * -parameters are the array containing the data to
	 *  be sorted, a temporary array for use with the
	 *  processing, and integers representing the start
	 *  and end positions of what data is to be sorted
	 *  within the array
	 */
public static void mergeSort(int[] dataArray, int[] tempArray,
							int start, int end)
{
		//array has been sorted
	if(start==end)
		return;
		//work towards sorted array by breaking the problem down
	else
	{
			//divide the data into two
		int center = (start+end)/2;
			//call the method on the first half
		mergeSort(dataArray, tempArray, start, center);
			//second half
		mergeSort(dataArray, tempArray, center+1, end);

			//merge the two halves into one sorted half
		int firstIndex = start;
		int secondIndex = center+1;
		int thirdIndex = start;

			//loop through both halves
		while(thirdIndex<=end)
		{
				/* work through both halves
				 * inserting smallest item into
				 * the temp array each time
				 */
			if(secondIndex>end ||
			(firstIndex<=center &&
			dataArray[firstIndex]<=dataArray[secondIndex]))
			{
				tempArray[thirdIndex]=dataArray[firstIndex];
				thirdIndex++;
				firstIndex++;
			}
			else
			{
				tempArray[thirdIndex]=dataArray[secondIndex];
				thirdIndex++;
				secondIndex++;
			}
		}
			//copy the temp contents into the main array
		for(int i=start; i<=end; i++)
			dataArray[i]=tempArray[i];
	}
}

Each time the method reaches the point of merging two halves, each half has already been sorted, since the mergeSort method has been first called on them, and on their subsections before they come to be merged, and so on. The method therefore solves the problem by repeatedly simplifying it and solving the simpler problems in turn. Now call the new method from your main method:

	//array to sort
int[] someData = {4, 3, 7, 6, 2, 8, 5, 9, 1};
	//extra helper array
int[] extraArray = new int[someData.length];
	//call the mergesort method on the whole array
mergeSort(someData, extraArray, 0, someData.length-1);

	//print the sorted array for testing
for(int pr : someData)
{ System.out.print(pr); }

Again, experiment by changing the values in the input array and observing the program output.

It can be difficult to get into the ‘recursive’ way of thinking and certainly requires practice, but once you do you will tend to find that you identify problems that could benefit from a recursive solution fairly quickly. It can help when writing a recursive method if you start from the simplest case, then take care of the steps that work towards it each time the method executes (rather than starting from the most complex input, which is the first one to be executed, and can therefore seem an intuitive starting point).

Searching

You will often face the task of finding a particular element in a data structure for one reason or another. If your array data is unsorted, the only way to do this is to look through each of the elements in turn. This is known as linear search – enter the following code in your main method:

//collection of arbitrary strings
String[] myStrings = {"potato", "carrot", "turnip",
		"onion", "leek", "courgette", "aubergine"};
	//find the index of 'leek'
int foundIndex=-1;
	//loop through the array
for(int veg=0; veg
	//binary search method
public static int binarySearch(String[] theData, String wanted)
{
		//-1 means item not found
	int foundIndex=-1;

		//keep track of both ends of searchable area
	int top = theData.length-1;
	int bottom = 0;

		//loop through, dividing searchable area each time
	while(bottom<=top)
	{
			//look at middle element
		int middle = (top+bottom)/2;

			//compare middle element to item searched for
		int comp = theData[middle].compareTo(wanted);

			//middle is item searched for
		if(comp==0)
			return middle;

			/* if middle element is greater,
			 * wanted element must be in lower half
			 * and vice-versa, so we reduce the
			 * searchable area accordingly
			 */

		else if(comp>0) //middle is greater
			top=middle-1;
		else //middle is lesser
			bottom=middle+1;

	}
		//finished searching
	return foundIndex;
}

Now call the method within your main method:

//array of sorted strings
String[] sortedStrings = {"aubergine", "carrot", "courgette",
		"leek", "onion", "potato", "turnip"};

	//call the method - returns -1 if item not found
int searchResult = binarySearch(sortedStrings, "potato");

System.out.println("found at index: "+searchResult);

Experiment with the code by searching for different elements in the array – you can also check how many iterations of the loop are required each time by including a System.out.print statement within the while loop in your binarySearch method. It is generally a good practice to include such ‘trace statements’ in your code, to check exactly what is happening at any stage in the program; it can be particularly helpful when debugging larger programs.

Although many of Java’s built-in datatypes provide sorting and searching methods, it can help with the efficiency of your own programs to think about the algorithms involved. Also, when you come to define your own data types, you may need to implement such methods yourself. There are numerous approaches to sorting and searching in Java, the examples above being only an introduction.

January 7, 2009 at 6:32 pm Leave a comment

Beginners Java Tutorial – Building a User Interface

We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial Videos

.

Beginners Java Tutorial – Building  User Interfaces

The Java language features a range of resources for building user interfaces. In this tutorial, we will use Swing and AWT to build a simple Graphical User Interface. The Swing libraries provide the graphical elements and AWT allows you to respond to user interaction.

Open your chosen IDE and create a new project. Create a Main Class (with your main method in it, but leave it empty for now) and a second Class, called MyGUI. In this Class, enter the following (don’t be alarmed if some of the syntax is unfamiliar, explanation follows):

/**
 * MyGUI User Interface Class
 */

//imports for graphics and user interaction
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * MyGUI class represents a graphical user interface
 * @author Your Name
 */
public class MyGUI extends JFrame implements ActionListener {

	/**
	 * Constructor function creates and displays
	 * the basic elements in the GUI
	 */
	public MyGUI()
	{
			//constructor code ...

	}

	/**
	 * actionPerformed will determine how the program
	 * responds to user interaction
	 */
	public void actionPerformed(ActionEvent e)
	{
			//event code ...

	}
}

Let’s look at the individual code elements:

  • The import statements allow us to use the Swing and AWT libraries for building our interface
  • In the line:
    • ‘extends JFrame’ relies on the notion of Inheritance, but don’t worry if you haven’t come across it before, at this stage you can simply treat the line as a formula that you use for any user interface Class.
      The Class inherits from the Class JFrame, meaning JFrame is its superclass.
    • ‘implements ActionListener’ has to do with Java Interface declarations – again, if this is unfamiliar to you don’t worry, just use this code whenever you need to respond to user interaction.
      The Class implements the ActionListener interface, meaning that it must provide the methods outlined in that Interface declaration.
  • public class MyGUI extends JFrame implements
    ActionListener
  • The method actionPerformed(ActionEvent e) must be provided whenever ActionListener is being implemented – this is where the code responding to user interaction will go. More on this follows.

Now we will add some ‘widgets’ to our GUI, to do this we need to create an instance variable for each, and constructor code to display them.

The first thing to do within the constructor is specify the window properties, such as size, location etc. Then, we need to create Panels to hold our widgets. The default layout for a JFrame GUI is called ‘Border Layout’; this means that items can bee added in positions North, South, East, West and Center. However, you can change the layout, as we will in one section below, in this case to Grid Layout, in which you can have a specified number of rows and columns. When you do this, items are given consecutive positions left to right/ top to bottom as you add them to the GUI (first being leftmost/topmost). The widgets themselves need to be instantiated within the constructor also, as you can see below. Our GUI will have a button, a checkbox and two radio buttons – enter the code:

/**
 * MyGUI User Interface Class
 */

//imports for graphics and user interaction
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * MyGUI class represents a graphical user interface
 * @author Your Name
 */
public class MyGUI extends JFrame implements ActionListener {

		//instance variables - elements in the GUI
	private JButton myButton;
	private JRadioButton firstRadio, secondRadio;
	private JCheckBox myCheck;

	/**
	 * Constructor function creates and displays
	 * the basic elements in the GUI
	 */
	public MyGUI()
	{
			//set the window properties
		setTitle("My GUI");
		setSize(200, 200);
		setLocation(100, 100);

			//create Panels
		JPanel northPanel = new JPanel();
		JPanel centerPanel = new JPanel();
		JPanel southPanel = new JPanel();
		add(northPanel, "North");
		add(centerPanel, "Center");
		add(southPanel, "South");

			//create widgets
		myButton = new JButton("a button");
		firstRadio = new JRadioButton("pick me");
		secondRadio = new JRadioButton("or me");
		myCheck = new JCheckBox("check me");

			//add widgets to the GUI - button
		northPanel.add(myButton);

			//create grid layout for centre (radio buttons)
		GridLayout myGrid = new GridLayout(1, 2);//1 row, 2 cols
		centerPanel.setLayout(myGrid);
		centerPanel.add(firstRadio);
		centerPanel.add(secondRadio);
			//create button group - only one may be selected
		ButtonGroup myGroup = new ButtonGroup();
		myGroup.add(firstRadio);
		myGroup.add(secondRadio);

			//add checkbox
		southPanel.add(myCheck);

			//make the GUI visible
		setVisible(true);
	}

	/**
	 * actionPerformed will determine how the program
	 * responds to user interaction
	 */
	public void actionPerformed(ActionEvent e)
	{
			//event code ...

	}
}

Try not to be intimidated by the amount of code, creating user interfaces can be long-winded but really is simple to program. Now, return to your main method and enter the following:

	//create an instance of the MyGUI class
MyGUI myGui = new MyGUI();

Run your program, it should look something like this:

gui

 

 

 

 

 

 

You’ll notice that although you can interact with the buttons etc, nothing actually happens when you do so – let’s add code to detect this interaction. At the end of your MyGUI constructor code (before setVisible) add the following:

	//listen for user interaction
myButton.addActionListener(this);
firstRadio.addActionListener(this);
secondRadio.addActionListener(this);
myCheck.addActionListener(this);

Now, whenever someone interacts with your buttons, the actionPerformed method will be called, passing information about the ‘event’ in the ActionEvent parameter. In the actionPerformed method, we therefore need to decide how to respond:

/**
 * actionPerformed will determine how the program
 * responds to user interaction
 */
public void actionPerformed(ActionEvent e)
{
		//which component had an event?
	if(e.getSource()==myButton)
	{
			//the button
		System.out.println("Someone pressed the button!");
	}
	else if(e.getSource()==firstRadio)
	{
			//first radio button
		System.out.println("first");
	}
	else if(e.getSource()==secondRadio)
	{
			//second radio
		System.out.println("second");
	}
	else
	{
			//must be checkbox
		boolean selected = myCheck.isSelected();
		System.out.println((selected ? "checked" : "unchecked"));
	}

}

Run the program and see what happens when you interact with the buttons now, you should see results printed to the output console.

You never call the actionPerformed method explicitly in your own code, it is called automatically when events are detected on any component you have added and ActionListener to. Obviously your real applications will have more sophisticated ways of responding to events, but this overview should indicate the basic pattern that you can adopt to create user interfaces in Java. The Swing library contains numerous resources you can experiment with such as TextAreas/Fields, ComboBoxes and more.

December 10, 2008 at 12:44 pm Leave a comment

Beginners Java Tutorial – Objects and Classes

We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial Videos – Programming

.

Java Tutorial – Objects and Classes

This Java tutorial assumes some very basic Java knowledge, e.g. method syntax.

Objects are the key to building robust and efficient Java applications. When developing a large or complex system, developers begin the design process by dividing up the various project requirements into application components. These are ultimately represented by Objects within the application, and are implemented in code by Class declarations. While it might be difficult to perceive the advantages to this technique while you’re learning (and working on small projects), if you adopt the right practices at this stage, you will develop the skills required for professional Java development.

Creating Objects

In your Java IDE, create a new Project called MyFirstObject, with Main Class MyFirstObject (if you’re using Netbeans myfirstobject.MyFirstObject with myfirstobject as the package name). Inside your MyFirstObject Class enter the following:

//class declaration
public class MyFirstObject
{
//main method
public static void main(String[] args)
	{
//code here will be executed when the program is run
	}
}

Using Objects is a way of dividing up responsibility for the different parts of an application. You can do this in a variety of ways: for example, you can carry out some of your program’s tasks within separate methods, calling these from the main part of your code. Using Objects is similar to this, but each Object requires a Class declaration, which you create in a separate .java file.

The Objects that you may have already used, such as those representing Java datatypes String, Array etc also have their own Class declarations – these are built into the Java language itself, and although you can’t see the code, you can see an overview as part of the Java API (Application Programming Interface). The Objects that you define yourself will function in the same way – let’s create a simple example.

In your project, create a new Class called MyHelper, entering the following:

	//class declaration
public class MyHelper {

		//instance variable
	private int helperNum;

		//constructor method
	public MyHelper()
	{
		helperNum=1;
	}

		//public method
	public int getNumber()
	{
		return helperNum;
	}
}

The above code is a simple Class declaration specifying the properties that any Object of the MyHelper Class will have – next we will create an ‘instance’ of the MyHelper Class within our Main Class, but first let’s look at the Class declaration.

Instance Variables

Instance variables represent any data that should be stored in every instance of your Object, meaning that every time you create a MyHelper Object it will contain a helperNum integer variable. Instance variables should always be private, so that their value cannot be changed except within the Class declaration itself – more on this later.

Constructor method

You can see that the constructor method looks the same as any other method, except that it doesn’t have a return type specified – this is because the constructor method is called when an Object of the Class is created (using the keyword ‘new’), and what it returns is – an Object of the Class. The constructor method should always have the same name as the Class. Within the constructor method, you carry out ‘initialisation’, meaning that you assign a value to your instance variables – when the constructor method has executed, none of your instance variables should be left without a value, as this can make your program unpredictable.

Public Method

The declaration contains one public method, ‘getNumber’, which can be called on any Object of the Class. Although the example may seem trivial, it is common to have methods which either set or return the value of an instance variable.

The reason for such methods relates to your instance variables being private. The basic principle underlying Object Oriented development is that your Objects have a ‘well-defined’ interface – this means that all access to the data contained within a Class should be through its methods. If the instance variables were public, external code would be free to change their values directly, which can be dangerous, since external code may not be aware of the implementation details for the Class. If you restrict all access to your instance variables, to the public methods in a Class, you can carry out any checks etc there to ensure that your data is not assigned invalid values.

Using your Class

Now go back to your Main Class and enter the following inside your main method:

//code here will be executed when the program is run
//create a MyHelper object
MyHelper mh = new MyHelper();
//call a method on it, assign the result to a variable
int num = mh.getNumber();
//write the variable out for testing
System.out.println(num);

Compile and run your program and you should see the number 1 written to standard output. You create an Object of your Class, and call methods on it, in exactly the same way as any other Object. From your main method, you can call any methods on the MyHelper Object that are declared as public inside the Class.

A Class may also have private methods that are for use within the Class only. For example, one of your public Class methods may involve complex or repetitive processing that you decide to separate out into its own method, calling this from the public method – in this case the separate method should be declared as private, as this method relates to the implementation of the Class itself, which external code should not have access to.

Object principles

If you’re new to Object Oriented development in general, it can help to think in terms of ‘black boxes’. One of the principles that makes Java suited to developing large projects, is the idea that any application developed in Java can in turn be used by anyone else as a component in another application. Many open source projects use Java, with people sharing resources that they have developed in the language.

For this approach to be feasible, it must not be necessary for someone using a component to have to understand all of the implementation details within it. So long as there is a ‘well-defined’ interface, you should be able to make use of external Java libraries and resources while knowing nothing about what goes on inside them – in the same way that you can use a String or Array without having to understand how it is implemented in the underlying code. In this approach, you can think of Objects as ‘black boxes’ – code external to the Class should be able to make use of it without having to be aware of the inner code. When you develop your own Objects, you should adopt the same principle – even if you’re developing an application single-handed, this approach makes for programs that are faster to build and easier to debug.

More on Classes

As a final note, you should be aware that you can have more than one constructor method in a Class, each one taking different parameters. In this case whichever method is called is dictated by what parameters are passed when an Object of the Class is created. To demonstrate, add a second constructor to your Class, beneath the existing one:

	//class declaration
public class MyHelper {

//instance variable
	private int helperNum;

//constructor method
	public MyHelper()
	{
		helperNum=1;
	}
//second constructor - takes a parameter
	public MyHelper(int value)
	{
		helperNum=value;
	}

//public method
	public int getNumber()
	{
		return helperNum;
	}
}

Now add the following in your main method, after the existing code:

	//create an object passing int parameter
MyHelper mh2 = new MyHelper(2);
int num2 = mh2.getNumber();
System.out.println(num2);

When you run your program, this time it should output 1 and then 2 for the new Object. Whichever constructor matches the type and number of parameters passed is the one that’s called during Object creation.

When using Objects in your programs, you should try to decide what the various Classes will be at the outset, by dividing up the different requirements that your project has, and assigning responsibility for these to your set of Objects.

Next Java Tutorial – Datatypes .

November 24, 2008 at 11:10 am 1 comment


Follow us on Twitter