Introduction to Java (Full Version)

All Forums >> [Gaming Community] >> [Legends and Lore] >> Artists of Legend >> Art Academy



Message


Krieg -> Introduction to Java (3/2/2008 14:36:49)

[image]http://i111.photobucket.com/albums/n131/Spenndragon/Java%20Tutorial/IntrotoJava.png[/image]


Table of Contents
I. Chapter 1: Welcome to Java
_A. Introduction
__1) To the Reader
__2) About Java
_B. Setting Up Your IDE
__1) About IDE's
__2) Setting Up TextPad
II. Chapter 2: Programming Basics
_A. Workflow
__1) Process
__2) IPO Chart
__3) Flowchart
__4) Pseudocode
_B. Reserved Keywords
III. Chapter 3: Java Basics - Part 1
_A. Hello World
__1) Print vs. Println
__2) Escape Characters
__3) Comments
_B. Decisions
__1) Input
__2) Variables
___a. Integer
___b. Double
___c. String
___d. Character
__3) If/Else
IV. Chapter 4: Java Basics - Part 2
_A. Errors and Debugging
__1) Syntax
__2) Run Time
__3) Logical
___a. Try/Catch
_B. Loops
__1) While Loop
__2) Do-While Loop
__3) For Loop
V. Chapter 5: Java Basics - Part 3
_A. Class Hierarchy
__1) Objects and Methods
___a. Return
___b. Public vs. Private and Scope
__2) Inheritance
___a. Extends
___b. Overloading Methods
___c. Super
___d. Static Methods
VI. Chapter 6: Java Basics - Part 4
_A. ArrayList
_B. Arrays
__1) Multi-Dimensional Arrays
VII. Chapter 7: Searching and Sorting Arrays
_A. Linear Search
_B. Binary Search
_C. Selection Sort
_D. Insertion Sort
VIII. Chapter 8: Searching and Sorting Arrays of Objects
_A. Interfaces
__1) Comparable Interface
__2) Searching and Sorting Objects
___a. Accessor Methods
_B. Abstract Class
_C.Polymorphism




Chapter 1: Welcome to Java

[IA1]To the Reader
If you're reading this tutorial, you're probably new to the programming world, a programmer willing to learn something new, or just someone who has some free time on your hands. Either way, welcome to my tutorial. Here, you will be learning the basics of programming in Java. Graphics will not be covered in this tutorial. Also note that this tutorial should not be used as a replacement for a formal course. This tutorial is merely a crashcourse to Java and will not cover everything Java has to offer.

[IA2]About Java
Java is a high level language, enabling us to program algorithms using the English language instead of in binary (aka sets of 0's and 1's). If you've never programmed before, then learning Java may seem a little overwhelming. Due to this, I'll try and explain everything as simply as I can. However, please acknowledge that there are no shortcuts in truly learning how to program so I expect you to read everything this guide has to offer.

[IB1]About Integrated Development Environments (IDE)
The Integrated Development Environment, or IDE for short, is virtually a text editor that helps programmers code programs by grouping all of the tools necessary in one place. An IDE generally contains a workspace where you'll be able to type code and a button to compile the code and check for errors. There are many IDE's available for various purposes. For this tutorial, I will be using the TextPad IDE which can be downloaded for free at TextPad.com.

[IB2]Setting Up TextPad
First, you will need the Java SDK (Java Software Development Kit) which can be downloaded from Java.Sun.com. This contains a library of all of the standard methods and objects available for Java programming and is required for compiling code. Install this.

Next, download and install TextPad. If you accidentally installed this before the SDK, you will need to modify the file path or start over. Otherwise, Congratulations! You're now ready to begin programming Java!




Chapter 2: Programming Basics

Exercise Files: Download (.zip)

[IIA1]There are six steps to programming:

1) Analyze the problem: think about what the problem is (input) and what needs to be done (output).
2) Plan a solution: plan how you would solve the problem.
3) Deskcheck the solution: check to see if your solution would solve the problem.
4) Implement the solution: code your solution.
5) Check your solution: check to see if your code works the way you intend it to work.
6) Debug the program if there are any errors.

I recommend that you do each step even if it seems tedious. When you are programming something complicated, following all of these steps will speed up your workflow.

[IIA2]Input/Process/Output Charts, or IPO for short, is a way to combine steps one and two. All an IPO chart is, is a list with three collumns: Input, Process, and Output. The process collumn is your algorithm.

Exercise 1: You are selling tickets for your school play. It costs $3 for children under 12 and $5 for those thirteen and older. Make an IPO chart of the problem.
spoiler:

http://i111.photobucket.com/albums/n131/Spenndragon/Java%20Tutorial/ExamplePlayTicket-IPOChart.png


[IIA3]Making flowcharts is a good way to visualize your solution and is an alternative to IPO charts. Unlike pseudocode (addressed next), there are a few standards:

Ovals: Start and End
Arrows: Flowlines to show direction of program
Rectangles: Processing (ie equations)
Diamonds: Decisions and choices to be made
Rhombi: Input and Output
Circles: Continuation (if run out of space)

Exercise 2: Same scenario as exercise 1. This time, make a flowchart.
spoiler:

http://i111.photobucket.com/albums/n131/Spenndragon/Java%20Tutorial/ExamplePlayTicket-Flowchart.png


[IIA4] Like aforementioned, there is not standard pseudocode. Pseudocode is basically words that describe your solution.

Exercise 3: Same scenario as Exercise 1. This time, write pseudocode.
spoiler:

Input age.
If age <= 12, cost is $3.
Else, cost is $5.
Output age.


[IIB] There are a few reserved keywords in Java. Reserved keywords are exactly what they sound like: words reserved for specific uses. We will talk more about this in future chapters. Here are a few we will be using: int, double, String, char, public, private




