You are on page 1of 25

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.
parameters is 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 the add() message in the following
statement.
getContentPane().add(button);

Statement Blocks
In Java, any sequence of statements can be grouped together to function as a single statement by
enclosing the sequence in braces. These groupings are called statement 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 Statements
Normally, 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 Selection
If Statements
If-Else Statements
Switch Statements
Extended If-Else Statements

conditional execution of a single statement


conditional selection among two statements
conditional selection among several statements
conditional selection among several statements

Repetition
While Loops
For Loops
Do-While Loops

Special Control Statements

pretest loops
pretest loops
posttest loops

Return Statements
Continue Statements
Break Statements

- return values from and terminate methods


- skip the remaining statements in an iteration of a loop
- exit a loop or switch statement

Conditional Execution and Selection


Java 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 Statements

The if statement has the following form.


if (boolean-expression) {
then-clause
}

Here,
boolean-expression is an expression that can be true or false.
then-clause is a sequence of statements. If there is only one statement in the sequence then
the surrounding braces may be omitted. The then-clause statements are executed only if
the boolean-expression is true.
If-Else Statements

The if-else statement has the following form.


if (boolean-expression) {
then-clause
} else {
else-clause
}

Here,
boolean-expression is an expression that can be true or false.
then-clause and else-clause are sequences of statements. If there is only one statement in a
sequence then the surrounding braces may be omitted. The then-clause statements are
executed only if the boolean-expression is true. The else-clause statements are executed if
the boolean-expression is false.
Switch Statements

The 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-expression is an expression of a simple type, such as int, char, or an enum type. It
cannot have float or double type.
constant-expression-1 through constant-expression-n are expressions of a type that converts
to the type of control-expression. The compiler must be able to evaluate these expressions to
constant values.
statements-1 through statements-n are sequences of statements.
When the switch statement is executed, control-expression is evaluated. The resulting value is
compared to the values of constant-expression-1 through constant-expression-n in order until a
matching value is found. If a match is found in constant-expression-i then statementsi through statements-n and default-statements are 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 the default-statements are executed whenever the
value of control-expression does not match any of the constant-expression-i values.
Extended If-Else Statements

Often, a programmer needs a construction that works like a switch 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 an extended 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-1 through boolean-expression-n are expressions that can be true or false.
statements-1 through statements-n and default-statements are 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 the default-statements are executed. In either case, execution
continues with the next statement after the extended if-else statement.
Repetition
Java 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 an iteration of 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 Loops

The while loop is a pretest loop statement. It has the following form.
while (boolean-expression) {
nested-statements
}

Here,
boolean-expression is an expression that can be true or false.
nested-statements is a sequence of statements. If there is only one statement then the braces
can be omitted.
The boolean expression is tested before each iteration of the loop. The loop terminates when it is
false.
For Loops

The for loop is a pretest loop statement. It has the following form.
for (initialization; boolean-expression; increment) {
nested-statements
}

Here,
initialization is an expression (usually an assignment expression).
boolean-expression is an expression that can be true or false.
increment is an expression.
nested-statements is 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 tested before each 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 Loops

The do-while loop is a post-test loop statement. It has the following form.
do {
nested-statements
} while (boolean-expression);

Here,
nested-statements is a sequence of statements. If there is only one statement then the braces
may be omitted.
boolean-expression is an expression that can be true or false.
The boolean expression is tested after each iteration of the loop. The loop terminates when it is
false.
Special Control Statements
Return Statements

The 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 type void use the following form.
return;

Methods with non-void returned type use the following form.


return expression;

Here,
expression is an expression that yields the desired return value. This value must be
convertible to the return type declared for the method.
Continue Statements

The 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 Statements

The 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
that sometimes are quite tempting to use, and
in future revisions of the standard. However,
extensions, your program might not compile on
some rewriting, and so might be less useful.

LANGUAGE EXTENSIONS,
may even be included
if you use language
other machines without

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 Literals


The constants refer to fixed values that the program may not alter during its execution. These fixed values are also
called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant,
or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their
definition.

Integer literals
An 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
215u
0xFeeL
078
032UU

/* Legal */
/* Legal */
/* Legal */
/* Illegal: 8 is not an octal digit */
/* Illegal: cannot repeat a suffix */

Following are other examples of various type of Integer literals:


85

/* decimal */

0213

/* octal */

0x4b

/* hexadecimal */

30
30u
30l
30ul

/* int */
/* unsigned int */
/* long */
/* unsigned long */

Floating-point literals
A 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 constants
Character literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable of char type.
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
sequence

Meaning

\\

\ character

\'

' character

\"

" character

\?

? character

\a

Alert or bell

\b

Backspace

\f

Form feed

\n

Newline

\r

Carriage return

\t

Horizontal tab

\v

Vertical tab

\ooo

Octal 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 <stdio.h>

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

return 0;
}

When the above code is compiled and executed, it produces the following result:
Hello World

String literals
String 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 Constants
There are two simple ways in C to define constants:
1. Using #define preprocessor.
2. Using const keyword.

The #define Preprocessor


Following is the form to use #define preprocessor to define a constant:
#define identifier value

Following example explains it in detail:


#include <stdio.h>

#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 : 50

The const Keyword


You can use const prefix to declare constants with a specific type as follows:
const type variable = value;

Following example explains it in detail:


#include <stdio.h>

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 Variable

Java 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 eight primitive 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 the compiler as 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 followed by 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 the Java compiler that 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 variables for other data types is exactly the same:
byte nextInStream; short hour; long totalNumberOfStars; float
reactionTime; double itemPrice;

Initializing Variables
Before 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 initialized
To 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 Names


