Professional Documents
Culture Documents
Comp Sci Chapter 1-7
Comp Sci Chapter 1-7
Comp Sci Chapter 1-7
Introduction to
Computers
and
Programming
• spreadsheets • games
• databases • etc.
• word processing
• Computers are versatile because they can be
programmed.
• Computer Programmers implement programs that
perform these functions.
javac Simple.java
java Simple
• Line 2 is blank.
• Blank lines are often inserted by the programmer because they can
make the program easier to read.
Class Header
Opening Brace
Class Body
Closing Brace
Method Header
Opening Brace
Method Body
Closing Brace
Statement
Variable Declaration
Assignment Statement
• Line 10 sends the string literal "The value is " to the print
method.
• Line 11 send the name of the value variable to the println method.
• When you send a variable name to print or println, the variable’s
contents are displayed.
Notice there are no quotation marks around the variable value.
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Variables and Literals
(cont’d.)
Higher -
Priority (unary negation) right to left x = -4 + 3; -1
* / % left to right x = -4 + 4 % 3 * 13 + 2; 11
Lower
Priority + - left to right x = 6 + 3 – 4 + 6 * 3; 23
int x;
double y = 2.5; This statement will cause a
x = y; compiler error because it is
trying to assign a double
value (2.5) in an int variable.
double x;
int y = 10;
x = y; Widening Conversion
int x;
double y = 2.5;
x = y; Narrowing Conversion
Cast Operator
a = (short)(b + c);
• Place two forward slashes (//) where you want the comment to
begin.
• The compiler ignores everything from that point to the end of the
line.
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Multiline Comments
import java.util.Scanner;
Read Primitive
Remove Newline
Read String
System.out.printf(FormatString, ArgumentList)
2-112
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Simple Output
The simplest way you can use the printf
method is with only a format string and no
additional arguments.
The value is 9
123456
If the value of the argument is wider than the specified field width, the
field width will be expanded to accommodate the value.
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Using Field Widths to Print
Columns
Field widths can help when you need to print values aligned in
columns. For example, look at the following code:
int num1 = 97654, num2 = 598;
int num3 = 86, num4 = 56012;
int num5 = 246, num6 = 2;
System.out.printf("%7d %7d\n", num1, num2);
System.out.printf("%7d %7d\n", num3, num4);
System.out.printf("%7d %7d\n", num5, num6);
This code displays the values of the variables in a table with three
rows and two columns. Each column has a width of seven spaces.
Here is the output for the code:
97654 598
86 56012
246 2
1234567 1234567
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Printing Formatted Floating-
Point Values
If you wish to print a floating-point value, use the %f format
specifier. Here is an example:
double number = 1278.92;
System.out.printf("The number is %f\n", number);
12
12345678
12
FormatString is ArgumentList is
a string that optional. It is a list of
contains text and/or additional arguments that
special formatting will be formatted according
specifiers. to the format specifiers
listed in the format string.
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The String.format Method
• See examples:
• CurrencyFormat2.java
• CurrencyFormat3.java
Animal
Animal
Method parameters
are shown inside the Rectangle
parentheses using the
same notation as
variables. - width : double
3-30
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Converting the UML Diagram to Code
The structure of the class can be public class Rectangle
compiled and tested without having {
private double width;
bodies for the methods. Just be sure to
private double length;
put in dummy return values for methods
that have a return type other than void. public void setWidth(double w)
{
Rectangle }
public void setLength(double len)
- width : double {
- length : double }
public double getWidth()
{ return 0.0;
+ setWidth(w : double) : void }
+ setLength(len : double): void public double getLength()
+ getWidth() : double { return 0.0;
+ getLength() : double }
public double getArea()
+ getArea() : double { return 0.0;
}
}
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Converting the UML Diagram to Code
Once the class structure has been tested, public class Rectangle
the method bodies can be written and {
private double width;
tested.
private double length;
+BankAccount(startBalance:double,
intRate :double):
+ deposit(amount : double) : void
+ withdrawl(amount : double: void
+ addInterest() : void
+ getBalance() : double
+ getInterest() : double
import java.util.Scanner;
import java.util.*;
Wear a coat.
if(x == y)
System.out.println("X is equal to Y");
if(x != y)
{
System.out.println("X is not equal to Y");
x = y;
System.out.println("However, now it is.");
}
Example: AverageScore.java
is functionally equivalent to
if (expression)
{
statement1;
statement2;
} Curly brace ends the statement.
if (expression)
statement1; Only this statement is conditionally executed.
statement2;
statement3;
- hoursWorked : double
- payRate : double
+ Payroll()
+ setHoursWorked(hours : double) : void
+ setPayRate(rate : double): void
+ getHoursWorked() : double
+ getPayRate() : double
+ getGrossPay() : double
No Yes
Is it cold
outside?
No Yes
Is it cold
outside?
Wear shorts.
No Is it Yes
snowing?
Expression 1 !Expression1
true false
false true
switch (testExpression)
{
…
}
case value_1:
// place one or more statements here
break;
• Example: IncrementDecrement.java
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Differences Between Prefix
and Postfix
• When an increment or decrement are the
only operations in a statement, there is no
difference between prefix and postfix
notation.
• When used in an expression:
• prefix notation indicates that the variable will be
incremented or decremented prior to the rest of the
equation being evaluated.
• postfix notation indicates that the variable will be
incremented or decremented after the rest of the
equation has been evaluated.
• Example: Prefix.java
Copyright © 2018 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The while Loop
• Java provides three different looping structures.
• The while loop has the form:
while(condition)
{
statements;
}
• While the condition is true, the statements will
execute repeatedly.
• The while loop is a pretest loop, which means that it
will test the value of the condition prior to executing
the loop.
true
boolean
statement(s)
expression?
false
while (condition)
{
statement;
statement;
statement;
}
• Example: TestAverage1.java
statement(s)
true
boolean
expression?
false
boolean true
statement(s) update
expression?
false
• Note that the only parts of a for loop that are mandatory are
the semicolons.
for(;;)
{
statement(s);
} // infinite loop
Warning: if the file already exists, it will be erased and replaced with a new file.
import java.io.*;
FileWriter fw =
new FileWriter("names.txt", true);
PrintWriter outFile =
new PrintWriter("A:\\PriceList.txt");
• Example: OverloadingDemo.java
Address
description: Pliers
units: 25
address
- courseName : String
- Instructor : Instructor
- textBook : TextBook
Instructor TextBook
- lastName : String - title : String
- firstName : String - author : String
- officeNumber : String - publisher : String
if(name != null)
System.out.println("Name is: " +
name.toUpperCase());
Day.THURSDAY
Day.FRIDAY
Day.SATURDAY
• Examples:
– EnumDemo.java, CarType.java, SportsCar.java, SportsCarDemo.java
Example: SportsCarDemo2.java
item2 Address
item2 Address
Stock
Know stock to purchase Stock class
Know number of shares None
Calculate cost of purchase Stock class
Etc. None or class name
0 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
Array element values are initialized to 0.
Array indexes always start at 0.
2 4 6 8 10
array1 holds an
Address
address to the array
Example:
array2 holds an
SameArray.java
Address
address to the array
showArray(numbers); 5 10 15 20 25 30 35 40
0 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
Array element values are initialized to 0.
Array indexes always start at 0.
outputFile.close();
Address
names[0] null
names[1] null
names[2] null
names[3] null
names[0] = "Bill";
The names variable holds names[1] = "Susan";
the address to the array. names[2] = "Steven";
names[3] = "Jean";
Address
System.out.println(names[0].toUpperCase());
char letter = names[3].charAt(0);
Address
inventory[0] null
inventory[1] null
inventory[2] null
inventory[3] null
inventory[4] null
Copyright © 2018 Pearson Education, Inc. All Rights Reserved
Arrays of Objects
• Each element needs to be initialized.
for (int i = 0; i < inventory.length; i++)
inventory[i] = new InventoryItem();
• Example: ObjectArray.java
description: “”
The inventory variable holds the address units: 0
of an InventoryItem array.
description: “”
Address units: 0
description: “”
inventory[0] Address units: 0
inventory[1] Address description: “”
inventory[2] Address units: 0
Algorithm1:
for (int i = 0; i < data.length; i++)
if (data[i] == target)
found = true;
Best-case: Algorithm2:
Suppose data[0] contains int i = 0;
target value and n is large
…how many steps while (!found && i < data.length)
does each algorithm take? {
if (data[i] == target)
Worst-case: found = true;
Suppose target is not in else
array…how many steps i++;
does each algorithm take? }
RunTimeDemo01.java and RunTimeDemo02.java
Copyright © 2018 Pearson Education, Inc. All Rights Reserved
Algebraic notation for number of
steps
• An algorithm based on n pieces of data
can be represented by an algebraic
expression for the number of steps
Example:
for (int i = 0; i < data.length; i++) n times
if (data[i] == target) (1)
found = true; (1)
Expression: 2n
Remember: approximation
Copyright © 2018 Pearson Education, Inc. All Rights Reserved
Example:
int i = 0; (1)
Expression: 2n + 1
Remember: approximation
Copyright © 2018 Pearson Education, Inc. All Rights Reserved
Big-O notation
• Approximation for an algorithm where we
ignore constants in the expression an focus
on n, because n can be very large
• Polynomials :
• Consider largest power of n
• n2 + 3n + 2 O(n2)
• Linear
• 2n + 7 O(n)
• Constant
•6 O(1)
Copyright © 2018 Pearson Education, Inc. All Rights Reserved
Sequential Loops
Expression: 1 + 2n + 1 + 2n = 4n + 2
Big-O: O(n)
Expression: 2n2
Big-O: O(n2)
0 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
Array element values are initialized to 0.
Array indexes always start at 0.
row 0
row 1
row 2
row 3
• Example: CommandLine.java
• It is not required that the name of main’s
parameter array be args.
• Example: ArrayListDemo1.java
See: ArrayListDemo6.java