Java tut from pergesu - 04/06/02 04:19 AM
Pergesu posted this awsome tut on my site. I thought it was something to share. So here it is.
Java Tutorial - Part I
Written by pergesu
Graciously hosted by RRFN (www.promodtecnologies.com)
Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.
Table of Contents
-------------------------
1) Brief intro
2) A little history of Java
3) What can I do with Java?
4) Basic output
a) Hello, world! console
b) Explanation of a class
c) More console output
d) Some graphical output
5) Basic input
6) Wrap up
--------------------------
Section 1
Brief Intro
---------------------------
Welcome to Part I of this Java programming tutorial. This first part is an introduction to Java programming, it will cover only basic stuff. It is mainly to acquaint you with Java's syntax, as well as learn some of the basic functionality of Java. This is really for the novice who has never programmed. If you're already a programmer just learning Java, then just check out the code and read the explanations on whatever confuses you. That said, I hope you learn and enjoy!
---------------------------
Section 2
A little history
---------------------------
In the Middle Ages of Computer Programming (ca. 1989), the Sun Microsystems saw a major problem with the majority of programming languages in use- they weren't easily portable. Code that worked on some processors and OSs didn't work on others without some major changes. There were a few languages, such as C and C++, that did not have to be greatly modified, but had to be modified nonetheless for portability. Sun envisioned a language that would run on every processor type and OS. They figured that they could create some kind of virtual machine that translated programmer code into machine code. Thus, to run a program, the user would only have to have a copy of the virtual machine for their processor and OS.
In 1991, Sun began to take steps toward achieving their vision of the "universal programming language." They funded an internal research project they code-named Green. The resulting language was one that was based on C and C++, and was originally called Oak. However, the creators found that another language was already named Oak, and so at a visit to a local coffee shop, the name Java was suggested. Thus, Java was born.
------------------------------
Section 3
What can I do?
-------------------------------
With Java, you are able to do two main, distinct things- write applets or applications. An application is just a regular program that runs on its own. An applet is generally imbedded into a web page to add extra functionality or entertainment value. A major appeal to Java is its ability to assist in creating dynamic content. Java is also being increasingly used in the development of imbedded systems. You can do everything with Java you can do with most other languages. Graphics, networking, whatever you want.
------------------------------
Section 4
Basic output
------------------------------
If you're like me, you skipped the first few sections to get to the code. Well here ya are...
--------------------------------
Section 4a
Hello, world! console
---------------------------------
// Hello.java
public class Hello
{
public static void main(String args[])
{
System.out.println("Hello, world!");
}
}
Cool, so we wrote our first program, just compile and run it. Oh shoot, we don't know how to do that yet. Let's get to it then! First thing to to is run over to http://java.sun.com and download the latest version of the SDK. The SDK contains all the tools you need to compile and run java programs. Read the accompanying documentation to install it, as it's a bit different for every OS. Now install the JDK, and we're set.
Before I explain the code, try compiling and running the the program. To do this, get a command prompt in your favorite OS, and switch on over to the directory that contains Hello.java. Then type
javac Hello.java
Hopefully you didn't get any errors. If so, make sure your code is exactly like mine, and the file name is Hello.java (I'll explain that in a bit). After this command, you will have a file called Hello.class in your directory. This contains the compiled Java code for the virtual machine to execute. If you don't know what the virtual machine is, read Section 2. So we have the Hello.class, then what? Type
java Hello
This should give us the following output:
Hello, world!
Alright, a run-down of the code...
First thing to know is that // signifies a comment. The compiler ignores everything that follows the //. It can appear on the same line as code, as long as it's after the code:
System.out.println("Hello, world!"); // Ouput a message
public class Hello
This line declares a class named Hello. In every Java program you write, you will declare at least one class. public is a keyword saying that it can be used in any program that you or anyone else writes. class, of course, says it's a class. Hello is the name of the class. It's possible to declare more than one class in a file. However, ONLY 1 CLASS MAY BE PUBLIC. This is important to remember. If you have more than one public class in a file, compilation will fail. Also, the name of the public class must also be the name of the file plus .java. Thus, public class MyClass goes in MyClass.java, public class BobsClass in BobsClass.java. If you don't name it like that, it won't compile. So go back up and rename the file Hello.java- that's why you had that problem (I know, I've changed examples around too!).
public static void main(String args[])
This line declares a method called main. For now, just think of methods as blocks of code that allow you to organize your programs better. They will be discussed in great detail later on. void means that the method does not return a value. Every method is called by some other method (with the exception of main()). Methods are able to return values to the methods that called them. This again is unimportant for the time being. main() is a method that gets called automatically when you run your program. Every application class you write must have one method named main(). String argv[] is a parameter to the method. This will also be discussed later. Here, it allows you to call your program with command-line options.
System.out.println("Hello, world!");
This is called a statement. All statements end in a semicolon (;). This just prints out "Hello, world!" without the quotation marks. What you enter between the parentheses is what is displayed. What is between the parentheses is known as a argument. A method can have multiple arguments; when this is the case, they are separated by commas.
---------------------------------
Section 4b
Class explanation
---------------------------------
Take a look at the program again:
// Hello.java
public class Hello
{
public static void main(String args[])
{
System.out.println("Hello, world!");
}
}
We saw what each line of code does, but you may be wondering how it all fits together. One thing to remember is that in Java, whenever you have an opening character- {, [, (- you must have a matching closing character- }, ], ). So we see the first line that says public class Hello. As was said, this declares our class. The opening curly brace on the next line signifies the beginning of the class. This means that everything between it and the closing curly brace on the bottom is a part of the class. The curly braces underneath the main() function designate the code that is part of the main() function. I will cover this fully in a later tutorial. But just so ya know...
---------------------------------
Section 4c
More console
---------------------------------
There are two ways to do basic console output. One is to use System.out.println(), and the other is to use System.out.print(). They both have the same syntax, they just operate a tad bit differently. System.out.print() will display the test you pass on a line, but will not create a new line. Thus subsequent calls to System.out.print() will be on the same line. System.out.println() displays text on its own line. Experiment with System.out.print() to see exactly what it does.
There are a few special characters that can be used in stuff you display. They're called escape sequences. A table is below to show you what they are and what they do:
Escape Sequence Description
--------------------------- -----------------
\n Newline. Positions screen cursor at beginning of next line
\t Horizontal tab. Move the screen cursor to the next tab stop
\r Carriage return. Position screen cursor at beginning of current line, don't go to next.
Stuff on this line can be overwritten
\\ Used to print a backslash character
\" Used to print a double quote character.
Here's a quick example: System.out.print("\"This text appears in quotes\" but this doesn't\n");
This will display: "This text appears in quotes" but this doesn't
and move the screen cursor to the next line. This means that all subsequent output occurs on the next line.
-------------------------------
Secion 4d
Graphical output
-------------------------------
This stuff is quite a bit cooler than the console output. To start, let's do a quick program:
// GraphicalOutput.java
import javax.swing.JOptionPane; // Import class JOptionPane
public class GraphicalOutput
{
public static void main(String args[])
{
JOptionPane.showMessageDialog(null, "Hello, world!");
}
}
Compile with javac GraphicalOutput.java and run with java GraphicalOutput.
What you should get is a dialog box that says "Hello, world!" and has a little information symbol on the side. Let's see what's goin on...
import javax.swing.JOptionPane;
This line allows us to include other classes into our programs. It's the same as #include in C/C++. Sun has created a huge library of functions that you can include so you don't have to "reinvent the wheel." This just lets us execute the single command in our program.
The first couple lines are the same.
JOptionPane.showMessageDialog(null, "Hello, world!");
This shows the dialog box. Don't worry about the first argument. Set it to null every time. The second one is obviously the text you want to show in the dialog box.
You can also call JOptionPane.showMessageDialog() with more argument. Here's how:
JOptionPane.showMessageDialog(null, display string, title bar string, message box type);
There are a few message box types: JOptionPane.ERROR_MESSAGE, JOptionPane.INFORMATION_MESSAGE, JOptionPane.WARNING_MESSAGE, and JOptionPane.PLAIN_MESSAGE.
To display a dialog with the title "I rule" and message "I'm a bad *** programmer" as a warning, use
JOptionPane.showMessageDialog(null, "I'm a bad *** programmer", "I rule", JOptionPane.WARNING_MESSAGE);
This is programming, so experiment with everything.
--------------------------------
Section 5
Basic input
--------------------------------
Oddly enough, input in Java is done far more easily graphically than it is using the console. Anyone working in a shell, get to a GUI for this!
// Addition.java
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String args[])
{
String firstNumber, secondNumber;
int number1, number2, sum;
// Read the first number from user as a string
firstNumber = JOptionPane.showInputDialog("Enter first integer");
// Read the second number
secondNumber = JOptionPane.showInputDialog("Enter second integer");
// Convert numbers from type String to type int
number1 = Integer.parseInt(firstNumber);
number2 = Integer.parseInt(secondNumber);
// Add the numbers
sum = number1 + number2;
// Display the results
JOptionPane.showMessageDialog(null, "The sum is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE);
System.exit(0); // Terminate the program
}
}
Wow! This is a lot bigger and more complex than our previous programs. It's not that bad, really. Compile and run it to see what it does before reading the explanation. It'll really help.
String firstNumber, secondNumber;
This line declares two variables of type String. As you might guess, these are strings. A variable is a way of storing values. The value in a variable can change at any time, thus the name variable. You declare one by typing type name. Note that variables of the same type may be declared at once, with each variable name separated by a comma.
int number1, number2, number3;
This line declares three values of type int. They're simple integers.
firstNumber = JOptionPane.showInputDialog("Enter the first number");
This line has the user enter something into a dialog box. As was said earlier, methods may return values. The method JOptionPane.showInputDialog() returns a string. This statements calls JOptionPane.showInputDialog(), and stores whatever value it returns nito firstNumber. The method returns a string, which, consequently, is the string that the user enters into the text box.
secondNumber = JOptionPane.showInputDialog("Enter second number");
Does the same as above, but stores the value in secondNumber;
number1 = Integer.parseInt(firstNumber);
number2 = Integer.parseInt(secondNumber);
If you want to add two numbers, you have to make sure they're in numerical form. When a number occurs in a string, it is treated as a string, rather than a number. This means you can't add, subtract, or do anything to the number that you want to do with numbers. There's an easy way to get past this. By calling Integer.parseInt() with a string as the argument, you get an int to work with. It does it by searching for a number in the string, and turns it into an integer. The method returns an int, so you have to assign it to a variable, as demonstrated above.
sum = number1 + number2;
If an explanation is necessary, stop reading and go back to first grade.
JOptionPane.showMessageDialog(null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE);
This is just display a dialog box, just like all the others we've done. Note that the second argument, "The sum is " + sum, seems to have two parts. If you have a string you want to display, and want to throw some variables in as well, you can join them with +. Java automatically converts it all to a string, so you don't have to worry about a thing. Pretty sweet...
--------------------------------
Section 6
Wrap up
--------------------------------
Alright, we covered quite a bit here. You learned the basic syntax for Java, did some simple console output, some simple graphical output, and a bit of input. You can convert user's input to integers, and perform any mathematical operation you like on those. I invite you to play around a bit, see what cool stuff you can do, before you head on to the next tutorial.
The next tutorial will cover control structures. This is decision structures and loops. You'll also learn about some of the other data types and how to use them. Happy brewing!
pergesu
Java Tutorial - Part I
Written by pergesu
Graciously hosted by RRFN (www.promodtecnologies.com)
Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.
Table of Contents
-------------------------
1) Brief intro
2) A little history of Java
3) What can I do with Java?
4) Basic output
a) Hello, world! console
b) Explanation of a class
c) More console output
d) Some graphical output
5) Basic input
6) Wrap up
--------------------------
Section 1
Brief Intro
---------------------------
Welcome to Part I of this Java programming tutorial. This first part is an introduction to Java programming, it will cover only basic stuff. It is mainly to acquaint you with Java's syntax, as well as learn some of the basic functionality of Java. This is really for the novice who has never programmed. If you're already a programmer just learning Java, then just check out the code and read the explanations on whatever confuses you. That said, I hope you learn and enjoy!
---------------------------
Section 2
A little history
---------------------------
In the Middle Ages of Computer Programming (ca. 1989), the Sun Microsystems saw a major problem with the majority of programming languages in use- they weren't easily portable. Code that worked on some processors and OSs didn't work on others without some major changes. There were a few languages, such as C and C++, that did not have to be greatly modified, but had to be modified nonetheless for portability. Sun envisioned a language that would run on every processor type and OS. They figured that they could create some kind of virtual machine that translated programmer code into machine code. Thus, to run a program, the user would only have to have a copy of the virtual machine for their processor and OS.
In 1991, Sun began to take steps toward achieving their vision of the "universal programming language." They funded an internal research project they code-named Green. The resulting language was one that was based on C and C++, and was originally called Oak. However, the creators found that another language was already named Oak, and so at a visit to a local coffee shop, the name Java was suggested. Thus, Java was born.
------------------------------
Section 3
What can I do?
-------------------------------
With Java, you are able to do two main, distinct things- write applets or applications. An application is just a regular program that runs on its own. An applet is generally imbedded into a web page to add extra functionality or entertainment value. A major appeal to Java is its ability to assist in creating dynamic content. Java is also being increasingly used in the development of imbedded systems. You can do everything with Java you can do with most other languages. Graphics, networking, whatever you want.
------------------------------
Section 4
Basic output
------------------------------
If you're like me, you skipped the first few sections to get to the code. Well here ya are...
--------------------------------
Section 4a
Hello, world! console
---------------------------------
// Hello.java
public class Hello
{
public static void main(String args[])
{
System.out.println("Hello, world!");
}
}
Cool, so we wrote our first program, just compile and run it. Oh shoot, we don't know how to do that yet. Let's get to it then! First thing to to is run over to http://java.sun.com and download the latest version of the SDK. The SDK contains all the tools you need to compile and run java programs. Read the accompanying documentation to install it, as it's a bit different for every OS. Now install the JDK, and we're set.
Before I explain the code, try compiling and running the the program. To do this, get a command prompt in your favorite OS, and switch on over to the directory that contains Hello.java. Then type
javac Hello.java
Hopefully you didn't get any errors. If so, make sure your code is exactly like mine, and the file name is Hello.java (I'll explain that in a bit). After this command, you will have a file called Hello.class in your directory. This contains the compiled Java code for the virtual machine to execute. If you don't know what the virtual machine is, read Section 2. So we have the Hello.class, then what? Type
java Hello
This should give us the following output:
Hello, world!
Alright, a run-down of the code...
First thing to know is that // signifies a comment. The compiler ignores everything that follows the //. It can appear on the same line as code, as long as it's after the code:
System.out.println("Hello, world!"); // Ouput a message
public class Hello
This line declares a class named Hello. In every Java program you write, you will declare at least one class. public is a keyword saying that it can be used in any program that you or anyone else writes. class, of course, says it's a class. Hello is the name of the class. It's possible to declare more than one class in a file. However, ONLY 1 CLASS MAY BE PUBLIC. This is important to remember. If you have more than one public class in a file, compilation will fail. Also, the name of the public class must also be the name of the file plus .java. Thus, public class MyClass goes in MyClass.java, public class BobsClass in BobsClass.java. If you don't name it like that, it won't compile. So go back up and rename the file Hello.java- that's why you had that problem (I know, I've changed examples around too!).
public static void main(String args[])
This line declares a method called main. For now, just think of methods as blocks of code that allow you to organize your programs better. They will be discussed in great detail later on. void means that the method does not return a value. Every method is called by some other method (with the exception of main()). Methods are able to return values to the methods that called them. This again is unimportant for the time being. main() is a method that gets called automatically when you run your program. Every application class you write must have one method named main(). String argv[] is a parameter to the method. This will also be discussed later. Here, it allows you to call your program with command-line options.
System.out.println("Hello, world!");
This is called a statement. All statements end in a semicolon (;). This just prints out "Hello, world!" without the quotation marks. What you enter between the parentheses is what is displayed. What is between the parentheses is known as a argument. A method can have multiple arguments; when this is the case, they are separated by commas.
---------------------------------
Section 4b
Class explanation
---------------------------------
Take a look at the program again:
// Hello.java
public class Hello
{
public static void main(String args[])
{
System.out.println("Hello, world!");
}
}
We saw what each line of code does, but you may be wondering how it all fits together. One thing to remember is that in Java, whenever you have an opening character- {, [, (- you must have a matching closing character- }, ], ). So we see the first line that says public class Hello. As was said, this declares our class. The opening curly brace on the next line signifies the beginning of the class. This means that everything between it and the closing curly brace on the bottom is a part of the class. The curly braces underneath the main() function designate the code that is part of the main() function. I will cover this fully in a later tutorial. But just so ya know...
---------------------------------
Section 4c
More console
---------------------------------
There are two ways to do basic console output. One is to use System.out.println(), and the other is to use System.out.print(). They both have the same syntax, they just operate a tad bit differently. System.out.print() will display the test you pass on a line, but will not create a new line. Thus subsequent calls to System.out.print() will be on the same line. System.out.println() displays text on its own line. Experiment with System.out.print() to see exactly what it does.
There are a few special characters that can be used in stuff you display. They're called escape sequences. A table is below to show you what they are and what they do:
Escape Sequence Description
--------------------------- -----------------
\n Newline. Positions screen cursor at beginning of next line
\t Horizontal tab. Move the screen cursor to the next tab stop
\r Carriage return. Position screen cursor at beginning of current line, don't go to next.
Stuff on this line can be overwritten
\\ Used to print a backslash character
\" Used to print a double quote character.
Here's a quick example: System.out.print("\"This text appears in quotes\" but this doesn't\n");
This will display: "This text appears in quotes" but this doesn't
and move the screen cursor to the next line. This means that all subsequent output occurs on the next line.
-------------------------------
Secion 4d
Graphical output
-------------------------------
This stuff is quite a bit cooler than the console output. To start, let's do a quick program:
// GraphicalOutput.java
import javax.swing.JOptionPane; // Import class JOptionPane
public class GraphicalOutput
{
public static void main(String args[])
{
JOptionPane.showMessageDialog(null, "Hello, world!");
}
}
Compile with javac GraphicalOutput.java and run with java GraphicalOutput.
What you should get is a dialog box that says "Hello, world!" and has a little information symbol on the side. Let's see what's goin on...
import javax.swing.JOptionPane;
This line allows us to include other classes into our programs. It's the same as #include in C/C++. Sun has created a huge library of functions that you can include so you don't have to "reinvent the wheel." This just lets us execute the single command in our program.
The first couple lines are the same.
JOptionPane.showMessageDialog(null, "Hello, world!");
This shows the dialog box. Don't worry about the first argument. Set it to null every time. The second one is obviously the text you want to show in the dialog box.
You can also call JOptionPane.showMessageDialog() with more argument. Here's how:
JOptionPane.showMessageDialog(null, display string, title bar string, message box type);
There are a few message box types: JOptionPane.ERROR_MESSAGE, JOptionPane.INFORMATION_MESSAGE, JOptionPane.WARNING_MESSAGE, and JOptionPane.PLAIN_MESSAGE.
To display a dialog with the title "I rule" and message "I'm a bad *** programmer" as a warning, use
JOptionPane.showMessageDialog(null, "I'm a bad *** programmer", "I rule", JOptionPane.WARNING_MESSAGE);
This is programming, so experiment with everything.
--------------------------------
Section 5
Basic input
--------------------------------
Oddly enough, input in Java is done far more easily graphically than it is using the console. Anyone working in a shell, get to a GUI for this!
// Addition.java
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String args[])
{
String firstNumber, secondNumber;
int number1, number2, sum;
// Read the first number from user as a string
firstNumber = JOptionPane.showInputDialog("Enter first integer");
// Read the second number
secondNumber = JOptionPane.showInputDialog("Enter second integer");
// Convert numbers from type String to type int
number1 = Integer.parseInt(firstNumber);
number2 = Integer.parseInt(secondNumber);
// Add the numbers
sum = number1 + number2;
// Display the results
JOptionPane.showMessageDialog(null, "The sum is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE);
System.exit(0); // Terminate the program
}
}
Wow! This is a lot bigger and more complex than our previous programs. It's not that bad, really. Compile and run it to see what it does before reading the explanation. It'll really help.
String firstNumber, secondNumber;
This line declares two variables of type String. As you might guess, these are strings. A variable is a way of storing values. The value in a variable can change at any time, thus the name variable. You declare one by typing type name. Note that variables of the same type may be declared at once, with each variable name separated by a comma.
int number1, number2, number3;
This line declares three values of type int. They're simple integers.
firstNumber = JOptionPane.showInputDialog("Enter the first number");
This line has the user enter something into a dialog box. As was said earlier, methods may return values. The method JOptionPane.showInputDialog() returns a string. This statements calls JOptionPane.showInputDialog(), and stores whatever value it returns nito firstNumber. The method returns a string, which, consequently, is the string that the user enters into the text box.
secondNumber = JOptionPane.showInputDialog("Enter second number");
Does the same as above, but stores the value in secondNumber;
number1 = Integer.parseInt(firstNumber);
number2 = Integer.parseInt(secondNumber);
If you want to add two numbers, you have to make sure they're in numerical form. When a number occurs in a string, it is treated as a string, rather than a number. This means you can't add, subtract, or do anything to the number that you want to do with numbers. There's an easy way to get past this. By calling Integer.parseInt() with a string as the argument, you get an int to work with. It does it by searching for a number in the string, and turns it into an integer. The method returns an int, so you have to assign it to a variable, as demonstrated above.
sum = number1 + number2;
If an explanation is necessary, stop reading and go back to first grade.
JOptionPane.showMessageDialog(null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE);
This is just display a dialog box, just like all the others we've done. Note that the second argument, "The sum is " + sum, seems to have two parts. If you have a string you want to display, and want to throw some variables in as well, you can join them with +. Java automatically converts it all to a string, so you don't have to worry about a thing. Pretty sweet...
--------------------------------
Section 6
Wrap up
--------------------------------
Alright, we covered quite a bit here. You learned the basic syntax for Java, did some simple console output, some simple graphical output, and a bit of input. You can convert user's input to integers, and perform any mathematical operation you like on those. I invite you to play around a bit, see what cool stuff you can do, before you head on to the next tutorial.
The next tutorial will cover control structures. This is decision structures and loops. You'll also learn about some of the other data types and how to use them. Happy brewing!
pergesu