CSE114 MIDTERM 1 & 2

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

literals

actual values

indexed variabled

array elements accessed through index indices are 0-based reprsented as: arrayRefVar[index];

creating arrays

arrayRefVar = new datatype[arraySize]; ex: myList = new double[10];

operator associativity

assignment operators are right-associative ex: a = b += c = 5 equivalent to a = (b += (c = 5))

variable gets a value in a(n) ____________

assignment statement

static methods

associates a method with a particular class name any method can call a static method either directly from within same class or using class name from outside class

format specifier

begins with a percent sign and specifies how an item should be displayed: numeric value, character, boolean value, or a string

true and false values

boolean expression is one whose value is either true/false (not both)

two way if statement

boolean expression with true statement and false statements as executable blocks

flag

boolean loop control; used as a loop condition inside loop

if statements notes

by default, the body of an if statement is restricted to the 1st statement that follows the "if(condition)" line indentation doesn't matter this can lead to trouble

useful String functions

charAt, equals, equalsIgnoreCase, compareTo, startsWith, endsWith, indexOf, lastIndexOf, replace, substring, toLowerCase, toUpperCase, trim s.equals(t) returns true if s and t have the same letters and sequence false otherwise

math class

class constant: PI, E class methods: trig methods, exponent methods, rounding methods, min, max, abs, and random methods

method signature

combination of the method name and the parameter list ex: mac(int num1, int num2)

ambiguous invocation

compiler cannot determine the most specific match and it is a compilation error

one way if statements

condition containment (use of parenthesis) necessary but no block containment (curly braces) necessary

array

data structure that represents a collection of the same type of data

switch statement rules

data types: char, byte, short, int, String break is optional but it terminates the remainder of the switch statement default is optional - executed when none of the specified cases matches the switch-expression

declaring and creating arrays 1 step

datatype[] arrayRefVar = new datatype[arraySize];

declaring array variables

datatype[] arrayRefVar;

declare a variable

declaration before use tells Java what behavior to expect from the variable writing the type, followed by the name (ex: int x; //declares an integer variable x)

all java variables must have a ________ type

declared

variables must be:

declared before being assigned values and initialized before being referenced (they can be dec and initialized at once) used inside the block or scope they are declared in declared once

comparing strings

don't use '==' to compare Strings as it compares their memory addresses and not the actual strings (char sequences) instead use the equals method supplied by the String class

equality for reals

don't use floating point values for equality checking in a loop control- floating point values are approximations for some values

rounding methods

double ceil(double x) x rounded up to nearest int; return as double double floor(double x) x rounded down to nearest int; return as double double rint(double x) if x equally close to two int, even one is returned as a double int round(float x) return(int)Math.floor(x+0.5) long round(double x) return(long)Math.floor(x+0.5)

summing elements

double total = 0; for (int i = 0; i < myList.length; i++) total += myList[i]; S.O.Pln("Total: " + total);

initializing arrays with input values

double[] myList = new double[10]; Scanner input = new Scanner(System.in); S.O.P("Enter " + myList.length + " values: "); for (int i = 0l i < myList.length; i++) myList[i] = input.nextDouble();

strings notes

each char is stores at an index; String class has methods to process strings strings are immutable (no methods to change them once they have been created)

exponent methods

exp(double a) returns e raised to the power of a log(double a) returns the natural logarithm of a log10(double a) returns 10-based log of a pow(double a, double b) returns a raised to power of b sqrt(double a) returns sqrt of a

for loop

for (initial-action; loop-continuation-condition; action-after-each-iteration) {

why use do...while?

for when you have a loop body that must execute at least once

random shuffling

for(int i = 0; i < myList.length; i++) { int j = (int) (Math.random() * myList.length); //generates index j randomly double temp = myList[i]; myList[i] = myList[j]; myList[j] = temp; //swap i list w/ j list

finding largest element

for(int i = 1; i < myList.length; i++) if(myList[i] > max) max = myList[i];

random method

generates a random double value greater than or equal to 0.0 and less that 1.0 ex: (int)(Math.random() * 10) return random int between 0 and 9 50 + (int)(Math.random() * 50) returns random int between 50 and 99

if statement

if (condition) statement (or block of statements) to be executed if the condition is true

if-else chains

if (expression_1) statement_1 else if (expression_2) statement_2 else statement_3

compound statements

if and else only execute a single following statement which we can get around by enclosing multiple statements in braces (compound statement) style note: use braces around the body of an if or else clause

infinite loops

if the loop-condition-continuation in a for loop is omitted, it is implicitly true

types of variables

int and long store integers char stores single characters('a) float and double store decimals

while loop

int count = 0; while (count < N) { System.out.println("Welcome to Java"); count++; }

increment and decrement operators

int i = 10; int newNum = 10 * i++; same effect as int newNum = 10 * i; i = i + 1; int i = 10; int newNum = 10 * (++i); same as i = i+1; int newNum = 10 * i;

java's primitive types

integers (whole numbers): byte short int long real numbers: float double char boolean

methods in the character class

isDigit(ch) true if char is dig isLetter(ch) true is char is a let isLetterOrDigit(ch) true if either isLowerCase(ch) true if so isUpperCase(ch) true if so toLowerCase(ch) returns lc toUpperCase(ch) returns uc

variable's type determines

kind of value it can hold and the necessary memory to reserve

scope of local variables

local variable: define inside a method scope: part of the program where the variable can be referenced a nested block cannot redefine a local variable

you can only directly execute a class file that contains a

main() method

why use iteration?

makes our code more flexible, dynamic, practical, and efficient how would we write code to print N! (factorial) where N is a number entered by the user?

min, max, and abs

max(a, b) and min(a, b) returns the max or min of two parameters abs(a) returns absolute value of parameter random() returns random double value

call-by-value

method formal arguments are copies of the original data

call stacks

methods are executed using a stack data structure

initializing arrays with random

myList[i] = Math.random() * 100;

mixing numeric types

no assigning big types to little types or real types to integer types

default values arrays

once created, elements are assigned the default value of 0 for the numeric primitive data types, '\u0000] for char types, and false for boolean types

length of an array

once created, size is fixed and cannot be changed find an array's size by using: arrayRefVar.length

String type is NOT a?

primitive type

a String type is a ?

reference type; a String variable is a reference variable, an "address" which points to an object storing the value or actual text

boolean operations

relational operators are used to compare two values logical operators combine smaller boolean expressions into a single, larger expression

iteration

repeating a set of instructions a specified number of times or until a specific result is achieved

scanner's methods

returns the next value of a given type (nextLine(), nextInt(), nextDouble(), etc.)

if-else statement

select one of 2 possible execution paths, based on result of a comparison if (expression) statement block 1 else statement block 2

conditional operator

selects one of two/three expressions and evaluates boolean expressions (like an if statement except instead of executing if code is true a conditional op will assign a value to a variable) (boolean-exp) ? exp1 : exp2 ex: if (x > 0) y = 1; else y = -1; is equivalent to y - (x > 0) ? 1 : - 1;

empty statements

semicolon by itself is a valid (but non-functional) statement common mistake: putting a semicolon immediately after an if statement with a semicolon, the print statement will execute regardless of the value of x

trigonometric methods

sin(double a) cos(double a) tan(double a) toRadians(double degree) toDegrees(double radians) acos(double a) asin(double a) atan(double a)

nested if statements

statement block may contain another if statement

object or reference type variables

store multiple pieces of data (ex: a String is a sequence of multiple char)

primitive type variables

store single pieces of data

interned strings

storing one copy of each distinct string value

type casting

temporarily change a data type to another type no type casting is allowed to/from boolean

type conversion reverse

to store a value in a smaller type, you must explicitly cast (convert) the value to the desired casting may lose data; casting value to an int does not round the resulting value

'='

to store a value in a variable; is assigned the value

class

unit of code that contains data (variables) and code (methods) and is used to define objects

common programming error

using '=' (assignment) instead of "==" (equality)

how not to copy arrays

using the assignment statement (=) you redirect the point: list2 = list1 you don't copy with "="!

type conversion

value can be stored in a variable of a larger type (ex: int can be stored as a float)

constant

value that cannot change to declare use "final" keyword; names are capitalized; strings are automatically constants

the assignment statement

variable = expression; solves and evaluates the expression first assigns resulting value to variable

formal parameters

variables defined in the method header

actual parameter

when a method is invoked, pass a value to the parameter: actual parameter or argument ex: int z = max(x, y); x and y are the actual parameters

3 types of iterative statements

while loop a do... while loop for loop

string concatenation

"+" is used for making a new string by concatenating strings

variables

"nouns" of a program that represent pieces of info

logical operators

&& (logical AND- true only if BOTH operands are true) | | (logical OR- true if AT LEAST ONE operand is true (inclusive OR) ! (logical NOT- true is operand is false and vice versa)

generating random characters

(char)((int) 'a' + Math.random() * ((int 'z' - (int 'a' + 1)) can be simplified to: (char) ('a' + Math.random() * ('z' - 'a' + 1))

making decisions`

1. branching (if-else) statements 2. selection (switch) statements

relational operators

< , > , <= , >= , == , !=

method abstraction

API = method body is a black box that contains the detailed implementation for the method

special characters

\n - newline \t - tab \" - quotation mark

random method in general

a + Math.random() * b returns a random number between a and a + b, excluding a + b

method

a method is a collection of statements that are grouped together to perform an operation

return value type

a method may return a value if it does not the returnValueType is the keyword void

return statement is required for?

a value-returning method

local variables and blocks

a variable declared inside a block is known only inside that block it is local to the block when it finished executing, local variables disappear

string type

char type only represents one character so to represent a string of characters, use data type called String

printing arrays

S.O.P(myList[i] + " ");

reading a string from the console

Scanner input = new Scanner(System.in); S.O.P("Enter ..."); String s1 = input.next(); String s2 = input.next(); String s3 = input.next(); S.O.Pln("s1 is " + s1); S.O.Pln("s2 is " + s2); S.O.Pln("s3 is " + s3);

reading a char from the console

String s = input.nextLine(); char ch = s.charAt(0);

printf statement

System.out.printf(format, items);


Ensembles d'études connexes

Community Health/Public Health BOOK QUESTIONS

View Set

Adult Nursing - PrepU - Chapter 4: Health Education and Health Promotion

View Set

Physical Science Lesson 1 (The Scientific Process)

View Set

MGT161 Chapter 6 Business Formation

View Set

World Geography Final Exam 1310 JO

View Set