Chapter 3: Java Basics - Part 1

Exercise Files: Download (.zip)

[IIIA1]Let's examine the ever-so-popular "Hello World" program:

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


Copy and paste the above code in TextPad, and save the file as HelloWorld.java. Then, compile the code via [Ctrl] + [1] or Tools > External Tools > Compile Java. There should not be any errors at this time. Then, run the Java application via [Ctrl] + [2] or Tools > External Tools > Run Java Application. This should open Command Prompt with "Hello World!" printed on it.

Even though these are only few lines of code, there is a lot to discuss about each of them. However, we won't go into detail just yet. For now, we'll just mention a few of them.

Line 1, "public class HelloWorld", pretty much determines what you have to name the file. So, if I wanted to call the program "MyWorld.java", I'd need to type "public class MyWorld".

Line 2 has what we call an open bracket "{". This tells the computer that everything between the open bracket and corresponding close bracket (in this case, line 7 "}") is part of that element. For example, line 5 (System.out.println("Hello World!");) is enclosed within open and close brackets corresponding to line 3 (public static void main(String[] args)) meaning that it is located under the main method which we will discuss next.

Line 3, "public static void main(String[] argS)" header (also called the main method), is necessary for all driver programs to have (aka the main program that coordinates all of the other classes). It just tells the computer "This is where the program starts."

Line 5, as you've probably already guessed, tells the computer to print a line that says "Hello World!". Now, try changing "println" to "print", compile, and run the application again. You should see that "Hello World!" and the standard "Press any key to continue" are on the same line. The command System.out.println() is basically the same as System.out.print() except that println() start a new line after it is executes while print() continues on the same line. All statements in Java end with a semicolon (note: headers are not statements).

All code in Java is case sensitive. This means that "public" is not the same as "Public". You may also want to be familiar with the term "white space". White spaces are just the spaces you leave in the program to make it more programmer-friendly. All that matters is the sequence of events.

Exercise 4:Modify your HelloWorld.java program so that it displays, "Hello, " and your name using both the print() and println() methods on the same line.
spoiler:

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


[IIIA2] Escape characters are pieces of code that enable you to put symbols between the quotes within System.out.println() that would otherwise cause errors. Here are a few:

"\t" inserts a tab space
"\n" creates a new line
"\'" creates a single quote
"\"" creates a double quote
"\\" creates a backslash

Exercise 5: Go back to your program in exercise 4. Modify it so that your name is in double quotes, the line is tabbed once, and there isn't a println() method but the "Press any key to continue" text is still on the second line.
spoiler:

public class HelloWorld
{
	public static void main(String[] args)
	{
		System.out.print("\tHello,");
		System.out.print(" \"Slythe.\"\n");
	}
}


[IIIA3] Comments, while they do not impact the code, are very important. Not only does commenting enable you to look back at old code and remind you what the methods did, but they can also be used to comment out, or render useless, pieces of code that you don't want to execute but still want to keep (ie during debugging). There are two types of comments that I will introduce.

Single line comments can be created with two slashes "//". They terminate at the end of the line and are useful when explaining certain lines of code.

Block comments can be created with a slash and an asterisk "/*". They terminate with the corresponding asterisk and slash "*/" and are useful when commenting multiple lines of code or just to create a header.

For Example:
System.out.print("Hello World!"); //example of print() method


[IIIB1] Most of you are probably wondering by now, "Can't I have any fun during run time?" One way is by using BufferedReader which reads your input and returns it as a String. You can created a BufferedReader object like this:
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

dataIn in the above code becomes a BufferedReader object. We will discuss more about objects in a later chapter.

We're not done yet. There are a few other modifications we need to make to the code to make the program run correctly. First, we need to import the java.io library into the program. In your HelloWorld.java program, type the folowing code above "public class HelloWorld":
import java.io.*

The asterisk tells the computer to import the entire java.io library. Sometimes, it may be more efficient to import only certain parts of the library.

Next, you need to add "throws IOException" at the end of the main header. This just tells the computer to ignore input and output errors.

Exercise 6: In your HelloWorld.java program, use BufferedReader and the .readLine() method to input your name during runtime, and have the program output the name you had input. Here are the first few lines:

import java.io.*;

