Java tutorial: Getting started and your first program


Introduction
  Sometimes when learning a new language, you can be instantly exposed to a multitude of new vocabulary, ways of thought, and problem solving techniques. For some people, it can be just too much at first. I'm writing this tutorial to explain in detail the basics of the Java programming language.







Terms to know
  These are some terms that you are going to or should know.
  • Java Run-time Environment - What all compiled Java runs on.
  • Java Development Kit - This is the tool used to create and compile Java.
  • Compiler - This turns Java source code into Machine code used by the JRE.
  • Java File (.java) - This is the source code of all Java programs.
  • Class File (.class) - This is the Machine code created by the JDK for use by the JRE.
  • Field - A declaration or statement, usually the instantiation of a variable or object.
  • Method - A block of code created to perform tasks.
  • Instantiation - Declaring a variable or object for use by the program.
Downloads and Resources
  These are downloads required or recommended, and helpful resources.
Getting started
  Since we are going to be learning and using the Java programming language, I think it best that one acquires a Java Run-time Environment. Also known as JRE, the Java Run-time Environment is what all compiled Java runs on. You will also need a Java Development Kit, or JDK. Both of these resources can be found above in the Downloads and Resources section. Once you have downloaded and installed both the JRE and the JDK, you might consider downloading an Integrated Development Environment, or IDE. An IDE is a powerful tool for programmers, as it allows access to a multitude of tools, debugging, and access to the compiler. With an IDE, you will be able to develop programs much faster, and much more efficiently. I recommend Eclipse, as it is fast, effective, and easy to use. It is also free. If you would like to download Eclipse, refer to the link in Downloads and Resources.






How to set up a DOS BATCH compiler/runner (Windows)
  First, you must have a Windows Computer, and second, skip this section if you already have one set up, or you chose to download an IDE, and successfully set it up.

  To begin, I recommend making a folder, anywhere is fine. Personally, I like to use the desktop, but that is just preference. Now, open up a text editor (notepad will work). For the needs of this tutorial, were are going to make a simple BATCH file to both run and compile our Java program. Inside the notepad, type this:

@echo off
title Java Suite
cls
:start
cls
echo Type in the name of the file you wish to compile, and press [Enter]. Do not include the extension.
set/p file=
javac %file%.java
echo Done!
echo Would you like to run the program, or go back to compiler?
echo Run: Type 1 and hit [Enter].
echo Compile: Type 2 and hit [Enter].
set/p option=
if %option%==1 goto run
if %option%==2 goto start
goto start
:run
echo Type in the name of the file you wish to run, and press [Enter]. Do not include the extension.
set/p file=
java %file%
echo Done!
echo Press any key to continue...
pause>nul
goto start

  Save this file in the folder where you will be writing your code, as "Java suite.bat". Test it out by typing random stuff in it. If you don't get any errors like "'javac' is not recognized" or something along the lines of that, then you are in the clear.

  Depending on your computer's configuration, you might have to go and replace "javac" with the location of the javac.exe and replace "java" with the location of the java.exe. If this is to difficult to understand, I recommend downloading the IDE under Downloads and Resources. You can also find a video on how to do this under Downloads and Resources, as well.







Your first program
  Hooray! It's now time to create your first program! For simplicity, I am going to do the overused "Hello, World!" tutorial. First, if you are in Eclipse or another IDE, start a new project or Source File. Otherwise, open a new text doctument. To start off our program, we need to declare what it the program is, and give it a name. 


public class HelloWorld {


  Public means that this resource is accesible by any other Java program. Class means that this is a Class, the basics of all Java programs. The "{}"'s are Brackets. When programming, they essentialy seperate groups of statemnents and declarations, and provide means of structuring code, which is useful for flow control and maintaining efficiency. HelloWorld is, duh, the name of the class. Whenever making a new class, you will almost always follow this pattern:


package <PACKAGE>;
import <TOIMPORT>;
public class <NAME> {
...
}


  That is the basic skeleton of any Java source. For this tutorial, we will not be using package, nor import. "import" allows you to include other classes, so that you can instantiate them, and use them. "package" is the location of this code withing the project. Package is never entirely needed, but it is highly encouraged when making multi source projects. 

  Next we are going to add the main method. This method is used for the main program in a project, and is required to be executed on
it own by the JRE. If a class does not have a main method, then it cannot be run normally by the JRE. The basic layout for the main method is as follows.



public static void main(String[] args){
//Do stuff here
}


