Big Java, Late Objects Flashcards Preview

3. Procedural Programming (CSC 1025) > Big Java, Late Objects > Flashcards

Flashcards in Big Java, Late Objects Deck (84)
Loading flashcards...
1
Q

What is a computer?

A

Machine that stores data, interacts with devices + executes programs. At heart of comp is CPU.

2
Q

What is the CPU?

A

Central Processing Unit, composed of millions of transistors. Performs program control + data processing + executes programs, carries out arithmetic operations + fetches + places processed data into storage, of which there are 2 kinds. May not be obvious where this data resides on a networked comp.

3
Q

What are the 2 kinds of storage?

A

Primary + secondary storage.

4
Q

What is primary storage?

A

Made from memory chips, electronic circuits that can store data so long as they have electric power.

5
Q

What is secondary storage?

A

Provides slower, less expensive storage which persists without power. Data + programs located here + loaded into memory when program starts. Program then updates program in memory + writes modified data back to sec storage. e.g. hard disk

6
Q

What is a hard disk?

A

Secondary storage. Consists of rotating platters coated with magnetic material + read/write heads which can detect + change magnetic flux on platters.

7
Q

What is magnetic flux?

A

Quantity/strength of magnetic lines produced by magnet.

8
Q

How does comp interact with user?

A

Peripherals.

9
Q

How do high level programming languages work?

A

Created to make writing program instructions less tedious. Specify actions your program should carry out + compiler translates these into language of CPU.

10
Q

What are applets?

A

Java code that can be located anywhere on internet. Java was first created for programming consumer devices but successfully used to write these in 1995.

11
Q

Why is Java so good?

A

Has rich library so you can write portable programs that can bypass proprietary operating systems. Micro + enterprise edition of this to allow for a wide range of uses. It is safe + portable as it as designed for the internet. Safety features allow it to be run in browsers without fear of attack. Help you learn lang faster too as when you make an unsafe error, it tells you what’s wrong.

12
Q

What makes Java portable?

A

The compiler doesn’t translate it directly into CPU instructions but instructions for the Java virtual machine, which simulates a real CPU.

13
Q

What are the cons of Java?

A

It’s not simple to write basic programs + you need a certain amount of technical machinery to write even the simplest program.

14
Q

What is an editor?

A

Program for entering + modifying text, such as a Java program.

15
Q

What is a compiler?

A

Java compiler translates source code (java) into class files which contains the info for the virtual machine. The VM then executes the program.

16
Q

What should be pointed out in relation to backups?

A

Back up often, rotate backups (where you backup), pay attention to the backup direction (don’t overwrite newer files with older files), check your backups + relax, then restore.

17
Q

What are classes?

A

These are the fundamental building blocks of Java programs. Each java program contains a class with a main method. When app starts, instructions in main method are executed. Each class contains declarations of methods which contain sequence of instructions.

18
Q

What does it mean if a program crashes?

What if it is hung?

A

It has quit spontaneously.

It failed to respond to your input.

19
Q

What is pseudocode?

A

An informal description of a sequence of steps for solving a problem. Use indentation to indicate which statements should be selected/repeated.

20
Q

What are the steps to creating a program?

A

Understand problem, develop + describe algorithm, test algorithm with simple inputs, translate into java + compile + test program.

21
Q

What are the steps to describing an algorithm with pseudocode?

A

Determine inputs + outputs, break down problem into smaller tasks, describe each subtask in pseudocode + test pseudocode by working out example problem.

22
Q

What does initialise mean?

A

To specify the value stored in the variable.

23
Q

What is a number literal?

A

When a value such as 6 or 0.335 occurs in a Java program.

24
Q

What is an assignment statement?

A

Used to name variable. Stores new value in variable, replacing previously stored value e.g. cans = 8; Doesn’t include data type.

25
Q

What is a variable declaration?

A

Used to name variable but includes data type + doesn’t necessarily include value.

26
Q

What is a constant?

A

A variable defined using reserved word ‘final’. Its value can never change. Written with capital letters + underscores e.g. final double BOTTLE_VOLUME = 2;

27
Q