public class HelloWorld
{
	public static void main(String[] args) throws IOException
	{
		String name; //declares a String variable called name

		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

spoiler:

import java.io.*;

public class HelloWorld
{
	public static void main(String[] args) throws IOException
	{
		String name; //declares a String variable called name

		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("Input Name: ");
		name = dataIn.readLine();

		System.out.print("\tHello,");
		System.out.print(" \"" + name + "\"\n");
	}
}


[IIIB2]As you saw in the last Exercise, we declared a String variable called name. String is a data-type that stores any textual information. You can declare any variable using the following syntax: [data-type] [name]. For example, if I wanted to declare an int variable, or a variable that stores integers (whole numbers), then I can say "int num;".

All variables must be initialized in a program on the same plane it was created. I intialized the name variable in the example using the readLine() method since it returns a String. Here is a list of common data-types and how you can initialize them:

int level = 0; //whole numbers
double damagePercentage = 0.0; //decimal numbers
String name = ""; //series of characters and numbers
char character = ''; //single character
Boolean dead = false; //true/false

While it doesn't matter to the computer. variables usually start off lower case. One exception is constant variables. Constant variables are variables that remain the same throughtout the program and cannot be changed. You can declare a variable as constant using the "final" reserved keyword. For example:

final double HP_UP = 0.07


Variables may contain characters, numbers, and underscores, but all variables must start with a character (ie num1_dog is valid, but 1st_dawg are _dog_ are not).

In some cases, you will need to convert a String to other data-types. To do this, you do something called parsing. Here are a few parse methods, assuming str is a String:

int level = Integer.parseInt(str); //converts a string into an integer
double damagePercentage = Double.paraseDouble(str); //converts a string into a double

Your variables should mean something to you so that any programmer looking at your code would be able to understand what it is without completely analyzing your code.

[IIIB3] The first exercise in this tutorial asked the computer to make a decision: is the person's age 12 or under. If yes, the ticket cost was only $3. However, if the person was over 12, the cost was $5. In this scenario, we can use the if... else statements. They can be summarized as follows:

if (age <= 12) //condition is true
{
	ticketCost = 3;
}
else //condition is false
{
	ticketCost = 5;
}


A single if statement can have multiple conditions connected by the && (and) and || (or) operators. For example, given condition1 and condition2 are Boolean variables:

if (condition1 == true || condtion2 == true) //one condition has to be true
if (condition1 == true && condition2 == true) //both conditions have to be true


As you can see in the above example, I used two equal signs (==) to show that the variables equalled something. A single equal sign can only be used to declare a variable as something and cannot be used as a condition. However, the double equal signs only work to check numbers and Booleans. For Strings, you will need to use the equals() method (ie str.equals("Hi");). Here is a list of conditions:

"==": something equals something
"!=": something doesn't equal something
"<=": something is less than or equal to something
">=": something is greater than or equal to something
"<": something is less than something
">": something is greater than something

Exercise 7: Let's change the first Exercise a little. Say there are three ticket costs: $2 for students 12 and under, $3 for student older than 12, and $5 for everyone else. Let the file be named TicketCost.java.
spoiler:

import java.io.*;

public class TicketCost
{
	public static void main(String[] args) throws IOException
	{
		String temp;
		int age, cost;
		Boolean student;

		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

		System.out.print("Age: "); //prompts for age
		temp = dataIn.readLine(); //reads user input
		age = Integer.parseInt(temp);

		if (age <= 12) cost = 2; //if equal or under 12
		else
		{
			System.out.print("Student (yes/no): ");
			temp = dataIn.readLine();

			if (temp.equals("yes")) student = true;
			else student = false;

			if (age > 12 && student == true) cost = 3; //if over 12 and is a student
			else cost = 5; //if over 12 and is not a student
		}

		System.out.println("Ticket Cost: $" + cost);
	}
}





Chapter 4: Java Basics - Part 2

Exercise Files: Download (.zip)

By now, most of you have probably run into errors. In Java, there are three types of errors: syntax, run time, and logical errors.

[IVA1] Syntax errors are programming errors that can be found using the compiler. These often occur by programming mistakes (ie capitalizing "Public" when it should be lower case "public") and typos (ie declaring a variable to be num1 and using a num!). Syntax errors can usually be fixed relatively easily.

[IVA2] Run Time errors can be difficult to find and only occur when the program is executed. These include, as we'll discuss in Chapter 6, NullPointerException for arrays when you accidentally attempt to access an object not part of the array.

[IVA3] Logical errors are usually of no fault from the programmer and can often be fixed using an if/else or try/catch statement, which we'll be discussing next. These are errors that occur during run time that are logically invalid, including attempting to divide by zero.

[IVA3a] try/catch statements are relatively easy to understand. In the context of if/else statements, try/catch can be stated like this: if this doesn't have any errors, execute the code under try. Else, execute the code under catch.

try
{
	try code;
}
catch (Exception e)
{
	catch code;
}


Exercise 8: Try writing a simple division program where the user inputs two decimal values. Make sure to cover division by zero. Display an error message when the denominator is zero and when the user input is not a number. Call the program Division.java.
spoiler:

import java.io.*;

public class Division
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
		double numerator=0.0, denominator=0.0, quotient=0.0;

		try
		{
			System.out.print("Numerator: ");
			numerator = Double.parseDouble(dataIn.readLine());

			System.out.print("Denominator: ");
			denominator = Double.parseDouble(dataIn.readLine());

			if (denominator != 0) System.out.println(numerator / denominator);
			else System.out.println("Denominator cannot be zero.");
		}
		catch (Exception e)
		{
			System.out.println("Input must be numbers only!");
		}
	}
}


[IVB] Sometimes you might want to do something for a certain amount of time without having to copy and paste the code for every time you want it to run. This is where loops come in handy. We will be covering three types of loops in this chapter.

[IVB1] The first type of loop is a while loop. These loops run until an unspecific condition is met; an improper condition can cause an infinite loop (run time error).
while(condition)
{
	stuff;
}


Exercise 9: Code a sum program allowing the user to input as many numbers as he or she wants until he or she types in 0.
spoiler:

import java.io.*;

public class Sum
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

		int sum=0, num;

		System.out.print("Input Numbers (Type \"0\" to find sum): ");
		num = Integer.parseInt(dataIn.readLine());

		while (num != 0)
		{
			sum += num; //same as sum = sum + num
			num = Integer.parseInt(dataIn.readLine());
		}

		System.out.println("Sum: " + sum);
	}
}


[IVB2] The second type of loop is a do-while loop. This loop is very similar to the while loop except whatever is in the while loop is guaranteed to run at least once. For example, we can rewrite Exercise 9 like this:
import java.io.*;

public class Sum
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

		int sum=0, num;

		System.out.print("Input Numbers (Type \"0\" to find sum): ");

		do
		{
			num = Integer.parseInt(dataIn.readLine());
			sum += num; //same as sum = sum + num
		} while (num != 0);

		System.out.println("Sum: " + sum);
	}
}


[IVB3] The third type of loop is a for loop. This loop can only run for a specified amount of time. You write a for loop like this:
for (int counter=0; counter<10; counter++) //counter++ is the same as counter = counter + 1;
{
	stuff;
}


