java statements.docx

29
Java Statements Methods and constructors are sequences of statements, along with variable definitions. The statements specify the sequence of actions to be performed when a method or constructor is invoked. They can alter the value of variables, generate output, process input, or respond to user mouse or keyboard actions. Different types of statements are described in the following sections. Assignment Statements An assignment statement has the following form. variable = expression; This statement changes the value of the variable on the left side of the equals sign to the value of the expression on the right- hand side. The variable is often just specified by a variable name, but there are also expressions that specify variables. Java treats an assignment as both an expression and as a statement. As an expression, its value is the value assigned to the variable. This is done to allow multiple assignments in a single statement, such as a = b = 5; By treating b = 5 as an expression with value 5, Java makes sense of this statement, assigning the value 5 to both a and b. Statements involving Messages Messages are the fundamental means of communication between objects in a Java program. A message has the following form. receiver.method-name(parameters) Here, receiver is an expression (often just a variable name) that specifies the object that should respond to the message. method-name is the name of the method that the receiver should execute.

Upload: patricia-joy-m-petez

Post on 04-Sep-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Java StatementsMethods and constructors are sequences of statements, along with variable definitions. The statements specify the sequence of actions to be performed when a method or constructor is invoked. They can alter the value of variables, generate output, process input, or respond to user mouse or keyboard actions.Different types of statements are described in the following sections.Assignment StatementsAn assignment statement has the following form. variable = expression;This statement changes the value of the variable on the left side of the equals sign to the value of the expression on the right-hand side. Thevariableis often just specified by a variable name, but there are also expressions that specify variables.Java treats an assignment as both an expression and as a statement. As an expression, its value is the value assigned to the variable. This is done to allow multiple assignments in a single statement, such as a = b = 5;By treatingb = 5as an expression with value 5, Java makes sense of this statement, assigning the value 5 to bothaandb.Statements involving MessagesMessages are the fundamental means of communication between objects in a Java program. Amessagehas the following form. receiver.method-name(parameters)Here, receiveris an expression (often just a variable name) that specifies the object that should respond to the message. method-nameis the name of the method that the receiver should execute. parametersis a comma-separated list of expressions that provide data that the receiver can use in its execution of the method.The receiver can be omitted if it is the object that you are writing code for. That is, you do not need to specify the receiver for messages sent from an object to itself.Messages can be used in three ways to form statements. First, if the method specified by a message returns a value then the message can be used as the expression in an assignment statement. variable = message;For messages with methods that do not return values, a statement can also be formed by just terminating the message with a semicolon. message;This statement form can also be used when the method returns a value, although it is not usually a good idea to ignore a returned value.Finally, if a message returns an object, then that object can be used directly as the receiver of a message. In an applet method, for example,getContentPane()returns a container to which components can be added. This container is the receiver of theadd()message in the following statement. getContentPane().add(button);Statement BlocksIn Java, any sequence of statements can be grouped together to function as a single statement by enclosing the sequence in braces. These groupings are calledstatement blocks. A statement block may also include variable declarations.Statement blocks are used to define methods and to allow multiple statements in the control structures described in the following sections.Control StatementsNormally, statements in a method or constructor are executed sequentially. Java also has control statements that allow repetitive execution of statements and conditional execution of statements. Java has the following types of control statements. Conditional Execution And SelectionIf Statements-conditional execution of a single statement

If-Else Statements-conditional selection among two statements

Switch Statements-conditional selection among several statements

Extended If-Else Statements-conditional selection among several statements

RepetitionWhile Loops-pretest loops

For Loops-pretest loops

Do-While Loops-posttest loops

Special Control StatementsReturn Statements-return values from and terminate methods

Continue Statements-skip the remaining statements in an iteration of a loop

Break Statements-exit a loop or switch statement