  Static means that this method is NEVER going to change throughout all of the times it can be run by the JRE. Again, it is public, allowing it to be executed by the JRE. Void means that it will not return any values. When a program returns something, it means that it is sending information back to the declaration that called upon that function or method. Returning a value can be very useful in many cases, such as formating an image, then returning the formatted image. Because there is only one method in this class, there is no need for a return. You also cannot add a return to a main method. The JRE is not a class, so returning a function would have no purpose, hence why it is not allowed. ALL main methods must be declared with the name "main". If it doesn't have main in the name, then it isn't a main method. String is a data type, that consists of an array of characters. The [] means that it is an array, which means it can hold more than one allocated value inside itself via a list. The name of this String array is "args". Normally, args are not used in simple programs, but they are used for things like declaring a file to open, or an application to start. Since this program is simple, we are not going to pay much attention to them. Again, you see the use of Brackets to form a code block. Everything contained inside the "{ .. }" is what the program will execute on creation by the JRE.

  Now it is time to add the declarations and statements. Add this inside the main method's brackets:

  System.out.println("Hello, World!");

  System is a class that is non-instantiable, which means you can never create your own System Objects, and it also means that at any given time, there is only one System in existance on the JRE. Out is a stream used by System to send information out to the JRE. In the case, we are going to call println (thing of it as printline), on out, on System. After the println we have two parenthisis. Anything inside these parenthisis is called a Parameter, which is used by the method being called to create a response, or act on. In this case, we are using the String "Hello, World!". A string's value is always declared inside of "..." 's. To a similar effect, '...' 's is used to create a char (Character, or letter/symbol). Some of you might say, "Well, how would we write a string that contains "...", since doing " "..." " cancels the middle section out, and causes a compile-time error"? The developers at Sun microsystems thought of this too. You can use the backslash to null the effect of a character that might otherwise cause an undesired result while creating Strings or chars. You can even cancel out a backslash with a backslash! Within our String, we only have 'Hello, World!', so we do not need to worry about this. Some of you might be thinking that when I say print, I mean to print it out of a printer. In Java, and most other programming languages, print means to display it. In this case, calling println displayes the contained string on the console.

  Every statement in java must end with ";". A statement is something that does not start or end a new code-block, so, most lines will end with ";". The ";" tells the compiler where the end of this statement is.

  To end our program, we will add a final "}", to close of the code block created by declaring the new class. We should now have the following in our editor/IDE:

public class HelloWorld {
public static void main(String[] args){
System.out.println("Hello, World!");
}
}

This is what it looks like in Notepad++
Posted Image


And this is what it looks like in Eclipse
Posted Image
  
  If you wanted to, you could add comments to the program, so you can remind yourself of how it works, what is going on. A basic one line comment is started with "//". Everything that follows after the "//" on that line will be excluded from the compiler, a
nd will only be visible in the java source. Make sure you use this form of comment only after the main contents of that line have been properly formed, and have a ";" or start a code block. Do NOT do this:



// Prints a message on the console System.out.println("Hello, World!");


  and expect it to work. Your program will compile, but It will be useless. The comment prevents System.out.println from ever occuring. A correct example of commenting the System.out.println(); would be:

System.out.println("Hello, World!"); // Prints a message in the console

  Another form of comment is by using "/*" and "*/". This type of comment can spread accross many lines, and can even be placed in the middle of a statement, and still have the statement work. You start the comment by typing "/*", and then it will then comment out EVERYTHING until it reaches a "*/". A few examples would be:

public int add(int i, int j){
/* Adds two Numbers together */ return i + j;
}

OR

public int add(int i, int j){
return i + j; /* Adds two Numbers together */
}

OR

public int add(int i, int j){
/* Adds two Numbers together
Still inside comment
*/
return i + j;
}

OR EVEN

public int /* Returns an Integer */ add /* Name */( int i, int j){
return /* add numbers together */ i + j /* and finish with semi-colon */ ;
}
  
  As you can see, comments can be very helpful, and you can even use them to remove code from a larger program, so that you can observe the effects that removing that block of code has on the rest. 

  It's time to finish our program. You should now proceed to save it as "HelloWorld.java". You can NOT save it as anything else. You must save a source file with the same name as the class or interface contained within. Once you have it saved, hopefully inside the folder you created earlier, run the compiler, and type in the name of the source file. If it says Done! with nothing else, then you have successfully followed through with this tutorial. You will then be prompted to run the program. Type in the name again, and if everything works as it should, you should get the message "Hello, World!". If you are using eclipse, compiling and running is as easy as clicking "build" and then "run". 


No comments:

Post a Comment