The 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 words cannot 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 make finding errors in your programs a lot easier.
Finally, there are naming conventions in 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 given a capital letter (e.g., reactionTime, numberOfDays.) This
is known as mixed case and is the preferred choice for variable identifiers

Organizational chart
From Wikipedia, the free encyclopedia

Functional Hybrid Organizational Chart Shri Lal Mahal.

An organizational chart (often called organization chart, org chart, organigram(me), or organogram) is
a diagram that shows thestructure of an organization and 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]

1 Overview

2 History

3 Limitations

4 Examples

5 See also

6 References

7 External links

Overview[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 as Horizontal)

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., 1917

The Scottish-American engineer Daniel McCallum (18151878) is credited for creating the first organizational charts
of American business[2] around 1854.[3][4] This chart was drawn by George Holt Henshaw.[5]
The term "organization chart" came into use in the early twentieth century. In 1914 Brinton[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, an organigraph may be more appropriate, particularly if one wants to show non-linear, nonhierarchical relationships in an organization.

They often do not include customers.

Introduction to Discrete Structures --- Whats and Whys

What 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 )2 at 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, say A, R and n, 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 after n years, denoted by S, can be
expressed as
S = A(1 + R) + A(1 + R)2 + ... + A(1 + R)n .
As well known, this S can be put into a more compact form by first
computing S - (1 + R)S as
S = A ( (1 + R)n + 1 - (1 + R) ) / R .
Once we have it in this compact form, it is fairly easy to compute S for different
values of A, R and n, though one still has to compute (1 + R)n + 1 . This simple
formula represents infinitely many cases involving all different values of A,
R and n. The derivation of this formula, however, involves another problem.
When computing the compact form for S, 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 for S is 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 of A,
R and n), 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 that S, especially with (1 + R)n + 1 to be
computed. Suppose again that we have written a program to compute S. How
can we know that the program is correct ? As we know, there are infinitely
many possible input values (that is, values of A, R and n). 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
of all (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 Types


The 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 to int, the Java
programming language supports seven other primitive 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: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum
value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory
savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that
a variable's range is limited can serve as a form of documentation.

short: The short data 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 with byte, the same guidelines apply: you can use a short to save memory
in large arrays, in situations where the memory savings actually matters.

int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -2 31 and a
maximum value of 231-1. In Java SE 8 and later, you can use the int data 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 use int data type as an
unsigned integer. See the section The Number Classes for more information. Static methods
like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic
operations for unsigned integers.

long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -2 63 and a
maximum value of 263-1. In Java SE 8 and later, you can use thelong data 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 by int. The Long class also contains methods
like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.

float: The float data 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 the Floating-Point Types, Formats, and Values section of the Java Language
Specification. As with the recommendations for byte and short, use a float (instead of double) 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 the java.math.BigDecimal class instead.Numbers and
Strings covers BigDecimal and other useful classes provided by the Java platform.

double: The double data 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 the Floating-Point Types, Formats, and Values section 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: The boolean data type has only two possible values: true and false. 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: The char data 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 the java.lang.String class. Enclosing your character string within double quotes will automatically create a
new String object; for example, Strings="thisisastring";. String objects are immutable, which means
that once created, their values cannot be changed. The String class 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
the String class in Simple Data Objects

Default Values
It'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 or null, 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 Type

Default Value (for fields)

byte

short

int

long

0L

float

0.0f

double

0.0d

char

'\u0000'

String (or any object)

null

boolean

false

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.

Literals
You may have noticed that the new keyword 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. A literal is 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 Literals
An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the
upper case letter L because the lower case letter l is hard to distinguish from the digit 1.
Values of the integral types byte, short, int, and long can be created from int literals. Values of type long that exceed
the range of int can be created from long literals. 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 prefix 0x indicates hexadecimal
and 0b indicates binary:

// The number 26, in decimal


int decVal = 26;
// The number 26, in hexadecimal
int hexVal = 0x1a;
// The number 26, in binary
int binVal = 0b11010;

Floating-Point Literals
A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with
the letter D or d.
The floating point types (float and double) 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 notation
double d2 = 1.234e2;

float f1

= 123.4f;

Character and String Literals


Literals of types char and String may 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\u00EDSe\u00F1or" (S Seor in Spanish). Always use 'single quotes' for char literals and "double
quotes" forString literals. Unicode escape sequences may be used elsewhere in a program (such as in field names, for
example), not just in char or String literals.
The Java programming language also supports a few special escape sequences
for char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \"(double
quote), \' (single quote), and \\ (backslash).
There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable,
except variables of primitive types. There's little you can do with a null value beyond testing for its presence.
Therefore, null is often used in programs as a marker to indicate that some object is unavailable.
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending " .class"; for
example, String.class. This refers to the object (of type Class) that represents the type itself.

Using Underscore Characters in Numeric Literals


In 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 an F or L suffix

In positions where a string of digits is expected

The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:

// Invalid: cannot put underscores

// adjacent to a decimal point


float pi1 = 3_.1415F;
// Invalid: cannot put underscores
// adjacent to a decimal point
float pi2 = 3._1415F;
// Invalid: cannot put underscores
// prior to an L suffix
long socialSecurityNumber1 = 999_99_9999_L;
// OK (decimal literal)
int x1 = 5_2;
// Invalid: cannot put underscores
// At the end of a literal
int x2 = 52_;
// OK (decimal literal)
int x3 = 5_______2;
// Invalid: cannot put underscores
// in the 0x radix prefix
int x4 = 0_x52;
// Invalid: cannot put underscores
// at the beginning of a number
int x5 = 0x_52;
// OK (hexadecimal literal)
int x6 = 0x5_2;
// Invalid: cannot put underscores
// at the end of a number
int x7 = 0x52_;

You might also like