Data Structures Using Java Exam 1

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

3 main things you need in a .java source file

package, import, and class (plus comments required by style guide)

I/O

performed in Java using built-in static objects, called System.out and System.in

printProgression(int n)* (pg. 70)

prints 1st n values of progression

Developing projects in the real world is difficult because*

projects run into problems with the software much more frequently than with the hardware (cost overruns, schedule overruns, reliability problems). Hardware development typically follows well-established design practices.

Scanner

provides methods for: hasNext(), next() to get any token hasNextDouble(), nextDouble() to get a variety of types hasNextLine(), nextLine() to read by lines versus token findlnLine(String s) to do regular expressions Good for file I/O. Syntax: Scanner myScan = new Scanner(new File("input.txt")); while (myScan.hasNext()){ name[i] = myScan.next(); ages[i] = myScan.nextInt(); i++ }

Creating your own exception class

public class EmptyStackException extends RuntimeException { public EmptyStack Exception (String err) { super(err); } }

enums

public enum Day(MON TUE); Day day = Day.MON; Day t = Day.valueOf("TUE");

resetToFirst()* (pg. 70)

resets and returns First from Progression class

Generics

similar to C++ templates Two approaches for building ADT which hold variety of data: 1. Cast to Object, and store Object 2. Make it a generic ... and still store Object

import command

specifies which library code may be needed to execute the program

Exception paradigm/syntax