Conditional Execution and SelectionJava has three kinds of statements that permit execution of a nested statement based on the value of a boolean expression or selection among several statements based on the value of a boolean expression or a control variable. These statements are the if statement, the if-else statement, and the switch statement.If StatementsThe if statement has the following form. if (boolean-expression) {then-clause }Here, boolean-expressionis an expression that can be true or false. then-clauseis a sequence of statements. If there is only one statement in the sequence then the surrounding braces may be omitted. Thethen-clausestatements are executed only if theboolean-expressionis true.If-Else StatementsThe if-else statement has the following form. if (boolean-expression) {then-clause } else {else-clause }Here, boolean-expressionis an expression that can be true or false. then-clauseandelse-clauseare sequences of statements. If there is only one statement in a sequence then the surrounding braces may be omitted. Thethen-clausestatements are executed only if theboolean-expressionis true. Theelse-clausestatements are executed if theboolean-expressionis false.Switch StatementsThe switch statement allows execution of different statements depending on the value of an expression. It has the following form. switch (control-expression) { case constant-expression-1:statements-1 . . . case constant-expression-n:statements-n default:default-statements }Here, control-expressionis an expression of a simple type, such as int, char, or an enum type. It cannot have float or double type. constant-expression-1throughconstant-expression-nare expressions of a type that converts to the type ofcontrol-expression. The compiler must be able to evaluate these expressions to constant values. statements-1throughstatements-nare sequences of statements.When the switch statement is executed,control-expressionis evaluated. The resulting value is compared to the values ofconstant-expression-1throughconstant-expression-nin order until a matching value is found. If a match is found inconstant-expression-ithenstatements-ithroughstatements-nanddefault-statementsare executed, with switch statement execution terminated if a break statement is encountered. Normally, the last statement in each sequence is a break statement so that only one sequence is executed.The default clause is optional. If it is present then thedefault-statementsare executed whenever the value ofcontrol-expressiondoes not match any of theconstant-expression-ivalues.Extended If-Else StatementsOften, a programmer needs a construction that works like aswitch statement, but the selection between choices is too complex for a switch statement. To make this work, a programmer can use a sequence of if statements where each if statement is nested in the else clause of the preceding if statement. This construction is called anextended is statement. It has the following form. if (boolean-expression-1) {statements-1 } else if (boolean-expression-2) {statements-2... } else if (boolean-expression-n) {statements-n } else {default-statements }Here, boolean-expression-1throughboolean-expression-nare expressions that can be true or false. statements-1throughstatements-nanddefault-statementsare sequences of statements.When this extended if-else statement is executed, the boolean expressions are evaluated in order until one is found that is true. Then the corresponding sequence of statements is executed. If none of the boolean expressions is true then thedefault-statementsare executed. In either case, execution continues with the next statement after the extended if-else statement.RepetitionJava has three kinds of loop statements: while loops, for loops, and do-while loops. Loop statements allow a nested statement to be executed repetitively. The nested statement can be a block statement, allowing repetition of a sequence of statements.When a loop is executed its nested statement can be executed any number of times. Each execution of the nested statement is called aniterationof the loop. The number of iterations is controlled by a boolean expression. The boolean expression is evaluated before each iteration (pretest) in while loops and for loops, and after each iteration (post-test) in do-while loops. When the boolean expression becomes false the loop is terminated.While LoopsThe while loop is a pretest loop statement. It has the following form. while (boolean-expression) {nested-statements }Here, boolean-expressionis an expression that can be true or false. nested-statementsis a sequence of statements. If there is only one statement then the braces can be omitted.The boolean expression is testedbeforeeach iteration of the loop. The loop terminates when it is false.For LoopsThe for loop is a pretest loop statement. It has the following form. for (initialization; boolean-expression; increment) {nested-statements }Here, initializationis an expression (usually an assignment expression). boolean-expressionis an expression that can be true or false. incrementis an expression. nested-statementsis a sequence of statements. If there is only one statement then the braces may be omitted.When a for loop is executed the initialization expression is evaluted first. This expression is usually an assignment (for example,i = 0) that sets the initial value of a loop control variable.The boolean expression is testedbeforeeach iteration of the loop. The loop terminates when it is false. The boolean expression is frequently a comparison (for example,i < 10).At the end of each iteration, the increment expression is evaluated. The expression is often an expression that increments the control variable (for example,i++).Do-While LoopsThe do-while loop is a post-test loop statement. It has the following form. do {nested-statements } while (boolean-expression);Here, nested-statementsis a sequence of statements. If there is only one statement then the braces may be omitted. boolean-expressionis an expression that can be true or false.The boolean expression is testedaftereach iteration of the loop. The loop terminates when it is false.Special Control StatementsReturn StatementsThe return statement is used in the definition of a method to set its returned value and to terminate execution of the method. It has two forms. Methods with returned typevoiduse the following form. return;Methods with non-voidreturned type use the following form. return expression;Here, expressionis an expression that yields the desired return value. This value must be convertible to the return type declared for the method.Continue StatementsThe continue statement is used in while loop, for loop, or do-while loop to terminate an iteration of the loop. A continue statement has the following form. continue;After a continue statement is executed in a for loop, its increment and boolean expression are evaluated. If the boolean expression is true then the nested statements are executed again.After a continue statement is executed in a while or do-while loop, its boolean expression is evaluated. If the boolean expression is true then the nested statements are executed again.Break StatementsThe break statement is used in loop (for, while, and do-while) statements and switch statements to terminate execution of the statement. A break statement has the following form. break;After a break statement is executed, execution proceeds to the statement that follows the enclosing loop or switch statement.1-3 GENERAL PROGRAMMING RULES ****************************** (Thanks to Craig Burley for the excellent comments)

Programming rules are an attempt summarize the programming experience of programmers, and the theoretical considerations raised by computer scientists. Some programming rules apply to all programming language, they stem from general principles like:

A) Modern computers are very powerful, memory became relatively cheap, and modern compilers automatically optimize code better than the average programmer.

So, saving memory or CPU time is no longer of prime importance: what is important is creating programs that are easy to VALIDATE (check that the results are correct) and MAINTAIN (change to suit different future needs).

B) The building units of program code, procedures and functions, should be made as GENERAL (suitable for many similar applications) and FLEXIBLE (able to handle different types of input and computing requirements) as possible.

This principle promotes CODE REUSABILITY (using parts of old programs in new ones), and also helps improve coding since programs that don't rely on special assumptions tend to be more reliable.

C) Programs should have a well organized internal structure. The MODULARITY PROGRAMMING PARADIGM requires partitioning every program into relatively small units, each performing a well defined task.

The interaction between code units can be described by a PROCEDURE CALLING TREE, the calling tree makes clear also the internal structure of the program. A subprogram call has a performance cost, so sometimes you don't partition the program to many subprograms but just arrange it in well defined blocks, optimizing compilers does such things automatically (procedure inlining).

(Some new programming paradigms like OBJECT ORIENTED PROGRAMMING and VISUAL PROGRAMMING are not yet supported directly by the current Fortran languages and dialects. It seems that implementing these paradigms degrade performance.)

D) Programs should be fully documented. Documentation consists of:

1) Self-explaining names for variables, procedures etc.

2) Short comments explaining the algorithms used, variables' roles and computation steps

3) Program header containing: A general description, bugs and problems, planned improvements, copyright and redistribution information

4) Procedure headers similar to the program header

5) A text file explaining how to compile, link, install and use the program (and/or a Makefile).

E) Programs should be portable. To achieve this goal you should:

1) Strictly adhere to the FORTRAN STANDARD 2) Avoid using operating system routines 3) Avoid using any processor dependent features

Languages standards are technical specifications describing a programming language in detail. Compiler writers check their compilers against the standard, and so ensure that a program that compiled correctly on one standard conforming compiler will compile correctly on another such compiler.

The problem is that most compilers offer nice LANGUAGE EXTENSIONS, that sometimes are quite tempting to use, and may even be included in future revisions of the standard. However, if you use language extensions, your program might not compile on other machines without some rewriting, and so might be less useful.

F) A program source is really just a text file; as such it can and should be as READABLE and EASY TO EDIT as possible.

Readable programs are easier to maintain and validate.

In the chapter on program layout we will try to set some FORTRAN guidelines and give some useful references.

G) A program should not depend on assumptions about the correctness of user's input, guesses about expected data etc, this is called DEFENSIVE PROGRAMMING.

Make your program check user's input and key computation results, if wrong, try to recover - go back to the last trusted point, or just give a detailed message and abort the program.

H) It is very important to carefully select appropriate algorithms.

+------------------------------------------------------+ | | | SUMMARY OF PROGRAMMING RULES | | ---------------------------- | | a) Clarity is more important than efficiency | | b) Generalize your code | | c) Write modular programs | | d) Document your program | | e) Write standard FORTRAN | | f) Improve your layout | | g) Program defensively | | h) Use appropriate algorithms | | | +------------------------------------------------------+C - Constants and LiteralsThe constants refer to fixed values that the program may not alter during its execution. These fixed values are also calledliterals.Constants can be of any of the basic data types likean integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.Theconstantsare treated just like regular variables except that their values cannot be modified after their definition.Integer literalsAn integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.Here are some examples of integer literals:212 /* Legal */215u /* Legal */0xFeeL /* Legal */078 /* Illegal: 8 is not an octal digit */032UU /* Illegal: cannot repeat a suffix */Following are other examples of various type of Integer literals:85 /* decimal */0213 /* octal */0x4b /* hexadecimal */30 /* int */30u /* unsigned int */30l /* long */30ul /* unsigned long */Floating-point literalsA floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.Here are some examples of floating-point literals:3.14159 /* Legal */314159E-5L /* Legal */510E /* Illegal: incomplete exponent */210f /* Illegal: no decimal or exponent */.e55 /* Illegal: missing integer or fraction */Character constantsCharacter literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable ofchartype.A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').There are certain characters in C when they are preceded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes:Escape sequenceMeaning

\\\ character

\'' character

\"" character

\?? character

\aAlert or bell

\bBackspace

\fForm feed

\nNewline

\rCarriage return

\tHorizontal tab

\vVertical tab

\oooOctal number of one to three digits

\xhh . . .Hexadecimal number of one or more digits

Following is the example to show few escape sequence characters:#include

int main(){ printf("Hello\tWorld\n\n");

return 0;}When the above code is compiled and executed, it produces the following result:Hello WorldString literalsString literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.You can break a long line into multiple lines using string literals and separating them using whitespaces.Here are some examples of string literals. All the three forms are identical strings."hello, dear"

"hello, \

dear"

"hello, " "d" "ear"Defining ConstantsThere are two simple ways in C to define constants:1. Using#definepreprocessor.2. Usingconstkeyword.The #define PreprocessorFollowing is the form to use #define preprocessor to define a constant:#define identifier valueFollowing example explains it in detail:#include

#define LENGTH 10 #define WIDTH 5#define NEWLINE '\n'

int main(){

int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE);

return 0;}When the above code is compiled and executed, it produces the following result:value of area : 50The const KeywordYou can useconstprefix to declare constants with a specific type as follows:const type variable = value;Following example explains it in detail:#include

int main(){ const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = '\n'; int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE);

return 0;}A variable is a container that holds values that are used in a Java program. To be able to use a variable it needs to be declared. Declaring variables is normally the first thing that happens in any program.How to Declare a VariableJava is a strongly typedprogramming language. This means that every variable must have a data type associated with it. For example, a variable could be declared to use one of the eightprimitive data types: byte, short, int, long, float, double, char or boolean.A good analogy for a variable is to think of a bucket. We can fill it to a certain level, we can replace what's inside it, and sometimes we can add or take something away from it. When we declare a variable to use a data type it's like putting a label on the bucket that says what it can be filled with. Let's say the label for the bucket is "Sand". Once the label is attached, we can only ever add or remove sand from the bucket. Anytime we try and put anything else into it, we will get stopped by the bucket police. In Java, you can think of thecompileras the bucket police. It ensures that programmers declare and use variables properly.To declare a variable in Java, all that is needed is the data type followedby the variable name:int numberOfDays;In the above example, a variable called "numberOfDays" has been declared with a data type of int. Notice how the line ends with a semi-colon. The semi-colon tells theJava compilerthat the declaration is complete.Now that it has been declared, numberOfDays can only ever hold values that match the definition of the data type (i.e., for an int data type the value can only be a whole number between -2,147,483,648 to 2,147,483,647).Declaring variablesfor other data types is exactly the same:byte nextInStream; short hour; long totalNumberOfStars; float reactionTime; double itemPrice; Initializing VariablesBefore a variable can be used it must be given an initial value. This is called initializing the variable. If we try to use a variable without first giving it a value:int numberOfDays; //try and add 10 to the value of numberOfDays numberOfDays = numberOfDays + 10; the compiler will throw an error:variable numberOfDays might not have been initializedTo initialize a variable we use an assignment statement. An assignment statement follows the same pattern as an equation in mathematics (e.g., 2 + 2 = 4). There is a left side of the equation, a right side and an equals sign (i.e., "=") in the middle. To give a variable a value, the left side is the name of the variable and the right side is the value:int numberOfDays; numberOfDays = 7;In the above example, numberOfDays has been declared with a data type of int and has been giving an initial value of 7. We can now add ten to the value of numberOfDays because it has been initialized:int numberOfDays; numberOfDays = 7; numberOfDays = numberOfDays + 10; System.out.println(numberOfDays);Typically, the initializing of a variable is done at the same time as its declaration://declare the variable and give it a value all in one statement int numberOfDays = 7;Choosing Variable NamesThe name given to a variable is known as an identifier. As the term suggests, the way the compiler knows which variables it's dealing with is through the variable's name.There are certain rules for identifiers: reserved wordscannot be used. they cannot start with a digit but digits can be used after the first character (e.g., name1, n2ame are valid). they can start with a letter, an underscore (i.e., "_") or a dollar sign (i.e., "$"). you cannot use other symbols or spaces (e.g., "%","^","&","#").Always give your variables meaningful identifiers. If a variable holds the price of a book, then call it something like "bookPrice". If each variable has a name that makes it clear what it's being used for, it will makefinding errorsin your programs a lot easier.Finally, there arenaming conventionsin Java that I would encourage you to use. You may have noticed that all the examples I have given follow a certain pattern. When more than one word is used in combination in a variable name it is givena capital letter(e.g., reactionTime, numberOfDays.) This is known as mixed case and is the preferred choice for variable identifiersOrganizational chartFrom Wikipedia, the free encyclopedia

Functional Hybrid Organizational Chart Shri Lal Mahal.Anorganizational chart(often calledorganization chart,org chart,organigram(me), ororganogram) is adiagramthat shows thestructureof anorganizationand the relationships and relative ranks of its parts and positions/jobs. The term is also used for similar diagrams, for example ones showing the different elements of a field of knowledge or a group of languages.Contents[hide] 1Overview 2History 3Limitations 4Examples 5See also 6References 7External linksOverview[edit]The organization chart is a diagram showing graphically the relation of one official to another, or others, of a company. It is also used to show the relation of one department to another, or others, or of one function of an organization to another, or others. This chart is valuable in that it enables one to visualize a complete organization, by means of the picture it presents.[1]A company's organizational chart typically illustrates relations between people within an organization. Such relations might include managers to sub-workers, directors to managing directors, chief executive officer to various departments, and so forth. When an organization chart grows too large it can be split into smaller charts for separate departments within the organization. The different types of organization charts include: Hierarchical Matrix Flat(also known asHorizontal)There is no accepted form for making organization charts other than putting the principal official, department or function first, or at the head of the sheet, and the others below, in the order of their rank. The titles of officials and sometimes their names are enclosed in boxes or circles. Lines are generally drawn from one box or circle to another to show the relation of one official or department to the others.[1]History[edit]

Organization Chart of Tabulating Machine Co., 1917The Scottish-American engineerDaniel McCallum(18151878) is credited for creating the first organizational charts of American business[2]around 1854.[3][4]This chart was drawn byGeorge Holt Henshaw.[5]The term "organization chart" came into use in the early twentieth century. In 1914Brinton[6]declared "organization charts are not nearly so widely used as they should be. As organization charts are an excellent example of the division of a total into its components, a number of examples are given here in the hope that the presentation of organization charts in convenient form will lead to their more widespread use." In those years industrial engineers promoted the use of organization charts.In the 1920s a survey revealed that organizational charts were still not common among ordinary business concerns, but they were beginning to find their way into administrative and business enterprises.[7]The term "organigram" originates in the 1960s.[8]Limitations[edit]There are several limitations of organizational charts: If updated manually, organizational charts can very quickly become out-of-date, especially in large organizations that change their staff regularly. They only show "formal relationships" and tell nothing of the pattern of human (social) relationships which develop. They also often do not show horizontal relationships. They provide little information about the managerial style adopted (e.g. "autocratic", "democratic" or an intermediate style) In some cases, anorganigraphmay be more appropriate, particularly if one wants to show non-linear, non-hierarchical relationships in an organization. They often do not include customers. Introduction to Discrete Structures --- Whats and WhysWhat is Discrete Mathematics ?

Discrete mathematics is mathematics that deals with discrete objects. Discrete objects are those which are separated from (not connected to/distinct from) each other. Integers (aka whole numbers), rational numbers (ones that can be expressed as the quotient of two integers), automobiles, houses, people etc. are all discrete objects. On the other hand real numbers which include irrational as well as rational numbers are not discrete. As you know between any two different real numbers there is another real number different from either of them. So they are packed without any gaps and can not be separated from their immediate neighbors. In that sense they are not discrete. In this course we will be concerned with objects such as integers, propositions, sets, relations and functions, which are all discrete. We are going to learn concepts associated with them, their properties, and relationships among them among others.

Why Discrete Mathematics ?

Let us first see why we want to be interested in the formal/theoretical approaches in computer science.Some of the major reasons that we adopt formal approaches are 1) we can handle infinity or large quantity and indefiniteness with them, and 2) results from formal approaches are reusable.

As an example, let us consider a simple problem of investment. Suppose that we invest $1,000 every year with expected return of 10% a year. How much are we going to have after 3 years, 5 years, or 10 years ? The most naive way to find that out would be the brute force calculation.

Let us see what happens to $1,000 invested at the beginning of each year for three years.First let us consider the $1,000 invested at the beginning of the first year. After one year it produces a return of $100. Thus at the beginning of the second year, $1,100, which is equal to $1,000 * ( 1 + 0.1 ), is invested. This $1,100 produces $110 at the end of the second year. Thus at the beginning of the third year we have $1,210, which is equal to $1,000 * ( 1 + 0.1 )( 1 + 0.1 ), or $1,000 * ( 1 + 0.1 )2. After the third year this gives us $1,000 * ( 1 + 0.1 )3.

Similarly we can see that the $1,000 invested at the beginning of the second year produces $1,000 * ( 1 + 0.1 )2at the end of the third year, and the $1,000 invested at the beginning of the third year becomes $1,000 * ( 1 + 0.1 ).

Thus the total principal and return after three years is $1,000 * ( 1 + 0.1 ) + $1,000 * ( 1 + 0.1 )2+ $1,000 * ( 1 + 0.1 )3, which is equal to $3,641.

One can similarly calculate the principal and return for 5 years and for 10 years. It is, however, a long tedious calculation even with calculators. Further, what if you want to know the principal and return for some different returns than 10%, or different periods of time such as 15 years ? You would have to do all these calculations all over again.

We can avoid these tedious calculations considerably by noting the similarities in these problems and solving them in a more general way.Since all these problems ask for the result of invesing a certain amount every year for certain number of years with a certain expected annual return, we use variables, sayA, Randn, to represent the principal newly invested every year, the return ratio, and the number of years invested, respectively. With these symbols, the principal and return afternyears, denoted byS, can be expressed asS=A(1 +R) +A(1 +R)2+ ... +A(1 +R)n.As well known, thisScan be put into a more compact form by first computingS- (1 +R)SasS=A( (1 +R)n + 1- (1 +R) ) /R.Once we have it in this compact form, it is fairly easy to computeSfor different values ofA, Randn, though one still has to compute(1 +R)n + 1.This simple formula represents infinitely many cases involving all different values ofA, Randn.The derivation of this formula, however, involves another problem. When computing the compact form forS, S- (1 +R)S was computed using S=A(1 +R) +A(1 +R)2+ ... +A(1 +R)n.While this argument seems rigorous enough, in fact practically it is a good enough argument, when one wishes to be very rigorous, the ellipsis...in the sum forSis not considered precise. You are expected to interpret it in a certain specific way. But it can be interpreted in a number of different ways. In fact it can mean anything. Thus if one wants to be rigorous, and absolutely sure about the correctness of the formula, one needs some other way of verifying it than using the ellipsis. Since one needs to verify it for infinitely many cases (infinitely many values ofA, Randn), some kind of formal approach, abstracted away from actual numbers, is required.

Suppose now that somehow we have formally verified the formula successfully and we are absolutely sure that it is correct. It is a good idea to write a computer program to compute thatS, especially with(1 +R)n + 1 to be computed. Suppose again that we have written a program to computeS. How can we know that the program is correct ? As we know, there are infinitely many possible input values (that is, values ofA, Randn). Obviously we can not test it for infinitely many cases. Thus we must take some formal approach.

Related to the problem of correctness of computer programs, there is the well known "Halting Problem". This problem, if put into the context of program correctness, asks whether or not a given computer program stops on a given input after a finite amount of time. This problem is known to be unsolvable by computers. That is, no one can write a computer program to answer that question. It is known to be unsolvable. But, how can we tell it is unsolvable ?. How can we tell that such a program can not be written ? You can not try all possible solution methods and see they all fail. You can not think ofall(candidate) methods to solve the Halting Problem. Thus you need some kind of formal approaches here to avoid dealing with a extremely large number (if not infinite) of possibilities.