The first part of the for loop is the counter. You can intialize a new integer variable for this (int counter=0). The second part is the condition of which allows the loop to continue running (counter<10 runs until counter is 10 or over). The third part is the increment (counter++); if you don't increment properly, you can have an infinite loop.

Exercise 10: Code a program that outputs factorial (ie 5! = 5 x 4 x 3 x 2 x 1) using a loop.
spoiler:

import java.io.*;

public class Factorial
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

		int factor, factorial=1;

		System.out.print("Enter a number: ");
		factor = Integer.parseInt(dataIn.readLine());

		for (int counter=factor; counter>0; counter--)
		{
			factorial *= counter;
		}

		System.out.println("Factorial of " + factor + " is " + factorial + ".");
	}
}





Chapter 5: Java Basics - Part 3

Exercise Files: Download (.zip)

Unfortunately, there are a few cases in Java where we have to discuss the technical aspects of things in order to understand it. In this case, we're going to talk about classes, objects, and methods.

[VA1] No doubt by now you've been wondering why we have to type "public class ________" at the beginning of each program. What is a class anyway? All a class is, is a blueprint of an object. What does that mean? Let's put this in the context of a RPG. When everyone creates a new character in a RPG, all of the characters start out the same: everyone has health points, defense, offense, etc. This is what is defined in a class. However, you usually have the power to modify what each field is: every character has its own name, strength, etc. In other words, every character is an object of a base character class (aka each character object is based off a character class). You can declare an object like this:

Object name = new Object(parameters);


Look familiar? It should. We, in chapter 3, created a BufferedReader class called dataIn. So, where did readLine() come from? readLine() is a method of the BufferedReader class. A method is just a piece of code that a programmer codes so that an object of that class can call/invoke/execute it at will instead of having to write it out every single time.

So, how do you create a class? Quite honestly, you've been doing it all of this time.

public class Something
{
	public Something(parameters) //constructor
	{
		// variable initialization
	}

	public returnType method(parameters)
	{
		//code
		return variable;
	}
}


You may be asking yourself "WTF just happened?" All I did was create a class called "Something" with a constructor and a method called "method". A constructor is always named after the class name and is always automatically called when you create an object from that class. Usually, the constructor just initializes variables.

Now, what's up with the method? A returnType is just the dataType of the information you want returned to the object that called it. At the end of each method that returns a variable, you need a return statement (ie if the return type was an integer, you need to return an integer variable). If you do not want the method to return anything, you can declare the method void (ie public void method()).

To use any of these objects, you will need to create a driver class. What is that? Quite simply, it's the class that contains a main method, which is where everything is run.

For example, if I wanted to create an object which I can do simple mathematical calculations to (these are two separate files):

//MathObject class

public class MathObject
{
	private int bNum; //creates a variable limited to this object

	public MathObject(int num) //constructor
	{
		bNum = num; //initialized bNum with the value of num
	}

	public int add(int num) //add method
	{
		return bNum + num;
	}
}

//Driver class

public class SimpleCalculator
{
	public static void main(String[] args)
	{
		final int num = 10;
		MathObject baseNumber = new MathObject(num); //creates and initializes a MathObject

		System.out.println(baseNumber.add(2));
	}
}


If you have parameters in your methods (or constructor, for the matter), you need to create a new variable with the same data type; the names don't have to be the same.

So, what's the deal with declaring the bNum variable private in the above example? There's something called variable scope. There are two types of variables: local variables and global variables. Local variables can only be used within braces (scope is between {} and is thus "local") while global variables can be used everywhere within the class (scope is "global" or throughout the class). By putting the variable declaration out side of all of the methods, I made it global. If I had placed it inside a method, only that method would be able to access and use the variable. I had made the bNum variable private so that no class outside of the MathObject class would be able to access the data directly since this would leave a hole in the program's security. If you want to be able to access variables within an object, you can create what's called an accessor method which just returns the value of the variable you want the data from.

Exercise 11: Modify the MathObject and SimpleCalculator classes to include subtraction, and allow the user to choose the base number, the modifying number, and the operator (add or subtract).
spoiler:

//Driver class

import java.io.*;

public class SimpleCalculator
{
	public static void main(String[] args) throws IOException
	{
		int bNum, mNum, output;

		BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));

		System.out.print("Enter Base Number: ");
		bNum = Integer.parseInt(dataIn.readLine());
		MathObject baseNumber = new MathObject(bNum);

		System.out.print("Enter Second Number: ");
		mNum = Integer.parseInt(dataIn.readLine());

		System.out.print("Add/Subtract? (a/s): ");
		if (dataIn.readLine().equals("a")) output = baseNumber.add(mNum);
		else output = baseNumber.subtract(mNum);

		System.out.println("\nAnswer: " + output);
	}
}

//MathObject class

public class MathObject
{
	private int bNum;

	public MathObject(int num)
	{
		bNum = num;
	}

	public int add(int num)
	{
		return bNum + num;
	}

	public int subtract(int num)
	{
		return bNum - num;
	}
}


[VA2] What if I wanted to have a class that would have much of the same methods as another class, but with some additional methods? Using the "extends" keyword after declaring the class name, we can extend the public methods and variables to another class. The base class is called a "parent" or "superclass". The class that inherits from the parent class is called a "child" or "subclass".

In the following example, class B is a subclass of class A:

[image]http://i111.photobucket.com/albums/n131/Spenndragon/Java%20Tutorial/ExampleInheritancechart.png[/image]

In the above example, class B has access to the num and var variables, but not the sum variable because it was declared as private.

