CS111: PROGRAMMING LANGUAGE II - WordPress.com · · 2015-08-22Why programming?? ......
Transcript of CS111: PROGRAMMING LANGUAGE II - WordPress.com · · 2015-08-22Why programming?? ......
Lecture Contents
Dr. Amal Khalifa, 2014
Course info
Why programming??
Why Java ??
Write once, run anywhere!!
Java basics
Input/output
Variables
Expressions
Conditions
Loops
Methods
Arrays
2
Course info
Dr. Amal Khalifa, 2014
Website
http://cs111spr14.wordpress.com/
Book
Course plan
Assessment methods and grading
Labs and practical assignments
The term Project
3
Quiz!!!!
What is a program? (instructions)
What is a programming language? (syntax/rules)
What is a Software Package? (application domain)
4
Dr. Amal Khalifa, 2014
Why Programming?? 5
Programming Enables you to make a computer do
anything you want.
First challenge. Learn a programming language.
Next question. Which one?
Dr. Amal Khalifa, 2014
Why Java??
It’s not about the language!
Develop general programming skills applicable to
many languages
Javatar!!
6
Dr. Amal Khalifa, 2014
Why Java?
Clarity - Keep it Simple
Relatively easy graphics
and GUI programming
Lots of library packages
Full documentation
http://java.sun.com
Colleges are teaching it
Companies are using it
Students want it
Teachers welcome it... ;)
Programmers drink it... :)
Free compiler and IDEs
7
Dr. Amal Khalifa, 2014
Java == class
Everything must be in a class. There are no
global functions or global data.
What about main??
8
Dr. Amal Khalifa, 2014
The Code life Cycle!!
Edit compile run
10
Dr. Amal Khalifa, 2014
Your first Java program.. 12
// indicates a
comment.
class keyword
Java is case
sensitive
braces { , }
delimit a
class body
main Method
Dr. Amal Khalifa, 2014
“Everything must be in a class”
There are no global functions or global data.
Text I/O
Standard output.
Flexible OS abstraction for output.
In Java, applications use the standard output object
(System.out) to display text on terminal.
Dr. Amal Khalifa, 2014
14
Command line output 15
Multiple line
O/P
Formatting
output
public class TestIO {
public static void main(String[] args)
{
System.out.println(“Welcome to java”);
System.out.println(“Welcome to \n java”);
System.out.print(“Welcome to”);
System.out.println(“java”);
System.out.printf(“%s\n%s\n“, “Welcome
to”,”java”);
}
}
}
Dr. Amal Khalifa, 2014
Strings & Text
String msg1 = new String( “Hello” );
String msg2 = “Hello” ;
String msg3 = “Year “ + 2005; //valid??
18
Dr. Amal Khalifa, 2014
Standard Input
input is received from Terminal window.
Input entered while program is executing.
Dr. Amal Khalifa, 2014
19
Reading values
Dr. Amal Khalifa, 2014
use : import java.util.Scanner;
Define an object of the Scanner class:
Scanner input = new Scanner(System.in);
input values:
num1 = input.nextInt();
Display after calculation:
System.out.printf(“the square is : %d
\n”, num1*num1);
20
variables
Declaration, memory allocation, initialization
int total = 0;
int count, temp, result;
Multiple variables can be created in one declaration
data type variable name
Dr. Amal Khalifa, 2014
23
Constants
Dr. Amal Khalifa, 2014
A “constant variable” is an identifier that is similar to a
variable except that it holds one value for its entire existence
Why constants:
give names to otherwise unclear literal values
facilitate changes to the code
prevent inadvertent errors
In Java:
final double PI = 3.14159265;
24
Arithmetic Expressions
An expression is a combination of operators and operands
Arithmetic expressions (we will see logical expressions later)
are essentially special methods applied to numerical data
objects: compute numeric results and make use of the arithmetic
operators:
Addition +
Subtraction -
Multiplication *
Division /
Remainder %
Dr. Amal Khalifa, 2014
25
Assignment-related Operators
Increment and decrement operators: ++, --
Assignment operators: +=, -=, *=, /=
count = count + 1;
count += 1;
count ++;
count = count - 10;
count -= 10;
these three expressions have the same effect
these two expressions have the same effect
Dr. Amal Khalifa, 2014
26
Operator Precedence
What is the order of evaluation in the following expressions?
a + b + c + d + e
4 3 2
a + b * c - d / e
3 2 4 1
a / (b + c) - d % e
2 3 4 1
a / (b * (c + (d - e)))
4 1 2 3
1
Dr. Amal Khalifa, 2014
27
How Do Data Conversions Happen?
Implicitly:
occurs automatically
uses widening conversion,
Examples: 4.0 / 8 (which / is it: double/double, float/float, int/int)
4 / 8.0 (which / is it: double/double, float/float, int/int)
4 + 5 / 9 + 1.0 + 5 / 9 / 10.0 (what is the value?)
Dr. Amal Khalifa, 2014
28
How Do Data Conversions Happen?
Dr. Amal Khalifa, 2014
29
Explicitly: Casting
widening / narrowing conversions
Examples: double MyResult;
MyResult = 12.0 / 5.0; //OK
int myInt = (int) MyResult; // truncation
MyResult = (double)myInt/3.0;
Be careful!!
Example: in 1996, Ariane 5 rocket exploded after
takeoff because of bad type conversion.
Dr. Amal Khalifa, 2014
30
Class Math
All Math class methods are static
Each is called by preceding the name of the method with the class name Math and the dot (.) separator
Method arguments may be constants, variables or expressions
Dr. Amal Khalifa, 2014
31
Example
Solve quadratic equation ax2 + bx + c = 0.
public class Quadratic {
public static void main(String[] args) {
double a,b,c,d;
// input coefficient values..
// calculate roots
d = Math.sqrt(b*b - 4.0*a*c);
double root1 = (-b + d) / (2.0*a);
double root2 = (-b - d) / (2.0*a);
// print them out
System.out.println(root1);
System.out.println(root2);
}
}
Dr. Amal Khalifa, 2014
33
Conditional Statements
A conditional statement lets us choose which
statement will be executed next
Conditional statements give us the power to make
basic decisions
Java's conditional statements:
the if and if-else statements
the conditional operator
the switch statement
Dr. Amal Khalifa, 2014
36
The if Statement
The if statement has the following syntax:
if is a Java
reserved word
The condition must be a boolean expression.
e.g., a boolean variable, a == b, a <= b.
It must evaluate to either true or false.
If the condition is true,
this statement is executed.
if ( condition )
statement1;
else
statement2;
If the condition is false,
this statement is executed. Dr. Amal Khalifa, 2014
37
•Several statements can be grouped together into a block statement
•A block is delimited by braces ( { … } )
Logic of an if-else statement
true false
condition
evaluated
Statement 1 Statement 2
Dr. Amal Khalifa, 2014
38
Loop Statements
while statement
do statement
for statement
while ( condition )
statement;
do
{
statement list;
} while ( condition );
for ( initialization ; condition ; increment )
statement;
Dr. Amal Khalifa, 2014
42
Example
Look at
the code
and
describe
the
output !!
// set initial value of month so that the while condition
// below is false initially
int month = -1;
while (month < 1 || month > 12)
{
System.out.print( “Enter a month (1 to 12): “);
month = scan.nextInt();
}
System.out.print( “Enter a month (1 to 12): “);
int month = scan.nextInt();
while (month < 1 || month > 12)
{
System.out.println( month + “ is not a valid month.” );
System.out.print( “Enter a month (1 to 12): “);
month = scan.nextInt();
}
Dr. Amal Khalifa, 2014
44
Example
What is
the
difference
here??
Dr. Amal Khalifa, 2014
int month; // no need to initialize month
do
{
System.out.print( “Enter a month(1 to 12): “);
month = scan.nextInt();
} while (month < 1 || month > 12);
// beginning of the next statement
46
Example
int sum = 0;
for (int counter = 1; counter <= max; counter++)
sum += counter;
// beginning of the next statement
counter++
Establish initial value of control variable.
Determine if final value of control
variable has been
reached.
counter <= max sum+= counter
true
false
int counter = 1
Body of loop (this may be
multiple statements)
Increment the
control variable.
Dr. Amal Khalifa, 2014
48
Methods
A method:
groups a sequence of statement
takes input, performs actions, and produces output
In Java, each method is defined within specific class
Dr. Amal Khalifa, 2014
49
Method Declaration: Header
A method declaration begins with a method header
method
name
return
type
parameter list
The parameter list specifies the type and name of each parameter The name of a parameter in the method
declaration is called a formal argument
public class MyClass
{
static int min ( int num1, int num2 ) …
properties Dr. Amal Khalifa, 2014
50
Method Declaration: Body
The header is followed by the method body:
static int min(int num1, int num2)
{
int minValue = num1 < num2 ? num1 : num2;
return minValue;
}
class MyClass
{ …
…
}
Dr. Amal Khalifa, 2014
51
The return Statement
The return type of a method indicates the type of
value that the method sends back to the calling
location
A method that does not return a value has a void
return type
The return statement specifies the value that will be
returned
Its expression must conform to the return type
Dr. Amal Khalifa, 2014
52
Calling a Method
Each time a method is called, the values of the actual arguments in the invocation are assigned to the formal arguments
static int min (int num1, int num2)
{
int minValue = (num1 < num2 ? num1 : num2);
return minValue;
}
int num = min(2, 3);
Dr. Amal Khalifa, 2014
53
Method Call Stack
A method can call another method, who can call
another method, …
min(num1, num2, num3)
println()
…println(…)
min(1, 2, 3);
main
Dr. Amal Khalifa, 2014
54
What is an array?
Dr. Amal Khalifa, 2014
Array
data structures
Group of variables (called elements) containing values of the same type.
related data items of the same type.
fixed length once created.
Elements referred to using index or subscript.
In java, Arrays are objects, so they’re considered reference types.
Every array object knows its own length and stores it in a length instance variable.
Elements can be either primitive types or reference types (strings).
55
An index must be a nonnegative integer.
Can use an expression as an index
Every array object knows its own length and stores it in a length instance variable
Array elements
Dr. Amal Khalifa, 2014
56
7.3 Arrays in Java
declare
create
initialize
int[] a;
int a[];
a = new int[5];
for(int i=0;i<5;i++)
a[i] = i*i;
Dr. Amal Khalifa, 2014
57