Title | The Art & Science of Java |
---|---|
Course | Foundations of Programming |
Institution | McGill University |
Pages | 15 |
File Size | 285.9 KB |
File Type | |
Total Downloads | 23 |
Total Views | 208 |
The summary of the chapters in the book...
The Art and Science of Java Notes Chapter 1 Components of the computer: • CPU: performs actual computation and coordinates t • Memory: • RAM (Random Access Memory): short term and • Secondary storage: Long term storage, does no i.e. USB • Input/output devices: Communication between users • Network Algorithms Algorithms must be: • Clearly and unambiguously defined • Effective, steps are executable • Finite, terminates after a bounded number of steps Stages in programming process: • Algorithmic design • Coding: translating the algorithm into computer langu Creating programs • Source file: a file containing program text Compilation • The compiler translates programming language into m
• Java encapsulates data and any associated operatio called objects Creation of Applets • So that the language would work well over a network Chapter 2 Programming By Example Comments • Contents enclosed between /* and */ symbols • Contents after // but only until end of line • Programs usually have a “program comment” at the b gives credit, etcetera Imports • After comments we see: import acm.graphics.*; import acm.program.*;
• This indicates the use of two library packages • Library package: a collection of tools written by other operations The main class • A class includes: • A header: defines essential characteristics • The body: fills in the details • “public” means: other programs have access
• When a new class is defined as an extension of an e • • • •
subclass of the original. A class is an extensible template that specifies the st Each object is an instance of a particular class, which different objects. To create an object, one must: • First define the class • Construct individual objects An object has both state and behavior: • State: consists of a set of entities that pertain to • Behavior: the ways in which that object respond
Class hierarchy • Inheritance: Subclasses takes on the public behavior • Overriding a method: Redefining an existing method is defined by its superclass Chapter 3 Expression • An expression is composed of terms and operators. • A term represents a single data value • An operator indicates a computational operation • A term must be one of the following: • A constant • A variable • A method call. By calling other methods, values • An expression in parentheses • Evaluation: The process of carrying out each of the s
• The data type “String” can be treated like “int” Constants and variables • Constants: (i.e. pi) values don’t change • Integer constants • Floating constants • Boolean constants: Only “true” or “false” • String constants: contents enclosed in “ ” • Variables: has a name, value, and type • Names in java are called identifiers • They must follow these rules: • Must start with a letter or the underscore charac • Uppercase and lowercase are considered differe • All other characters must be letters, digits, or the • Must not be a reserved word Declarations • Must declare a variable type identifier = expression;
• Variables declared inside a method are called local v method • Instance variables: Variables declared inside outside as part of each object • Class variables: With keyword “static”, declared in m private static final double PI = 3.1415926;
• 9 / 4 will result in 2, an integer • 9.0 4 = 2.25 • The remainder (%) requires both operands to be of ty Precedence • For arithmetic expressions: • Unary minus operators first (-) • Multiplicative operators second (*, /, and %) • Additive operators last (+ and -) Type conversion • Automatic type conversion double total = 0;
• Java will convert 0 to 0.0, an integer to floating-point • Type cast: int n = (int) 1.9999;
• Java converts 1.9999 to an integer, 1, simply by throw truncation • Type cast operator has very high precedence Assignment statements • Stack frame: a collection of variables associated with • Shorthand assignment operators
• && Logical and (true if both operands are true) • || Logical or (true if either or both operands are • De Morgan’s Laws: ! (p && q) is equivalent to !p || !q Short-circuit evaluation • If java encounters “exp1 && exp2" and if exp1 is false Flags • Variables of type boolean are called flags Precedence Table
Chapter 4 Statement Forms Statement types • Simple statements: perform some action • Compound statements: combine other statemen • Control statements: affect the way other statem • Compound statements are also known as a block
condition ? expression1 : expression2
• Example: max = (x > y) ? x : y; The switch statement • Syntax: switch (e) { case c1: statements1 break; case c2: statements2 break; …more case clauses… default: statementsdef break; }
• where: • e is the control expression, used to choose wha • each ci is a constant value • each statementsi is a sequence of statements to • statementsdef is a sequence of statements to b the expression e
• statements: statements to be repeated • “for(;;)” is similar to “while(true)” • Floating-point numbers are not exact and may cause Chapter 5 Methods • Methods reduce the complexity of programs A quick overview of methods • A method consists of a set of statements that have b • Calling a method: executing the set of statements as • To call a method, write the name of the method, follo parentheses. These expressions are called argumen • The operation of going back to the calling program is Method as mechanisms for hiding complexity • Information hiding: Methods provide a way of hiding l the caller need not be bothered by them Difference between a program and a method • Programs are for users • Methods are tools for programmers • Programs receive input from users • Methods receive input from the calling program, whic Method calls as expressions • Static method: methods not associated with an objec whole • Java requires one to specify the name of the class al
• • • •
visibility: public or private type: type of value returned, “void” if method ret name: name of the method parameters: list of parameter declarations. Sam initial value assignment • Example: “private double celsiusToFahrenheit(d • Followed by method body Return statement • Syntax return expression;
• expression: value to be returned • If no result, then “return;” Methods involving internal control structures • I.e. the factorial method Methods that return non numerical values • Returns strings Predicate methods • Methods that return values of type boolean • “equals” and “==“ are not exactly the same • “equals” asks if one object has the same value a • “==“ asks if its operands are precisely the same • “if (answer.equals(“yes”))
• Use arguments whenever individual callers are likely parameter • Use named constants whenever callers are likely to b Algorithmic methods • Brute force approach: A strategy that tries every poss Euclid’s algorithm • Divide x by y and compute the remainder, call the rem • If r is 0, the procedure is complete, and the answer is • If r is not 0, set x equal to the old value of y, set y equ Chapter 6 Objects and Classes • Deterministic: • Actions are predictable with any given set of inp • Produces the same value every time • Nondeterministic: • Produces random values Pseudorandom numbers • Programs simulates randomness but are not truly ran RandomGenerator class
• A programmer who implements a class is called an im • Programmers who use the facilities are called clients • Layered abstractions: the hierarchies where each ne provided by its predecessors Defining your own classes Structure • Syntax: public class name extends super { class body }
• name: name of the new class • super: name of the superclass • class body: includes constructors, methods, nam • If “extends” is missing, then the class becomes a dire • • • •
(highest) Constructors: Specify how to create new instances o Instance variables: maintain the state of the objects Constructors: Defined the same way as methods, ex • The name of the constructor is the same as the • Does not specify a result type Instance variables are declared the same as any oth are at the top of a class rather than inside a method d
Controlling the visibility of entries • Access types:
}
• In this way, the java compiler can recognize the varia belonging to this object and the variables on the right Getters and setters • Methods whose only function is to retrieve the value some new value are called getters and setters. String name = topStudent.getName(); topStudent.setCredits(97);
• By convention, getters begin with prefix “get” and set • For retrieving Boolean values, getters usually use pre The toString method • “+” Rational numbers • Constructors and methods that have multiple argume to be overloaded • Immutable: Classes whose internal state cannot be c method calls Rules for inherited constructors • When a new object is initialized, java must make sure superclasses is invoked during the construction proce • Constructors that don’t explicitly include a call to “sup
Bits, bytes, and words • Bit: records the simplest possible value - 0 or 1 • Byte: smallest combined unit, contains 8 bits • Words: 4 bytes = 32 bits • KB = 2^10 = 1024 bytes • MB = 2^20 = 1048576 bytes • GB = 2^30 = 1037741824 bytes Review notes for binary and hexadecimal conversions Memory addresses • Byte, short, int, long - 8 bit, 16 bit, 32 bit, 64 bit Allocation of memory to variables • Static variables and constants: allocated at the begin • Dynamically allocated objects: Objects created using • Local variables: assigned to stack • Declaring an object variable: reserve memory in both to store the object - stack. The reference (memory ad • Example: Rational half = new Rational(1, 2);
• “half” is a local variable: appears in the stack fra However, a reference to the object can be store • The object itself is stored in the heap. The heap values “num” and “den” along with additional inf • The additional info (management information) is
• Each of the wrapper classes has a constructor that c corresponding primitive type • For example: “ Integer a = new Integer(17); ” creates value is n and assigns it to “a” • To retrieve value use: “ a.intValue() ” Boxing and unboxing • The automatic process of adding or removing the wra and unboxing • Remark: “ == ” compares if two objects are PRECISE Linking objects together • Creating an object that contains references to other o programming technique. Such objects are said to be • A reference to “null” means that it is the last object Chapter 8 Strings and Characters The principle of enumeration • The process of listing all the elements in the domain • A type defined by listing all of its elements is called a • Integer encoding: assigning an integer to each eleme Defining new enumerated types • Example public enum Weekday { SUNDAY, MONDAY, TUESDAY, WEDNE SATURDAY
Compare strings • Cannot use “ == ” as this tests if the strings are exact • To compare strings use s1.equals(s2), or s1.compar • If s1 precedes s2 in alphabetical order, compare • If s1 follows s2 in alphabetical order, compareTo • If the two strings are exactly the same, compare StringTokenizer • Divides a string into tokens Midterm Review...