A Java Tutorial
Page 1 of 2 12 LastLast
Results 1 to 10 of 19

Thread: A Java Tutorial

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

    A Java Tutorial

    I didn't like how the only java tutorial I found on this site didn't catch the essence of java which is
    that it is an object oriented programming language. First I'll show you a little program without
    using the object oriented part of java.
    Code:
    public class test
    {
    	public static void main(String args[])
    	{
    		System.out.println("Testing");
    	}
    }
    This is about as simple as java gets. First of all, let me just say that for this program to compile
    and run you must have it saved as test.java. Now let's analyze the program.

    public class test

    every program must have this at the top and the third word must be the same as what you
    saved the program as. If it is different you will get an error.

    public static void main(String args[])

    every program must also have a main method. This is where you handle your output.

    System.out.println("Testing");

    This is the standard form of showing output. You can also do

    System.out.print("Testing");

    This statement does the same thing except that it won't go to the next line after it prints
    Testing. If you wanted the next output to go to the next line you could use

    System.out.print("\nThis will be on a new line");

    The \n puts the output on a new line.

    Now let's add a new class to the program.

    Let's say you had the same as above. You could put a whole new class within the program.
    In this class you can have methods. A method is like a function in C++. You put stuff you want
    done such as output or adding numbers in the method then you call it from the main class.
    Here's an example.
    Code:
    public class test
    {
    	public static void main(String args[])
    	{
    		System.out.println("Testing");
    		stuff.print();  // this calls the print method
    	}
    }
    
    class stuff
    {
    	public static void print()
    	{
    		System.out.println("Hello World");
    	}
    
    }
    If you compile and run this program you will see this output

    Testing
    Hello World

    Now let's get into the object oriented part of java. If you change the program above to this.
    Code:
    public class test
    {
    	public static void main(String args[])
    	{
    		stuff s1=new stuff();		
    		System.out.println("Testing");
    		s1.print();  // this calls the print method
    	}
    }
    
    class stuff
    {
    	public void print()
    	{
    		System.out.println("Hello World");
    	}
    }
    notice how it's public void print() instead of public static void print().
    This is because we want to make different objects of the stuff class. We do this using these lines
    which are in the main method above.

    stuff s1=new stuff();

    This creates an object or instance of the stuff class called s1. Then we used s1 to call the
    print() method.

    s1.print();

    You could even make another method in the first class called test and leave out the second class
    stuff. Here is how this would be done.
    Code:
    public class test
    {
    	public static void main(String args[])
    	{
    		System.out.println("Testing");
    		print();
    	}
    	public static void print()
    	{
    		System.out.println("Hello World");
    	}
    }
    As you can see there are many ways to do the same thing in java. The last 3 programs all have
    the same output, but they are all different. Some say the proper way to do it is to make a new class
    for each task you are trying to do. If you take the second example
    Code:
    public class test
    {
    	public static void main(String args[])
    	{
    		System.out.println("Testing");
    		stuff.print();  // this calls the print method
    	}
    }
    
    class stuff
    {
    	public static void print()
    	{
    		System.out.println("Hello World");
    	}
    }
    You could also leave off the second class stuff and make it into a whole different file.
    I used the java sdk from sun and jcreator for my development environment. As long as you save it in
    the same directory you can have two separate files. This is how they want you to program in java.
    They don't want one file with a bunch of garbage. Every time you do a new task you either make a
    new method to do within the class, or make a whole different class. Using this method you would have
    Code:
    public class test
    {
    	public static void main(String args[])
    	{
    		System.out.println("Testing");
    		stuff.print();
    	}
    }
    edit:
    does anyone know how to get spaces to show up?
    This would be the first file saved as test.java.(don't forget the .java)

    Then you would have this in a separate file saved as stuff.java *in the same directory
    Code:
    public class stuff
    {
    	public static void print()
    	{
    		System.out.println("Hello World");
    	}
    }
    You would have to run this from the first file called test.java because that contains the main method.


    Here is a program using integers
    Code:
    public class calc
    {
    	public static void main(String args[])
    	{
    		int num1;
    		int num2;
    		int num3;
    		num1 = 2;
    		num2 = 3;
    		num3 = num1 + num2;
    		System.out.println(num1 + "+" + num2 + "=" + num3);
    	}
    }
    Generally in java you declare the variables at the top of the main method as shown above. If
    you declare a variable and don't set it equal to anything you will get an error saying variable
    not initialized. You could just start it out at zero when you declare it by typing

    int num1=0;

    This program adds num1 and num2 and puts the answer in num3. within the
    System.out.println statement you see a lot of pluses. you have to use pluses between each
    thing you are printing out. You would get an error if you left any of the pluses out.

    Now I'm going to talk about constructors. Look at the sample program below.
    Code:
    public class test
    {
    	public static void main(String args[])
    	{
    		stuff s1 = new stuff(5);
    		System.out.println(s1.showValue());
    	}
    }
    class stuff
    {
    	private int getValue;  //if you are going to use a variable throughout the class declare 	
    //here to be able to use it in each method
    	
    	public stuff(int num)  // this is the constructor and it receives the 5 that you put 
    	{                      //within the parenthesis when you instantiated the object
    		getValue=num;     // in the main method
    	}
    	public int showValue()
    	{
    		return getValue;
    	}
    }
    Whether you make a constructor or not it is automatically done behind the seens and it initializes
    all the values to zero (or false if its boolean).
    here we have a return method(public int showValue()).
    All return methods must return something or you get an error. You could just say return 0;
    if you want. The variable must be the same type as declared in the head of the method.


    ex.
    Code:
    public String getString()
    {
    	String a= "Hello";
    	return a;
    }
    You could also use double. Whenever you do a return method the output is not printed out.

    This is why I did System.out.println(showValue()); in the main method.

    if you were wondering what the private keyword does private int getValue;
    This makes that variable only accessable through the stuff class. You can return it to the
    test class through a method but you cannot change it from the test class.

    I forgot something. You can also instantiate an object like this.

    stuff s1;
    s1=new stuff(); //you can put this part anywhere within the class, it doesn't have to be right under the stuff s1; line

    I'm getting tired of typing now. If you all would like to see more like maybe some
    graphics, just post some replies on what you would like to know. This should be enough to get
    anyone started in java. I hope you all enjoyed it. p.s. If you see any errors please post about
    them and I will fix them.


  2. #2
    Good write-up.
    I noticed there was no java tut here touching the basics and was working on one but you beat me to it.
    Good job.
    edit:
    does anyone know how to get spaces to show up?
    I am not sure what you mean by this but you could put your code snippets between code tags like
    [code] (close) with the [fwd-slash code]
    If it is something else I dunno

    Kudos
    noODLe

  3. #3
    Elite Hacker
    Join Date
    Mar 2003
    Posts
    1,407
    Thanks for the tip on the [code] thing noODle.
    It looks a little better now.

  4. #4
    Solid stuff.

    Let's talk about bubble sorting an ArrayList. (I'm just kidding. Really).

    Good thing you pointed out the requirement for initializing variables. I've come from C++ and things are a bit different here. Only thing - I don't believe you have to initialize instance variables that appear in a called method.

    l00p

  5. #5
    Elite Hacker
    Join Date
    Mar 2003
    Posts
    1,407
    "Only thing - I don't believe you have to initialize instance variables that appear in a called method. "

    What do you mean?

    if you do this
    Code:
    class stuff
    {
                 private int num;
    
                 public int getNum()
                 {
                        num=2;   //are you talking about here.   Are you saying I could just return num 
                                        //without doing this line?
                        return num;
                 }
    }
    please explain so I can correct any errors I've made.

    Also I didn't mention if and else. And for and while loops.
    here's an example
    Code:
    public class test
    {
          public static void main(String args[])
          {
                int i = 1;
                if (i == 1)   //if you use more than one statement in the if, else, elseif, for, while  you 
                                  //need {} surrounding the statements.
                {
                     System.out.println("i is equal to one");
                     System.out.println("yay for i");
                } 
                elseif (i != 1)  //!=  means not equal to 
                     System.out.println("i is not equal to one");  
                elseif (i <= 0)  //<= less than or equal to
                     System.out.println("i is less than or equal to zero");
                else
                      System.out.println("i is not any of the above");
                       
                 for(int j= 0; j<=5; j++)  // does something 6 times
                 {
                        System.out.println(j);
                 }
                        
                  while(i<10)  // uses i from above which is one and keeps doing the loop until i gets to ten
                  {
                       System.out.println(i);
                  }
                         
                  do
                  {
                        System.out.println(i);
                  }
                  while (i<10);       // will print at least once because it checks after it prints.
                          
                  for (int k = 10; k>=0; k++)        // an infinite loop because k is always going to be 
                                                                      //greater than zero.
                  System.out.println(k);
          }
    }
    That's just a little about if, elseif, else, for, while, and do while.

  6. #6
    Sorry, I should type more clearly.

    What I meant was, inside a called method, you don't need to:

    int x = 2;
    [more code..]

    You can just create the instance of variable x without assigning it a value off the bat. I think you mentioned somewhere that initalizing a variable at the same time you declare it is required... if not, please ignore my ramblings.

    You also asked the below:
    class stuff {
    private int num;

    public int getNum() {
    num=2; //are you talking about here. Are you saying I could just return num
    //without doing this line?
    return num;
    }
    }

    Actually, yes, you can, but the value returned is going to be NULL. That's one tricky thing I've found about passing objects or values back. They can be of the declared return type, or they can be NULL.

    So, you can actually:

    num=2;
    return null;

    And the compiler won't complain. It's useful if you expect a value to be returned, but want the next line of code to do something different if no value is returned.

  7. #7
    Senior Member
    Join Date
    Oct 2001
    Posts
    186
    while we are on the subject of java does anyone have any good links which discuss and explain polymorphism and inheritance in java. Also I would like to find corresponding source code which could help me better understand these topics. If anyone has any links it would help me out alot.
    Ben Franklin said it best. \"They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.\"

  8. #8
    Elite Hacker
    Join Date
    Mar 2003
    Posts
    1,407
    http://www.schram.org/

    I haven't really explored this site but I know he wrote the book we used in class, which was on cd-rom. You can probably download the bood at that site. It is called exposure java. It talks about polymorphism and inheritance.
    I you can't find it let me know and I can cut and paste some stuff since I have the cd-rom.
    Good luck.

    edit
    it looks like you have to order the exposure java cdrom.
    Is it alright to cut and paste info as long as I put the source or is it illegal?
    If it's alright I will post some info on those subjects.

  9. #9
    Senior Member
    Join Date
    Oct 2003
    Posts
    234
    I found a good E-Book (PDF, the site called it an E-Book ) called Thinking in Java by Bruce Eckel. You can get it at http://www.planetpdf.com/mainpage.asp?WebPageID=314. I'm not a big Java user (I prefer Microsoft .Net), but I found it to be very informative. The file is zipped on this site, so be sure you can unzip it before downloading . Good tut, by the way!

  10. #10
    Thanks a lot h3r3tic. I just saw this but it's really helpful. I know c++ and the general stucture is the same, but I had bit of trouble getting my foot in the door and you fixed that. Again, thanks a lot.

    -It is I, me-

Posting Permissions

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

 Security News

     Patches

       Security Trends

         How-To

           Buying Guides