Thread Rating:
  • 5 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Introduction to Java 2
#1
Introduction to Java 2

Outline
1. Order of Operation
..1.1 Operator Precedence
2. Nested Flow Control Statements
..2.1 Nested If Statements
..2.2 Nested While/For Loops
3. Using Classes
..3.1 Instantiating a Class
..3.2 String Class
..3.3 Math Class
..3.4 Arrays
4. Methods
..4.1 Using Methods
..4.2 Creating Methods
5. File Input/Output
..5.1 File Input
..5.2 File Output
6. End








1. Order of Operation

It is important to understand operator precedence.

Go here for a complete list of operator precedence.





2. Nested Flow Control Statements

It is very useful to know about nested flow control statements.

2.1 Nested If Statements

An example of a nested If statement:
Code:
if (a)
    if (b)
        do();

This nested If statement first tests whether or not a

is true.
If so, it proceeds and then tests whether or not b is

true.
If so, it proceeds to call the do() method.

This can't be written as if (a && b)?
Yes, it could be written that way; however, there may be special cases where someone will find it practical to use a nested if statement.
Such as:
Code:
if (a)
{
    c++; // we want to increment C regardless of /b/'s value.
    if (b)
        die();
}


2.2 Nested While/For Loops

An example of a nested For loop inside a While loop:
Code:
boolean input = true;
while (input)
    for (int i = 0; i < 3; i++)
        System.out.println(3-i);

This code block will print out 3 to 1, each number on a separate line.
You may have noticed that this will continuously print out:
Code:
3
2
1

Every pass through the while loop, it makes 3 passes through the for loop.
Since input is always true, while's condition will always return true; thus, we have an infinite loop.


3. Using Classes

Using classes is another very important part of Java programming.


3.1 Instantiating a Class

Most classes need to be instantiated before being used.

Insantiate?
Instantiating is the act of creating an instance of a class; an object.

The syntax for instantiation is:
Code:
ClassName identifier = new ClassName;

However, if the class requires any parameters to be passed, it could look this way:
Code:
ClassName identifier = new ClassName(1, 2, 3);

The following is also valid:
Code:
ClassName identifier;
identifier = new ClassName;

The first line only creates a reference variable, a variable that points to an object.
Since we have not instantiated an object, there is nothing to point to; thus, we have a null pointer.
You may have guessed that a null pointer points to nothing.
This would be a good opening to explain Java's garbage collection.
When a reference variable stops pointing to an object, and no other reference variables are pointing to it, that portion of the memory is automatically freed up and available.
This is called garbage collection.



3.2 String Class

Java uses a String class for string-type variables; however, it is quite different from normal classes.
While the new operator can be used to instantiate a String object, it is not required.
(Only true with the String class. No other classes can be instantiated without the new operator.)
So this makes creating String objects much like creating regular variables of primitive data type.
A String object can also be represented as an array of characters.

Code:
String name = "name";
String lastName;
lastName = "last name";


3.3 Math Class

The Math class is also unique. The Math class is static; therefore, its methods can be invoked directly through dot notation, without an object being instantiated.

Example of square root function:
Code:
System.out.println(Math.sqrt(16)); // displays 4
System.out.println(Math.sqrt(4)); // displays 2


3.4 Arrays

Arrays can be difficult to grasp for a newborn programmer. I will try to explain them the best I can.
An array holds multiple values under one identifier. To reference these values, you use an index number (or subscript) between two brackets, [].

Example:
Code:
int[] grades = new int[2];
grades[0] = 10;
grades[1] = 50;
grades[2] = 100;

The above example instantiates an array of int type, and of size 2.
Array indexes start at 0, so it can technically hold 3 values. In index 0, 1, 2 and 3.

You can also instantiate an array like so:
Code:
int grades[] = new int[2];

I will be instantiating arrays this way from now on.

Arrays are also easier to manage than multiple variables.
Let's say you had 100 values you wanted to add 1 to.

Which of the following would you prefer?

Code:
var1++;
var2++;
var3++;
...
var99++;
var100++;

or

Code:
for (int i = 0; i < 100; i++)
    var[i]++;


I think 100 lines vs 2 lines speaks for itself here. Smile


4. Methods

Now, on to methods. Isn't this fun? Big Grin

Methods are used to break up your driver's code and used for segments of code that would usually be repeated.

4.1 Using Methods

Methods are fairly simple to use. They may return any type of data, or they may return nothing.
A method with the return type void will not return anything.
To call a method, you simply use the name of the method and if it has any parameters, include them.

Example of a void method:
Code:
displayNumbers();

This method obviously displays some numbers. It requires no parameters, and has nothing to return.

Example of an int method:
Code:
int x;
x = add(1, 3); // x = 4

This method returns an integer, and in this case, it returns 4, the sum of 1 and 3.
If it's not obvious already, to store the value a method returns, you need to store it in a variable of the same data type.


4.2 Creating Methods

Methods consist of a method header and a body of code.
In the method header, we have a visibility modifier, a return type, a method name and a list of parameters

public int add(int a, int b)

