Вы находитесь на странице: 1из 9

Java Tutorial for Students Entering CS1302 Who Learned C++ in CS1301 By Pat Roth (Copyrighted)

Introduction > There are a lot of similarities between C++ and Java but the full object-oriented approach of Java and its huge number of provided classes make it significantly different from C++, especially for the beginning student. This tutorial will try to review the highlights of CS1301 as taught in Java. Background > a C++ program is translated into the machine language version of the computer environment it is on (Windows PC, UNIX workstation, Macintosh, etc.) and then the object code is executed in that computer environment. Java programs are translated into a standard machine language, called Bytecode, and then a JVM (Java Virtual Machine) reads and translates the Bytecode into the machine language of the running computer. This final step is interpretation, rather than compilation. None of this changes the way you code the program but it is an important difference between the way Java is compiled when compared with other languages. Knowing this 2 step approach will help you understand your compiler/translator messages better. Object-Oriented Approach - > every Java program consists of at least one class with possible data types and associated methods. Most operations will be methods called by objects, as in mydate.print(). There is no encouragement to write stand alone functions, such as print(mydate). Java has a large library of classes we will only begin to use some of these but you should try to become familiar with as many as you can. Check the appendix of any text. Naming Program Elements - > same rules as in C++, except you may use a letter, underscore or dollar sign to start a name and the rest of the name can contain numbers, letters, underscore or dollar sign. You really should not use the dollar sign since it has special meaning in some Java systems and you should not begin a name with an underscore, since it also has a special meaning in some systems. Introduction to Java Data Types - > The primitive or built-in data types in Java are byte (new in Java), short, int, long, float, double, char and boolean (instead of bool) which work the same way as they do in C++. String (with a capital S) is a reference data type in Java. (You do not have to include a library to use String.) In Java, the character set for the char data type is called Unicode and includes characters for writing in many languages; it includes many more characters than the ASCII character set in C++. If you put final before a declaration, it is a constant. See sample program on next page. Screen Output -> Java provides an object that represents an output device, which is, by default, the screen. The name of the object is System.out and it has two methods, print and println (skips to a new line after printing). No special libraries need to be included to use this object. All output to the screen is considered String data type so the concatenation symbol (+) is used to join items to be printed. For example: int x = 10; System.out.println(The value of X is + x); System.out.print(The value of ); // same output System.out.print(X is ); // with this System.out.println(x); // arrangement