Why are roundoff errors a fact of life?

A

There isn’t always an exact representation of the decimal number you want in floating point numbers.

28
Q

What is a magic number?

A

A numeric constant that appears in code without explanation e.g. totalVolume = bottles * 2. Name variable e.g. totalVolume = bottles * BOTTLE_VOLUME; Also allows us to change value rather than having to go back and find and change every 2.

29
Q

What do you do if you want to compute with really large nums?

A

Use big number objects e.g. BigInteger + BigDecimal classes in java.math package. No limits on size + precision. However, computations using them is much slower + have to use diff operators e.g. add, subtract, multiple, not +, -, *. e.g. BigInteger oneHundred = new BigInteger (“100”); \n System.out.print(oneHundred.multiply(fiftyMillion)); BigDecimal carries out floating point calculations without roundoff errors.

30
Q

What is an expression?

A

Combination of variables, literals, operators +/or method calls.

31
Q

How can we make this expression shorter:

total = total + cans;

A

Combine arithmetic + assignment, total += cans

32
Q

What is a package?

A

Collection of classes with related purpose. Only classes in java.lang packae are automatically available in programs, must import all other classes.

33
Q

What is the API documentation?

A

Application Programming Interface documentation. Lists all classes + methods of Java library.

34
Q

What is an application programmer?

A

A programmer who uses the Java classes to put together a Java program/application.

35
Q

What is a system programmer?

A

A programmer who designs + implements the library classes.

36
Q

What happens when one of the arguments of the operator is a string?

A

The other argument is converted into a string.

37
Q

What is true of objects?

A

Strings + Scanners are objects. Each object belongs to a class e.g. strings are objects of string class. Class declares methods you can use with its objects. Method invoked with dot notation (object, method name, method, parameters in parentheses) Can’t invoke methods on nums.

38
Q

What are static methods?

A

Classes can declare these methods that aren’t invoked on objects. Used when manipulating nums. e.g. Math.sqrt(2).

39
Q

What is an instance method?

A

A method that is invoked on an object. Used when processing strings or inputs/outputs.

40
Q

What is an if statement for?

A

Used to implement decision. When condition fulfilled, one statement executed, otherwise, other set of statements executed. Can carry out diff actions depending on nature of data being processed. No semicolon after if condition. If we have duplicate code, move to outside of if statement.

41
Q

What is a relational operator?

A

> , >=,

42
Q

How do you test whether strings are equal?

A

string1.equals(string2) == would check if they’re stored in same location.

43
Q

How do we test if floating point numbers are the same?

A

Don’t test if they’re the same but if they’re close enough to each other. (x-y)

44
Q

What is a switch statement?

A

Similar to if statement but compares value against multiple alternatives. Each branch must end with break (or else executes rest of program) + tests same variable. Can only use with int, String, enum + values must be constant, can’t test greater than.

45
Q

What is a nested statement?

A

When decision statement contained inside branch of other decision statement.

46
Q

What is hand tracing?

A

Working out problem by hand by using columns. Work through + change values as values in program change.

47
Q

What is a dangling else?

A

If you don’t use braces, statement will attach itself to wrong if/else statement. Occurs in nested decision statements.

48
Q

What is an enum?

A
Has finite set of values E.g. public enum FilingStatus {SINGLE,MARRIED,MARRIED_FILING_SEPARATELY} To declare: FilingStatus status = FilingStatus.SINGLE;
If wrong value typed in, error flagged. Use the == value to compare enum values. Place enum declaration inside class that implements program.
49
Q

What are flowcharts for?

A

Made up of elements for tasks, input/output and decisions. Show structure of decisions + tasks that are required to solve problem. Each branch of decision can contain tasks + further decisions. Never point arrow inside another branch (spaghetti code)

50
Q

What are test cases?

A

Each branch of program should be covered by test case. Test boundary conditions + invalid inputs. If you have flowchart, can check off each branch. Design them before coding.

51
Q

How do you get a printout of the program flow?

A

