cs 151 quizzes

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/55

encourage image

There's no tags or description

Looks like no tags are added yet.

Last updated 6:14 AM on 5/18/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai

No analytics yet

Send a link to your students to track their progress

56 Terms

1
New cards

precondition

a condition that must be true right before executing the code

2
New cards

defensive programming

The practice of writing code that anticipates and safely handles incorrect, unexpected, or misuse scenarios to make the software robust

  • Always assume the consumer (user / caller) of your code is a rookie

  • In case preconditions are not satisfied, implementer should do a null-check at the beginning of the method

3
New cards

postcondition

A condition that must be true right after executing the code, provided that the preconditions were satisfied

4
New cards

Class invariant

A condition that should ALWAYS be true

  • Right after creation of the object

  • Before and after any operation in the object

5
New cards

java assertion - when to use it

When the “precondition” is violated, you should check it and warn the user right away

6
New cards

java assertion syntax

  • assert condition;

  • assert condition : explanation;

Enable assertions:

  • -enable assertions

  • Short form: -ea

7
New cards

if assertion is true

the rest of the code executes

8
New cards

if assertion is false

an AssertionError exception is thrown, and a message will be shown on the console (includes class name and line number)

(no further code is executed)

9
New cards

exception - when to use

To catch a failure (eg precondition violation), it is also common to throw an exception

10
New cards

root of Exception hierarchy

“Throwable” class

11
New cards

Exception tree

knowt flashcard image
12
New cards

Types of exceptions in java (2)

  • checked

  • unchecked

13
New cards

unchecked exceptions

the compiler does not check them at compile time

  • all subclasses of RuntimeException are unchecked

  • NullPointerException & IndexOutOfBoundsException

14
New cards

Checked exception

The compiler checks them at compile time

  • We need either catch them by try-catch block or list them in the throws clause of the method

15
New cards

Try-catch: a catch clause gains the control of the program’s execution if …

A statement inside the try-block throws an exception

A method called from inside the try-block throws an exception

16
New cards

finally block (after try-catch)

The code in the finally block will always be executed; we usually put cleanup code inside finally block

17
New cards

how to order the catch block (parameters)

Order exceptions from most restricted to the least restricted

18
New cards

Creating a new Exception class

  • It must extend Exception class

  • It should have at least one constructor

  • The constructor should have an argument of String type

    • The string is used to signify the reason for the exception

  • In the constructor, just call the constructor of the super-class

<ul><li><p>It must extend Exception class</p></li><li><p>It should have at least one constructor</p></li><li><p>The constructor should have an argument of String type</p><ul><li><p>The string is used to signify the reason for the exception</p></li></ul></li><li><p>In the constructor, just call the constructor of the super-class</p></li></ul><p></p>
19
New cards

When to use Precondition / Postcondition / Class Invariant vs Exceptions

In private methods, using preconditions/postconditions/class invariants is OK

In public methods, throwing exceptions is more appropriate

20
New cards

Liskov Substitution Principle (LSP)

Derived classes must be substitutable for their base classes

aka Subclasses must be substitutable for their superclass

<p>Derived classes must be substitutable for their base classes</p><p>aka  Subclasses must be substitutable for their superclass</p>
21
New cards

Precondition of the subclass should be …

either the same as the superclass or weaker

22
New cards

Interface Segregation Principle (ISP)

Make fine grained interfaces that are client specific

aka Make smaller interfaces that are customized to a specific client.

23
New cards
<p>Added the new animal sparrow and two features walk and fly </p><p>What is the issue with this and how do you fix?</p>

Added the new animal sparrow and two features walk and fly

What is the issue with this and how do you fix?

Animal interface is too “big” or “polluted” for the concrete classes

Instead:

  • Segregate (split) the big interfaces into smaller ones

  • We can split Animal interface into 3 smaller interfaces: WalkableAnimal, FlyableAnimal, Animal

<p>Animal interface is too “big” or “polluted” for the concrete classes</p><p>Instead:</p><ul><li><p>Segregate (split) the big interfaces into smaller ones</p></li><li><p>We can split Animal interface into 3 smaller interfaces: WalkableAnimal, FlyableAnimal, Animal</p></li></ul><p></p>
24
New cards

Java Object Class

All java classes are directly or indirectly subclasses of “Object class”

If your class doesn't extend another class, it extends directly Object class, even though you don't mention it

25
New cards

toString Method - goal and default behavior

Goal: creating a descriptive string to represent the object’s STATE

Default behavior: returns a string containing the object’s package name, class name, and a hash key in hex format

26
New cards

Equals Method - goal and default behavior

Goal: checking equality of two objects

Default behavior: uses ==

27
New cards

what does x == y mean in Java?

it checks whether x and y are references to the same object, called the identity test

28
New cards

clone method - goal and default behavior

