|
Definition: Introduction to Programs and JAVA Memory is an ordered sequence of bytes that is used to store data and program instructions for the central processing unit (CPU) to execute. A program and its data must be brought into memory, usually from an external storage device, before it can be executed. Every byte of memory has an unique address. This address is used by the CPU to locate the data for storing and retrieving the information contained in that byte. Memory is volatile. Storage Devices are devices where programs and data are permanently stored and moved into memory when called for by the CPU. Some storage devices are hard disk, DVD, solid state flash-memory sticks and tapes. An Input Device is one which accepts data for processing to the computer. An Output Device is one which outputs results from the computer. A Program is a set of exact instructions for a computer to carry out. Also known as software. Machine Language is a set of primitive instructions in the form of binary code that instruct the computer. Extremely hard for humans to read, but extremely rapid execution for the computer. Assembly Language is a low-level programming language in which primitive mnemonic codes are used to represent machine language. Difficult for humans to read or write. But after the assembly language is translated via an assembler into machine language it runs extremely fast on the computer. High-Level Languages such as COBOL, JAVA, REXX and C++ are English-like and much easier to learn and used to program. A program written in this language form is called the source program. (a) If the source program is translated by a compiler to produce an object program, then it is called a compiled language. The object program is in machine language. Object programs are linked together via the linkage editor to create an executable machine language program. Compiled languages include COBOL, FORTRAN, and C++ (b) If the source program, may or may not require a compilation process, but is further translated at run time by an interpreter into executable machine language, then it is called an interpreted language. Intrepreted languages include REXX, Shell Script and JAVA. The JAVA language programs are compiled into an architecture neutral "bytecodes". These bytecodes will run on any computer with a Java Virtual Machine (JVM) installed. The bytecodes are interpreted by the JVM into executable native machine code. This is the feature that makes JAVA portable across all operating platforms. "Write Once, Run Everywhere". JAVA Language Specification: JDK is the JAVA Development Kit that supports compilation and execution, and contains a wealth of pre-compiled class libraries. IDE is the Integrated Development Environment, such as SunMicrosystems NetBeans, it is used to create, compile and execute programs from scratch. Structure of a JAVA program Comments are used to help programmers communicate information regarding the logic and to help remember what the code actually does. Classes are the essential JAVA constructs which encapsulates the program and their routines. Statements are lines of code, terminated by a semicolon, that performs some action or work. Methods are a procedural set of instructions or statements, a routine, that may take arguments and performs some work and may produce a returned result. Properties are definitions of data which include its type and number of storage bytes allocated. Blocks are used to group components of a program. A block is delimited by braces {}. Every method employs a method block that groups the statements in the method. The main method defines where the control of flow for a JAVA program begins. The JVM executes the application by invoking the main method. Modifiers Visibility Scope Return_Type MethodName (Argument_List) Examples: public static void main(String[] args) private int myroutine(String[] args, int, String, float)
|
|
Definition: Data Types in JAVA JAVA is a strongly typed language meaning that every defined variable must have a declared type. There are eight primitive variable types in JAVA. Integer
Types Note that each bit, except for the leftmost bit, represents a numerical power of 2. The leftmost bit may represent a sign of negative or positive. The initial definition of the variable must include the type. Referencing a defined variable does not require using the type. Examples: int aSmallNumber; long myBigNumber = 987453627 Floating-Point
Types Examples: Character
Type Special characters that we will
use: boolean
Type Examples: Operators Do not confuse the "=" sign which means assignment with the "==" sign which means exactly equal to. Simple Math Functions Strings Unreferenced strings are automatically "garbage collected" by the JAVA Virtual Machine. Example: Converting Strings to Integers Discussion on JAVA floating-point numbers (FYI only***) A floating-point number has four parts -- a sign, a mantissa, a radix, and an exponent. The sign is either a 1 or -1. The mantissa, always a positive number, holds the significant digits of the floating-point number. The exponent indicates the positive or negative power of the radix that the mantissa and sign should be multiplied by. The four components are combined as follows to get the floating-point value: Floating-point numbers have multiple representations, because one can always multiply the mantissa of any floating-point number by some power of the radix and change the exponent to get the original number. For example, the number -5 can be represented equally by any of the following forms in radix 10:
For each floating-point number there is one representation that is said to be normalized. A floating-point number is normalized if its mantissa is within the range defined by the following relation: A normalized radix 10 floating-point number has its decimal point just to the left of the first non-zero digit in the mantissa. The normalized floating-point representation of -5 is -1 * 0.5 * 10 1. In other words, a normalized floating-point number's mantissa has no non-zero digits to the left of the decimal point and a non-zero digit just to the right of the decimal point. Any floating-point number that doesn't fit into this category is said to be denormalized. Note that the number zero has no normalized representation, because it has no non-zero digit to put just to the right of the decimal point. "Why be normalized?" is a common exclamation among zeros. Floating-point numbers in the JVM use a radix of two. Floating-point numbers in the JVM, therefore, have the following form: The mantissa of a floating-point number in the JVM is expressed as a binary number. A normalized mantissa has its binary point (the base-two equivalent of a decimal point) just to the left of the most significant non-zero digit. Because the binary number system has just two digits -- zero and one -- the most significant digit of a normalized mantissa is always a one. The most significant bit of a float or double is its sign bit. The mantissa occupies the 23 least significant bits of a float and the 52 least significant bits of a double. The exponent, 8 bits in a float and 11 bits in a double, sits between the sign and mantissa. The format of a float is shown below. The sign bit is shown as an "s," the exponent bits are shown as "e," and the mantissa bits are shown as "m":
A sign bit of zero indicates a positive number and a sign bit of one indicates a negative number. The mantissa is always interpreted as a positive base-two number. It is not a twos-complement number. If the sign bit is one, the floating-point value is negative, but the mantissa is still interpreted as a positive number that must be multiplied by -1. The exponent field is interpreted in one of three ways. An exponent of all ones indicates the floating-point number has one of the special values of plus or minus infinity, or "not a number" (NaN). NaN is the result of certain operations, such as the division of zero by zero. An exponent of all zeros indicates a denormalized floating-point number. Any other exponent indicates a normalized floating-point number. The mantissa contains one extra bit of precision beyond those that appear in the mantissa bits. The mantissa of a float, which occupies only 23 bits, has 24 bits of precision. The mantissa of a double, which occupies 52 bits, has 53 bits of precision. The most significant mantissa bit is predictable, and is therefore not included, because the exponent of floating-point numbers in the JVM indicates whether or not the number is normalized. If the exponent is all zeros, the floating-point number is denormalized and the most significant bit of the mantissa is known to be a zero. Otherwise, the floating-point number is normalized and the most significant bit of the mantissa is known to be one. The JVM throws no exceptions as a result of any floating-point operations. Special values, such as positive and negative infinity or NaN, are returned as the result of suspicious operations such as division by zero. An exponent of all ones indicates a special floating-point value. An exponent of all ones with a mantissa whose bits are all zero indicates an infinity. The sign of the infinity is indicated by the sign bit. An exponent of all ones with any other mantissa is interpreted to mean "not a number" (NaN). The JVM always produces the same mantissa for NaN, which is all zeros except for the most significant mantissa bit that appears in the number. These values are shown for a float below:
Exponents that are neither all ones nor all zeros indicate the power of two by which to multiply the normalized mantissa. The power of two can be determined by interpreting the exponent bits as a positive number, and then subtracting a bias from the positive number. For a float, the bias is 126. For a double, the bias is 1023. For example, an exponent field in a float of 00000001 yields a power of two by subtracting the bias (126) from the exponent field interpreted as a positive integer (1). The power of two, therefore, is 1 - 126, which is -125. This is the smallest possible power of two for a float. At the other extreme, an exponent field of 11111110 yields a power of two of (254 - 126) or 128. The number 128 is the largest power of two available to a float. Several examples of normalized floats are shown in the following table:
An exponent of all zeros indicates the mantissa is denormalized, which means the unstated leading bit is a zero instead of a one. The power of two in this case is the same as the lowest power of two available to a normalized mantissa. For the float, this is -125. This means that normalized mantissas multiplied by two raised to the power of -125 have an exponent field of 00000001, while denormalized mantissas multiplied by two raised to the power of -125 have an exponent field of 00000000. The allowance for denormalized numbers at the bottom end of the range of exponents supports gradual underflow. If the lowest exponent was instead used to represent a normalized number, underflow to zero would occur for larger numbers. In other words, leaving the lowest exponent for denormalized numbers allows smaller numbers to be represented. The smaller denormalized numbers have fewer bits of precision than normalized numbers, but this is preferable to underflowing to zero as soon as the exponent reaches its minimum normalized value.
Week
3
|
|
Definition: Standard Out is the output that is normally directed to the terminal console. Standard In is the input that is normally read from the terminal keyboard. Standard Err is the error message output that is normally sent to the terminal console. More on Strings Substrings are subsets of some defined String. Substrings themselves are Strings. Strings can be concatenated by joining them with a "+" sign. Testing strings for equality can be done using String's "equals" or "equalsIgnoreCase" methods. The "trim" method returns a new string without the leading and trailing spaces.
Data Input Scanner class, new with JDK 5.0, will read input from the terminal console window. JOptionPane class, using the showInputDialog method, will put up an input window to enter the input you wish read along with a prompt.
Data Output System.out.printf which is the "printf" method of the "PrintStream" class called by the "out" field property of the static "System" class is the new JDK 5.0 opting to put data to the terminal console with formatting. |
|
Definition: Exceptions are events that occur during the execution of a program and may disrupt the normal flow of control. A program that does not provide logic for handling exceptions may abnormally terminate, causing problems for the user. JAVA provides programmers with the capability to handle runtime errors. This is referred to as exception handling. Possible errors can be caught by using the try-catch[-finally] block construct. This allows the exceptions to be handled programmatically, prevent "ugly" messages to the user and permit execution to continue. If an exception occurs within the try clause then the remainder of the lines in the try clause are skipped and the control is then transferred to the catch clause. After the exception is caught and processed, control is transferred to the finally clause, if there is one, or to the next statement after the try-catch block. If you as a programmer do not catch the exception, the JVM will and put out an ugly message(s) for your users, then terminate execution. Prototype:
try The next statement following try-catch-[finally] block Example:
String s = null; JAVA has 3 classes of exceptions: exceptions describes errors caused by your program and external circumstances. These should be caught and handled by your program. runtime exceptions are those that describe programming errors, such as bad casting, accessing an out of bounds array and numeric errors. They are generally thrown by the JVM. If an exception occurs that is caught by your program's catch statement, then the particular exception class is instantiated and can be referenced by the variable name you assign to the exception. Using this instance variable you can call on its method "getMessage()" to obtain information regarding the cause of the exception. Example: System.out.println("An error occurred, information received is: " + exc.getMessage() ); Flow Control Program flow control concerns itself with the order in which statments are executed in a program. Most programming does not execute its statements in sequence. Often situations occur in which you must provide alternate instruction paths. If-then-Else Statement Prototype:
if (boolean_expression) Example:
boolean starsAreOut = false; Nested If |
|
Definition: The SWITCH SWITCH statements are employed when nested IF-ELSE statements would make a program difficult to read and interpret by the human programmer. The SWITCH statment will handle multiple conditions efficiently and may make it easier to program and debug. Prototype: switch
(expression) { The "switch" statement will check all cases and execute beginning at the statement in the matched case. It will execute or "fall-through" all remaining statements unless there occurs a "break;" statement. The switch "expression" must yield a value of char, byte, short or int type. The "value" must have the same data type as that yielded by the switch "expression". LOOP Statements Loops are constructs that control repeated iterated executions of a block of statement code. Each loop contains a loop continuation condition that controls the execution. Prior to each iteration the loop continuation condition is re-evaluated. If the condition is true, then the execution continues, if the condition is false then the loop terminates and passes control to the next statement outside of the loop. There are three types of loop in JAVA: while, do-while and for while loop while (continuation_condition_is_true) for loop for (initial_value;
continuation_condition_is_true; action_after_each_iteration) Nested loops are loop constructs within loop constructs. The nested loop appear to the outer loop as a statement to be executed independently. Any loop can be terminated early by way of the break statement. The break statement issued in an inner loop will cause execution to continue with the next statement in the set of statements being performed by the outer loop. Any iteration within a loop can be terminated early by way of the continue statement. The continue statement will cause a pre-empting of any further statements in this iteration of the loop and continue the loop with the next iteration. Nested for loop for (initial_value_a;
continuation_condition_is_true; action_after_each_iteration) |
|
Definition: Calling a Method In creating a subroutine, you give a definition of what the routine is to do. To employ the subroutine you have to call or invoke it by way of a method call. The subroutine must reside in either this class or another class which your program has access to via packaging or import statment. There are two ways to call a subroutine; the choice is based on whether the method returns a value or not. If the method returns a value it is called a function. Example: int root = Math.sqrt(196); If the method returns no value it is known as a void method or a procedure. Example: System.out.println("Hello World"); Method Prototype Definition: Example: public int mySubroutine(int arg1, int arg2, String arg3, double arg4)
Prototype for Invoking a method: Example: int rc = mySubroutine(arg1, arg2, arg3, arg4);
Transfer of Control
Passed Arguments
Results
Method Overloading
Scope of Variables A variable that is defined outside of all methods but within the class is called "global" to all in-class methods.
Method Abstraction |
|
Definition: An Array is a fixed-size sequential collection of elements of identical types. In JAVA they are defined to be of some fixed immutable number of elements. During allocation the array size must be given to specify the number of elements that can be stored in it. Prototype for Declaring an array: Example: String[] myArray; Prototype for Creating an array: Example: myArray = new String[100]; Prototype for Declaring and
Creating an array in one step: Example: String[] myArray = new String[100]; FYI: While the array variable appears to hold an array, it actually contains just a reference to that array. The array variable and the array are different. Initial Storage Contents When an array is created its elements are initialized with the value of ZERO if the data type is defined as numeric. If the array data type is defined as String or char then it is filled with unicode '\u0000' (null characters). If the array data type is defined as boolean then each element is set "false". Relative Addressing The size of the array can be queried by using the Array Reference Variable Length. ie. int myTableSize = myArray.length The array elements are accessed through an index. The index variable must be an integer. The first element of an array is Element ZERO. ie. myArray[0] The last element of an
array is one less
than the Array Reference
Variable Length, ie. myArray[myArray.length - 1] Accessing an array out-of-bounds is a common programming error. It will throw a runtime ArrayIndexOutOfBoundsException. To avoid this error, make sure that you do not use an index beyond arrayRefVar.length - 1. Copying Arrays To copy one array to
another you can: Note that the statement arrayList1 = arrayList2 may appear to copy the array but it is simply creating another reference pointer to the same array. Passing Arrays to Methods JAVA uses "pass by value" to pass arguments to a method if the arguments are the variables of primitive data types. For an argument that is of an array type, the value of the argument contains a reference to an array; this reference is passed to the method. ie.
int[] x = new int[100]; Returning an Array from a Method A method may also return an array. Again it returns a reference pointer to the caller. .ie.
int[] x = new int[100];
public int[] someRoutine(int[] y)
|
|
Definition: An Multi-Dimensional Array is a fixed-size sequential collection of elements of identical types, like a single dimensional array, but is is used to represent n-dimensional data structures. During allocation the array size in all dimensions must be given to specify the number and type of elements that can be stored in it. Arrays of 2 dimensions are called tables or matrices. Tables are usually identified with rows and columns. Prototype for Declaring a
2-dimensional array, a.k.a table: Example: String[][] myArray; Prototype for Creating a
2-dimensional array, a.k.a table: Example: myArray = new String[100][50]; Prototype for Declaring and
Creating a matrix in one step: Example: String[][] myArray = new String[100][200]; This creates a tables of strings with 100 rows and 200 columns. Relative Addressing The elements x[0], x[1], x[2], ..., x[n-1] are arrays in themselves. The size of the array in the first dimension can be queried by using the Array Reference Variable Length. ie. int myTableSize = myArray.length The sizes of the arrays in the second dimension can be queried by using the Array Reference Variable Length of each element from the first dimension. ie. int myTableSize = myArray[0].length int myTableSize = myArray[1].length int myTableSize = myArray[myArray.length-1].length
The array elements are accessed through an multiple indices. Each index variable must be an integer. The first element of a table can be thought of as Row Zero, Column Zero . ie. myArray[0][0] The last element of a
table is one less
than the Array Reference
Variable Length for both rows and columns. ie. myArray[n][m] ie. myArray[myArray.length - 1] [myArray[myArray.length-1].length - 1]
|
|
Definition: Inheritance is the object-oriented programming concept that allows you to derive new classes from existing ones. In fact, every class in JAVA is inherited from an existing class, either explicitly or implicitly. The parent of all JAVA classes is Object If class PGM1 is derived from another class PGM2, then PGM1 is called a subclass (or child class) and PGM2 is called its superclass (or parent class). A subclass inherits accessible variables and methods from its superclass. The subclass may extend the superclass by adding new variables and methods. Note that the subclass is NOT a subset of its superclass. On the contrary since the subclass extends and is a specialization of the superclass; every instance of a subclass is an instance of its superclass. Therefore it is the superclass that is a subset of the subclass. The inheritance relationship enables a subclass to inherit features from its superclass with additional new features. "this" and "super" keywords Calling
Superclass Constructors The statement super() must appear in the first line of the subclass constructor. If not invoked explicitly then the compiler puts super() as the first statement in the constructor. Calling
Superclass Methods and Using Superclass Properties
super.myVariable Overriding
Methods Note: Static methods can be inherited but it cannot be overridden. Polymorphism Polymorphism allows methods to be used generically for a wide range of object arguments. If a methods parameter type is a superclass (ie. Object) you may pass an object to this method of any of the parameter's subclasses. Example: Protected Data and Methods A protected data field or method in a public class can be accessed by any class in the same package or its subclasses. Use the private modifier to hide the members of the class completely so that they cannot be accessed directly from outside the class. Use no modifiers to allow the members of the class to be accessed directly from any class within the same package but not from other packages. Use the public modifier to enable the membrs of the class to be accessed by any class. The private and protected modifiers can only be used for methods and variables. The public and no modifier (default) can be used on members as well as the class itself.
|
|
Definition: Class design should ensure that a superclass contains common features of its subclasses. Sometimes a superclass is so abstract that it cannot have any specific instances nor define any concrete implementation details defining behaviour. Such a class is referred to as an Abstract class. Prototype: JAVA does not allow multiple inheritance. Each JAVA class may inherit directly from at most one superclass. This restriction is known as single inheritance. An abstract class will define methods that cannot be implemented in the superclass because their implementation details are dependent on the specific type of object being defined by the subclass. These methods are referred to as abstract methods. Abstract classes are like regular classes with variables and methods, but you cannot create instances of abstract classes via the "new" operator. An abstract method is a method signature without implementation. The abstract class can contain concrete methods as well as signature-only methods. The implementation is to be provided by the subclasses. An Interface is a classlike construct that contains only constants and abstract methods. An interface is similar to an abstract class, but an abstract class can contain variables and concrete methods as well as constants and abstract methods. Each method of an Interface has only a signature without implementation. Prototype: Interfaces are similar to abstract classes and you can use them more or less the same way. A class may implement multiple Interfaces. An Interface may extend (and therefore inherit) multiple super Interfaces. Both Abstract classes and Interfaces are used to define generic classes and methods. |
[Return
to Professor
Page]