Discrete mathematics is the foundation for the formal approaches. It discusses languages used in mathematical reasoning, basic concepts, and their properties and relationships among them. Though there is no time to cover them in this course, discrete mathematics is also concerned with techniques to solve certain types of problems such as how to count or enumerate quantities. The kind of counting problems includes: How many routes exist from point A to point B in a computer network ? How much execution time is required to sort a list of integers in increasing order ? What is the probability of winning a lottery ? What is the shortest path from point A to point B in a computer network ? etc.

The subjects covered in this course include propositional logic, predicate logic, sets, relations, and functions, in particular growth of function.

The first subject is logic. It is covered in Chapter 1 of the textbook. It is a language that captures the essence of our reasoning, and correct reasoning must follow the rules of this language. We start with logic of sentences called propositional logic, and study elements of logic, (logical) relationships between propositions, and reasoning. Then we learn a little more powerful logic called predicate logic. It allows us to reason with statements involving variables among others. In Chapter 1 we also study sets, relations between sets, and operations on sets. Just about everything is described based on sets, when rigor is required. It is the basis of every theory in computer science and mathematics. In Chapter 3 we learn mathematical reasoning, in particular recursive definitions and mathematical induction. There are sets, operations and functions that can be defined precisely by recursive definitions. Properties of those recursively defined objects can be established rigorously using proof by induction. Then in Chapter 6 we study relations. They are an abstraction of relations we are familiar with in everyday life such as husband-wife relation, parent-child relation and ownership relation. They are also one of the key concepts in the discussion of many subjects on computer and computation. For example, a database is viewed as a set of relations and database query languages are constructed based on operations on relations and sets. Graphs are also covered briefly here. They are an example of discrete structures and they are one of the most useful models for computer scientists and engineers in solving problems. More in-depth coverage of graph can be found in Chapter 7. Finally back in Chapter 1 we study functions and their asymptotic behaviors. Functions are a special type of relation and basically the same kind of concept as the ones we see in calculus. However, function is one of the most important concepts in the discussion of many subjects on computer and computation such as data structures, database, formal languages and automata, and analysis of algorithms which is briefly covered in Chapter 2.

Before we start the study of discrete structures, we briefly learn general framework of problem solving. If you are a good problem solver, you may skip that and go to logic.Primitive Data TypesThe Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen:int gear = 1;Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition toint, the Java programming language supports seven otherprimitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are: byte: Thebytedata type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). Thebytedata type can be useful for saving memory in largearrays, where the memory savings actually matters. They can also be used in place ofintwhere their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation. short: Theshortdata type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As withbyte, the same guidelines apply: you can use ashortto save memory in large arrays, in situations where the memory savings actually matters. int: By default, theintdata type is a 32-bit signed two's complement integer, which has a minimum value of -231and a maximum value of 231-1. In Java SE 8 and later, you can use theintdata type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to useintdata type as an unsigned integer. See the section The Number Classes for more information. Static methods likecompareUnsigned,divideUnsignedetc have been added to theIntegerclass to support the arithmetic operations for unsigned integers. long: Thelongdata type is a 64-bit two's complement integer. The signed long has a minimum value of -263and a maximum value of 263-1. In Java SE 8 and later, you can use thelongdata type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided byint. TheLongclass also contains methods likecompareUnsigned,divideUnsignedetc to support arithmetic operations for unsigned long. float: Thefloatdata type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in theFloating-Point Types, Formats, and Valuessection of the Java Language Specification. As with the recommendations forbyteandshort, use afloat(instead ofdouble) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use thejava.math.BigDecimalclass instead.Numbers and StringscoversBigDecimaland other useful classes provided by the Java platform. double: Thedoubledata type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in theFloating-Point Types, Formats, and Valuessection of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. boolean: Thebooleandata type has only two possible values:trueandfalse. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined. char: Thechardata type is a single 16-bit Unicode character. It has a minimum value of'\u0000'(or 0) and a maximum value of'\uffff'(or 65,535 inclusive).In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via thejava.lang.Stringclass. Enclosing your character string within double quotes will automatically create a newStringobject; for example,String s = "this is a string";.Stringobjects areimmutable, which means that once created, their values cannot be changed. TheStringclass is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about theStringclass inSimple Data ObjectsDefault ValuesIt's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero ornull, depending on the data type. Relying on such default values, however, is generally considered bad programming style.The following chart summarizes the default values for the above data types.Data TypeDefault Value (for fields)