Cloning means copying/pasting an object

Default behavior: shallow copy

Class needs to implement Cloneable interface in order to clone (otherwise, JVM throws an CloneNotSupportedException)

29
New cards

reference variable copy

Objects share a reference, it is the same object

30
New cards

Shallow copy

Shallow copy: If X and Y are objects, and Y is a shallow copy of X, then:

  • All primitive attributes of X are copied into Y

  • Both X and Y share the non-primitive instance variables

  • If an immutable object changes, a new object will be created

  • If a mutable object changes, it remains shared

Note: Static attributes remain shared

31
New cards

deep copy

If X and Y are objects, and Y is a deep copy of X, then:

  • All attributes are copied into Y

32
New cards

how to deep copy

override the clone method

call object’s default clone method for shallow copy

clone only instance variables that are mutable

33
New cards

Java type

A type is defined as:

  • A set of values (objects)

  • A set of operations (visible methods or behavior) that can be carried out with those values

Ex. int (primitive type) or Employee class (Java type)

34
New cards

type violation

When you assign / pass a value to the wrong type variable / argument

Example: int x = “Hello”;

35
New cards

Compile or runtime detection of type violation (which is better)

Compile-time, the sooner we catch the error, the lower the cost

Most rules for Java types are validated in compile time

36
New cards

Java types (5)

Primitive, class, interface, array, null

37
New cards

Interface type

Interface type is only used for declaration, not instantiation

Interface type can be used for:

  • Variables (local, instance)

  • Method arguments

  • Return types

38
New cards

Values in Java

Any value in Java is one of the following:

  • A value of a primitive type

  • A reference to an object

  • A reference to an array

  • null

39
New cards

type-subtype relationship is used for

polymorphic relationships

40
New cards

Why did java create wrappers?

in some cases, we need the primitive types fulfill as an object

41
New cards
<p>instanceOf operator</p>

instanceOf operator

It returns true if emp refers to an object of Employee or one of its subtypes

A good place to use instanceof operator is before casting to make sure that the casting won’t fail

42
New cards

Class Class

JVM associates an internal object of Class type to each class in your app

So class object holds all needed data about all objects of a class

43
New cards

access Class object (3 methods)

Use getClass() method of Object class

  • Employee emp = new Employee();

  • Class c1 = emp.getClass();

Using Class literal

  • Employee emp = new Employee();

  • Class c2 = Employee.class;

    • class literal is a static reference to Class object (which is why we use Employee class name, not emp object)

Using Class.forName(String className) - not reccommended

  • Class c3 = Class.forName(“package.Employee”);

44
New cards

How to precisely check object type of a variable

if (emp.getClass() == Employee.class) {}

  • checking returns true if emp is exactly Employee object

45
New cards

Enumerated types

special data type in programming that defines a fixed set of named constants

In java, enum is a class type

<p>special data type in programming that defines a fixed set of named constants</p><p>In java, enum is a class type</p>
46
New cards

generics

generic type (general purpose) for any kind of classes

47
New cards

is there type subtype relationship between generic types?

no

48
New cards

generic method

a method with one or more type variables

Example: write a generic method, called printList that prints elements of an ArrayList of any type

49
New cards

generic class

A generic class is a class with one or more type-variables

Example:

  • Write a generic Box class that simulates a box of any type of objects such as Integer, String, Cat, etc…

  • We can put some objects into it, remove some objects, and print its contents

  • To get familiar with a useful Java collection, we use Java HashSet as the underlying data structure

50
New cards

Type bound

a restriction applied to generic type parameters

51
New cards

Wildcards (3 flavors)

? = any type

? extends E = all subtypes of E including E itself

  • wild card with upper bound

? super E = all supertypes of E including E itself

  • wild card with lower bound

<p>? = any type</p><p>? extends E = all subtypes of E including E itself</p><ul><li><p>wild card with upper bound</p></li></ul><p>? super E = all supertypes of E including E itself</p><ul><li><p>wild card with lower bound</p></li></ul><p></p>
52
New cards

Law of Demeter

A class should only call direct members of the other classes

Example (bad): SomeType foo = objA.getObjB().doSomethingB();

53
New cards

Loose Coupling

ClassA is loosely coupled with ClassB if the only information ClassA has about classB is whatever classB exposes through its interface

  • LoD tries to keep the degree of coupling at the loose-coupling level

54
New cards

Tight Coupling

ClassA is tightly coupled with ClassB if ClassA has some information about how ClassB is implemented (i.e more than just interface)

  • ClassA depends on B’s internal implementation, meaning if ClassB changes, classA is likely to break!

55
New cards

Solutions for LoD

Remove the dependency of ClassA

If your class has dependency on ClassA, then write a wrapper in ClassA to hide ClassB

56
New cards

Serialization

The mechanism of converting objects (states) into stream of bits