[VA2b] What if we're very stingy and want to name a method the same name in a subclass as a method in the superclass? Every method has a specific signature which consists of the return type, parameters, and name. So, "public int sum(int num)" is different from "public double sum(double num)" and "public int sum(int num1, int num2)". However, we can still create a method with the same signature in the subclass as in the superclass. This is called method overloading: if the method is called via the subclass, the method called would be the one in the subclass and not from the superclass. However, if the method does not exist in the subclass, it will look for it in the superclass. Also note that if a constructor is not provided in the subclass, then the program will use the constructor of its parent class. If the parent class doesn't have a constructor either, it will use the constructor from the Object class, or the class where all classes are automatically extended from.

For example, if we take the MathObject class and extend its methods to a MathObject2 class which includes addition of two numbers +1, and multiplication:

public class MathObject2 extends MathObject
{
	private int bNum;

	public MathObject2(int num)
	{
		super(num);
		bNum = num;
	}

	public int add(int num)
	{
		return bNum + num + 1;
	}

	public int multiply(int num)
	{
		return bNum * num;
	}
}


[V2c] What is that super method doing there? The super method, in this case, initializes the num variable in the parent class, MathObject, and is mandatory. The super keyword can also be used to call methods in the subclass from the superclass (ie super.subtract(num)) which can be very useful in more complicated programs.

[C2d] You can also create a static method by declaring a method to be static. This just means that instead of calling the method with an object, you call it via its class (ie MathObject.add(2)). The variables (not from parameters) also need to be declared as static.

Exercise 12: Create a class with a static add method that returns the sum of two integer numbers.
spoiler:

public class StaticAddition
{
	public static int add(int num1, int num2)
	{
		return num1 + num2;
	}
}

public class StaticAdditionDriver
{
	public static void main(String[] args)
	{
		int num1=2, num2=5;
		System.out.println(num1 + " + " + num2 + " = " + StaticAddition.add(num1,num2));
	}
}





Chapter 6: Java Basics - Part 4

Exercise Files: Download (.zip)

[VIA] ArrayLists are very useful to make lists (or a group) of objects of unknown length. For example, let's look at a shopping list. Each item on a shopping list has at least a name and price. We can create a Product class to address these two variables and create an object for each product on the list. We can add and remove items from the list at will. This is what an ArrayList enables you to do, along with automatic shifting of objects when you add and remove them from the list.

To use an ArrayList, we first need to import its Java library:
import java.util.ArrayList;

Then, we can declare it like we do for objects:
ArrayList shoppingList = new ArrayList();

If you have Java SDK 6 and up, you can also declare an ArrayList like this if you know exactly what type of objects will be in the list (only one type):
ArrayList <Object> shoppingList = new ArrayList();


Here are a few important methods of the ArrayList class:
.add(Object); //adds the object to the end of the ArrayList
.add(int index, Object); //adds the object to a specific index, shifting the previous object
.clear(); //removes all objects from the ArrayList
.get(int index); //returns the object from the specific index
.indexOf(Object); //looks for an object in an ArrayList, and returns its index
.remove(int index); //removes the object at the specific index
.remove(Object); //searches for an object in the ArrayList and removes it
.set(int index, Object); //replaces the old object in the index with a new one
.size(); //returns the size of the ArrayList

It's very important to note that in ArrayLists and Arrays (as we'll discuss next), the index starts at 0 and not 1. So, the last index of an ArrayList is actually size() - 1.

Exercise 13: Create a shopping list using an ArrayList with at least two items on it (just use their name). Use a loop to display the contents of the ArrayList once all of the items are added.
spoiler:

import java.util.ArrayList;

public class ShoppingList
{
	public static void main(String[] args)
	{
		ArrayList list = new ArrayList();

		list.add("Video Game");
		list.add("Programming Book");
		list.add("New Music CD");
		list.add("Paper");
		list.remove(0);

		for (int i=0; i<list.size(); i++)
		{
			System.out.println(list.get(i));
		}
	}
}


[VIB] Arrays are slightly different from ArrayLists. For one, there are a few more limitations: Arrays can only contain one type of Object or data type, you must know how many items you're going to list in the Array, and you'll need to worry about whether there is an object in the index or not. Still, because of its primitive behavior, Arrays may actually be easier to use than ArrayLists to some (including me). You can think of an Array like a spreadsheet.

To declare an array, you do not need to import anything:
Object[] myArray = new Object[size];

To put something in an array:
myArray[index] = Object;

To get something from an array:
Object myObject = myArray[index];

To get the size of an array:
myArray.length;


[VIB1] You can also create a multidimensional array. One pair of brackets [] is a one dimensional array (ie one column, limited number of rows), two pair of brackets [][] is a two dimensional array (ie a standard spreadsheet), etc.

Exercise 14: Same as Exercise 13, but use an Array instead of an ArrayList.
spoiler:

public class ShoppingList2
{
	public static void main(String[] args)
	{
		String[] list = new String[4]; //array has 4 indexes from 0 to 3

		list[0] = "Video Game";
		list[1] = "Programming Book";
		list[2] = "New Music CD";
		list[3] = "Paper";

		for (int i=0; i<list.length-1; i++) //removes first item in array
		{
			list[i] = list[i+1]; //shifts items over
		}

		list[3] = null; //removes data from index 3

		for (int i=0; i<list.length; i++)
		{
			System.out.println(list[i]);
		}
	}
}





Chapter 7: Searching and Sorting Arrays

Exercise Files: Download (.zip)

There are two ways you can search for items in an array: linear search and binary search.

[VIIA] Linear search is basically going through an array and looking at each value in each index of the array to find whatever you're looking for. In general, this type of sorting is very resource consuming, but it is useful when the array is not sorted.

Exercise 15: Create an Integer array with random values and write a linear search method that looks for a number that may or may not be in the array. This method should then return a boolean stating if the number has been found or not.
spoiler:

public class LinearSearch
{
	public static void main(String[] args)
	{
		int[] numArray = {5,2,6,8,4,1,0};
		System.out.println(findNum(numArray, 6));
	}