Insert trace messages into program. E.g. if (status==SINGLE){System.out.println(“Status is SINGLE”);} However, must remove these when done + put back in if another error so use Logger class. Use global logger object (Logger.getGlobal()) Then (Logger.getGlobal().info(“Status is SINGLE”);) By default, message is printed, but if you use (Logger.getGlobal().setLevel(Level.OFF);) at start of main method, log printing suppressed. Set level to Level.INFO to turn back on.

52
Q

Describe boolean.

A

Boolean variable = true/false. AKA flag variable. Use && and || (boolean operators) && = both true. Or = both/either one true. Boolean operators have lower precedence than relational operators. To invert condition, use ! not operator. && and II operators computed using short circuit evaluation. Once true, no other conditions evaluated.

53
Q

What is De Morgan’s law?

A

Used to simplify Boolean expressions. E.g. !(A&&B) = !A || !B. !(A || B) = !A && !B. And and or operators reversed by moving not inward.

54
Q

How can you validate input?

A

If wrong value input, runtime exception occurs + program terminated. To avoid, call hasNextInt/hasNextDouble method which checks whether next input is int. If true, can safely call nextInt. Otherwise, print error message + exit program.

55
Q

What is a while loop?

A

Repeats step while variable certain value. Executes instructions repeatedly while condition true. Statements being executed are body of statement. Variables declared inside them are local and not seen anywhere else in program. Condition controlled/indefinite. Pre-test loop.

56
Q

What are infinite loop?

A

Loops which run forever, stopped only by killing program or restarting comp. Continuous output or program just hangs.

57
Q

What are off by one errors?

A

Common with loops, use simple test cases to avoid them.

58
Q

When is a for loop used?

A

When value runs from starting point to ending point with constant increment/decrement. Can use while loop with counter instead. Count controlled/definite. Pre-test loop.

59
Q

What are symmetric values?

A

If same operator is on both bounds e.g. 1 <=i<=10

60
Q

What is a do loop?

A

Loop body only executed once. Body executed first then condition tested. Post-test loop.

61
Q

What is a sentinel value?

A

Denotes end of data set but not part of data. Can use boolean variable to control loop. Set variable before entering loop, then set to opposite to leave loop. May have 2 checks which ends loop, then ensures sentinel isn’t processed as input value.

62
Q

What is a loop and a half?

A

When check is in middle of program so must go halfway through program until you know if you need to terminate program. Can use break otherwise {break;}

63
Q

What is input/output redirection?

A

Can use input redirection to read input from file + output redirection to capture program output in file e.g. java.SentinelDemooutput.txt

64
Q

What is a storyboard?

A

Annotated sketches for each step in action sequence. Helps to understand inputs + outputs. Must ask what info provided, what inputs/outputs + in what order?

65
Q

How could you compute average?
How could you count values that fulfil condition?
How could you find largest value?
How could you compare adjacent inputs?

A

Keep total + count of all values, initalise total + count with 0. Check all values + increment counter for each match, if goal to find match, exit loop when found. Update largest value so far when see larger one. Store preceding value in variable e.g. in previous = input

66
Q

What is a nested loop?

A

When body of loop contains another loop. Typical use is printing table with rows + columns.

67
Q

How are simulation programs used?

A

Use comp to simulate real life activity. Can introduce randomness with Math.random() which gives float num >=0 and <1/ Not truly random as drawn from sequence of nums that don’t repeat for long time. Called pseudorandom nums. To choose range, e.g. Math.random()*6

68
Q

What is the monte carlo method?

A

Find approx solutions to problems that can’t be precisely solved. Use Math.random() to do it.

69
Q

What is the draw method?

A

Receives object of type Graphics which has methods for drawing shapes + remembers colours used for drawing operations.

70
Q

What is a method?

A

Named sequence of instructions. Can call method to execute instructions. Args supplied when method called, return value is result that method computes. Must provide name, variable for each arg + result type when declaring method. declaration is called header. Should be reusable where possible. Keep short, should fit on 1 screen.

71
Q

What is a parameter?

A

Parameter values hold arguments supplied in method call + yield method result. Compile time error if some branches return values and others don’t. Use return type void to indicate method doesn’t return value.

72
Q

What is stepwise refinement?

A

Decompose tasks into smaller ones.

73
Q

What is a stub?

A

When writing larger programs, not always possible to implement + test all methods at once so can use temp stub method to replace one which hasn’t yet been implemented. Returns simple value to test method.

74
Q

What is a recursive method?

A

Calls itself. Solves problem by using solution of same problem with simpler inputs. For it to terminate, must have special cases for simplest inputs.

75
Q

What is an array?

A

Collects sequence of values of same type. Num of elements is length of array. Start at index 0. Each index in array contains element. Bounds error if try to access something out of index range. Can’t add values to array you’ve already declared length of. If you copy array ref, changing value in 1 also changes value in other. Can create partially filled array but must keep companion variable to store how many elements in use. Use Arrays.sort(values,0,currentSize) to sort. e.g. double {}values=new double[10] OR double[]values={1,2,3,4,6,8}

76
Q

What is an enhanced for loop?

A

Can use to visit all elements of array. Element variable assigned value[0] while in basic for loop, index variable assigned these. Use enhanced if don’t need index values in loop body. When separating elements, don’t place separator before first element. Can also use for ArrayList.

77
Q

What is a linear/sequential search?

A

Inspects elements in sequence until match found. Before inserting element, move elements to end of array starting with last one. Can copy array using x.copyOf. Can sort it using Arrays.sort(values). If array sorted, use binary search algorithm. This means check if value in first half, then check in second half. Arrays can occur as method arguments and return values.

78
Q

How can you store a 2D array e.g. Matrix?

A

Supply num of rows + columns e.g. new int[7][3]. Can do same with multidimensional array. Array list stores sequence of values whose size can change + ArrayList class supplies methods for common tasks like inserting + removing elements. ArrayListnames=new ArrayList(); To use it, must do import java.util.ArrayList. ArrayList is generic class.

79
Q

How do you collect numbers in ArrayList?

A

Must use wrapper classes. Cap letter for type + use full name. e.g. ArrayList. Conversion between primitive types + corresponding wrapper class automatic, called auto-boxing. Can use similar code for them but yse get. To find length of ArrayList use a.size()

80
Q

How do we read files in Java?

A

Use Scanner to read files. Constuct File object with name of input file (File inputFile=new File(“input.txt”), then use file object to construct scanner object (Scanner in = new Scanner (inputFile). To write output to file, construct PrintWriter object with file name (PrintWriter out=new PrintWriter(“output.txt”). Must declare what we want program to do if file doesn’t exist so may put throws FileNotFoundException at main method declaration. When spec file name as string literal, use 2 backslashes due to escape character.

81
Q

How do we read contents of webpage?

A

String address = https://www.bbc.co.uk;URL pageLocation=new URL(address);Scanner in = new Scanner(pageLocation.openStream();

82
Q

How do we use file dialog boxes?

A

JFileChooser class implements file dialog box for Swinh user interface toolkit. Construct object, then call showOpenDialog or showSaveDialog method. Can use InputStream to read binary data. To write binary data to file, use FileOutputStream. Next method rads string that is delimited by white space. Can use UseDelimiter method to discard anything that’s not a letter. Can use Character class to analyse + classify characters. e.g. Character.isDigit(ch); To read entire line of string, use String line = in.nextLine(); If string contains digits of num, use Integer.parseInt to obtain num value.

83
Q

How can we signal an exceptional condition?

A

Use throw statement to throw exception object. When we do this, processing continues in exception handler. If withdraw too much money, throw IllegalArgumentException. Place statements that can cause exception inside try block + handler inside catch clause. Call exception.getMessage() to retrieve message associated with exception. Internal errors reported by descendants of type Error e.g. outOfMemoryError. Descendants of RuntimeException like OutOfBoundsException indicate code errors, unchecked exceptions.

84
Q

What are checked exceptions?

A

All other errors, indicate something gone wrong for external reason beyond our control. Once try block entered, statements in finally clause guaranteed to be executed, whether exception throws or not. Better to throw exception than get incorrect answer. Don’t use catch + finally in same try statement as hard to understand + often wrong. For each exception, must decide which part of program can competently handle it.