First Sample Program -> /* Notice that comments are the same in C++ and Java */ public class SampleScreenOutput { // no class variables or instance variables here - we will discuss later // every program must have at least one class with one main method // the format for the main heading line remains the same in every program public static void main(String[] args) { final String first = Hello; // constant variable/field final String second = World!; // constant variable/field int x = 10; // local variable/field int y = 20; // local variable/field System.out.println(first + + second); // prints Hello World! System.out.println(The sum is + (x+y)); // prints The sum is 30 // does the addition first and then joins the String of 30 to The sum is System.out.println(The sum is + x + y); // prints The sum is 1020 // joins the String of 10 to The sum is and then joins 20 to it } } NOTE1: If one of the expressions either to the right or left of a + operator is a String, then the other side is automatically forced to become a String as well and both are concatenated. NOTE2: Whenever you type in your source code, save it as programname.java More Detail on Java Data Types -> Java data types are organized into primitive types and reference types. Primitive types take a fixed amount of space in memory. Java chooses an address in computer memory for each, keeps track of the location with the variable name given, and stores values in those locations. Primitive data types include all integral and floating point data types, also char and boolean. For reference data types, Java stores the address of the data stored in memory in the variable named. See example below using String data. Reference variables have the advantage of saving memory if two locations are set equal to one another they both store the same address. The data, which can be lengthy, is not duplicated. String message1, message2; message1 = Hello; // message1 holds the address of where Hello is stored // in memory message2 = message1; // message2 now holds the same address which is in //message1 Hello / message1 \ message2

Arithmetic Operators - > These (+, -,*,/,%) operations work the same in Java as they do in C++. The only difference is that floating-point divide by 0 gives the infinity symbol as the answer and modulus 0 gives NaN on the output. Combination operators (+=, - =,*=,/=,%=) and increment (++) and decrement (--) operators are also available and work the same as in C++. Type conversion and explicit casting also follow the rules in C++.

Built-in Mathematical Methods - > These methods are provided automatically no special library need be included but they are methods of the Math class so each method is preceded by Math., as in: x = Math.abs(someint); // there are abs methods for float, double, etc. y = Math.sin(z); // all trig. functions available a = Math.pow(3.0,2); // returns 3, squared, or 9 Some of the Available String Methods - > Length String myname; String fullname; myname = "Pat"; int size; size = myname.len(); fullname = myname + " Roth"; size = fullname.len(); Index of String state; state = "Mississippi"; int location; location = state.indexOf("iss"); // assigns 1 to location, first position is 0 // if not found, location = -1 // can also search for single char or blank // assigns 3 to size // assigns 8 to size

Substring String first; String second; first = "CS 1301"; second = first.substring(0,5); System.out.println(second + '2');

// places "CS 13" in second // prints -> CS 1302

Conditions Using Logical and Relational Operators - > same as C++. If, Nested If and Switch Statements - > same as C++. Short-circuiting -> same as C++. While, For and Do- While Statements -> same as C++. More Information on Reference Data Types in Java -> As I pointed out before, Java data types are organized into primitive types (byte, char, short, int, long, float, double, and boolean) and reference types (array, interface (covered in CS1302), and class). All reference data must be declared AND instantiated (created in memory). When you set up an integer location, you just declare it, as in: int x; However, when you set up an object of a class that you have defined (or one that is provided by the Java language), or if you set up an array or interface, you are creating a reference data type. You must declare the variable name (where the address of the data will be stored remember the String example above?) and then you must call a method of that class which actually sets up the memory for that

object - instantiation. Lets look at an example. Suppose you want to use random numbers. Java provides a Random class, which will generate random numbers with the different methods provided. To set up a Random object, you must declare a Random variable and then instantiate it. import java.util.Random; // See NOTE3 below public class SampleRandomNumbers { public static void main (String[] args) { Random mynumber; // declare the variable mynumber = new Random(); // instantiate it using new and classname int first, second; first = mynumber.nextInt(); // generates a random number and stores // it in first using the method nextInt second = mynumber.nextInt(); // generates another random number System.out.println(Two random #s are + first + + second); } } NOTE3: Anytime you use a class provided by Java (except String and Math), you must import (like the #include in C++) the package of classes that the particular class is in. The Random class is part of the utility package. File Input and Output -> To set up a file in a Java program, you will import the library package called java.io.*. We will use four classes from that package: FileReader, FileWriter, BufferedReader, PrintWriter 1.) Using the first two classes a. Declare the file identifiers FileWriter outFile; // same way you declare any variable name FileReader inFile; b. Instantiate a file object for each file variable (and give the external name of the file) outFile = new FileWriter(a:outfile.txt);//associates outFile with outfile.txt on disk inFile = new FileReader(a:infile.txt);// associates inFile with indata.txt on disk These two statements are like opening the files and must be done before any other file methods are called. NOTE: Our biggest problem with file data (in all languages) always seems to be the open statement. Be sure the path is correct for the external file name (the name in quotes). I have found that the safest approach, to start, is to type the data file in NotePad (not Word) and save it on a diskette. If you saved it as a:mydata, NotePad will add a .txt to the data name and that must be included in the path name, as I have done above. If you save it in your student area, your must use the complete path name and each backslash must be preceded by an additional backslash. Good luck use the lab assistants! c. Use file methods to read or write data to or from the file. To write to an output file use: outFile.write(..); All string data is written, a number is converted to string, \n is newline. To read from an input file, use: data = inFile.read(); // data would be defined as int A single char is read and converted to integer and stored in data. To use it as char youd have to cast it. char letter = (char)data; d. Close the files

inFile.close(); outFile.close(); 2.) Extending File I/O with PrintWriter and BufferedReader processing a whole line at a time: a. define the files with PrintWriter and BufferedReader PrintWriter payFileOut; BufferedReader dataFileIn; b. instantiate: payFileOut = new PrintWriter(outFile); //outFile must already be instantiated as a FileWriter file OR payFileOut = new PrintWriter(new FileWriter(outfile.txt);//in 1 step dataFileIn = new BufferedReader(inFile); //inFile must already be instantiated as a FileReader file OR dataFileIn = new BufferedReader(new FileReader(infile.dat);//in 1 st c. PrintWriter has print and println methods like System.out PayFileOut.print(Rate is + rate + \n); //both are the same PayFileOut.println(Rate is + rate); NOTE: System.out displays output only on the screen, is automatically instantiated and doesnt have to be closed. d. BufferedReader has a readLine method that returns an object of class String contains a line of information from file (discards EOL marker). Therefore you copy a file, a line at a time, with the following code: String dataLine; while (dataLine = dataFileIn.readLine() != null) // removes EOL { dataLine = dataLine + ****; //could add data to each line // before writing it PayFileOut.println(dataLine); //adds EOL } e. read and readline sense the end of file: read returns 1 //int readLine returns null //special value other than empty string f. to read numbers from an input file, use: (data should be 1 number/line) dblnumber = Double.valueOf(dataFileIn.readLine()).doubleValue(); intnumber = Integer.valueOf(dataFileIn.readLine()).intValue(); Since all numbers are read as a String, that String of numbers is converted to a class object of Double or Integer first in Java and then that data type is converted to the built-in value of double or integer.