	private static boolean findNum(int[] numArray, int num)
	{
		boolean found=false;

		for (int i=0; i<numArray.length; i++)
		{
			if (numArray[i] == num)
			{
				found = true;
				i = numArray.length; //terminates loop
			}
		}

		return found;
	}
}


[VIIB] Binary search can only really be used for a sorted array. What it does is first looks at the object in the center of the array and compares it to what you're looking for. If the value of what you're looking for is greater than the center value, then it splits the second half of the array and compares again until the values match. Once there is nowhere else to look, the search ends. For example:

Given int[] numArray = {0,1,2,3,4,5,6,7,8,9,10};
Look for 7.

1st test number = 5. 5 < 7.
2nd test number = 8. 8 > 7;
3rd test number = 6. 6 < 7;
4th test number = 7. 7 = 7; //number is found

It may not seem that helpful when working with small arrays, but when you put it on the large scale (ie searching through an array with thousands of items), this can be very useful.

[VIIC] There are a few ways of sorting arrays, one of which is selection sorting. Selection sort consists of looking for values and putting them in their final order. Usually, it looks for the smallest number first and swaps it with the value in the first index. Then, it looks for the second smallest number and swaps it with the second index and so on. For example:

Given []int numArray = {5,2,6,8,4};
1st Pass: 2,5,6,8,4
2nd Pass: 2,4,6,8,5
3rd Pass: 2,4,5,8,6
4th Pass: 2,4,5,6,8 //numbers are finally sorted

[VIID] Insertion sort is slightly different from selection sort. Insertion sort compares nieghboring values and inserts the values in comparison to the others. When it is inserted, the values all move up one index. For example:

Given []int numArray = {5,2,6,8,4};
1st Pass: 2,5,6,8,4
2nd Pass: 2,5,6,8,4
3rd Pass: 2,5,6,8,4
4th Pass: 2,4,5,6,8




Chapter 8: Searching and Sorting Arrays of Objects

Exercise Files: Download (.zip)

[VIIIA] Interfaces are just collections of constants and public method headers. These can be very helpful when using polymorphism, as we'll be discussing later. You can create an interface like this:
public interface anInterface
{
	//insert constants and method headers.  Don't forget the semicolons!
}


To implement an interface (aka use it), you need to use the keyword "implements" after declaring the class. For example:
public class someClass implements anInterface


You can implement multiple interfaces at once by separating the interfaces with commas.

To use an interface, you will need to implement code for the methods that the interface provides (write code for the method headers). For example, if a class implements an interface that has the method header:
public int getNum();


you will need to write code for it, such as:
public int getNum()
{
	return num;
}


[VIIIA1] An important,standard interface when it comes to sorting arrays of objects is the Comparable interface. The comparable interface only has one method: compareTo(Object). This method should always return an integer. Usually, it should return a positive integer if the first object is greater than the second object, 0 if they are equal, or a negative number if it is less than. You decide what determines if one is greater than the other when you implement the method.

Exercise 16: Create a BaseCharacter class that implements the Comparable interface. Write a driver class that orders the characters in accending order according to strength.
spoiler:

//Exercise 16

public class BaseCharacter implements Comparable <BaseCharacter>
{
	private int strength;

	public BaseCharacter(int cStrength)
	{
		strength = cStrength;
	}

	public int getStrength()
	{
		return strength;
	}

	public int compareTo(BaseCharacter b)
	{
		if (this.getStrength() > b.getStrength()) return 1;
		else if (this.getStrength() < b.getStrength()) return -1;
		return 0;
	}
}

public class CharacterSort
{
	public static void main(String[] args)
	{
		BaseCharacter fChar = new BaseCharacter(2);
		BaseCharacter sChar = new BaseCharacter(3);

		if (fChar.compareTo(sChar) > 0) System.out.println("Greater than");
		else if (fChar.compareTo(sChar) < 0) System.out.println("Less than");
		else System.out.println("Equal to");
	}
}


[VIIIA2] In Exercise 16, we compared two objects using an accessor method. Accessor methods are just methods that other methods can call to return the values of a variable. They're pretty easy to create:
public dataType method()
{
	return variable;
}


Apply this concept to those learned in Chapter 7 and you'll know how to search and sort objects.

[VIIIB]Abstract classes are very similar to interfaces, but there are a few differences:
1) Abstract classes can contain method implementations unlike interfaces
2) Abstract classes cannot be static
3) Abstract classes are extended and not implemented

Also note that method placeholders (such as those in interfaces) must have be declared as abstract. The class that extends this abstract class must also implement every abstract method unless it too is an abstract class.

To create an abstract class:
public abstract class anAbstractClass

To create an abstract method:
abstract public dataType method();



[VIIIC] There is something called Polymorphism in Java that allows you to create objects using a superclass and/or interface. This is especially helpful when creating methods: for classes, instead of creating a method with a different signature for each possible parameter, you'll only need to code one method; For interfaces, you can call methods of that interface implemented in the class. So, you can do all of this (assume Animal is the superclass of Dog both containing the method .speak(), and anInterface is an interface and impInterface is a class that implements anInterface that contains method .die()):
Animal dog = new dog();
dog.speak(); //executes the .speak() method as defined in the dog class even though the object dog is an Animal

anInterface myEnemy = new impInterface();
myEnemy.die(); //executes the .die() method as defined in the impInterface class





Congratulations! This completes my tutorial. By now, you should have a better idea of what Java is about and are on your way to becoming a better programmer. I wish you the best of luck on your journey.

Regards,

~Slythe Penndragon




Text-Based RPG Battle Simulator

