Results 1 to 8 of 8

Thread: Java Tutorial #2

  1. #1
    Elite Hacker
    Join Date
    Mar 2003
    Posts
    1,407

    Java Tutorial #2

    Java Tutorial #2
    By: h3r3tic

    Please read my first tut before reading this one. I write this one
    assuming you have read the first one found here:
    http://www.antionline.com/showthread...hreadid=248863

    I'll start off with a simple program using arrays:

    Code:
    import java.util.*;
    
    public class ArrayTest 
    {
    	public static void main(String args[])
    	{
    		Random gen = new Random(31459);
    		int[] array1 = new int[10];
    		int[] array2 = {10,20,30,40,50};
    		System.out.println(array2[2]);
    		for(int i = 0; i<array1.length; i++){
    			array1[i] = gen.nextInt(100) + 1;
    		}
    		printArray(array1);
    	}
    	public static void printArray(int[] a){
          for (int i=0; i<a.length;i++){
            System.out.print(a[i] + " ");
          }
          System.out.println();
          }
    }
    the output of this program would be:
    30
    84 8 85 90 48 98 2 79 25 41

    Now let's analyze:

    the first line:import java.util.*;
    imports all of the packages of util including Random,
    which is the one we used.

    Then we declare a new instance of the Random class
    called gen:
    Random gen = new Random(31459);

    The numbers in the parenthesis are the seed of Random.
    If you change the numbers you will get different
    Random numbers, but if you don't, you will get the
    same "Random" numbers each time the program is run.

    next two lines:
    int[] array1 = new int[10];
    int[] array2 = {10,20,30,40,50};

    the first one declares a new integer array called array1.
    The 10 in square brackets sets the size of the array.
    Arrays always start at position zero so this array would go from 0-9.
    The second part is initializing array2 to the values in the
    brackets. That is the standard way of giving initial values
    to arrays. in this example array2 would have 5 values going
    from position 0-4 shown below. Which brings us to the next
    point:

    System.out.println(array2[2]);

    This prints out the value stored in position 2 of array2.
    Code:
    {10,20,30,40,50}
     0  1  2  3  4
    Now for the next part:

    for(int i = 0; i<array1.length; i++)

    This is a for loop which takes the random values and stores
    them in the positions of
    array1.

    here is standard for loop format:
    Code:
    for (int i=0;                  i<array1.length; 
    initialize counter  conditional statement which breaks loop
    
         i++;)
    increment counter
    once i hits 10, which is the value of array1.length, it will
    break out of the loop because the conditional statement
    is failed.

    Now this part:
    array1[i] = gen.nextInt(100) + 1;

    this stores a different random number in each position of
    the array. The positions are given by the value of the
    counter i. gen.nextInt(100) gives us random values of
    0-99 so we add one it to get values from 1-100.

    printArray(array1); calls the printArray method which
    I will talk about in just a second. The array1 part
    in parenthesis is the parameter you are sending as the
    (int[] a) part of the actual method. So all the stuff
    referred to as a in the printArray method, is actually
    the parameter we send in which is array1.

    Now to explain the printArray() method:
    public static void printArray(int[] a)

    you have to include static in the head of this method
    because we are using variables from the main method
    which is static. The (int[] a) part is set to the
    value put in when we call the method from main which
    is (array1). The void part I can't explain, but
    there are also return type methods which you can
    use where you would replace the word viod with the
    type of value you are returning such as String.
    I might give an example later in the tut if I
    remember.

    Now the guts of the printArray method:
    Code:
    for (int i=0; i<a.length;i++){
            System.out.print(a[i] + " ");
          }
          System.out.println();
    the line beginning with for is the same as above
    except we are using a.length instead of array1.length,
    even though a represents array1 in this method. The
    System.out.print(a[i] + " "); prints the value from
    each position of the array with a space following it.
    Notice how it is print instead of println, this is
    because we don't want a new line after each print,
    which is also why it is smart to put the space in.
    Then we do the System.out.println(); after all the
    values of the array are print out to make a new line
    so the next output won't come up on the same line.


    Here is another program:
    Code:
    import java.io.*;
    
    public class WordTest 
    {
    	public static void main(String args[]) throws IOException
    	{
    		BufferedReader input = new BufferedReader
    		(new InputStreamReader(System.in));
    		System.out.print("Enter a string: ");
    		String one = input.readLine();
    		System.out.println(getString(one));;
    	}
    	public static String getString(String str){
              int i = 1;
    	    while(i<=str.length()){
              System.out.print(str.substring(0,i));
              System.out.println();
    	    i++;
            }
            return "hello again";
          }
    }
    You start off with another import statement except
    this time it is to get the package that lets you
    input data from the keyboard.

    The throws IOException is there to get rid of errors.
    You do a lot of exception throwing java so get used to it.

    Next we instantiate our instance of the BufferedReader
    class:
    BufferedReader input = new BufferedReader
    (new InputStreamReader(System.in));

    This is the standard syntax, or at least it was for
    me in high school. So just stick to using that.

    Now for the next two lines:
    System.out.print("Enter a string: ");
    String one = input.readLine();

    The first line prompts the user for a string, and
    the second one uses the BufferedReader object "input"
    that we just created along with the built-in method
    readLine() to read the input. I'm pretty sure you
    will always use the readLine() method for any input.
    Notice we set the users input equal to the String
    one, this will be passed as a parameter to our
    getString method.

    The getString() method:
    Code:
    public static String getString(String str){
        for (int i=1; i<=str.length();i++){
           System.out.print(str.substring(0,i));
           System.out.println();
        }
        return "hello again";
    }
    First off we'll look at the parenthesis. The
    String str part is set to the parameter we
    passed in the main method, which is the String
    one. So now str will be a reference to one
    when used within the method. The while loop basically
    just checks a conditional statement each time
    it runs through and as soon as it is false
    it breaks out of the loop. I initialized i to 1
    then checked to see if it was less than the length
    of the String. Each time it was less than the String
    it would go throught the while loop hitting the part
    that says i++. This increments i so that eventually
    it will be greater than the length of the string.
    Then it would exit the loop because the conditional
    statement I setup would be false.
    The str.substring(0,i) part is refering
    to a substring of str. Let me explain,
    substring is built-in to the String class
    and no imports are needed for it. It can
    only be used on Strings. 0 is always the
    very first letter of the string. So here
    we are printing out the first letter of the
    string on every line up to position i.
    When i is finally equal to str.length(), then
    the whole word is printed out. If you were
    to just do str.substring(0) it would simply
    print out the whole word because you specified
    a substring starting at the first letter without
    an ending, so it prints to the last letter.
    The return part is required for any method with
    a data type in the head(String, int, double).
    Here we used String (public static String
    getString(String str)). So we have to return a
    String withing the method. If I had used int we
    would have had to return an int. I could have
    just used void instead of String and left out
    the return statement, but I wanted to teach you all
    about return methods.

    Now for one last program which will demonstrate GUI
    input and output without using an applet:

    Code:
    import javax.swing.JOptionPane;
    
    public class GuiTest
    {
       public static void main(String args[])
       {
    	
    	String strnum1;
    	String strnum2;
    	int num1;
    	int num2;
    	int sum;
    	
    	strnum1=JOptionPane.showInputDialog("Enter a NUMBER");
    	strnum2=JOptionPane.showInputDialog("Enter another NUMBER");
    	num1=Integer.parseInt(strnum1);
    	num2=Integer.parseInt(strnum2);
    	sum=num1+num2;
    	JOptionPane.showMessageDialog(null,"You Entered: "+ strnum1 + 
    	"+" + strnum2 + "=" + sum);
    	System.exit(0);
       }
    }
    Again we started off by using an import. This time we
    imported the JOptionPane package. The first few
    lines you should already know what they do.

    Now for the interesting lines:
    strnum1=JOptionPane.showInputDialog("Enter a NUMBER");
    strnum2=JOptionPane.showInputDialog("Enter another NUMBER");

    These two lines prompt the user to input two numbers, it
    will pop up with a box for the user to input the numbers
    into. This is standard notation for input with JOptionPane,
    so use it.

    Next we have:
    num1=Integer.parseInt(strnum1);
    num2=Integer.parseInt(strnum2);
    sum=num1+num2;

    num1 and num2 both take the input of the user and
    convert it to integers using Integer.parseInt(strnum1);
    or Integer.parseInt(strnum2); for the second one.
    You can also do Double.parseDouble, but you can't
    do String because it is already a String to begin
    with. sum just takes the values of num1 and num2
    and adds them together.

    The last two lines:
    JOptionPane.showMessageDialog(null,"You Entered: "+ strnum1 +
    "+" + strnum2 + "=" + sum);
    System.exit(0);

    First let me say that what I consider a line ends at
    each semicolon. So the first two parts of that are
    one line. the showMessageDialog() is standard for
    JOptionPane so again I'll say use it. You must
    have the "null," at the start of the parenthesis
    or it won't work. Then you just add all the
    values you want to output concatenating then
    with plus(+) signs. The last line I believe is
    also standard for JOptionPane, it just ends the program.

    There you have it, my second java tutorial(If you don't count
    the one on applets). I don't know if I will write anymore,
    it depends on the feedback I get on this one. This should
    give you all a few tools of java to mess around with for a
    while. Hope I converted everyone to java, and helped you
    to understand it. And don't forget to have a cup of java
    every day.

  2. #2
    Kick ass. I like it even though I have not thoroughly(spelling?) read it. I give you greenies, even if they have no wieght since i dont have lots of posts.

    -JESSUS IS COMING!!!! QUICK EVERYBODY LOOK BUSY!!!-

    Edit: I have to "spread my points around" sorry buddy. I'll give them to yah when I can.

  3. #3
    Member
    Join Date
    Oct 2003
    Posts
    78
    An enjoyable post, I like arrays. I always use JCreator to run programs the download is free (freeware version).




    Click here to visit JCreator.com








  4. #4
    Elite Hacker
    Join Date
    Mar 2003
    Posts
    1,407
    I'm glad you all enjoyed it, and thanks PAWS for giving that link in jcreator. I thought I had it in the first tutorial but I think it is actually in the one I wrote about applets. To use jcreator you will also need to download the java sdk
    from http://java.sun.com
    make sure to install the sdk first, then jcreator because jcreator needs the sdk to compile and run the programs.

  5. #5
    Netbeans IDE is very nice as well and of course is freeware.

    www.netbeans.org

    Note: Sun has this Packaged with one of the SDK downloads

  6. #6
    Member
    Join Date
    Oct 2003
    Posts
    78
    Glad I could be of help, I forgot to say about downloading the sdk before using JCreator, sorry. Thanx for the antipoints h3r3tic.





  7. #7
    Senior Member
    Join Date
    Nov 2002
    Posts
    186
    I would like to add one thing. I have been working with Java for close to 4 years now during university and co-op work terms. One thing I saw and never really understood was the static keyword above. I knew when it had to be there, but I never knew why. I noticed you mentioned it above. About a month ago I took the time to look it up myself. I think it is important to mention here so anyone learning the language does not stumble around like I did:
    static
    Definition -
    A Java language keyword used to define a variable as a class variable. A class maintains a single copy of class variables which are shared by all instances of the class.
    The static keyword can also be used to define a method as a class method, which is invoked using the class, instead of a specific instance, and can only operate on class variables.
    taken from: http://java.about.com/library/glossary/bldef-static.htm

    To add to the above definition, I read an article once that said static is a bad word, rather it should be one of or per-class. Whenever they say class method, they mean static (or per-class) method. The same goes for class variables.

    Paragraph 1 is saying that no matter how many times you create a instances of the class (ClassName foo = new ClassName() ), the static variables will hold a common value across all instances. To illustrate with an example, look at the below code and output.

    Without a static variable:
    Code:
    /**
       Created: Mon Oct 27 20:13:23 2003
       @author Alastair Grant & 3062173 (email: <x3y11@unb.ca>)   
    */
    
    public class test {
      public static void main(String[] args) {
        Student foo = new Student();
        Student bar = new Student();
        System.out.println(foo.studentNumber());
        System.out.println(bar.studentNumber());
      }
    } // test
    
    class Student{
      private int i;
      private int studentNum;
      public Student(){
        i++;
        studentNum = i;
      }
      public int studentNumber(){
        return studentNum;
      }
    }
    Output :
    1
    1

    With the static variable:
    Code:
    /**
       Created: Mon Oct 27 20:13:23 2003
       @author Alastair Grant & 3062173 (email: <x3y11@unb.ca>)   
    */
    
    public class test {
      public static void main(String[] args) {
        Student foo = new Student();
        Student bar = new Student();
        System.out.println(foo.studentNumber());
        System.out.println(bar.studentNumber());
      }
    } // test
    
    class Student{
      private static int i;
      private int studentNum;
      public Student(){
        i++;
        studentNum = i;
      }
      public int studentNumber(){
        return studentNum;
      }
    }
    Output:
    1
    2

    Note the static variable is "i" in the Student class.

    Paragraph 2 is saying that if you have a non-instantiatable class (basically just a collection of methods such as java.lang.Math) you simply call the methods that only interact with static variables.
    You cannot say:
    Math foo = new Math(45);
    double radians = foo.toRadians();

    You simply say:
    double radians = Math.toRadians(45);

    For example:
    Code:
    public class test {
      public static void main(String[] args) {
        System.out.println(Student.studentNumber());
        System.out.println(Student.studentNumber());
      }
    } // test
    
    class Student{
      private static int i;
      private Student(){
      }
      public static int studentNumber(){
        i++;
        return i;
      }
    }
    Output:
    1
    2

    Obviously this does not make much sense for a student (where you would want to store the student number, but one can see how it does work for the Math class where there is no real data to store.

    Hopefully this clears things up for a few people out there and you won't stumble around like me.

  8. #8
    Elite Hacker
    Join Date
    Mar 2003
    Posts
    1,407
    Thanks Algaen, those programs illustrate perfectly how the static keyword works. It is a bit technical, but I understood it and hopefully everyone else will also. I've been getting a lot of questions through the PM system about java(which I don't mind at all). Maybe now you will take some of the load off Algaen.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •