# Notes

# Best programming practices

# What is a program

A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of mathematical equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or something graphical, like processing user input on an ATM device.

# Essence or "Workflow" of a Program

Error: Failed to launch the browser process! spawn /Applications/Google Chrome.app/Contents/MacOS/Google Chrome ENOENT


TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md
input
Get data from the "outside world". This might be reading data from the keyboard or a file, or even some kind of sensor like a microphone or GPS.
process
Perform computions by the CPU (Central Processing Unit) of the device
output
Display the results of the program on a screen or store them in a file or perhaps write them to a device like a speaker to play music or speak text.

# Design Aspects for problem solving

# Basic Building Block of a Program

Every program goes thru either or all of the following flows

  1. Sequential (Top Down execution)
  2. Selective (Decision making execution)
  3. Iterative or "Loop repetition"

# Java Fundamentals

# Variables

Defined: a value stored in memory that can change

  1. Declarations
    Establish good naming conventions!

    Ex. emp_Rate or empRate empHours , empId

  2. Scope (variable visibility)

    Variables can be defined to be "visible" or seen at the local vs. class level (static).

# Constants

Defined: a value stored in memory that cannot change

Use of keyword -> final

final int ival = 20;  //value needed immediately upon declaration!

# Basic Data Types

Primitives (8)Reference or Class based examples
byteRandom
booleanString
floatFloat
doubleDouble
intInteger
shortShort
longLong
charCharacter
int j=0, k=1;
double a = 2.0;
double b = 5;

Avoid a common pitfall!

int result = 3/4;  //0 as truncation occurs

# Operators

Know operator precedence and associativities!

Order of operations (highest to lowest)

  1. Arithmetic
  2. Conditionals ( and && , or || , not ! )
  3. Relational ( > , < , >= , <= , != , == )

Keynote: use shortcut operators in assignment statements

++count;  //pre increment operator (change to variable takes place immediately) 
// vs.
count++;  //post increment operator (change to variable takes place after assignment ends)
// same as
count = count + 1;
// or
count+=1;

Avoid a common pitfall! -Checking for equality!!

FOR NUMERIC TYPES USE

int a = 12;
(5 == a)

FOR STRING TYPES USE EQUALS METHOD!

String name1 = "Joe", name2 = "Jack";
(name1.equals(name2))

# Conditionals

# if statements

format:

if(a>b)
 //if true do something
else
 //if false do something else

Make use of curly bracies { } to combine statements

Example
if(a>b) {
 result = a;
 System.out.print("Value = " + result);
}
else {
 result = b;
 System.out.print("Value = " + result);
}

# Other forms- multi branched, nested

if alternative – the CEO (Conditional Expression Operator)

Known as a ternary operator - ? :

format: conditon ? true expression : false expression

Example
int result = a>b ? a : b;
// if statement equivalent
if(a>b)
 result = a;
else
 result = b;

# Truth tables

And && Expression- a>b && b>cOr || Expression- a>b || b>cNot ! Expression- !(a>b)
Cond.ResultCond.Result
T && TTT || TT!T = F
F && TFF || TT!F= T
T && FFT || FT
F && FFF || FF

# Loops

while, do-while, for, for enhanced

format: while (some condition holds true)

Example
int count = 0;
while (count<10)  {
 //do something
 count++;  //increment counter variable
}

# Arrays

  • Index or subscript based

  • Holds a series or list of values

  • Can be fixed or dynamic

  • Chief advantages
    Can be sorted, searched, averaged, find max/min values, printed…

  • Any disadvantages???

int array[] = {1,2,3,4,5};
array[2]=14; //update array at subscript 2, element #3
Element numberSubscript number (or index)Value at subscript position
101
212
3214
434
545

Ex. Cycle thru array up to array length - 1

for (int i = 0; i < array.length; i++)
	System.out.print(array[i] + " ");

# Review

# True/False

  1. The first step to the problem-solving process is to implement the algorithm in a programming language, such as Java, and verify that the algorithm works.

    译:解决问题过程的第一步是用一种编程语言(例如 Java)实现该算法,并验证该算法是否有效。

    1. Define Problem 定义问题
    2. Create (suggest) a solution (s) 创建一个解决方案
    3. Code away!! 编写代码
    4. Test 测试
    5. Maintenance (ongoing) (持续)维护
  2. The symbol '5' does not belong to the char data type because 5 is a digit.

    char letter = 'a';
    String letter = "a";

  3. If ++x is used in an expression, first the expression is evaluated, and then the value of x is incremented by 1 .

    ++x; same as => x = x + 1;
    ++x; (先加再运算)
    x = x + 1; (update to variable occurs AFTER expression is evalutated 对变量的更新发生在表达式被赋值之后)

  4. In Java, ! , && , and || are called logical operators.

    1. Arithmetic 算数
    2. Conditional 条件
    3. Relational 关系
  5. Suppose P and Q are logical expressions. The logical expression P && Q is false if both P and Q are false.

    Ex. P => A>B , Q => A==2 is P&&Q a true outcome

  6. The output of the Java code, assuming that all variables are properly declared, is 32.

    num = 10;
    while (num <= 32)
       	num = num + 5;
    System.out.println(num);

    Result:
    15 20 25 30 35
    Ending value is 35

    Loop Trace!

    Loop count (cycle)Result (num)
    115
    220
    325
    430
    535
  7. A constructor has no type and is therefore a void method.

    译:构造函数没有类型,因此是一个空方法。
    PURPOSE: SET THE OBJECT(S) TO AN INITIAL STATE.
    目的:将对象设置为初始状态。
    构造函数没有 返回类型,所以没有 void。

  8. Given the declaration

    double[] numList = new double[20]; //0-19 INDICIE

    the statement

    numList[12] = numList[5] + numList[7];

    updates the content of the thirteenth component of the array numList.

  9. A subclass can override public methods of a superclass.

    子类可以重写父类的方法

  10. If an exception occurs in a try block and that exception is caught by a catch block, then the remaining catch blocks associated with that try block are ignored.

    如果在一个 try 块中发生异常,并且该异常被 catch 块捕获,那么与该 try 块关联的其余 catch 块将被忽略。

# Multiple Choice

  1. To develop a program to solve a problem, you start by .

    • analyzing the problem
    • implementing the solution in Java
    • designing the algorithm
    • entering the solution into a computer system
    • 分析问题
    • 用 JAVA 实现解决方案
    • 设计算法
    • 将解决方案输入计算机系统
  2. The first step in OOD is to identify the components called .

    • classes
    • objects
    • methods
    • data

    OOD:Object-Oriented Design,即面向对象设计

  3. Which of the following is a valid int value?

    • 3279
    • 3,279
    • 3270.00
    • -922337203684547758808

    For letter b response above, you can include a character like a comma ( , ) to be stored as a numeric value
    For letter c response above, you can't include a decimal ( . ) to be stored as a 'int' numeric value
    For letter d response above, the value is too large to be stored as an 'int'. Try coding the variable with that value as an assignment and see the error message.

  4. Which of the following is a valid statement?

    (i) int num = new int(67);
    (ii) String name = new ("Doe");
    (iii) String name = "Doe";

    • Only (i)
    • Only (i) and (ii)
    • Only (iii)
    • Only (ii) and (iii)

    Syntax for ( i ) is invalid. Type should be Integer not 'int' when creating an integer type object
    Syntax for ( ii ) s/b String name = new String ("Doe");

  5. Declaring a class level variable as static means .

    • access is obtainable only thru a class object
    • any method (static, instance) can have access
    • no methods can have access
    • none of the above

    将类声明为静态意味着什么?

    • 只能通过类对象进行访问
    • 任何方法 (静态、实例) 都可以访问
    • 没有方法可以访问
    • 以上都不正确
  6. Consider the following statements.

    double x;
    String y;
    y = String.format("%.2f", x);

    If x = 285.679 , what is the value of y?

    • "285.00"
    • "285.680"
    • "285.68"
    • "285.068"

    保留两位小数

  7. What is the output of the following Java code?

    int x = 0;
    if (x > 0)
        System.out.println("positive ");
        System.out.println("zero ");
    System.out.println("negative");
    • zero
    • negative
    • zero negative
    • positive zero negative

    Notice that the second statement although aligned under the if statement namely System.out.println("zero "); executes no matter what as the if statement has no braces { } to encompass the 2nd println statement.
    尽管第二个语句 System.out.println("zero ");if 语句对齐,但 if 语句没有用大括号 {} 将第二个 println 语句括起来,因此它总是会被执行。

  • For the executions using the compareTo built-in java method that follows (questions 18-20), outcomes are basically as follows

    If str1 > str2 when comparing characters from (left to right each time) the outcome will be some positive number result
    If str1 < str2 when comparing characters from (left to right each time) the outcome will be some negative number result
    If str1 == str2 when comparing characters from (left to right each time) the outcome will be 0.

    Comparisons like the above are good when sorting data.

  1. If str1 is "Hello" and str2 is "Hi", which of the following could be a result of str1.compareTo(str2); ?

    • 4
    • -4
    • -1
    • 1

    Here when comparing
    H e l l o with
    H i
    The e and the i when comparing characters from each string from left to right show a lexographical difference of 4 characters.
    As str1 > str2, a negative result appears by a distance of 4 characters yielding a -4.

  2. If str1 is "Hello" and str2 is "Hi", which of the following could be a result of str2.compareTo(str1); ?

    • 4
    • -4
    • -1
    • 1

    Here similarly to question 18 result there is a difference of 4 characters, yielding a positive 4 as str2 is greater than str1.

  3. If str1 is "Hello" and str2 is "Hello", which of the following could be a result of str1.compareTo(str2); ?

    • 4
    • -4
    • 0
    • 1

    Here comparisons between string values (characters) are equal, hence the 0 outcome.