Download: BattleSimulator.zip
I created this as my final project for AP Computer Science A. It is a very basic Text-Based RPG Battle Simulator that includes a few monsters, the ability to fight, shop, and a few other miscellaneous things. Please feel free to edit or play with it at your leisure. The driver class is BattleSimulator. Have fun!




zenron the great -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 14:45:49)

sounds good to me. I know very little about Java. It would probably help me alot if I could be bothered learning it XD




Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 14:53:33)

Well, once I finish, you'll have a quick reference that you can access any time you are connected to the internet for whenever you feel like learning. ;)

All I put up so far are the basics of programming that can be applied to many other programming languages. I'll see if I can release Chapter 3 tomorrow so I can get some people started on programming. No guarantees, though.




Gers1 -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 15:01:05)

I was going to learn this, and when I seen this, I just went for it. Thanks for this man!




Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 15:13:09)

Heh, don't thank me just yet. Just wait until my other chapters come out. ;)

Programming isn't easy, but it can be fun if you keep working at it.




Gers1 -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 15:17:46)

Game programming is what I want to do when I'm an adult, so I'm starting whenever you get chapter 3 out, and as god is my witness, I will work hard at it!

P.S. For the record, I'm not religious.




LightningIsMyName -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 15:19:37)

Nice - I'm learning this on school (on computer science lesson)

I'm probably at the end of chapter 5 :D




Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 15:51:11)

Gers1: Well, I can't promise you that this tutorial will help you much, but it'll get you started thinking like a programmer. ;)

LiMN: Hehe, I just finished chapter 10 at school. When I get there, I'm going to have such a hard time explaining the concept. Recursive programming is so hard for me to understand!!! <_<

Anyway, it's a good thing you're that far along. You'll be able to tell me if I am missing anything important. :P




Mo -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 18:20:44)

Great tut for now.




Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 19:16:10)

Just added Chapter 3. That took a lot longer to write than I thought it would, but then again, it covers a lot of concepts that aspiring programmers need to understand. It's a good thing I broke it up into four parts.

Anyway, as I've noted on the top, I'll be away for a few days starting Tuesday. I'll see if I can get Chapter 4 in before I leave, but no guarantees; even doing Chapter 2 was a surprise. So, if you have any questions regarding Chapter 3, I suggest that you ask them ASAP because I won't be back until next week and you may need to rely on random other programmer for answers until then.




EragonZZZZ -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 20:44:40)

Wow, I'm fluent in Java but I'm no good at tutorial writing.

You, on the other hand...apparently are :D


Personally, however, I'd shove the basic OOP explanation in as early as humanly possible, maybe even before the syntax.
That way, you can say things like "class" and "object" without people wondering what they are.

Nice job though.

(I'd love for you to add linkedList into your ArrayList/Array section...not the Java Class necessarily, but explain the data structure, etc. It's an important concept, specially for game programming where speed is imperative.)




Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 21:06:20)

Yeah, I was tripping over myself the entire time because I didn't know where to introduce the concepts of classes, objects, and methods without sounding too repetitive. I think you're right, though, that I should include it somewhere in the beginning. I'll insert it in when I have the chance. ;)

As for the LinkedList class, I'm afraid I've never heard of it until you mentioned it. You'll have to teach me about it if you want it included. :P

Thanks for the compliment. As I've mentioned already, this is the second tutorial I've ever written. It's a bit messy because I'm trying to cater towards beginners who'd rather apply concepts than learn and understand them (it's a lot easier to explain all of the concepts before application imo), but I think it gets most of the points across to those with the ability to read the entire tutorial without skipping around and/or falling asleep. XD

BTW, this was what I wanted to add to your "How to Make a Game" tutorial a while back, though in far less detail. Have you considered finishing that tutorial?




EragonZZZZ -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 21:45:07)

Well, in a nutshell, the idea of a linked list is as follows. You already understand OOP so this shouldn't be too much of a stretch (if it is one at all)

Basically, you create a "Node" class that defines objects with two parameters (for a single-linked list, anyway):
-Data: an object with whatever data you want to include in this node
-Next: the next node in the list, should be an instance of the "Node" class you are creating

You create a series of these nodes so that each subsequent node in your list is referenced by the node preceding it.
In diagram form:

O ---> O ---> O ---> O

Each "O" is a node in your list. Some quick code:

public class Node
{
	Object data;
	Node next;

	public Node(Object dat, Node nex)
	{
		data = dat;
		next = nex;
	}

	public void setNext(Node nex)
	{
		nex = next;
	}

	public Node getNext()
	{
		return next;
	}

	public Object getData()
	{
		return data;
	}
	
}


Hopefully this basically demonstrates what a Node of a linked list is. Basically, what the linked list class would do (and the node class, if you expanded on what I whipped up here) is provide methods for linking and unlinking nodes in the list, as well as sorting, etc.

While this doesn't seem much different than an Array, it's much more useful because it has no definite size, and removing/adding objects takes less time to execute (not going into that, it's a rather long explanation).

Whew, that was fun.
And yeah, I remember that tutorial...I might revive it, I might not. Depends on how active I see that Multimedia section get. I still regard the Gallery as a new thing that most forumites have yet to discover and utilize :P







Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/2/2008 22:33:25)

I'm a little confused. What you're describing sounds more like an ArrayList of class hierarchies with each subclass inheriting methods from the parent class, though I guess there is no easy way to explain it (Wikipedia says something similar). Here's how I interpret it so far:

Let's say we have a 1x5 cell array. A singly-linked list would allow cell 2 (the node) to have its own methods which are connected to the methods of cell 1 (previous node), and so on. Linked list would allow for the removal of any node (ie cell 4) without disrupting the nodes already created (cell 5, after it is created).

I'm sure this is probably easier than it looks, but I was always a slow learner. <_<

By the way, you've got a problem in your setNext() method: you switched the parameter and object variables around. ;)




