Beginners Java Tutorial – Methods – Control Structures

December 3, 2008 at 5:44 pm 1 comment

Java – Methods and Control Structures

This Java tutorial is intended for people in the early stages of beginning Java programming.

When you compile and run a Java program, the JVM executes whatever is within the main method. These instructions are carried out sequentially unless dictated otherwise by the code itself, for example by using control structures, calling methods or creating Objects. This tutorial introduces basic control structures and method invocation in Java.

When you start programming in any language, it can seem intuitive to think of a program as a series of instructions that are executed in a linear fashion. However, when building applications, you will structure your code in a number of different ways.

For example, if your application allows user interaction, whatever code is executed will depend on what the user does at any point. Whenever your programs use external input, whether from user interaction or e.g. where content comes from a database, you need to tailor the behaviour of your code to suit the particular input that it receives.

Conditionals

Imagine you have an application in which a series of products are being displayed, the product details being pulled from a database. Your display will look messy if the product names are longer than 20 characters so you decide to display only the first 20, cropping the remaining letters off. In your IDE, create a new Java project and enter the following in your main method:

//main method
public static void main(String[] args)
{
		//product name - would have come from database
	String productName = "Deluxe Man-Size Tissues";
		//name as it will be displayed
	String displayName = "";
		//conditional statement
	if(productName.length()>20)
		displayName = productName.substring(0, 20);
	else
		displayName = productName;
		//test the result
	System.out.println(displayName);

}

In this trivial example, the product name is ‘hard-coded’ into the program but imagine that when you sit down to write the program, you have no idea what String value will be in that variable. Look at the conditional statement and think about what happens at runtime. If the variable name is indeed longer than 20 chars, only the code under the ‘if’ will execute, with the ‘else’ being ignored. If the name is 20 chars or less, only the ‘else’ executes, with the ‘if’ ignored. The statement within the ‘if’ brackets (‘productName.length()>20’) is a test which, when carried out, returns a true or false value – if true the instructions carry out the ‘if’, if false they jump to ‘else’. When you run the program, it should output “Deluxe Man-Size Tiss” – experiment by changing the productName variable.

Loops in Java

Another basic way to introduce a control structure to your code is by using loops. You will often find when programming that you need to carry out repetitive processing – you can reduce the amount of code that you actually need to write by using ‘while’ or ‘for’ loops.

Imagine you have an array of products whose names you want to display – enter and run the following code:

//product array
String[] products = {"Hats", "Shoes", "Ties"};
	//print each to standard output
for(int i=0; i

The code within this loop will execute as many times as there are elements in the array. What happens when the instructions reach the loop:

  • The first time the loop is carried out, the value 0 is assigned to the i variable.
  • The test i<products.length is carried out, returning a true or false value.
    • If the test returns true
      • the content of the loop (printing out the value at position i in the array) is carried out
      • i++ is executed (i is incremented to keep track of how many times the loop has executed)
      • the loop is then re-entered – the test carried out again to see if i is still less than the length of the array
    • If the test returns false, the loop is abandoned and whatever code lies after it is executed.

A while loop can be used to the same effect:

int j=0;
while(j

Methods

You will often find that you are carrying out the same processing in more than one place within your program, for example, imagine you have several arrays that you wish to display the contents of in the same way – you can define your own methods to do this. In your project, enter the following:

//class declaration
public class MyClass
{
		//main method
	public static void main(String[] args)
	{
			//product array
		String[] products = {"Hats", "Shoes", "Ties"};
			//call the method, passing it the product array
		int elems = printElements(products);
			//test the result
		System.out.println(elems + " printed");
	}

		//method prints the elements in a given array
	public static int printElements(String[] elements)
	{
		for(int e=0; e

When creating your own methods like this, you have to decide what the type and number of parameters are, what the return type is (int in this case, void if there is none), as well as the content and name of the method (try to make this meaningful but concise if possible).

You can then call the method passing it any other String array and it will perform the same action with it – try it by creating a second array with different length and content.

Advertisements

Entry filed under: Java. Tags: , .

Beginners Java Programming Tutorial – Datatypes Dreamweaver CS4 Tutorial Video

1 Comment Add your own

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Follow us on Twitter

Error: Twitter did not respond. Please wait a few minutes and refresh this page.


%d bloggers like this: