Introduction to Java 2 - Printable Version +- Support Forums (https://www.supportforums.net) +-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87) +--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18) +---- Forum: Java Programming (https://www.supportforums.net/forumdisplay.php?fid=22) +---- Thread: Introduction to Java 2 (/showthread.php?tid=77) Pages:
1
2
|
Introduction to Java 2 - Psycho - 10-04-2009 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) 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) 2.2 Nested While/For Loops An example of a nested For loop inside a While loop: Code: boolean input = true; 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 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; 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"; 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 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]; 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++; or Code: for (int i = 0; i < 100; i++) I think 100 lines vs 2 lines speaks for itself here. 4. Methods Now, on to methods. Isn't this fun? 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; 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) 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
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; 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. 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. 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:
The structore of that loop will successfully read every line in the file. Let's implement this! Code: import java.util.Scanner; 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; It is now safe to run your program. Your output should be something like: Code: Enter a file name: file.txt 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? 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; 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.
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; 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. RE: Introduction to Java 2 - Etheryte - 10-05-2009 (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. RE: Introduction to Java 2 - Skajper - 10-08-2009 Another great tutorial well done ;P RE: Introduction to Java 2 - ReVamped - 10-09-2009 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 RE: Introduction to Java 2 - JavaGuy - 10-20-2009 Great tutorial but quick question where did you learn Java? RE: Introduction to Java 2 - Psycho - 10-21-2009 (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. ;) RE: Introduction to Java 2 - JavaGuy - 10-23-2009 (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 I RE: Introduction to Java 2 - Akshay* - 10-24-2009 That was a nice tutorial for the newbies.Thanks for sharing this. RE: Introduction to Java 2 - nevets04 - 11-29-2009 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 RE: Introduction to Java 2 - nevets04 - 12-01-2009 Just finished 1 and 2, they are both great. Keep them coming if you can. |