Cool Dragonz -> RE: Introduction to Java - Chapters 1 and 2 (3/3/2008 10:29:48)

Duudee! This will help many people m8! Thanks!




Mc_srewball -> RE: Introduction to Java - Chapters 1 and 2 (3/3/2008 12:05:58)

Thanks a ton dude, i completely suck at Java!

Possibly, with this i may be able to get from not suck, to below mediocre, ;)
lols. [:D]




LightningIsMyName -> RE: Introduction to Java - Chapters 1 and 2 (3/3/2008 13:59:12)

offropic: I'm at chapter 7 now

ontopic:
I know a nice program called Jcreator (free for non-commercial use) for java editing - it's a really advanced program. (you can google it Jcreator by Xinox Software)

also - you skipped in your index the do while loop - although it's not commonly used it can be very helpful since it can save lots of typing because the checking of the condition is done at the end (also gaurantees at least one run)

If you haven't learned this, PM me and I'll be glad to fill this out for you ;)




Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/3/2008 15:49:45)

EragonZZZZ: I just took a look at my textbook and found that linked lists are in the next chapter. Unfortunately, we won't be covering it in class, but I can probably learn it on my own. Thanks. ;)

LiMN: Yeah, we use JCreator at school, but I prefer using TextPad because it is more basic, encouraging new programmers to type every bit of code instead of allowing JCreator to autocreate it. It's just my preference: whoever follows this tutorial could use whatever IDE they want.

Also, while I've never used the Do While loop, I just took a quick look and found it to be an easy concept to grasp. Thanks for the tip; I'll add it in. :)




EragonZZZZ -> RE: Introduction to Java - Chapters 1 and 2 (3/3/2008 16:23:55)

Yeah, from your initial response it looks like you grasp it pretty well, including why it won't disturb anything if you remove an object.
Well played.




Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/3/2008 19:53:30)

Thanks. I still am far from fully grasping it though. <_<

Recursion is also still giving me issues. I find it usually more inefficient than iterative methods, but according to my teacher, there are cases where recursive methods are better. For the simple programs I will be demonstrating, though, they will be inefficient in comparison.

As for describing the relationships between objects and classes, I think I'll leave it where it is now. There's no point in knowing what it is until the reader has a basic concept of Java.

I've also updated the Table of Contents to include the LinkedList and Do-While Loop. If there are any more suggestions, feel free to voice them. To let everyone know, I will be formatting the tutorial a little better after I finish writing the content; while I do recognize it's currently hard to follow, I think it's more important to get the content out first.

Anyway, again, I will be away from tomorrow to Sunday so chapter 4 won't be released until next week. If you have any questions, I'm sure there are a few Java programmers around here that are willing to help you out in my absence.




Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/10/2008 20:21:53)

Wow. I'm surprised that no one had any questions. I meant for this tutorial to be thorough, but I didn't think it would leave anyone without a few questions to ask. :o

Hehe, I'm also quite pleased that this thread got FAQed, even if incomplete. :D

Anyway, like promised, I've released chapter 4. It contains a basic introduction to errors because error handling is self explanatory and different in every scenario in my opinion (if it doesn't work, fix it), and information on three types of loops. Chapter 5 should come within a week.

Also, if you were curious, I was in Disney World for the senior trip. It was very tiring: the first day, our plane was delayed and we arrived at 12am. Our room key was swapped with someone else so it took a while to get that sorted out. We didn't sleep until 3am and we had to wake up by 6am to get ready for the day. The first day, one of my room mates lost his park pass and so we went through a three hour ordeal to get a new one because the guest relations weren't very helpful (one of them literally said "I can't confirm your pass is lost until you show it to me.") The second day was pretty fun, even if exhausting; I got souveniers for my siblings at Epcot. The third day just poured heavily so we couldn't do much. The fourth day was pretty short: it was mandatory that we go to the first place we went to so it was pretty boring, especially since the only ride that we didn't go on was rendered unavailable because a cheerleading competition was taking the space, and the winds prevented one of the stunt shows from being completed. After a 6+ hour delay at the airport, including daylight savings, I got home at around 5:30am yesterday morning. Even after sleeping over 20+ hours since yesterday, I'm still dead tired, so much that it is surprising I even got a chapter in instead of sleeping.




Krieg -> RE: Introduction to Java - Chapters 1 and 2 (3/18/2008 22:08:01)

Sorry I'm late. I've been very busy lately. <_<

Anyway, Chapter 5 is out. I may have taken more short cuts than I should have, but it still is pretty lengthy. It contains a concept that can be hard to understand until you practice it a lot.

Spring break is next week for me, and I'm staying home. So, if you have any questions, feel free to ask. ^_^




Mo -> RE: Introduction to Java - Chapters 1 and 2 (3/20/2008 15:55:56)

As I've said before, this is a great tut. I could learn java from my mom but I think this would help me so that I would understand the concepts and then my mom could go completely in depth.




Krieg -> RE: Introduction to Java - Chapter 6 Released! (3/27/2008 11:43:56)

I usually scold people for not replying immediately to posts in their own thread, but there isn't really much to discuss. I wish you the best, Mo. :)

Anyway, I've released Chapter 6. I've taken out linked lists for now, but I may add it back in later. Good luck, everyone.




Krieg -> RE: Introduction to Java - Chapter 6 Released! (4/13/2008 14:41:56)

Sorry for the extremely late update. I've been really busy these past few weeks and did not have the time to work on this.

Anyway, Chapter 7 is released providing an introduction to searching and sorting arrays of values. Chapter 8, which you can expect to come very soon, will discuss searching and sorting objects.




Page: [1] 2   next >   >>

Valid CSS!




Forum Software © ASPPlayground.NET Advanced Edition
0.203125