The above is the header for a method that adds two numbers together and returns the sum.
public being the visibility modifier, which decides who can access this method.
More on visibility modifiers will be discussed in Encapsulation.
int is the data type of the value we return when the method is finished.
"add" is the name of our method, the name we will use to call it.
And then we have the parameter list, which defines variables that are local to the method.
More on variable scopes will be discussed in Scopes.

The full method looks like:
Code:
public int add(int a, int b)
{
    return a + b; // return sum of a and b

}

The return statement returns the value given to it and ends the method regardless of its position.


5. File Input/Output

Ah, file input and output. Usually a dreaded topic for any beginner. No worries, file input and output is quite simple when you understand it.

5.1 File Input

We will start with file input. In Java, inputting a file required the use of two classes, both can be found in the java.io package.
These two classes are
  • FileReader
  • BufferedReader

How do we use them? Well, I'm getting to that.

Let us assume you have a program that needs to print every line of a text document into the console.

First, your code would look something like this:
Code:
import java.util.Scanner;
public class FileIO
{
    public static void main(String [] args)
    {
        Scanner keyboard = new Scanner(System.in);
        
        // Input file name
        System.out.print("Enter a file name: ");
        String fileName = keyboard.nextLine();

        // read from the file
        // read
        // display
    }
}

Obviously, we have not implemented the part where we read from the file and display the contents.

Before dumping all the code on you, let me explain the two classes we will be using.
The FileReader class requires one parameter to be instantiated. That is, the file name/path.
As you may have guessed, the syntax for instantiating a FileReader object would look like:

FileReader fr = new FileReader ("document.txt");

As for the BufferedReader class, this one accepts one parameter, too. It wants an object of type FileReader.
Looks like we are in luck, we just instantiated one of those. ;)
The syntax for instantiating a BufferedReader object would look like:

BufferedReader br = new BufferedReader (fr);

We pass in a FileReader object, and the BufferedReader class is happy. Smile

How do we make use of these? That is exactly what I am about to teach you.

The BufferedReader class has a method that allows us to read a line from a file, close the file, and all of that good stuff.

How do we invoke this method? Simple! Using dot notation, you can invoke the readLine() method.
Example: br.readLine();

Yes, it is that simple to read a line from our file. ^_~

--Wait, we just dropped the line we read on the floor. Since readLine() returns a String and we never stored it, we simply read the line and threw the String away. Sad

Let's fix that: String line = br.readLine();

What if there are no more lines left to read? Then the readLine() method returns null.
How do we handle that? I am getting to that right now.

Now, because we want to read every single line and display them, we'll need a loop.
And because we have no idea how large the file is, or how many lines we will be reading, we will be using the While loop.

Our plan is to develop a loop that reads every single line (except the null, non-existing ones).
So, a basic outline:

  1. Read our first line
  2. WHILE (Our line is not null)
  3. {
  4. Display the line
  5. Read another line
  6. }

The structore of that loop will successfully read every line in the file.

Let's implement this!

Code:
import java.util.Scanner;
import java.io.*; // ***Remember to include your IO package!***
public class FileIO
{
   public static void main(String [] args)
   {
      Scanner keyboard = new Scanner(System.in);

      // Input file name
      System.out.print("Enter a file name: ");
      String fileName = keyboard.nextLine();

      FileReader fr = new FileReader(fileName);
      BufferedReader br = new BufferedReader(fr);

      String line = br.readLine();

      while(line != null)
      {
         // display
         System.out.println(line);

         // get next line
         line = br.readLine();
      }

      br.close();
   }
}

Now let's create a file to read from. Name it whatever you'd like. I'm naming mine file.txt with "Hello" on one line and "world!" on the second line.
Now run your new Java program! ^_^


--Hm? Errors?

Ah, yes! We have errors! Why? Because we did not put our file input statements in a try/catch block.

All file input/output statements must have some form of exception handling.
You do not even have to handle the exception, if you do not wish to.
I, however, do not recommend you let exceptions occur without either letting it crash with a stack trace or notifying the user and handling it.

So, let's fix our program.

Code:
import java.util.Scanner;
import java.io.*; // ***Remember to include your IO package!***
public class FileIO
{
   public static String newline = System.getProperty("line.separator");
   public static void main(String [] args)
   {
      Scanner keyboard = new Scanner(System.in);

      // Input file name
      System.out.print("Enter a file name for input: ");
      String fileName = keyboard.nextLine();

      try
      {
         FileReader fr = new FileReader(fileName);
         BufferedReader br = new BufferedReader(fr);

         String line = br.readLine();

         while(line != null)
         {
            // display
        System.out.println(line);

            // get next line
            line = br.readLine();
         }

     br.close();
      }
      catch(Exception e)
      {
         System.out.println(e);
      }
   }
}

It is now safe to run your program. Smile
Your output should be something like:
Code:
Enter a file name: file.txt
Hello
world!
Press any key to continue. . .

See, that wasn't so bad,was it?


5.2 File Output

Whew, now time for File Output.

