Showing posts with label method. Show all posts
Showing posts with label method. Show all posts

Thursday, July 10, 2008

The void Type

'Pierre


void can be the most confusing type. It's an odd word to start with. It's part of the long string of words that appear before the word main in the declaration of that method.

Void means 'empty' or 'nothing'. In the case of a Java method, it means that that method returns nothing:

public void drawTriangle(){ ...

This is as opposed to a method with another type, which returns an object of that type:

public int sum(int a, b){
return a + b;
}

This returns an int object to the caller:

int count1, count2, amt;
...
amt=sum(count1, count2);

Why would you want a method that returns nothing? Because often you have methods that do something that doesn't affect the state of the program itself. Drawing something is an example of this. A method that draws something makes its results obvious in what it draws. It doesn't need to pass any information back to the other parts of the program. Instead it is expressing the state of the program to the outside world.
StumbleUpon

Sunday, July 6, 2008

Parens and Brackets and Braces, Oh My!

If you paid attention in English class when they were discussing the use of parentheses, curly braces, square brackets and so on I'm afraid it won't do you much good in Java. Java has a specific use for each of these, and it definitely pays to get then sorted out.

Knowing the names for each of the symbols is a good starting point:

{ } are curly braces.
( ) are parentheses (one is called a parenthesis.) Parens or paren for short.
[ ] are square brackets.
< > are called angle brackets. They're the same characters as the less than and greater than signs.

The first one of any pair is called the "opening" item; opening curly brace, opening parenthesis, etc. The second of a pair is called the "closing" item; closing square bracket, closing paren, and so on.

{ }
We discussed curly braces in Code Blocks, and mentioned briefly that they are a form of divider in Java in Those Pesky Semicolons. Curly braces mark the start and end of a code block.

Hold the phone! There's another use of curly braces. They can also be used to enclose a list that is used as an array initializer. For example:
int nums[] = {1, 2, 3};
This line declares an array named nums[] and initializes its first three elements to values 1, 2, and 3.

( )
Parentheses happen a lot in Java. They mark the start and end of the parameter list of a method. This includes both constructor methods and instance methods. The parameter list contains the information that is passed to the method to let the method do its job. If the method doesn't need any information, the parens are still there, there's just nothing between them: println(). A pair of parens at the end of a name is an easy way of identifying a method.

[ ]
Square brackets are used to enclose the "indexing expression" of an array. If you see square brackets, it's an array.

< >
When <> are not playing the part of "less than" and "greater than" they enclose the indexing expression of a collection. Collections are like arrays but considerably more flexible in the things they can do. Consider them as a sort of "super array."

There you are. Now you're prepared to punctuate your Java programs with the best of them, and hopefully you'll be able to read Java programs more easily. If you get into a dispute with your English teacher over these symbols, though, you're on your own!
StumbleUpon

Thursday, July 3, 2008

Constructor Methods

A constructor method is a method that creates an object. To create the object, it uses the class as a sort of blueprint for what member variables the object has, what instance methods, and so on.

The name of a constructor method is the same as the name of the class. For example, if we have a class named Dragon its constructor will be named Dragon as well:
public class Dragon{

  public Dragon(){
    super();
  }
}

There are a couple of things to notice here. One is that, unlike a regular method, the first character is upper-case, just like the class name. The constructor name must exactly match the class name. While it is only a convention that classes (and therefore, their constructor methods) start with a capital letter, it is an iron-clad requirement that the constructor name match the class name.

The other thing you'll want to notice is that there's no type given in the method declaration. A normal method (called an instance method, if we want to get formal) has a type provided in its declaration, just as a variable has a type in its declaration:
public void dragon(){ }    // Instance Method.
public int dragonCount;    // Instance Variable.
public class Dragon{ }    // Class.
public Dragon(){ }    // Constructor.
In the constructor's declaration, there's a scope called out (public) but no type. This is because, as a constructor for the object, it will be returning an object of the type it is a constructor for. OK, that sounds worse than it is. Let's try again...

A Dragon constructor returns a Dragon object. A String constructor returns a String object. That's what it constructs, so that's what it returns. Declaring a type would be redundant:
public Dragon Dragon(){ }    // This is NOT correct code, just an example of silliness!

A Subtle Error

If you accidentally have a typo in your program that results in your class and constructor having different names, the compiler will complain that you've got a method without a type declaration. You'll look at the code and say "Hey! That's a constructor. It doesn't need a type declaration! What is my compiler smoking?"
public class Dragon{

public Dragin(){
super();
}
}

Dragon.java:3: invalid method declaration; return type required
public Dragin(){
^
1 error

What's happening here is that the compiler sees that the name of the method is different from the name of the class. Aha, it says, this isn't a constructor since it doesn't have the same name as the class. So it must be an instance method. Hey, instance methods need a type! There's no type! Then it prints the error message.

Note that spelling errors include capitalization. So having a class named Dragon with a constructor called dragon() would cause the same error.

For more about constructor methods, see Multiple Constructor Methods.
StumbleUpon

Thursday, June 19, 2008

main()

There are two basic types of Java programs: applets and applications.* Applets run through a browser or a special program called AppletViewer. Applications are stand-alone programs that run on the same system they're stored on, like most traditional programs. Since there's lots of information elsewhere on applets, we'll concern ourselves mostly with applications.

Every application has a special method called main(). The main() method marks the starting point in the program for the Java Virtual Machine. Here's a short example program:

public class Hello{
public static void main(String arg[]){
System.out.println("Hello");
}
}

When this program is compiled using javac then run with the command
>java Hello
the JVM loads Hello.class and looks in it for the main() method, then starts executing the code inside main()'s code block.

Now, you'll notice there's a bunch of other stuff with main():
public static void main(String arg[]){

Because of how Java works, that stuff has to be there in a Java application. You can't just put "main(){" on the line by itself. The other stuff has a purpose, though it all looks very confusing, and certainly it looks like a lot of extra junk in a short program.

public allows the method to be accessed from outside the class (and its package--we'll get into that later.) If you leave out public, the JVM can't access main() since it's not available outside of Hello.

static says that this is the one and only main() method for this entire class (or program). You can't have multiple main()s for a class. If you leave static out, you'll get an error.

void says that main() doesn't pass back any data. Since the JVM wouldn't know what to do with any data, since it's not set up to accept data from main(), main() has to be of type void, which is to say that it's a method that doesn't pass any data back to the caller. If you leave this out main() won't have a data type, and all methods have to have a data type, even if it's void.

Inside main()'s parentheses is String arg[]. This is a way for the program to accept data from the host system when it's started. It's required that main() be able to accept data from the system when starting. And the data must be in the form of an array of Strings (or a variable-length list of Strings as of Java 5, but that's something we'll save for later.) The name "arg" can be whatever you want to make it. It's just a name I've given the array. It could just as well be:
public static void main(String fred[]){

I'd just have to be sure to use fred whenever I wanted to access the information that the system has passed to my application when it started, instead of arg.

Finally, after the parentheses, comes the open curly brace { that marks the start of main()'s code block.




* There are other types as well, but I'm limiting my discussion to Java SE/client side stuff for now.
StumbleUpon