Basic Java Tutorial

Discussion in 'Programming General' started by DarkestFreestyle, Feb 18, 2007.

Basic Java Tutorial
  1. Unread #1 - Feb 18, 2007 at 11:24 PM
  2. DarkestFreestyle
    Referrals:
    0

    DarkestFreestyle Guest

    Basic Java Tutorial

    I've been taking Java in school and since I'm new here I thought I might as well make a tutorial. Please post comments and suggestions to add to this guide.

    Introduction

    Java is an object-oriented programming language developed by Sun Microsystems. It runs on the Java Virtual Machine (JVM) which gives it platform independence and is powerful yet easy to learn.

    First, you must download Java off Sun's website. After navigating to the downloads section, click on the link for the most recent Java Development Kit (JDK):

    [​IMG]

    Pick what installation suits you, and download and install like a normal program.

    Then open up Control Panel -> System -> Advanced -> Environment Variables. Add wherever you installed Java plus "\jdk1.6.0\bin" to the Path variable after a semicolon, for example:

    [​IMG]

    After that, edit the CLASSPATH variable and make sure that there is a "." as one of the entries. If not, same as before, add the dot after a semicolon:

    [​IMG]

    Congratulations, Java should be set up and ready to go.

    One more thing that you might need to set up. Since we are using notepad for this tutorial, if you don't have your folder options set to display the file extensions, then open up Control Panel -> Folder Options -> View and disable the "Hide extensions for known filetypes" option, as shown here:

    [​IMG]

    First Program

    There are many Java compilers out there for you to use, but we will be sticking with the simplest way to compile and run Java programs: Notepad and the command prompt.

    Open up notepad and paste into it the code below:

    Code:
    public class HelloWorld
    {
       public static void main(String[] args)
       {
          // prints Hello World!
          System.out.println("Hello World!");
       }
    }
    
    Next, save it as FirstProgram.java (make sure it is .java and not a .txt file or it won't work).

    Open up command prompt and navigate to the folder. Then type in these two commands:
    Code:
    javac FirstProgram.java
    
    java FirstProgram
    
    After all this, it should display "Hello World!" in the command prompt. The first command that you entered compiled the .java file into a .class file. If you look, there should now be a FirstProgram.class file in the same folder. The second command ran that .class file. Notice how the first command requires the .java while the second does not require the .class.

    Breaking down this program bit by bit:

    Don't worry about "public" for now. This will be explained later.

    "class HelloWorld" is obviously the name of the class. If you don't know how to compile .java files into .class files then try to find a tutorial that will teach you. However, I may add that later if needed.

    The braces ("{}") enclose the code in a block. The block pertains to the code before it. For example, the the first set of braces encloses the code that is in the HelloWorld class. The second set of braces encloses the code in the main.

    The "public static void main(String[] args)" is the entry-point into your program and as far as I know, every Java program must begin with the execution of the main.

    The double forward slashes ("//") create a comment. A comment is not read by the compiler and is for documentation purposes only. Another type of comment is "/*...*/" where the "..." is the information inside. This is useful for comments that span more than one line. Using comments is a good habit to get into.

    Finally, "System.out.println("Hello World!");" is the meat of the code. All this does is write or print "Hello World!" to the command prompt. A statement like this is called a method; more will be explained later. Also, notice the "ln" part: this means that any more text printed after this would fall on the next line, as opposed to "System.out.print()". Notice I put a semicolon after. Statements like this in Java require a semicolon.

    Variables

    Some people consider variables a box where you can put anything in it. Think of a variable in math where in one problem x may equal 5 but in another it equals 3. There are eight basic, or primitive, types of variables:

    int - The most common integral variable, it can store integers from -2,147,483,648 to 2,147,483,647 and is 32 bits.

    byte - Another integral type that stores integers between -128 and 127, 8 bits.

    short - A third integral type that stores integers between -32,768 and 32,767 and is 16 bits.

    long - A fourth integral type that store integers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 and is 64 bits.

    float - A floating point variable with a range of approx. -3.40292347E38 to 3.40292347E38, 32 bits.

    double - A floating point variable with a range of approx. -1.79769313486231570E308 to 1.79769313486231570E308, 64 bits.

    char - A 16 bit Unicode character variable from '\u0000' to '\uFFFF'. You will mostly use this variable for letter and number characters such as 'D' and such.

    boolean - A variable that stores either true or false. 1 bit because it is either a 1 or a 0.

    You will probably only use a few of these for a while since memory will not be an issue.
    Note that the "Hello World!" from the first program is a String and is not a primitive type.

    Code:
    public class IntegerTest
    {
       public static void main(String[] args)
       {
          int x = 5;
          System.out.println(x);
          x = 342;
          System.out.println(x);
       }
    }
    
    The above code demonstrates the use of the int variable. Although the print command was the same both times, because the variable changed, a different number was printed each time.

    Notice how the first time I used x, I put the "int" and the second time I didn't. The first time, I was not only assigning the variable to 5, but I was declaring it as well. The second time, the variable was already declared and I was just assigning another value. You don't have to combine the declaration and the assignment; I just think it's easier.

    The first time a variable is assigned a value is called initialization.

    Decision Making

    What use is a program if it can't make decisions?

    The if statement is used to do something if a condition is true. The basic setup is:

    Code:
    if (condition)
    {
       // execute the code within the braces
    }
    
    There is also the else statement which goes with the if and performs only if the if is not. Here are some different situations using the if statement.

    Code:
    public class IfTest
    {
       public static void main(String[] args)
       {
          int x = 10; // notice how here only one equals is used for assignment...
    
          if ( x == 10 ) // ...while here two equals are used for testing equality
             System.out.println("x is equal to 10 so this if statement executes.");
             // if there are no braces for an if statement, then it applies to only the next line
          else if ( x == 10 )
          {
             System.out.println("This will never print because the else the if statement before it has the same condition.");
             System.out.println("If you take away the else then it would print.");
          }
          else
          {
             System.out.println("This will only print if x does not equal 10.");
             System.out.println("Notice there is no if (condition) afterwards; if none of the preceding if statements don't execute then this will.");
          }
          System.out.print("This will always print regardless of x.");
       }
    }
    
    Looping

    It would be pretty annoying to have to type out every single task you want a program to do if it is basically the same thing. Programs can easily perform repetitive tasks using loops.

    The while loop does something while a condition is true. The basic format of a while loop is:
    Code:
    while(condition)
    {
       // execute the code within the braces
    }
    
    Another loop is the for loop. This is basically a while loop with some of the code in the loop statement itself. The basic setup for a for loop is:
    Code:
    for(statement 1; condition; statement 2)
    {
       // execute the code within the braces
    }
    
    The "statement 1" usually initializes a variable to count the loop while "statement 2" increments it. See the loop example below.

    The last loop is the do-while loop. This is similar to a while loop but the code inside will execute before testing if the condition is true. This is used if you want the code inside to always execute at least once. The basic setup is"
    Code:
    do
    {
       // execute the code within the braces
    } while(condition); // note the semicolon
    
    As you can see, all of these loops are very similar, and the while and for loops can always do exactly what the other can. The difference is in preference. Here's an example where the loops all do about the same thing:
    Code:
    public class LoopTest
    {
       public static void main(String[] args)
       {
          int whileCounter; // notice that I haven't initialized any of these yet
          int forCounter;
          int doWhileCounter;
    
          whileCounter = 1;  // i am initializing this variable before the loop
          while(whileCounter <= 10)  // <= is less than or equal to, >= is greater than or equal to
          {
             System.out.println(whileCounter);
             whileCounter = whileCounter + 1;
             // the code above is one way to increment a variable by one
          }
    
          for(forCounter = 1; forCounter <= 10; forCounter++)
          {
             System.out.println(forCounter);
             // instead of initializing the variable before the loop as in the while, the variable can be initialized right in the statement itself
             // the "forCounter++" part is just another way to increment a variable, one that is a bit shorter
          }
    
          // here i have set the variable to zero instead of one and i have changed the condition from <= to <
          // then, instead of printing the variable first, i am incrementing it
          // if you think about it, it does exactly the same thing and is all a matter of personal preference
          doWhileCounter = 0;
          do
          {
             doWhileCounter++; // using the shorter increment again
             System.out.println(doWhileCounter);
          } while(doWhileCounter < 10); // < is less than, > is greater than
    
          System.out.println("As you can see, this code prints the numbers 1-10 for each loop.");
          System.out.println("Although the loops are different, they can mostly be used for the same things.");
       }
    }
    
    Input and Importing Useful Functions

    There are probably many ways to do input, but the one I learned uses Java's Scanner. I'm going to stick with the Scanner for this tutorial because that will also allow me to talk about imports and objects.

    Sometimes when you do something in Java, you'll be able to use another class file instead of writing the code yourself. Many common math things such as pi, trig functions, square root, and exponents are built right into the Java API. You can find the massive list of these here.

    Here is an example of a program using the Scanner to read input and then using a common math function with it:

    Code:
    import java.util.Scanner; // notice the imports come before the class
    import java.lang.Math;
    public class InputMath
    {
       public static void main(String[] args)
       {
          // this creates an object of Scanner called input
          Scanner input = new Scanner(System.in);
    
          int number; // declares number as an integer
    
          System.out.print("Enter an integer to square: ");
          // reads input from the user and assigns it to number
          number = input.nextInt(); // gets the user's input and assigns it to number
          // prints the number and its square using printf
          System.out.printf("\nThe number is %d and the square is %d", number, (int)Math.pow(number, 2));
       }
    }
    
    Ok, in this program there is a lot of new stuff, so I will go through it step by step.

    The first thing you notice that's different is the imports. These come before the class and are used later in the program.

    Next, we have the "Scanner input = new Scanner(System.in);" statement. In the Java API, there is a class called Scanner and we've just imported it in the statements before this, but we still can't use it yet. We have to create an object of class Scanner. Here we've named that object input, but you can really call it anything you want. Sort of like declaring a variable, declaring an object requires a type first - here it is the first "Scanner". Next we have an equals just like assigning a variable would and then we construct the object as a "new Scanner" with the parameter of "System.in" which is the standard input stream. If you don't really understand this paragraph, that's ok - all you need to know for now is that you need this bit of code in order to read input.

    After we tell the user to enter the integer with the print method, we use a new method "input.nextInt" to read the input from the keyboard and store it to number with the assignment statement "number =". When this is run, the program will wait until the user presses enter before assigning whatever was input into "number".

    Now, you see a new print method, "printf". This prints text regularly like print except it is able to use certain commands such as "%d" here to sort of pull out the variable after it into the string that is printed. Although you could substitute this for something like "System.out.print("The number is " + number + " and the square is " + (int)Math.pow(number, 2));", as you notice it is longer and more confusing. Instead, printf will let you format (that's what f stands for) the string first and then add the numbers to go in later. The %d formats an integer - another common command is %f which formats floating-point numbers (floats and doubles).

    Onto the "(int)Math.pow(number, 2)". First of all, notice that although the printf statement was able to format the square successfully, we did not assign the square to number. Therefore, if we were to print "number" again, it would still be the same. Ignore the "(int)" for now and look at the method itself. This method from the java.util.Math that we imported, as you hopefully have figured out, squares the number for us. The documentation for this method on the Java website is as follows:
    Code:
    public static double pow(double a,
                             double b)
    
        a - the base.
        b - the exponent.
    
    So, looking at "(double a, double b)" and knowing that a is the base and b is the exponent, you can figure out that we took "number" to the power of 2. Simple enough, however, why didn't we just create an object like we did with the Scanner. The reason is because of the "static" in the method. Methods that are static do not have an object created for them, they just use the class itself, in this case "Math". That is why the code is "Math.pow" instead of "anObjectThatWeCreated.pow".

    Looking at the method documentation once more, you see the word "double". This means that the method, after executing will return a double. So, after we square number it will come back as a double...but since we are already working with integers in the first place, why not change it to an integer. The "(int)" in front of the method assures us that we will receive an integer as an answer.

    Hopefully that all made sense. I will add more things later.

    Remember, this guide is not finished yet.
    Coming up: Arrays, OOP Basics, and some program examples
     
  3. Unread #2 - Feb 22, 2007 at 4:50 AM
  4. Magic Arrow
    Joined:
    Feb 3, 2007
    Posts:
    4,129
    Referrals:
    673
    Sythe Gold:
    49
    Extreme Homosex Sythe Awards 2013 Winner

    Magic Arrow Protector of the homosex, defender of the AIDS
    $5 USD Donor Mudkips Retired Sectional Moderator

    Basic Java Tutorial

    i was ninteresting in learning java, and if this is basic, u just turned me off
     
  5. Unread #3 - Feb 22, 2007 at 5:45 AM
  6. Mod Josh
    Joined:
    Feb 2, 2007
    Posts:
    142
    Referrals:
    0
    Sythe Gold:
    0

    Mod Josh Active Member
    Banned

    Basic Java Tutorial

    Okay, it is a really good TuT, but, what would make it better is if you'd explain what Java is, and how you use it. Because, for this to all make sense to some people, they have to know those little details.
     
  7. Unread #4 - Feb 22, 2007 at 12:43 PM
  8. DarkestFreestyle
    Referrals:
    0

    DarkestFreestyle Guest

    Basic Java Tutorial

    To Magic Arrow: It's actually not that hard once you get into it.

    To Mod Josh: Well I thought they'd be able to look at the other tuts in this forum, but I'll add a section on that.

    Thanks for the comments.
     
  9. Unread #5 - Feb 23, 2007 at 9:28 PM
  10. bkatz
    Joined:
    Apr 21, 2005
    Posts:
    402
    Referrals:
    0
    Sythe Gold:
    0

    bkatz Forum Addict
    Banned

    Basic Java Tutorial

    Nice tutorial, I'm taking java in school as well. I saw you used a scanner to get input, just thought I'd share that there is an easier way, I prefer this way instead of the scanner:

    Code:
    //you will need to import javax.swing.JOptionPane before using this.
    int whatever = JOptionPane.showInputDialog("Are you a n00b?");
    System.out.println(whatever);
    
     
  11. Unread #6 - Mar 11, 2007 at 6:22 PM
  12. Olan14
    Joined:
    Jan 26, 2007
    Posts:
    581
    Referrals:
    0
    Sythe Gold:
    0

    Olan14 Forum Addict

    Basic Java Tutorial

    Nvm compiled it with a Grene Penguin Compiler and it was cool. I ahve HelloWorld.class :). I can finally understand more of what the code in my server files meant. XD O and i fixed my servers Illegal Expression in "public static boolean IsDropping = false;". Simply needed a bracket in front :p
     
  13. Unread #7 - Mar 17, 2007 at 5:37 PM
  14. T-Trader
    Joined:
    Mar 15, 2007
    Posts:
    92
    Referrals:
    0
    Sythe Gold:
    0

    T-Trader Member

    Basic Java Tutorial

    Hmm.. Can't you make a tutorial for coder with a bit more experience? ;-) :p

    Because I'm learning Java atm and later C++, but I already know this from PHP.
     
  15. Unread #8 - Mar 19, 2007 at 12:08 AM
  16. IcY
    Referrals:
    0

    IcY Guest

    Basic Java Tutorial


    lol that wouldn't work :)

    it'd have to be
    Code:
    public void Input()
    {
        try
        {
            int x = Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));
            System.out.println(x);
        } catch(Exception e) { System.out.println("ENTER A NUMBER PLS!"); Input(); }
    }
    
     
  17. Unread #9 - Mar 21, 2007 at 8:03 PM
  18. Massive Mage 333
    Joined:
    Jan 21, 2007
    Posts:
    95
    Referrals:
    0
    Sythe Gold:
    0

    Massive Mage 333 Member

    Basic Java Tutorial

    Nice tutorial! It helps out newer people like myself (or if you want to call us noobs go ahead). This tut really helped me understand the language better.
     
< ReportViewer NOT Printing? | 2 questions >

Users viewing this thread
1 guest


 
 
Adblock breaks this site