byte0

short0

int0

long0L

float0.0f

double0.0d

char'\u0000'

String (or any object) null

booleanfalse

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.LiteralsYou may have noticed that thenewkeyword isn't used when initializing a variable of a primitive type. Primitive types are special data types built into the language; they are not objects created from a class. Aliteralis the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type:boolean result = true;char capitalC = 'C';byte b = 100;short s = 10000;int i = 100000;Integer LiteralsAn integer literal is of typelongif it ends with the letterLorl; otherwise it is of typeint. It is recommended that you use the upper case letterLbecause the lower case letterlis hard to distinguish from the digit1.Values of the integral typesbyte,short,int, andlongcan be created fromintliterals. Values of typelongthat exceed the range ofintcan be created fromlongliterals. Integer literals can be expressed by these number systems: Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number system you use every day Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later)For general-purpose programming, the decimal system is likely to be the only number system you'll ever use. However, if you need to use another number system, the following example shows the correct syntax. The prefix0xindicates hexadecimal and0bindicates binary:// The number 26, in decimalint decVal = 26;// The number 26, in hexadecimalint hexVal = 0x1a;// The number 26, in binaryint binVal = 0b11010;Floating-Point LiteralsA floating-point literal is of typefloatif it ends with the letterForf; otherwise its type isdoubleand it can optionally end with the letterDord.The floating point types (floatanddouble) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).double d1 = 123.4;// same value as d1, but in scientific notationdouble d2 = 1.234e2;float f1 = 123.4f;Character and String LiteralsLiterals of typescharandStringmay contain any Unicode (UTF-16) characters. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape" such as'\u0108'(capital C with circumflex), or"S\u00ED Se\u00F1or"(S Seor in Spanish). Always use 'single quotes' forcharliterals and "double quotes" forStringliterals. Unicode escape sequences may be used elsewhere in a program (such as in field names, for example), not just incharorStringliterals.The Java programming language also supports a few special escape sequences forcharandStringliterals:\b(backspace),\t(tab),\n(line feed),\f(form feed),\r(carriage return),\"(double quote),\'(single quote), and\\(backslash).There's also a specialnullliteral that can be used as a value for any reference type.nullmay be assigned to any variable, except variables of primitive types. There's little you can do with anullvalue beyond testing for its presence. Therefore,nullis often used in programs as a marker to indicate that some object is unavailable.Finally, there's also a special kind of literal called aclass literal, formed by taking a type name and appending ".class"; for example,String.class. This refers to the object (of typeClass) that represents the type itself.Using Underscore Characters in Numeric LiteralsIn Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example. to separate groups of digits in numeric literals, which can improve the readability of your code.For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.The following example shows other ways you can use the underscore in numeric literals:long creditCardNumber = 1234_5678_9012_3456L;long socialSecurityNumber = 999_99_9999L;float pi = 3.14_15F;long hexBytes = 0xFF_EC_DE_5E;long hexWords = 0xCAFE_BABE;long maxLong = 0x7fff_ffff_ffff_ffffL;byte nybbles = 0b0010_0101;long bytes = 0b11010010_01101001_10010100_10010010;You can place underscores only between digits; you cannot place underscores in the following places: At the beginning or end of a number Adjacent to a decimal point in a floating point literal Prior to anForLsuffix In positions where a string of digits is expectedThe following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:// Invalid: cannot put underscores// adjacent to a decimal pointfloat pi1 = 3_.1415F;// Invalid: cannot put underscores // adjacent to a decimal pointfloat pi2 = 3._1415F;// Invalid: cannot put underscores // prior to an L suffixlong socialSecurityNumber1 = 999_99_9999_L;

// OK (decimal literal)int x1 = 5_2;// Invalid: cannot put underscores// At the end of a literalint x2 = 52_;// OK (decimal literal)int x3 = 5_______2;

// Invalid: cannot put underscores// in the 0x radix prefixint x4 = 0_x52;// Invalid: cannot put underscores// at the beginning of a numberint x5 = 0x_52;// OK (hexadecimal literal)int x6 = 0x5_2; // Invalid: cannot put underscores// at the end of a numberint x7 = 0x52_;