Java Notes
|
Warning: These notes have been collected from several different sources - each uses different terminology... they may even be contradictory... Java is case sensitive so upper and lower case characters are important. Java has many data types built into it, and you (as a programmer) can create as many more as you want. However, all data in Java falls into one of two categories: primitive data and objects. The only type of data a programmer can define is an object data type (a class). Every object in Java is an instance of a class. The class definition has to exist first before an object can be constructed. Any data type you invent will be a type of object. There are only the eight primitive data types (see chart below). A (crude) analogy is that a primitive data value is like a nut or a bolt, but an object is like a whole machine. There are types of data that are so fundamental that ways to represent them are built into Java. These are the primitive data types. In the phrase primitive data type the word primitive means "a fundamental piece that is used to create other, larger parts." To solve a large problem, you look for the primitive operations that are needed, then use them to build the solution. The eight primitive data types are:
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
For each primitive data type, there is a corresponding wrapper class. A wrapper class can be used to convert a primitive data value into an object, and some type of objects into primitive data. To convert to a corresponding wrapper class, merely capitalize the name of the primitive data type such as "byte" to "Byte". Variable names are called Identifiers (programmer-picked variable name.) Here are the rules for choosing an identifier: Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character '_', and character '$'. A name can not contain the space character. Do not start with a digit. A name can be any length. Upper and lower case count as different characters. So SUM and Sum are different names. A name can not be a reserved word. (has a predefined meaning in Java) A name must not already be in use in this part of the program.Constants follow the same rules as the names for variables. The reserved word final tells the compiler that the value will not change, it is a constant. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of the language.) An operator is a symbol +, -, *, /, % that calls for an arithmetic operation. An operand is a value that is acted upon by an operator. An expression is a combination of literals, operators, variables, and parentheses used to calculate a value. An integer operation is always done with 32 bits or more. If one or both operand is 64 bits (data type long) then the operation is done with 64 bits. Otherwise the operation is done with 32 bits, even if both operands are smaller. Arithmetic expressions are not the only kind of expression: "This is" + " a string" + " expression" An assignment statement is one way to change the value in a variable. variableName = expression; (The equal sign "=" means "assignment.") variableName is the name of a variable that has been declared somewhere in the program. expression is a collection of characters that calls for a value. An assignment statement asks for the computer to perform two steps, in order: 1. Evaluate the expression on the right of the equal sign, (that is: calculate a value.) 2. Store the value in whatever variable is on the left of the equal sign. Input and output are commonly referred to by an abbreviation: IO Inputting data is usually called reading data. Outputting data is usually called writing data (or printing data if the output stream is connected to a monitor or a printer.) There are three IO streams usually connected to your program: System.in --- the input stream. System.out --- the output stream for normal results. System.err --- the output stream for error messages.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Methods... variableName.readLine( ) Integer.parseInt( variableName ) the method parseInt( ) of the Integer wrapper class. Double.parseDouble( variableName ) will not run under versions of Java earlier than 1.2 Boolean Expressions (often make comparisons between numbers)
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
The condition is a Boolean expression; i.e., something that evaluates to true or false. The boolean expression is always surrounded by parentheses. The condition can be very complicated, with relational operators and logical operators. The statement is a single statement. However it can be (and usually is) a block statement containing several other statements. The statement is sometimes called the loop body. Three parts of a loop must be coordinated in order for the loop to work properly: 1. The initial values must be set up correctly. for example: int count = 1; 2. The condition in the while loop must be correct. for example: while ( count <= 3 ) 3. The change in variable(s) must be set up correctly. for example: count = count + 1; In a counting loop the variable count is initialized, tested, and changed. A counting loop uses a loop control variable to count upwards or downwards (usually by an integer increment.) Counting loops are by far the most common type of loop. A counting loop increments a counter (loop control variable) after each input line is read. To control a counting loop, a special value may be assigned (a "sentinel") that is used to determine whether to execute or exit a loop. In a sentinel controlled loop the user may enter "some predetermined value" to tell the program that the iterations (loops) are complete. The special sentinel value must not be a value that could ever occur in the data. A sentinel controlled loop reads in lines until reaching a line that contains a special value (the "sentinel"). Another type of loop is the result-controlled loop also known as free loop or general loop. It keeps looping until the computation has reached a particular goal. It is like the instruction in a cookie recipe that says "keep stirring until the ingredients are thoroughly blended." You know when to quit only when the desired result has been achieved. A result-controlled loop reads in lines until a desired result has been achieved. Rule for Matching if and else: Start with the first "if" and work downward. Each "else" matches the closest preceding unmatched "if." An "if" matches only one "else" and an "else" matches only one "if." An "else" inside a set of braces cannot match an "if" outside of that pair. Within each pair of matching braces: start with the first "if" and work downward. Each "else" matches the closest preceding unmatched "if." A file is a semi-permanent, named collection of information. semi-permanent---files are usually stored on magnetic disk, where they will remain for years even when the power is off. Of course, a file can be deleted (sometimes by accident) so they are semi-permanent, not permanent. named---a file has a name that is used to find it when it is needed. You probably know that MS Windows file names
look like: mydata.txt, program1.java, doom.exe, and so on... collection of information---the purpose of a file is to contain a collection of related information, such as a word processing document, a program source file, a spread sheet, a data base, and so on.Files are the only way for an application program (such as the programs you usually use) to store information semi-permamently. Files are used when information is stored on the hard disk, a floppy disk, and all other physical forms of storage. All information in a file (no matter what file) is kept in binary form. a file can contain any type of information that can be represented with symbols, such as: numbers, characters, text files, images, program source files, machine language and many other types. The system software of a computer system uses a few other semi-permanent forms of storage, such as the ROM (read-only memory) of the computer and the boot sector of a hard disk. However from an application program's point of view the only form of semi-permanent storage is file storage. As far as the hardware of a computer system is concerned, all files look alike. Each file is regarded by hardware as a collection of bytes. The hardware makes no distinction between (say) image files and text files. Its all bytes to the hardware. What those bytes are being used for is up to the software. What makes an "object" ? An object is made of tangible material (a pen is made of plastic, metal, ink) An object may also be an intangible thing, a concept (such as a bank account.) An object holds together as a single whole (the whole pen, not a fog.) An object has properties (the color of the pen, where it is, how thick it writes...) An object can do things and can have things done to it. An object is usually a "noun", a thing, real or imaginary, simple or complex... (bicycle, receipt, complex number, ball, satellite dish, person, employee) An object has identity (it acts as a single whole, it has it's own variables) An object has state (it has various properties, which might change... the values held in it's variables) An object has behavior (it can do things and can have things done to it, often using those variables) A good object has both: attributes/properties/descriptors/variables and actions(a verb)/operations/responsibilities/behaviors/methods A challenge in object-oriented development is finding the right objects (nouns) to model the system being represented. Identifying objects in a problem domain is an art, not a science. Some nouns are merely variations of other nouns, they might express actions or events, or are attributes like color. Test objects to determine their validity: 1. Are they relevant to the problem domain, the main purpose of the system/program? 2. Do they have both: attributes/variables and actions/behaviors/methods? 3. Do they have independent existence? Do they make sense by themselves? Do they need to exist independently, rather than being an attribute or action of another object? Can they exist without any other objects? A computer/software "object" consists of both variables (state information) and methods (recipes for behavior.) Both of these are called "members" of the object. This object has some variables (color, size, and location) that describe it and has some methods (move, resize, set and get) that control its behavior. First the object must be created. Creating an object is called instantiation. Then object "does things" by running it's methods. All method names will have "( )" at their end. When a Java application is being executed (as the program is running), the objects are instantiated (are created) and their methods are invoked (are run.) To create an object, there needs to be a description/plan of the possible object (or objects.) A class is a description of a kind of object. A programmer may define a class using Java, or may use predefined classes that come in class libraries. The class does not by itself create any objects. A class is a description of potential objects and can be used many times to make many objects of the same type. The objects do not have to have the same data inside of them, just the same over all plan. Every object in Java is an instance of a class. The class definition has to exist first before an object can be created/constructed. A class is like a cookie cutter that can be used many times to make many cookies. There is only one cookie cutter, but can be used to make many cookies. Cookies are objects and each one has its own individuality because each one is made out of a different section of dough. Different cookies may have different characteristics, even though they follow the same basic pattern. For example, different cookies can have different candy sprinkles or frosting, or can be baked at different times (values/variables). Cookie cutter (class), Cookie (object), Sprinkles (values). Cookies can be created. Cookies can be destroyed. But destroying cookies does not affect the cookie cutter. It can be used again if there is enough cookie dough left. A big cookie jar might require many cookies made with many different cookie patterns (stars, hearts, squares, gingerbread androids...) A big cookie (such as a gingerbread house) might be built out of many smaller cookies of several different sizes. Classes are mostly used to create objects, just as a cookie cutter is mostly used to create cookies. But a class has an existence, just as a cookie cutter has an existence. A class and its objects are different types of things, just as a cookie cutter and its cookies are different types of things. A cookie cutter has characteristics that are not shared with cookies. For example, a cookie cutter is made of steel and has sharp edges. After a cookie cutter has been used for a while, there will be many cookies (soft, rounded, doughy things) but still only one thing made of steel with sharp edges. In the Java language, characteristics of a class definition (but not of its objects) are called static. There is only one class definition for a given class, so when a program is running, if something is static then there is only one of it. Important: A program can execute a static method without first creating an object! All other methods (not static) must be part of an object, so an object must exist before they can be executed. The first method to run is the method named main( ). There should be only one method named main( ) in an application. In a small application, main( ) might do by itself all the computation that needs to be done. In a larger application, main( ) will create objects and use their methods.
class CookieCutter
{
public static void main ( String[] args )
{
String cookie1; // cookie1 is a reference
// that refers to an object,
// but the object does not exist yet.
String cookie2; // cookie2 is a reference
// that refers to an object,
// but the object does not exist yet.
int len1, len2; // len is a primitive variable of type int
cookie1 = new String("with red sprinkles");
// create a cookie object of type String
cookie2 = new String("with pink sprinkles");
// create a cookie object of type String
len1 = cookie1.length( ); // invoke the object's method length( )
System.out.println("The string for cookie1 is "
+ len1 + " characters long");
len2 = cookie2.length( ); // invoke the object's method length( )
System.out.println("The string for cookie2 is "
+ len2 + " characters long");
}
}
When this program is executed/run the output would be:The string for cookie1 is 18 characters long The string for cookie2 is 19 characters long The file defines a class called CookieCutter. The class has a static method called main( ). Since main( ) is a static method, it belongs with the class, not with any object made from the class. Since main( ) is a static method, there will be only one main( ) method. The main( ) method starts running, creates an object, invokes its length( ) method, and gets stuff done. An object is a section of memory (with variables and methods), and a class is a description of a possible object. When an object is created (instatiated) the description is followed. One way in which objects are created is when the new operator is used with a constructor. A constructor has the same name as the class. The new operator says to create a new object. It is followed by the name of a constructor. The constructor String( ) is part of the definition for the class String. Constructors often are used with values (called parameters) that are to be stored in the data part of the object that is created. There are usually several different constructors in a class, each with different parameters. Sometimes one is more convenient to use than another, depending on how the new object's data is to be initialized. However, all the constructors of a class follow the same plan in creating an object. The two types of things inside of an object---variables and methods---are sometimes called members of that object. The members of an object are accessed using dot notation. The example program creates a String object, referred to by the variable cookie1. The length( ) method is a member of cookie1. To refer to this method of the object cookie1 put the two together with a dot: len = cookie1.length( ); 1.The expression on the right of the "=" is evaluated. 2.The resulting value is stored in the variable on the left of the "=" sign. The right-hand side of this particular assignment statement executes the method length( ) which is member of cookie1. Executing this member method will return the number of characters in the object. This dot notation is also known as a method call. if (stringA.equals( stringB )) The String referred to by stringA has an equals( ) method. That method is called with a parameter, a reference to stringB. The method checks if both strings contain identical characters, and if so, evaluates to true ("returns true"). Careful: People often say "String" when they really mean "reference to a String". This is fine, but remember that a variable like stringA is not the object, but only a reference to an object. Therefore, the equals method of the String referenced by stringA is called with a reference to stringB. The variables and methods of a class will be documented somewhere. With a Java development environment such as such as Borland JBuilder or Symantec Café the documentation is on line (push F1). If you downloaded the JDK from Sun Microsystems, look on your hard disk, in someplace like C:\jdk1.3\docs\index.html. Here is a short version of the documentation for the class String. There are more methods than in this list. // Constructors public String( ); public String(String value); // Methods public char charAt(int index); public String concat(String str); // concatenation of strings ie: String name = first.concat ( last ); // the first two strings (referenced by first and last) // supply the data that concat( ) uses to construct // a third string (referenced by name.) public boolean endsWith(String suffix); public boolean equals(Object anObject); public boolean equalsIgnoreCase(String anotherString); public int indexOf(int ch); public int indexOf(String str); public int length( ); public boolean startsWith(String prefix); // tests if one String is the prefix of another, // this is frequently needed in programs public String substring(int beginIndex, int endIndex); public String toLowerCase( ); // constructs a new String object containing all lower case letters. public String toUpperCase( ); public String trim( ); String concatenation, done by concat( ) or by +, always constructs a new object based on data in other objects. Those objects are not altered at all. When an operator such as + changes meaning depending on its arguments, it is said to be overloaded. Overloading is permitted because several methods (with the same name, in the same class) have different argument lists, and therefore a different signature or memory location/reference to a String. It is safer to construct a new object than to modify an old one. (Because the old object may be referred to in many places, some of which are not expecting a change.) Many Java classes, objects cannot be altered after construction. The class String is one of those. String objects are immutable. This means that after construction, they cannot be altered. Confusion Alert!! This is a place where it is important to be careful about reference variables and their objects. A reference variable (even one referring to a String) can be altered. A String object cannot. For example: String ring = "One ring to rule them all, " String find = "One ring to find them." ring = ring + find; The String objects don't change. The reference variable ring is changed in the third statement to refer to a different String than originally in the first statement. The sequence "\n" represents the control characters (in a string) that represent a new line. Although you do not see them printed, the control characters are part of the data in the String. The string "\t" tells the compiler that you want the tab character. The public String toLowerCase( ); method constructs a new String object containing all lower case letters. String line = "The Sky was like a WaterDrop" ; String a = line.toLowerCase( ); String b = "Clear, Tranquil, Beautiful".toLowerCase( ); System.out.println( "Deep, Dark, Dank".toLowerCase( ) ); An object reference variable can exist without referring to an object. A reference variable can be declared without initialization: String myString; Also, a reference can be set to null: String b = null; * Remember: String a = ""; is NOT the same as: String b = null; the first is like having a blank sheet of paper, versus having no paper at all (an empty string.) An object can exist without an object reference variable referring to it. As in the String myString; example. Such objects are temporary. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
See Java Links for more info, Object & Classes , Data Types , Operators , Conditionals , Definitions , Keywords , File Structure , Code Examples , Class Skeleton , Java Notes



Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character '_', and character '$'.
A name can not contain the space character.