try, throw, catch try { //RISKY CODE (throw in the method where the error could happen, not here) } catch (exception_type1 id1) { ... } finally { ... } Note: Java 7 uses Scanner and doesn't use finally Note2: A loop surrounding the try-catch block can work nicely

super keyword

typically called in the constructor to insert a call to our superclass constructor. We then just write the constructor implementation for the data unique to the subclass. Can also be used to call a superclass method

Implements keyword

used to implement an interface-- ISA relationship

Java's performance is...

worse than compiled languages but isn't significant for many applications

Differences from c++

-No #include, #define, etc - No global variables or functions (although public static members are close) - No pointers...kind of (references are really pointers, but it is all transparent to user) - Garbage collection, no delete required - No goto, no big loss - Can invoke method before defined, without prototyping - No struct and union types - No typedef (declare a class instead) - No method pointers (can often be worked around using interfaces)

JUnit

1. A simple framework for writing and running automated tests 2. Performs unit testing for a class or package. Allows you to define tests which thoroughly test code, but which are located in a separate class from your production code and are thus not a part of the production release. 3. Methods are annotated to describe purpose @Test. Name of method should start with "test." You write the body of the method, usually instantiating an object of class being tested, and performing actions on it.

Objects look similar to C++ but meaning is different because...

1. All object names are merely object references (similar in concept to a pointer) 2. When you declare an object, you are actually just saying that the name is a reference or pointer to the object type. 3. Although it is a reference, we can still use the dot operator to access fields or methods.

Casting rule

1. An explicit cast is required if a loss of precision might occur due to cast (double to int requires explicit cast). 2. You can always cast a derived class into its superclass. 3. Casting from superclass to subclass must be done explicitly and will cause runtime exception if you try to cast into improper type.

Interface*

1. Central to how to develop ADTs for data structures 2. Simply a complete abstraction of how a person would interact with a particular type of object. In other words, "a completely "abstract class" that is used to group related methods with empty bodies." 3. Methods are empty. Class will never be instantiated- only lays out set of methods which any credible object which claims to implement a TVViewer ought to provide. If you use that interface, you MUST provide implementations for all the abstract methods. 4. If you create an interface, and create a class which implements the interface, then you can use references to the interface to point to objects of the class implementing the interface. [modifiers] class Joe [extends superclass] [implements interface(s)]{ }

Asymptomatic performane

1. How does the performance vary with the problem size? I.e. how does the runtime grow proportional to the problem size n? 2. Most common approach for how to get a feel for how the algorithm performs as the problem size grows (overall, program analysis) 3. Never accept an asymptotic analysis at face value

Java bottomline

1. If execution speed isn't a big factor, Java is a great choice for most app because of it's IDE's and libraries 2. Industry wants Java programmers

What goes in a class?

1. Instance variables 2. Methods 3. Static variables (class fields) 4. Static methods (class methods)

Object-oriented design

1. Models the way we view the world 2. Encourages modularity, helps manage complexity OOD changes the design process and the organization of the implementation by using objects and interactions instead of functions and data.

Inheritance

1. Objects inherit the data members and methods of their parents or baseclass or superclass 2. Often objects drived from a superclass satisfy the is-a relationship. 3. We say that the derived object extends, or specializes the superclass object 4. Java only allows SINGLE INHERITANCE (however, can implement multiple interfaces, which can almost be a substitute)

Static variables

1. Only one copy per program-not one per object 2. Good for declaring constants or counters 3. public static somewhat like global variables

@Test methods

1. Regular java code inside that tests object 2. Test primarily center around assertions (assertEquals, assertTrue, assertFalse, etc). When an assertion fails, an AssertionError exception is thrown. Don't catch is because the testing framework will.

Goal of software engineering

1. Reliable 2. Understandable 3. Cost effective 4. Adaptable/Reusable 5. Secure

Static methods

1. Somewhat like global functions 2. Can be called even if no objects instantiated (like Integer.toString(myInt));

Lambda expressions

1. Syntax for handling anonymous functions/classes. 2. Provide alternate syntax for anonymous classes. 3. When you do Swing you can use an anonymous class for event handlers. 4. Only have parameters and body Button b = new Jbutton(Hi Mom!"); b.addActionListener((e) -> System.out.println("HW"));

JUnit 5 Testing

1. Uses asserts like the rest of JUnit 2.@BeforeAll, @AfterAll -- Run once during the testing of a class, before and after any test class methods (other than constructors) are run. Allows initialization of things that only have to happen. 3. @BeforeEach, @AfterEach -- Test initializer methods, run before and after each test defined in the test class, can be used to set up some variables, can be used if all tests requires some detailed setup (avoids duplicating code in test methods)

How can we analyze code for performance?

1. Writing a high-level description of the code in pseudo-code (high-level description which is language independent). 2. Often, analysts focus on worse-case performance because performance varies widely based upon either the size or nature of the inputs

forEach() method

1. used for iterating through data structures which support the functional iterable interface 2. The argument to forEach() is itself an Object which satisfies another functional interface: Consumer which has an accept(arg) method 3. Thus, we canc all forEach() and pass a lambda expression List<String>names = new ArrayList<String>(); ...// names.forEach(nane->System.out.println(name));

abstract class modifier

A class which contains abstract functions. 1. Have no body and must be overridden 2. Will be the superclass for another class which will declare concrete function. 3. CANNOT INSTANTIATE A CLASS

General syntax of a throw statement

An exception is actually an object. We create the object and then throw it to be caught, perhaps several functions down in the call tree. if (arrayIndex > arraySize) { throw new BoundaryViolationException("Read off end of array at index" + arrayIndex); } You can specify in method headers that the method may result in an exception being throw, either in the method itself or in methods it may call (Required for many types of exceptions). public void readAllArrayValues () BoundaryViolationException { }

Byte code

An intermediate language between source code and object code. Java first compiles source code into byte code and then interprets the byte code with a the Java Virtual Machine (JVM)

How can we analyze code performance from pseudo-code?

Approximate the primitive operations required just by looking at the pseudocode. If we can determine how many times the loops iterate, we can come up with a rough guess of execution time.

Modularity*

Break a program up into distinct section with all common functionality (e.g. network code) in same section which isolates problems and can help with security.

public class modifier

Can be see and instantiated by anyone. 1. Same package see automatically 2. Other package can see if they use an import statement 3. If not declared public, a class can only be used by other classes in the same package

Big-Theta

Combination of Big-o and Big-Omega

Cannot call static variables and methods as...

method/var of a particular object. Cannot use classname.var or classname.method(). Must call with the class that they were statically defined with. Ex. thisJoe.getTotalJoes() //NO thisJoe.totalJoes++; //NO Joe.totalJoes++; //OK

All objects must be created dynamically using which operator?

new

Annotations

Hints to the compiler or another tool looking at the code regarding what you mean. @Keyword Also used to override methods. @Override

Joe, Pete, Sam example*

If Joe is a class with a method main, running java Joe from the command line will execute the code in main. If Pete and Sam are other classes in the directory, also with main methods, java Pete and java Sam would also work. NOTE: Joe may call routines of Pete and Sam, even though they have a main associated with them.

Example of ADT:

Integer, Float, Boolean

functional interface

Interface with a single abstract method. Occasionally you create this interface, but often you use a functional library interface. ActionListener has a single method: void actionPerformed(ActionEvent e) Button b = new Jbutton("Hi Mom!"); b.addActionListener(e->System.out.println("HW")); Java knows name and return type; only need parameters and body

Big-Omega

Inverse of Big-O: there exists c, n0 so that f(n) >= c g(n) for some n0

Interfaces in Java 8

Java 8 allows interfaces to specify static or default method implementations. 1. Static can be called but not overridden in implementing class. 2. Default is instance and can be overridden 3. If interface changes for either static or default, don't have to change everyone who implements it.

JDK*

Java Development Kit, necessary for compilation

JRE*

Java Runtime Environment, environment which any any official release of Java must support

What kind of language is java?

Java is primarily an interpretive language, designed for portability between platforms

Exponential special class*

O (a^n)

Logarithmic special class*

O (log n)

Linear special class*

O (n)

Quadratic special class*

O (n^2)

Polynomial special class*

O (n^k)

3 types of comments

Old C comments: /* */ C++ comments: // Javadoc comments: /** */

final class modifier

no classes can be derived from it, which provides protection from someone deriving a class and getting access they otherwise shouldn't get

Abstraction*

Process of extracting relevant properties of an object while ignoring inessential details

It is surprisingly difficult to develop...*

Secure Software due to malicious agents (nation-states, terrorists, criminals, corporate espionage, hobby hackers). Most issues are from ad hoc programming practices.

Encapsulation/Information Hiding*

Separating aspects of an object into internal and external aspects. Once you have abstracted the essential external properties of an object, you hide the internal properties.

Extends keyword

The keyword the specifies that a class inherits data and functionality from an existing class-- ISA relationship. Classes automatically inherit all data from their superclass. They can only access public and protected. If they're in the same package they can use friendly methods (methods without modifiers).

What is our purpose in this course?*

To honor and glorify God by the way we conduct ourselves. Colossians 3:22-24

Big O Notation

We define f(n) is O(g(n)) if: there exists a real constant c>0 and an integer constant n0 >= 1 such that f(n) <= c g(n) for every integer n > n0. We typically say the function is order n^3 or O(n^3).

Instance variable declaration

[modifiers] type name [= init_val]; double height = 2.6; public, private, protected modifiers are on each variable

Applet*

a program that runs within another application such as a website

Query*

a question about data, or making a decision regarding data

ADT*

abstract data type: a well-defined and complete data abstraction that uses information hiding. An ADT specifies the operations which can be performed on the data, but hides how the data is stored and how the operations actually manipulate the data.

Object class

all Java classes have a superclass, the Object class. If a class is not declared with extends, it automatically extends from the Object class. So you can manipulate it as an Object.

Data Structure

an efficient, systematic way of organizing and accessing data. The key is to determine how data needs to be used and then structure it to be done efficiently by optimizing the most common case.

public variable/method modifier

anyone can access NEVER USE ON A VARIABLE

final variable modifier

basically a constant, must be assigned an initial value which cannot be changed - often associated with static -- static final double PI = 3.14;

In Java all parameters are passed...

by value. However, since all object names are actually object references, objects in effect are passed by reference.

instanceof*

checks whether an object is an instance of a specific class or an interface

.jar file

collection of classes grouped together in an archive for easy deployment

computeNext()* (pg. 70)

compute and return next value

default modifier

considered "friendly" and can be accessed by other classes in the package

Javadoc comments required for...

each class, each major method of the class (generally the public ones)

Good performance =

generally means running time, but occasionally memory usage is a concern

ALWAYS

have a lowercase directory and public static void on main

Override

if a subclass has any method with the same signature as the superclass, the subclass will OVERRIDE the methods of the superclass. Note: Signature includes method name and type and number of parameters, not return type. But it is illegal to have 2 methods which differ only in return type.

final method modifier

indicates that the method cannot be overridden by a derived class

static method modifier

indicates that the method is associated with the entire class, not a particular instance. Makes a class method.

abstract method modifier

indicates the method has no body, and is intended to be overridden (like C++ pure virtual). Makes class abstract

Java's biggest strength is that...*

it is hot and has the best technology in library code and IDE development

static variable modifier

makes it a static variable, i.e. not associated with an individual object. Makes a class variable.

private variable/method modifier

only class methods can access

protected variable/method modifier

others in package, or any derived classes (subclasses) can see


Set pelajaran terkait

La Tour Eiffel Lecture Vocabulaire

View Set