0% found this document useful (0 votes)
17 views

Chap1 2

Uploaded by

aalshhrany460
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Chap1 2

Uploaded by

aalshhrany460
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

•Computer Science is the study of problems, problem-solving, and the solutions that come out

of this problem-solving process.

•An algorithm is a step-by-step list of instructions to solve the problem.


•An algorithm a step-by-step series of instructions to complete a task
•An algorithm is a set of obvious, logical, and sequential steps that solve a specific problem.

• Programming is the process of encoding your algorithm into a programming language, so that
it can then be executed by a computer.

• who is good at Programming?


The one who good at problem solving.
The one who good at strategy.

• A Computer is not intelligent ( cannot analyze a problem and come up with a solution ) .

To write a program for a computer to follow, we must go through a two-phase process:


1- problem solving phase ‫ﻣرﺣﻠﺔ ﺣل اﻟﻣﺷﻛﻼت‬
• Analysis and Specification ‫\ اﻟﺗﺣﻠﯾل واﻟﻣواﺻﻔﺎت‬
Understand (define) the problem and what the solution must do.(‫)ﻧﻔﮭم اﻟﻣﺷﻛﻠﺔ واﯾش اﻟﺣل اﻟﻲ ﻻزم ﻧﺳوﯾﮫ‬
• General Solution (Algorithm) ‫ اﻟﺣل اﻟﻌﺎم ﻧﻛﺗب اﻟﺧوازﻣﯾﺔ‬/
Specify the required data types and the logical sequences of steps that solve the problem. ‫) ﺣدد‬
( ‫أﻧواع اﻟﺑﯾﺎﻧﺎت اﻟﻣطﻠوﺑﺔ واﻟﺗﺳﻠﺳل اﻟﻣﻧطﻘﻲ ﻟﻠﺧطوات اﻟﺗﻲ ﺗﺣل اﻟﻣﺷﻛﻠﺔ‬
• Verify ‫ ﺗﺣﻘق‬/
Follow the steps exactly to see if the solution really does solve the problem.
‫ﻧﺗﺑﻊ اﻟﺧطوات اﻟﺗﻲ ﺗﺣل اﻟﻣﺷﻛﻠﺔ ﻟﻧرى إذا ﻛﺎن اﻟﺣل ﯾﺣل اﻟﻣﺷﻛﻠﺔ‬

2- implementation phase ‫ﻣرﺣﻠﺔ اﻟﺗﻧﻔﯾذ‬


• Concrete Solution (Program) ‫ اﻟﺣل اﻟﻣﻠﻣوس‬/
Translate the algorithm into a programming language.( ‫) ﻧﺗرﺟم اﻟﺧوارزﻣﯾﺔ إﻟﻰ ﻟﻐﺔ ﺑرﻣﺟﺔ‬

•Test ‫\ اﻻﺧﺗﺑﺎر‬
◦ Have the computer follow the instructions.( ‫) ﻧطﻠب ﻣن اﻟﻛﻣﺑﯾوﺗر اﺗﺑﺎع اﻟﻣﻌﻠوﻣﺎت‬
◦ Then manually check the results. ( ‫) ﺛم ﻧﺗﺣﻘق ﯾدوﯾًﺎ ﻣن اﻟﻧﺗﺎﺋﺞ‬
◦ If you find errors, analyze the program and the algorithm to determine the source of the
errors, and then make corrections.
( ‫) اذا وﺟد أﺧطﺎء ﻓﻘم ﺑﺗﺣﻠﯾل اﻟﺑرﻧﺎﻣﺞ واﻟﺧوارزﻣﯾﺔ ﻟﺗﺣدﯾد ﻣﺻدر اﻷﺧطﺎء ﺛم ﻗم ﺑﺗﺻﺣﯾﺢ اﻷﺧطﺎء‬

• Maintenance ‫ اﻟﺻﯾﺎﻧﺔ‬/
requires modification of the program to meet changing requirements or to correct any
errors that show up while using it.
( ‫) اﻟﺗﻌدﯾل ﻋﻠﻰ اﻟﺑرﻧﺎﻣﺞ ﻟﺗﻠﺑﯾﺔ اﻟﻣﺗطﻠﺑﺎت اﻟﻣﺗﻐﯾرة أو ﻟﺗﺻﺣﯾﺢ أي أﺧطﺎء ﺗظﮭر اﺛﻧﺎء اﻻﺳﺗﺧدام‬
Steps in Program Development

1. Define the problem into three separate components:( ‫ ﻣﻛوﻧﺎت ﻣﻧﻔﺻﻠﺔ‬٣ ‫) ﻧﻌرف اﻟﻣﺷﻛﻠﺔ إﻟﻰ‬
• Inputs‫اﻟﻣدﺧﻼت‬
• Processing steps to produce required outputs. ‫ﺧطوات اﻟﻣﻌﺎﻟﺟﺔ اﻟﺗﻲ ﺗﻌطﻲ اﻟﻧﺗﯾﺟﺔ اﻟﻣطﻠوﺑﺔ‬
• Outputs‫اﻟﻣﺧرﺟﺎت‬

2. Outline the solution.(‫)اﻛﺗب ﻣوﺟز اﻟﺣل‬


• Decompose the problem to smaller steps.‫اﺣﻠل اﻟﻣﺷﻛﻠﺔ إﻟﻰ ﺧطوات اﺻﻐر‬
• Establish a solution outline.‫اﻧﺷﺎء ﻣﺧطط اﻟﺣل‬

3. Develop the outline into an algorithm.( ‫) ﻧﺣول ﻣﺧطط اﻟﺣل إﻟﻰ ﺧوارزﻣﯾﺔ‬

4. Test the algorithm for correctness.( ‫)اﺧﺗﺑﺎر اﻟﺧوارزﻣﯾﺔ‬

5. Code the algorithm into a specific programming language.


( ‫) ﻧﺣول اﻟﺧوارزﻣﯾﺔ إﻟﻰ ﻟﻐﺔ اﻟﺑرﻣﺟﺔ‬

6. Run the program on the computer.(‫) ﻧﺷﻐل اﻟﺑرﻧﺎﻣﺞ ﻋﻠﻰ اﻟﻛوﻣﺑﯾوﺗر‬


• This step uses a program compiler or interpreter, and programmer-designed test data to
machine-test the code .
‫)ھذه اﻟﺧطوات ﺗﺳﺗﺧدم ﻣﺗرﺟم او ﻣﻔﺳر ﯾﺎﺧذ اﻟﻛود وﯾﺣوﻟﮫ إﻟﻰ ﻟﻐﺔ ﯾﻔﮭﻣﮭﺎ اﻟﻛﻣﺑﯾوﺗر‬
(‫ﺑﻌد ذﻟك اﻟﻛﻣﺑﯾوﺗر ﯾﻧﻔذ اﻟﺧوارزﻣﯾﺔ ﺛم ﻣﺻﻣم اﻟﺑرﻧﺎﻣﺞ ﯾﺧﺗﺑر اﻟﺑرﻧﺎﻣﺞ ﺑﺎﺳﺗﺧدام ﺑﯾﺎﻧﺎت اﺧﺗﺑﺎر ﻣﺧﺻﺻﺔ‬

7. Document and maintain the program.( ‫)اﻟﺗوﺛﯾق واﻟﺣﻔﺎظ ﻋﻠﻰ اﻟﺑرﻧﺎﻣﺞ‬

What is an algorithm?
◦ A step-by-step series of instructions in order to perform a specific
task.
An algorithm must:
▪ Be lucid (clear), precise and unambiguous.
▪ Give the correct solution in all cases, and eventually end.
• Flowchart A graphical representation of the sequence of operations in an
information system or program.

Program flowcharts
• show the sequence of instructions in a single program or subroutine.
• shows logic of an algorithm
• emphasizes individual steps and their
interconnection

–Note: Different symbols are used to draw each type of flowchart.

Different symbols are used to draw each type of flowchart:


Relational Operators

Computer programs ( known as software) : are instructions to the computer.


* Programs are written using programming languages.

Programming Languages

Language Machine Language Assembly Language High-Level

Machine language is a set of primitive instructions built into every computer.

* The instructions are in the form of binary code .


* the programs are highly difficult to read and modify.
* For example, to add two numbers, you might write an instruction in binary like this:
1101101010011010
Assembly languages were developed to make programming easy.

* the computer cannot understand assembly language .


* a program called assembler is used to convert assembly language programs into machine code.
* For example, to add two numbers, you might write an instruction in assembly code like this:

ADDF3 R1, R2, R3

The high-level languages are English-like and easy to learn and program.
* For example, the following is a high-level language statement that computes the area of a circle with radius 5:

area = 5 * 5 * 3.1415;
• A program written in a high-level language is called a source program or source code.
• a program tool called an interpreter or a compiler is used to convert a source program
into machine code.

Interpreting Source Code Compiling Source Code

An interpreter reads one statement from A compiler translates the entire source code into
the source code, translates it to the a machine-code file, and the machine-code file is
machine code or virtual machine code, . then executed
.and then executes it right away ‫) ﯾﺗرﺟم اﻟﻣﺗرﺟم ﻛود اﻟﻠﻐﺔ ﻋﺎﻟﯾﺔ اﻟﻣﺳﺗوى ﺑﺎﻟﻛﺎﻣل إﻟﻰ ﻣﻠف ﻛود‬
ً
‫ﺟﻢ ﺳﻄﺮ او ﺟﻤﻠﺔ واﺣﺪا ﻓﻘﻂ ﻣﻦ اﻟﻠﻐﺔ‬BC‫) ;ﻘﺮأ اﻟﻤ‬ ( ‫ ﺛم ﯾﺗم ﺗﻧﻔﯾذ ﻣﻠف ﻛود اﻵﻟﺔ‬، ‫ﻟﻐﺔ اﻵﻟﺔ‬
f‫ ﺛﻢ ﻳﻨﻔﺬە ﻋ‬،‫ﺟﻤﻪ إ] ﻟﻐﺔ اﻻﻟﻪ‬BCZ‫ﺔ اﻟﻤﺴﺘﻮى و‬U‫ﻋﺎﻟ‬
( ‫اﻟﻔﻮر‬

JAVA

* Java enables users to develop and deploy applications on the Internet for servers, desktop
computers, and small hand-held devices.

Java is a general purpose programming language.*

* Java is the Internet programming language.

* Java can be used to


1 - develop standalone applications.
2 - develop applications running from a browser.
3 - develop applications for hand-held devices.
4 - develop applications for Web servers.
Characteristics of Java
1 - Java Is Simple
• Java is partially modeled on C++, but greatly simplified and improved.

‫ﻢ‬H‫) ﺗﻢ ﺗﺼﻤ‬Java ‫ ﻃﺮاز‬O‫ﺎ ﻋ‬Hً‫ ﺟﺰﺋ‬C(gh‫ﻞ ﻛﺒ‬c‫ﺸ‬a ‫ﻄﻬﺎ وﺗﺤﺴ_ﻨﻬﺎ‬H‫ﺴ‬Z‫ﻦ ﺗﻢ ﺗ‬X‫ وﻟ‬، ++

Some people refer to Java as "C++--" because it is like C++ but with more functionality and fewer
negative aspects.

3‫ﺸ(' )ﻌﺾ اﻷﺷﺨﺎص إ‬% )Java" ‫ )ﺎﺳﻢ‬C ‫" ﻷﻧﻬﺎ ;ﺸ<ﻪ‬- ++ C( ‫ﺔ أﻗﻞ‬O‫' وﺟﻮاﻧﺐ ﺳﻠﺒ‬IH ‫ وﻟ@ﻦ ﻣﻊ وﻇﺎﺋﻒ أ‬++

2 - Java Is Object-Oriented
• Object-oriented programming (OOP) is a popular programming approach that is replacing
traditional procedural programming techniques.
• Java was designed from the start to be object-oriented.
• Object- oriented programming provides great flexibility, modularity, clarity, and reusability
through encapsulation, inheritance, and polymorphism.
3 - Java Is Distributed
• Distributed computing involves several computers working together on a network.
• Java is designed to make distributed computing easy.
• Since networking capability is inherently integrated into Java, writing network programs is like
sending and receiving data to and from a file.
4 - Java Is Interpreted
• The programs are compiled into the Java Virtual Machine code called bytecode.
• The bytecode is machine- independent and can run on any machine that has a Java interpreter,
which is part of the Java Virtual Machine (JVM).
5 - Java Is Robust
• Java compilers can detect many problems that would first show up at execution time in other
languages.
• Java has eliminated certain types of error- prone programming constructs found in other
languages.
• Java has a runtime exception-handling feature to provide programming support for robustness.
6 - Java Is Secure
• Java implements several security mechanisms to protect your system against harm caused by
stray programs.
7 - Java Is Architecture-Neutral
• Write once, run anywhere
• With a Java Virtual Machine (JVM), you can write one program that will run on any platform.
8 - Java Is Portable
• They can be run on any platform without being recompiled.
9 - Java's Performance
• They can be run on any platform without being recompiled.
10 - Java Is Multithreaded
11 - Java Is Dynamic
• Java was designed to adapt to an evolving environment.
JDK Editions \ ( ‫) ﺣزم ﺗطوﯾر ااﻟﺟﺎﻓﺎ‬

* Java Standard Edition (J2SE) ‫ھذا اﻟﻲ ﻧﺳﺗﻌﻣﻠﮫ‬


– J2SE can be used to develop client-side standalone
applications or applets.
* Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications such as Java servlets, Java ServerPages,
and Java ServerFaces.
* Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.

Popular Java IDEs


• NetBeans
• Eclipse

* An IDE is a software application that provides computer programmers a suitable environment


for software development
* An IDE is Stands for “Integrated Development Environment”

Anatomy of a Java Program


Class name
• Every Java program must have at least one class , Each class has a name.
• class names start with an uppercase letter. ‫ﻻزززم اﺳم اﻟﻛﻼس ﯾﺑدا ﺑﺣرف ﻛﺎﺑﺗﯾل‬
Main method
• the class must contain a method named main.
• The program is executed from the main method.
Statements
• A statement represents an action or a sequence of actions.
Statement terminator
• Every statement in Java ends with a semicolon (;).
Reserved words
• words that have a specific meaning to the compiler and cannot be used for other purposes in
the program.
Comments
• Three types of comments in Java :
1. Line comment: A line comment is preceded by two slashes (//) in a line.
2. Paragraph comment: A paragraph comment is enclosed between /* and */ in one or multiple
lines.
3. javadoc comment: javadoc comments begin with /** and end with */. They are used for
documenting classes, data, and methods.
* They can be extracted into an HTML file using JDK's javadoc command.
Blocks
• A pair of braces in a program forms a block that groups components of a program.
Programming Style and Documentation

Appropriate Comments
1 - Include a summary at the beginning of the program to explain what the program does, its
key features, its supporting data structures, and any unique techniques it uses.
‫ وأي ﺗﻘﻧﯾﺎت‬، ‫ وھﯾﺎﻛل اﻟﺑﯾﺎﻧﺎت اﻟداﻋﻣﺔ‬، ‫ وﻣﯾزاﺗﮫ اﻟرﺋﯾﺳﯾﺔ‬، ‫) ﻗم ﺑﺗﺿﻣﯾن ﻣﻠﺧص ﻓﻲ ﺑداﯾﺔ اﻟﺑرﻧﺎﻣﺞ ﻟﺷرح ﻣﺎ ﯾﻔﻌﻠﮫ اﻟﺑرﻧﺎﻣﺞ‬
( ‫ﻓرﯾدة ﯾﺳﺗﺧدﻣﮭﺎ‬
2 - Include your name, class section, instructor, date, and a brief description at the beginning of
the program.

Naming Conventions
1 - Choose meaningful and descriptive names.
2 - Class names:
– Capitalize the first letter of each word in the name.
For example, the class name ComputeExpression.

Proper Indentation and Spacing Lines


1 - Indentation
– Indent using a tab ( ‫) ﻣﺳﺎﻓﺔ ﺑﺎدﺋﺔ ﺑﺎﺳﺗﺧدام ﻋﻼﻣﺔ ﺗﺎب‬
– Or with three to five spaces.
2 – Spacing
– Use blank line to separate segments of the code.

Block Styles ( ‫) ﺷﻛﻠﯾن ﻟﮫ‬


• Next-line style
• End-of-line style

Special Symbols
Programming Errors
• Syntax Error

• Runtime Errors
– Causes the program to terminate in an
abnormal way
– Known as “crashing” or “my program crashed”
– Often caused by input mistakes, where the user enters a value the program cannot handle
– Another example: divide by zero

! Logic Errors
– Produces incorrect result
– Program does not run the way we intended
– Usually the result of logical mistakes
– In fact, the program “works”, but the output is wrong due to our logical mistake.
– These errors are harder to detect.

! Common Errors

– Missing a semicolon
– Missing a closing brace, missing a semicolon, missing quotation marks for strings, and
misspelling names are common errors for new programmers.
– Misspelling Names:
– – main is misspelled as Main
– String is misspelled as string
! Identifiers are the names that identify elements of your program, such as classes, methods, and
variables.
! An identifier is a sequence of characters that consist of letters, digits, underscores (_), and
dollar signs ($). ( ($)‫( و‬-) ‫) اﻟﻣﻌرف ﻣﻣﻛن ﯾﺣﺗوي ﻋﻠﻰ ﺣروف وأرﻗﺎم و‬
! An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with
a digit. ( ‫( وﻻ ﯾﻣﻛن ان ﯾﺑدا ﺑرﻗم‬$) ‫( او‬-) ‫) ﻻزم ﯾﺑدا ﺑﺣرف او‬
An identifier cannot be a reserved word ( ‫ ) ﻻﯾﻣﻛن ان ﯾﺣﺗوي اﻟﻣﻌرف ﻋﻠﻰ ﻛﻠﻣﺎت ﻣﺣﺟوزة‬and cannot be
true, false, or null.
! An identifier can be of any length.
! Examples of legal identifiers:
area, radius, ComputeArea, $2, average
! Examples of illegal identifiers( syntax error):
2A and d+4
! Note: Java is case sensitive
area, Area, and AREA all are different identifiers

Java Numerical Data Types


! Every data type has a range of possible values that it can have/hold
! Java provides eight primitive data types
Name Range Storage Size

7 7
byte –2 to 2 – 1 (-128 to 127) 8-bit signed
15 15
short –2 to 2 – 1 (-32768 to 32767) 16-bit signed

int –231 to 231 – 1 (-2147483648 to 2147483647) 32-bit signed

long –263 to 263 – 1 64-bit signed


(i.e., -9223372036854775808 to 9223372036854775807)

float Negative range: 32-bit IEEE 754


-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to -4.9E-324

Positive range:
4.9E-324 to 1.7976931348623157E+308

! Examples

largest value you can save into an integer data

This will not work (Solution: use a different data type) .


.

! Java uses four data types for integers:


byte, short, int, long (Choose the type that is most appropriate for your variable)
! Normal usage:
– int is normally used for integers
– double is normally used for real numbers

Number Literals

A literal is a constant value that appears directly in the program.


• int i = 34;
• long x = 1000000;
• double d = 5.0;

1 -Integer Literals
! An integer literal is assumed to be of the int type.
! To denote an integer literal of the long type, append it with the letter L or l.
‫ﯾﻔﺿل اﺳﺗﺧدام ﺣرف ال) ( اﻟﻛﺎﺑﯾﺗل ﻋﺷﺎن ﻣﺎن ﻧﻠﺧﺑط ﺑﯾن ال ) ( اﻟﺳﻣول ورﻗم واﺣد‬

2- Floating-Point Literals
! Floating-point literals are written with a decimal point.
! By default, a floating-point literal is treated as a double type value
For example, 5.0 is considered a double value, not a float value.
! You can make a number a float by appending the letter f or F, and make a number a double by
appending the letter d or D.

The double type values are more accurate than the float type values.

Declaring Variables

! Variables are used to represent values that may be changed in the program.

Syntax for declaring a variable:


datatype variableName;

! If variables are of the dame data type, they can be declared together:
datatype var1, var2, var3,…, varn;
Example:
int i, j, k;

! You can also use shorthand form to declare and initialize variables of the same type together:
Example:
int i = 62, j = 78, k = 35;

! A variable represents a value stored in the computer’s memory


Assignment Statements
assigning a value give tha variable a value.
! The equal sign (=) is used as the assignment operator.
! The syntax for assignment statement is as follows:
variable = value;
or
variable = expression ‫; ﺷرط‬

! If a value is assigned to multiple variables, you can use this syntax:


i = j = k = 5;
! This is equivalent to:
k = 5;
j = k;
i = j;

! You can also use the same variable on both sides of the assignment statement
! Example:
‫ھﺬا‬x = x + 1; ‫ ﻧﻔﺲ ھﺬا‬a++; ‫ او‬++a;
a+=1; ‫ﻧﻔﺲ ذي‬

! The variable’s data type is the kind of data that you can store in that particular variable.
1 public class ComputeArea {
2 public static void main(String[] args) {
3 double radius;
4 double area;
5
6 // Assign a radius
7 radius = 20;
8
9 // Compute area
10 area = radius * radius * 3.14159;
11
12 // Display results
13 System.out.println("The area for the circle of radius " +
14 radius + " is " + area);
15 }
16 }

-The following table shows the value in memory for the variables area and radius
as the program is executed.

-This method of reviewing a program is called “tracing a program”.

The plus sign (+) has two meanings in Java:


" Addition
" Concatenation (combining two strings together)
The plus sign (+) in lines 13-14 is called a string concatenation operator.
" It combines two strings into one string.
" If a string is concatenated with a number, the number is converted into a string and then
concatenated with the other string.
• In Java, a string cannot be written across multiple lines in the source code.
• The following statement would result in a compile error:

System.out.println(“Introduction to Java Programming, by


Y. Daniel Liang”);

• To fix the error, break the string into separate substrings and use
concatenation (+) to combine:

System.out.println(“Introduction to Java Programming, ” +


“ by Y. Daniel Liang”);

Reading Input from the Console


! Java uses the Scanner class for console input
– System.out refers to the standout output device
" By default, standard output is the monitor
– System.in refers to the standard input device
" By default, standard input is the keyboard

! so how do you read from the keyboard?


Example:

Scanner input = new Scanner(System.in);


int value = input.nextInt();

Method Description

nextByte() reads an integer of the byte type.


nextShort() reads an integer of the short type.
nextInt() reads an integer of the int type.
nextLong() reads an integer of the long type.
nextFloat() reads a number of the float type.
nextDouble() reads a number of the double type.

! Before you can use the Scanner class, you must import it!
! The Scanner class is in the java.util package.
! Notice that we do this import before we start coding our actual class.
– There are two types of import statements:
" Specific import: specifies a single class that should be imported
– Example:
import java.util.Scanner;
" Wildcard import: imports all the classes in a package by using the asterisk as the wildcard.
– Example:
import java.util.*;

! A named constant is an identifier that represents a permanent value.


! a named constant, or simply constant, represents a permanent data that never changes.

final datatype CONSTANTNAME = value;


Example:
final double PI = 3.14159;
final int SIZE = 15;

! the benefits of using constants?


! You don’t have to repeatedly type the same value if it is used multiple times
! If you have to change the value, you only need to change it in a single location in the
code ( Instead of changing it at all locations )

Naming Conventions

! Choose meaningful and descriptive names.


– Do not use abbreviations ‫ﻻ ﺗﺴﺘﺨﺪم اﺧﺘﺼﺎرات‬

! Variables and method names:


– Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and
capitalize the first letter of each subsequent word in the name.
– For example, the variables radius and area, and the method computeArea.

! Class names:
– Capitalize the first letter of each word in the name.
– For example, the class name ComputeArea.
! Constants:
– Capitalize all letters in constants, and use underscores to connect words.
– For example, the constants PI and MAX_VALUE
Numeric Operators
Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

What is integer division?


- “Normal” division: 7 / 2 = 3.5
- In Computer Science , When both operands of a division are integers, we will use integer
division.
" 5/2=2
" 7/2=3
" 15 / 2 = 7

Remainder Operator
The % operator is known as the remainder operator, or also as the modulo operator
" 7%3=1
" 12 % 4 = 0
" 20 % 13 = 7
" an even number % 2 is always 0
" An odd number % 2 is always 1

Example:
" If today is Saturday, it will be Saturday again in 7 days. Suppose you and your friends
will meet in 10 days. What day is it in 10 days?
" Let us assume Sunday is the 1st day of the week.
" We can find that in 10 days, the day will be Tuesday by using the following equation:
Saturday is the 7th day in a week
A week has 7 days
(7 + 10) % 7 is 3
The 3rd day in a week is Tuesday
After 10 days
! Calculations involving floating-point numbers are approximated because these numbers are not stored
with complete accuracy.
! For example:

System.out.println(1.0-0.1-0.1-0.1-0.1-0.1);

displays 0.5000000000000001, not 0.5, and

‫اﻟﺠﻮاب ﻏﯿﺮ اﻟﺪﻗﯿﻖ اﻟﻲ ﯾﻌﺮﺿﮫ اﻟﺠﺎﻓﺎ‬ ‫اﻟﺠﻮاب اﻟﺪﻗﯿﻖ‬

" Integers are stored precisely.( ‫) ﺑﺪﻗﺔ‬

Exponent Operations

System.out.println(Math.pow(2, 3));
// Displays 8.0 ‫اﻟﻨﺎﺗﺞ ﯾﻜﻮن رﻗﻢ دﺑﻞ‬

Arithmetic Expressions
! Java expressions are written the same way as normal arithmetic expressions.
! Example:

3 + 4 x 10( y - 5)(a + b + c) 4 9+ x
- + 9( + )
5 x x y

is translated into
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
Augmented Assignment Operat

! we use the current value of a variable, we modify it, and then save it back to the same
variable.
Example:
count = count + 1;

" Java allows you to combine this addition and assignment into one operator, which is called the
augmented assignment operator.
Example:
count += 1;

! The augmented assignment operator is performed last after all the other operators in the
expression are evaluate
Example:
x /= 4 + 5.5 * 1.5;
is same as
x = x / (4 + 5.5 * 1.5);

Caution : + = should be += (with no space)


Increment and Decrement Operators
! Java gives you special increment and decrement operators (by one)
• Increment operator: ++
• Decrement operator: --

§ Examples:
int i = 3, j = 3;
i++; // i becomes 4
j--; // j becomes 2

§ Examples:
int i = 3, j = 3;
++i; // i becomes 4
--j; // j becomes 2

If the statement is ONLY doing increment or decrement, the effect of j++ and ++j is the same.

in other types of statements :


§ ++i: the increment is done before evaluating an expression
§ i++: the increment is done after evaluated an expression
§ Examples:

! Another example:
– Consider the following code:
double x = 1.0;
double y = 5.0;
double z = x-- + (++y);

– What is the value of x, y, and z after are three lines are executed?
" x becomes 0.0
" y becomes 6.0
" z becomes 7.0

Avoid using these operators in expressions that modify multiple variables, or the same variable
for multiple times such as this:
int k = ++i + i;
Numeric Type Conversions

" If you add an integer with a floating-point number, Java automatically coverts the int to a
floating point value.

Example:
" 3 * 4.5 is the same as
" 3.0 * 4.5

Example:
" You can save an int into a double, because the double is much wider (larger) than the int
int x = 4;
double y;
y = x; //y =4,0
" This is allowed, because x can easily “fit” into y.

you cannot assign a value to a variable of a data type with a smaller range of values.
§ Unless you use type casting

Casting is an operation that coverts a value of one data type into a value of another data type

" Casting a type with a small range to a type with a larger range
is known as “widening a type”
" Casting a type with a large range to a type from a smaller range
is known as “narrowing a type”

Java will automatically widen a type, but you must request a narrowing explicitly

! Casting:
– Example:
System.out.println((double)1/2);
" 0.5 gets printed.
" Why? Because 1 is cast into 1.0. Then 1.0 is divided by 2.
– Example:
System.out.println(1 / 2);
" Be careful!
" Here, 0 (zero) gets printed. Why? 1 and 2 are both inters and the result should be an integer.

Implicit casting range increases


double d = 3; // (type widening) byte, short, int, long, float, double
Explicit casting
int i = (int)3.0; // (type narrowing)
int i = (int)3.9; // (Fraction part is truncated)
Conversion Rules

1. If one of the operands is double, the other is converted into double.


2. Otherwise, if one of the operands is float, the other is converted into float.
3. Otherwise, if one of the operands is long, the other is converted into long.
4. Otherwise, both operands are converted into int.

int sum = 0;
sum += 4.5; // sum becomes 4 after this statement

This is equivalent to:


" sum = (int)(sum + 4.5);

Common Errors and Pitfalls


! Common Error # 1: Undeclared/Uninitialized Variables and Unused Variables
– a variable must be declared and a value assigned to it before you use it.
– Common errors include not declaring or not initializing a variable

" Common Error #2: Integer Overflow


– Remember: numbers are stored with a limited number of digits
– If you try to save a value that is too large for a variable, an overflow error will occur
– Example:
! int value = 2147483647; // allowed
– but this number is the biggest possible int, therefore…
! value++; // will result in an error

! Common Error #3: Round-off Errors


! Example:
– System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
– The output should be 0.5, but the output is really 0.5000000000000001
– System.out.println(1.0 - 0.9);
– The output should be 0.1, but the output is really 0.09999999999999998

" Common Error #4: Unintended Integer Division


if both operands are integers, Java will automatically use integer division
" Common Pitfall #1: Repeated Input Objects
– New programmers often make many Scanner objects each time they want input
! This is a mistake!
– See the code below:

– The correct code is below:

You might also like