g. Close the files the same way as FileWriter and FileReader above. NOTE: Exceptions with Input and Output when a method signals that an unusual error has occurred, it throws an exception. If the exception is not caught by the program and handled (try and catch code), JVM halts the program. To inform Java that you realize an exception may occur and to have it pass the exception to its caller for now, add throws IOException to any method using FileReader, BufferedReader and FileWriter, as in: public static void main(String[] args) throws IOException Sample Program with file data: (one number/line on input file)

/* This program sums a file of integer values and prints the sum on an output file */ import java.io.*; public class SampleFileIO { public static void main(String[] args) throws IOException { int sum = 0, number; String dataLine; BufferedReader myFileIn; // declare filename PrintWriter myFileOut; // declare filename myFileIn = new BufferedReader(new FileReader(infile.txt)); // instantiate file myFileOut = new PrintWriter(new FileWriter(outfile.txt)); // instantiate file while (dataLine = myFileIn.readLine() != null) // read 1 String of numbers { number = Integer.valueOf(dataLine).intValue();// change String to integer sum += number; // sum number } myFileOut.println(Sum of numbers is + sum); myFileIn.close(); myFileOut.close(); } } Classes and Methods - > Except for the occasional need for isolated, primitive data fields, all data should be arranged into objects in Java. As a programmer, you need to analyze each problem with an emphasis on what objects (car, date, student, paycheck, etc.) are needed and what methods (sum(), test_equal(), input(), output(), etc.) are needed to process those objects. For example, suppose you wanted to design a class, called Counter, whose objects would be able to be set to a value, incremented by one, decremented by one (unless already zero), compared to other Counter objects, and outputted. You would design the class, called Counter, with its basic data field of an integer and all of its methods. You would then save it as a package. That package can then be imported into any Java program that needs a Counter object. See the code below uses one package for one class definition: package counter; // See NOTE4 below on package public class Counter // See NOTE5 below on data types { static int ZERO = 0; // class variable available to all objects private int count; // instance variable each object will // have its own count data field public void set (int n) // method to set count to n { count = n; } public void increment() // method to add 1 to count { count = count + 1; } public void decrement() // method to subtract 1 from count, { if (count > ZERO) // unless count is already zero count = count 1; else System.out.println (Cannot take count below zero!); } public int getCount() // method to obtain count data field { return count; }

public void output() // method to print count field { System.out.println (The current value of count is + count); } public boolean equalTo(Counter other) // method to compare this { return ( count == other.getCount()); // count with another count } // end of Counter class

import counter.*; public class sampledriver // Testing Counter class { public static void main(String[] args) { int i; Counter mycounter, yourcounter; // create mycounter and yourcounter mycounter = new Counter(); // instantiate mycounter yourcounter = new Counter(); // instantiate yourcounter mycounter.set(10); yourcounter.set(0); for (i=1; i<=10; i++) { mycounter.decrement(); // should decrement and print 10 times mycounter.output(); } if (mycounter.equal.To(yourcounter)) System.out.println (Counters equal); // should print equal else System.out.println (Counters not equal); mycounter.increment(); // change mycounter if (mycounter.equal.To(yourcounter)) System.out.println (Counters equal); else System.out.println (Counters not equal);// should print not equal } // end of main method } // end of class sampledriver NOTE4: Package is a way of grouping and storing related class definitions. Once compiled and debugged, classes can be stored separately and imported into those programs that need to use them. Classes in a package can access each others nonprivate members. The format of the import statement is: import package_name.classname; // specifies particular class of a package import package_name.*; // any class in package can be used NOTE5: There are three types of variables in Java local, instance, and class. A local variable is any variable defined inside a method, such as i, mycounter, and yourcounter in the main method above. These variables are set up when the method is called and go out of existence when the method finishes execution. An instance variable is one that is set up with a class definition, such as count in the Counter class above. Every object of type Counter will have a integer count set up for it; so mycounter and yourcounter each have a count data field. They are created by JVM from a free pool or heap memory when the new operator is encountered. Instance variables exist as long as the object exists. Class variables are variables that are common to all objects of a class. They must be set up after the open brace of a class definition and usually are labeled static. They are oftentimes class constants, such as ZERO in Counter class above.

One Dimensional Arrays -> Single arrays in Java are similar to single arrays in C++. However, there are a few significant differences. 1. When you declare an array name the [] go before the name, as in: int [] myarray; The array name, myarray, is a reference variable so it will hold the address of the array. 2. You must instantiate an array as well as define the array name. The second line of code becomes: myarray = new int[size]; An array of the size and type given will be set up in memory and the address of the array will be stored in myarray. 3. You can declare an array, instantiate it, and initialize it all in one statement: int [] myarray = {10, 20, 30, 40}; A four position integer array with the values shown will be set up in memory and its address placed in myarray. In this format new is done automatically. 4. Java provides its own out-of-bounds error (C++ did not). If you address an element of an array with an index less than 0 or greater than the number of elements 1, an ArrayIndexOutOfBoundsException is thrown. You should write your code to prevent this rather than catching the error. 5. Every array that is set up in Java has its own length field, called length, which contains the number of elements in the array. It can be used in the for loop to avoid out of bounds errors. for (int i = 0; i < arrayname.length; ++i) 6. Aggregate array operations process the whole array, not just one element, but you must be careful since arrays, like classes, are reference types. If we set array1 equal to array2 with the following assignment statement: array1 = array2; the two address locations are set equal to one another (shallow copy). Consequently, the following if statement would return true: if ( array1 == array2) . . . . no matter what data is in the two arrays! However, if array1 and array2 are defined as, int [] array1 = { 1, 2, 3}; int [] array2 = { 1, 2, 3}; the following if statement would return false: if ( array1 == array2) . . . . even though the data in the two arrays is equal! In both examples, you are only storing or comparing the addresses of the arrays. 7. If you want to store or compare arrays, element for element, you must write the code to do that usually a for loop. 8. Semantic content in the index totals for each day of the week for a company, assuming there are 7 values in the input file, inFile. int [] totals = new int [7]; for (int i = 0; i < 7; ++i) totals[i] = Double.valueOf(inFile.readLine()).doubleValue; This assumes that totals[0] is Sunday sales, totals[1] is Monday sales, etc. The index has some application value or is semantic. 9. Array of class objects not all arrays have primitive components you may have an array of Dates, array of Distances, array of Strings, etc. If we instantiate an array of class objects, which themselves have not been newed yet, the array is an array of null values, the default of an address variable. Consider this array of 100 Dates: Date [] arrayofDates = new Date [100];

ArrayofDates ---> |_null_|

|_null_| |_null_| . . . 10. To test for end-of-file when reading data into an array: read one String item as a priming read and start an index at 0, test to see if it is not null (meaning nothing was read) in a while loop, process the good String by placing it in the next array position, increment the index and read another String element. This is a classic end of file approach. Keep a count (index will suffice) in the read-in/while loop, so that count (not length) can be used to further process the partial array of its valid contents. This end-of-file and count approach can be used to read a variable number of Strings or any other types of data into an array. Set up the array to a maximum size. 11. An array name has a base address in it. The first data item, if primitive, is stored at that base address and each successive item is stored at continuous memory positions beyond the base address. If the components of the array are composite items, the address of/reference to the first item is stored at the base address, the addresses of the rest of the composite elements are stored in continuous positions beyond the base address. 12. Consider how you would refer to the data members of an array of Dates, called BigEvents. Since each element of the array is a Date object with a String month, int day, and int year, a reference to the first Date is: BigEvents[0] month of first Date: BigEvents[0].month day of first Date: BigEvents[0].day and so on. 13. You can pass an array or an element/component of an array to a function. Just remember that all functions pass arguments to the corresponding parameter by value. If you are passing the component of an array and it is a primitive type, the function/method cannot change the value of the argument in the calling module. If you are passing the component of an array and it is a composite type, the function/method could possibly change the value of the argument in the calling module. This is not good programming technique and could cause serious errors!

// null will be changed to the address of a Date object // when the Date objects are instantiated

Keyboard Input - > Keyboard input is not easy to code in Java there is no simple cin statement. Many authors provide a keyboard class in their texts so the beginning Java programmer can key in sample data. Read pages 98-103 and 287-290 in the CS1302 text, Java Software Solutions by Lewis and Loftus, to learn how to use this class. Additional Reading -> If you find this tutorial hard to follow, read the first six chapters of the CS1302 text, Java Software Solutions by Lewis and Loftus. Those chapters cover the bulk of what is taught in CS1301.

Вам также может понравиться