First, let me start by saying the new line character may vary from OS to OS. It may work on one, but not the other.
You want your program to work on *all* operating systems, don't you? Big Grin
When writing to a file, you should use the system independent new line character.

We can easily do this by using the following statement:
Code:
public static String newline = System.getProperty("line.separator");

The String newLine now has a newline character that will work for whichever OS the program is run from.
Now, let's move on to file output.

In this section, we will assume you want to take the contents of one file and transfer them all to another file.
This requires us to both read a file and write to a file. Good practice! ;)

Let's assume you half of the program implemented (which looks much like the last one):

Code:
import java.util.Scanner;
import java.io.*; // ***Remember to include your IO package!***
public class FileIO
{
   public static String newline = System.getProperty("line.separator");
   public static void main(String [] args)
   {
      Scanner keyboard = new Scanner(System.in);

      // Input file name
      System.out.print("Enter a file name: ");
      String fileName = keyboard.nextLine();

      FileReader fr = new FileReader(fileName);
      BufferedReader br = new BufferedReader(fr);

      String line = br.readLine();

      while(line != null)
      {
         // instead of displaying, we will write
         //write

         // get next line
         line = br.readLine();
      }

      br.close();
   }
}

Notice the newline String instantiated right above the main method.
Also, like the comment says, rather than displaying the lines, we will write them.

So what classes do we need to write to a file? We need two, again.
  • FileWriter
  • BufferedWriter

Notice these two are File and Buffered Writer classes, not Reader.
Setting up these two objects is much like before. FileWriter needs a file, BufferedWriter needs a FileWriter.

So, let's move on to the write() method. We simply call this method and pass a value to it, and it will write it to the desired file.

So, basically, our code would look something like:

Code:
import java.util.Scanner;
import java.io.*; // ***Remember to include your IO package!***
public class FileIO
{
   public static String newline = System.getProperty("line.separator");
   public static void main(String [] args)
   {
      Scanner keyboard = new Scanner(System.in);

      // Input file name
      System.out.print("Enter a file name for input: ");
      String fileName = keyboard.nextLine();

      System.out.print("\n\nEnter a file name for output: ");
      String wFileName = keyboard.nextLine();
      try
      {
         FileReader fr = new FileReader(fileName);
         BufferedReader br = new BufferedReader(fr);
         FileWriter fw = new FileWriter(wFileName);
         BufferedWriter bw = new BufferedWriter(fw);

         String line = br.readLine();

         while(line != null)
         {
            // instead of displaying, we will write
            bw.write(line + newline);

            // get next line
            line = br.readLine();
         }

         br.close();
         bw.close();
      }
      catch(Exception e)
      {
         System.out.println(e);
      }
   }
}

Note: I went over this fairly quickly, please do ask questions if you do not understand something. I am always happy to answer a question about my tutorials.


7. End

Thank you for reading my tutorial. And as I said above, ask as many questions as you'd like.
Also, I would appreciate it if you could notify me of any mistakes/errors.
Reply
#2
(10-04-2009, 06:52 PM)Psycho Wrote: Array indexes start at 0, so it can technically hold 3 values. In index 0, 1, 2 and 3.

A typo here, otherwise well done.
Reply
#3
Another great tutorial well done ;P
Reply
#4
Wow. I just skipped over this in a few seconds, and this is probably one of the best 'forum' Tuts I've seen yet.
Good job Thumbsup
[Image: 23lfxh3.png]
Want to set up your own Runescape server? PM Me.
Reply
#5
Great tutorial but quick question where did you learn Java?
Reply
#6
(10-20-2009, 06:43 PM)JavaGuy Wrote: Great tutorial but quick question where did you learn Java?

I learned the basics through a computer science course and the rest the Java documentation. ;)
<Aoi-chan> everyone's first vi session. ^C^C^X^X^X^XquitqQ!qdammit[esc]qwertyuiopasdfghjkl;:xwhat
Reply
#7
(10-21-2009, 04:24 PM)Psycho Wrote: I learned the basics through a computer science course and the rest the Java documentation. ;)
So am IThumbsup
Reply
#8
That was a nice tutorial for the newbies.Thanks for sharing this.
[Image: 2d75599e9a.png]:superman:
Reply
#9
I will read through this once I get home, but I did notice something scimming through it:

7. End

When in the outline it says:

6. End

Not really a big deal, just thought I'd let you know Big Grin
Reply
#10
Just finished 1 and 2, they are both great. Keep them coming if you can.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  why java haphazard 8 1,438 12-12-2011, 03:23 AM
Last Post: RDCA
  Need Java help from java expert. Blazin 2 1,903 09-07-2011, 02:43 PM
Last Post: AceInfinity
  Introduction to Java Psycho 41 9,655 06-09-2011, 06:12 AM
Last Post: xMan
  Java help php 1 830 04-06-2010, 06:41 AM
Last Post: php
  Java Problem for real java programmer Testgamma1 10 4,483 03-14-2010, 09:08 AM
Last Post: uber1337

Forum Jump:


Users browsing this thread: 1 Guest(s)