Java by Example - simple methods and basic data types
Here you can see how to use a simple method with one parameter. The parameter is used to change the y-coodinate of the text output. Everything that is done more than once, should be put inside a method to make it reusable. Remember: elegance always pays off!
The most common basic variable types in Java are:
To declare a variable, just write the type (int, float, String, Font etc.) followed by a blank and the variable name and a semicolon. The variable name can be almost any name you can imagine (except for the the reserved words of the Java language, no number at first place and no blanks inside the name), but it should be short and descriptive, of course. In the following examples you will quickly see what I mean. Note that Java is a case sensitive language, you have to be careful about upper/lowercase letters!
You can define variables almost anywhere you like, but you will usually declare them either on top of the class, or (if they only have to be visible inside a method) inside the method, right after the method head. You can declare several variables at the same time: int a, b, c;. You can also initialize a variable at the same time it is declared: int a=10;, String s="Hi!";and you can use a mixture: int a, b=3, c=10;. If you don't initialize a variable when you declare it, Java assigns a standard value (see above table), but don't count on it! In most cases it is neccessary to initialize a variable before using it.
In this applet you can see how to use variables of type String (for text strings) and type int (for integer numbers, without fractional part). To use numbers for text output, you can simply add the number to the string with a + sign. If you have only a number variable to put out with drawString, you can put empty "" before your number, in order to convert them to a string.
|