JAVA

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

types

(1)primitive types:int, double, char, boolean, etc) - these are all pre-defined2) compound types (called reference types in your book) - these are both pre-defined and created by the programmer

local class

- created in a method- can have access to all the fields and local variables available to the code where the class is created.- any local variable accessed by the class must be final so that the variable can be moved off of the stack- there can be two "this" values in the body of an local class (assuming it was created inside a non-static method body

how to write constructors

1) The first line of a constructor must be a call to another constructor. (This is also the only place in the code were we can have a constructor call.)These are the two possibilities:super() <- possibly with input in the parentheses. This calls (i.e. executes) the constructor of the parent class (the class this class extends). this() <- possibly with input in the parentheses. This calls a constructor of the same class. If you do not explicitly have a constructor call as the first line of your constructor body, Java automatically places super(), with no input, there.

non static nested classes

- you must create an instance of the containing class before you can create an instance of the nested class.- these classes have access to all the static and non-static elements of the containing class.- there are two "this" values in the instance methods of the nested class. One for the nested class instance and one for the containing class instance.- there is the different way of creating objects using new when outside of the containing class.

string loops

.length() . .charAt, start at 0 last character is length - 1

point of super class

- Every class "inherits" all public and protected instance methods of the super class.- Every class has access to all public and protected fields, class (i.e. static) methods, and nested types of the super class.(More about this later.)

how new works

1) allocates space in the heap for the instance2) calls the constructor for Employee2.a) the first thing the constructor for Employee does is call super(), the constructor for Object. That initializes all the Object fields.2.b) next the constructor initializes the Employee fields2.c) the constructor does whatever other processing is in its body3) returns the location in the heap of the instance

how if else works

1) the condition is evaluated2a) if the condition is true, the then-statement is executed2b) if the condition is false and the else-statement exists, the else-statement is executed3) the next statement of the program is executed

boolean

1-bit of data

new does what

1. Allocate space in memory for the type instance.2. Initializes the instance using the input data (it does this by calling a special method/function, called a constructor, whose sole purpose is initializing instances)3. Returns the location in memory of the instance. This location is called the "reference" of the instance.

Good Object Oriented programming

1. Any data that must be stored in a type should be stored in a private field.2. Any access of the data or other actions of the type should be implemented using a public method.3. Anytime we want to access the field, we should use the public method instead of the field.

OO rules

1. Create private fields2. Create public getter/setter methods so that classes that extends this class can change behavior if they want.3. Everywhere in our code that uses a value, we use the getter/setter methods instead of the fields.4. Except in the constructor where, if we want a field to be initialized, we use the field directly.

throw exception

1. Place "throws ExceptionType" in the header of the method. See the lab example with IOException. This must be done if throwing a checked exception.This notation in the header both informs the compiler that the specified exception may be thrown and sets the default behavior of the method to throw the exception should it occur.2. Explicitly throw the exception with the throw statement.throw e;throw new ExceptionType();

basic loops

1. while loop 2. for loop 3. do-while loop 4. foreach loop

char

16- bits of data

short

16-bits of data

float

32-bits of data

int:

32-bits of data.

equals method

@Override public boolean equals(Object o) { if (o instanceof Employee) { Employee e = (Employee)o; return this.getEmployeeNumber() == e.getEmployeeNumber(); } else return false;}

interfaces

A Java interface is like a class, but it can only (essentially) contain public abstract method stubs (the method header, but no method body).An interface actually can contain more things, but the main purpose is to contain public abstract methods.An interface can also contain static fields, public static nested types,

Computer

A computer is composed of wires and switches. Data is transmitted down wires and each wire can have two different values: on (has current) or off (no current).

fields

A field is a variable that is declared inside the class instead of being inside a method.A field can be:a) static (class): one copy of the variable shared by all instances of the class. The variable exists for the duration of the program.b) non-static (instance): every object has its own copy of the variable. The variable exists as long as the instance exits.

final

A final value in Java is one that will not change once it is assigned its initial value.

how long do local variables exist

A local variable exists from the moment it is declared (that is when it is placed into its frame, method frame or mini-frame, until the end of the compound

nested

A nested type is a type defined inside another type. A nested class is a class defined inside another class.

this

A special variable inside an instance method that stores the address of the object the method is acting on.

abstract class

An abstract class is a class that cannot be instantiated. It is used to enforce common behavior of all its child classes.

abstract methods

An abstract method is a method with no body (i.e. it is a method stub). All classes inherit the abstract method, but unless the class is abstract, it must override the abstract method to give it a body.

anonymous

An anonymous class is one defined in the new expression that is creating the instance of the class. Note, that you should not create new methods when writing an anonymous class, but you should just override existing methods. (A reminder, that when we created the anonymous classes, all local variables used inside the anonymous class have to be final.

array

An array is a collection of variables of the same type, stored in a contiguous chunk of memory. array1 = new int[100]; array1[0] = 12;

class fields

Class fields are memory that is allocated outside of the instances.. Add static

4 types of variables

Class fields, instance fields, local variables, method parameters

for each

For each loops are a Java shortcut for Iterable classes and for arrays.The form of a foreach loop is: for (T i : Iterable<T>)and it reads as "foreach type T in iterable"For example, if list is a LinkedList<Integer>, we could have: for (Integer i : list)which reads as "foreach Integer in list"

Wrapper class

For each primitive type (including void), Java provides a wrapper class that allows you to store the primitive inside an object. This allows us to useprimitives where the code is expecting Objects. For the most part, the wrapper class is the same name as the primitive, but with a capital letter: Java will automatically convert between the wrapper class and the primitive, when needed and when it is clear what type is needed.

has a rule

If A has-a B, then make B a method/methods in A.

is a rule

If A is-a B then we make A and B classes where A extends B.

method reference

It is written to -appear- as if we are passing a method as input to another method, but that is not what is happening.Instead, the "method reference" is effectively another form of an anonymous class. b.addActionListener(this::reset);

what does extends mean

It says that any instance that is type of the class also is type of whatever it extends. The Phone class "inherits" all the public and protected methods of Object.The Phone class "has access to" all the public and protected fields, class (i.e. static) methods, and nested classes of Object.

iterator

Iterator is an object that lets us run through the contents of the class. These Iterator methods generalize the main components of a loop. If we have an Iterator for the abstract data type, we can loop through the abstract data type's contents by calling thehasNext() and next() methods of the Iterator. Thus, code using the Iterator does not need to know about the implementation details of the abstract data type.

iterable methods

Iterator<T> iterator() -> returns an object that implements the Iterator interface, and has the same generic as the Iterable class.

wildcard

Java provides a wildcard ? that means "Don't Care" for the generic.We can use the wildcard if we really do not care. That means we don't do anything where we require the generic to be anything other than Object.

java reflection

Java reflection is a way to look inside the structure of an object or a class even if we do not have access to the source code.We can also use reflection to manipulate any object or class. Object obj = new JFrame();Class<?> cls = obj.getClass();cls now stores the class information about the JFrame class. (Note we could have created the JFrame object using just reflection, too!)We can get a list of all non-private methods of the JFrame class:cls.getMethods();or all the methods (including the private ones) declared in the JFrame class:cls.getDeclaredMethods();

static constructors

Likewise, when a class is loaded into the heap, a "static constructor" can be used to initialize the class structure (basically the static fields).The static constructor is just a compound statement preceded by static:static {.. the code to run when the class is first loaded into the heap}

super

Similar to this, but it is used to access methods and fields (and nested types) of the parent class

constructor

Special methods that are used by new to initialize an object. The method has no return type and the name must be the same as the class name.

static nested classes

Static nested classes: used the same as "normal" classes except they are located inside another class.- these classes have access to all the static elements of the containing class.

current type

The "current type" is which of its polymorphic types it is typecast to.Every place that value is used in the code will have a current type associated with it.(The "current type" is called the "compile-time type" in Java references.) The current type determines what methods you are allowed to call as well as what fields and inner classes you will access.

true type

The "true type" is the type it is created as: new iPhone() means the instance will have true type iPhone.(The "true type" is called the "run-time type" in Java references.)Every object knows its true type (it is stored in the object's data, and the true type does not change. The true type determines the version of an instance method that is called.

comparable

The Comparable interface takes a generic type that indicates the type this object will be compared to.The Comparable interface requires a compareTo method that takes a parameter of the generic type.It should return < 0 if this object comes before the parameter in the default ordering of the type.It should return > 0 if this object comes after the parameter in the default ordering of the type.It should return = 0 if the two objects are equivalent in the default ordering of the type.

iterable

The Iterable interface is used to indicate that we can create an Iterator for the class, and an Iterator is an object that lets us run through the contents of the class.Every class that is an abstract data type and can store multiple elements should implement the Iterable interface.

what do constructors do

The constructors do the following when they are run: a) The first line of the constructor that calls another constructor is executed. (Recall that Java adds super() if you omit this line.) b) All fields of the instance are initialized. c) The rest of the constructor body is executed.

what does current type determine

The current type determines what methods you are allowed to call as well as what fields and inner classes you will access.

generic

The generic is a placeholder for a type to be specified later. We -declare- a generic before we can use it. There are two places we can declare a generic:- immediately after the type name in the non-primitive type header- immediately before the return type in a method

Generic Type

The generic type is used by the compiler so it only affects the current type. The compiler makes sure that the types that you specify match.

heap

The heap is unorganized memory used for data that needs to be more permanent. In Java, all classes and objects are stored in the heap. The heap is used to store classes and instances.

Weird Math

Mathematics in Java is not the same as "real" mathematics. Errors will crop up due to the fixed size of the numeric data types that would not appear if we were manipulating the numbers using "real" mathematics. A programmer must always be alert to situations where such errors could occur so that they do not cause

jar files

The jar file is just a collection of Java class files. (It can contain source files, too, but that is not needed for the jar file to work.)We typically collect programs and libraries into a jar file, and then we can share the jar file with others without having to send all the java and class files.On most systems, a user can just click on an executable jar file to run the program.

true type current type main point

The key point is that an object always runs the version of the method for it's true type. (This is for instance methods.)The current type can change whether we are allowed to run the method, but the true type determines what version is run.

Integer p = 4

The line is really: "Integer p = new Integer(4)". THen p + 1 is p = new Integer(p.intValue() + 1);"

main

The main method is a special method of Java. Every stand-alone program must have a main method. It is what the Java Virtual Machine calls to start your program.Each class may have one (and only one) main method. The form ispublic static void main(String[] args) {

Stack frame contains

The stack frame contains:1. Method parameters (including the "hidden" parameter this for non-static methods) and any local variables declared inside the method2. Bookkeeping needed to return from a function (where in the code do we need to start executing, and what should we do with the value returned by the method?)

stack

The stack is organized memory used for method calls. In Java, the default is to set aside about 1MB for the stack (this can be changed when you launch Java).

what does true type determine

The true type determines the version of an instance method that is called.

Data

The type of a piece of data is what the piece of data represents. It is specified by the programmer and by rules of the programming language. Java is a "strongly typed" language. That means that every piece of data will have a well defined type and unambiguous type and the compiler will verify that every type is used correctly.

instance (or non-static) fields

There is a separate field with each instance of the type.

class (or static) fields

There is a single field that belongs to the class. All instances of the class share that field.

breakpoint

This is a spot in your code where you want the execution to pause. You set this using the menu you get when you right click the mouse while on the code.Then you can run your code by entering appropriate Java into the interactions pane. When the execution reaches the breakpoint, the execution will pause.

new

To create an instance of a reference/compound type, use the new operatornew desired-type(0 or more input values)

Typecast rules

Values are automatically converted "narrower" to "wider" types. A conversion from a "wider" to a "narrower" typerequires an explicit typecast. Generally, when converting to a wider type, Java converts the value to be as close aspossible to the original value.

binary search

Proposed Algorithm (Binary Search)1. Examine the middle element.2. If the middle element is smaller than x, repeat on the upper half of the array.3. If the middle element is larger than x, repeat on the bottom half of the array.

Method Overriding:

We override a method by creating another method withthe same access modifier, return type, name, and input types and order (called the parameter signature). You can change the behavior of any inherited method by overriding it (providing a method with the same method header as the inherited method).Java uses the current type to make sure the method call is valid.Java uses the true type to call the correct version of the method. Every object knows its true type. Every object makes sure the proper method version is used.

method overriding

We replace an inherited instance method by writing a method with the same name, return type, and parameter signature(More precisely, if the return type is non-primitive, the return type can be narrower.)

Top-down design

We start with the entire idea for the program and break it into the separate tasks.We then break each task into sub-tasks.We continue breaking down the sub-tasks further until we get to a stage where we finally see how to write code for it.

weakest precondition

Weakest Preconditions:Given a goal for a statement, or sequence of statements, the "weakest precondition" is the minimum that must be true in order to guarantee that the goal is true after we execute the statements.

subgoal of loop

What is the subgoal of the loop. It is what must be true after each iteration for the loop to continue: "x is not in the first i elements of array"

Narrow Wider Primitive Types

Widest: double, float, long, int, short/char, byte : Narrowest

class (or static) methods

With a static method (class method), the method "operates" on the compound type itself.

instance (or non-static) methods

With an instance method, the method "operates" on an instance of the class.

lambda expression

a lambda expression is an anonymous function that can be stored to a variable, input to another function,returned from a function, etc. b.setOnAction((ActionEvent e) -> {JButton b2 = (JButton)e.getSource(); b2.setText("Click count: " + ++count);}

instance fields

a separate variable stored in each instance of the class. Every instance has its own version. - an instance field exists as long as the containing instance exists

local variables

a variable declared inside a method. It exists from the moment created until the end of the compound statement it is declared it.

assignment opertor:

a) The left operand must evaluate to a variable. The variable can be any type (primitive or non-primitive).b) The type of the right operand must be the same or narrower as the type of the variable on the left (*)c) The result is the same type as the variable and the value that was stored in the variable.

boolean operators:

a) The operands (or operand for !) must be booleand) The result is booleanc) && and || use "short-circuit evaluation". If the result value is known from just the left operand, the right operand is not evaluated:

equality operators:

a) The operands can be any type (primitive or non-primitive, and The narrower operand is automatically widened to the wider operand's type. - it is an error if the automatic type conversion is not allowedb) The result is booleanc) The value is determined by comparing the boolean values of the two operands (after the automatic widening).

comparison operators:

a) The operands must be a numeric primitive (a non-boolean primitive)b) The result type is booleanc) The narrower operand type is automatically widened before the operation is performed

Primitive operations:

a) The two operands (or one operand for the unary operators) must be a numeric primitive type (i.e. not boolean)b) The narrower operand is automatically widened to match the wider operand, and if both operands are narrower thanint, they are automatically widened to int.c) The result is the type of the wider operand, or int if both operands are narrower than int

iterator methods

boolean hasNext() -> returns true if there are more elements in the listT next() -> returns the next element in the list, and "iterates" so the next time we call next(), we get the next element of the list

3 <= 3.1

boolean legal

what does heap store

classes and instances.

5.0 + 3

double

new Integer(5) == new Integer(5)

false

what goes in class body

field declarations (these can include assignment operators)- methods- other non-primitive type definitions (these are called inner types or nested types)- constructors: special methods used to initialize instances of the class- initializers: used to initialize the class itself - these are rarely used in Java programs and so we might not cover them in the course

for loop

for (initial statement; condition; increment statements) loop-body-statementthe initial statement is a single statementincrement statements are 0 or more statements, separated by commas (no terminating semicolons)condition and loop-body-statement are the same as for while loops. For loop behavior:1) the initial statement is executed2) the condition is evaluated3) if the condition is true3a) the loop body statement is executed3b) the increment statements are executed3c) repeat step 2if the condition is false, go to the next statement of the program

'a' + 'b'

int

short)3 + (byte)5

int

double x = 5

legal

double x x = 1

legal

false != true

legal

int y = (int)3.0

legal

short s = 1000000 / 10000

legal

x = y = 3

legal

5 == 5.0

legal true

char c = 'a' + 5

legaql

linear search

no assumptions, works for all arrays but isn't that efficient Looks through every element of the array, in order

recursion

public int lengthFromHere() { if (this.getNext() == null) // there are no nodes after this one return 0; else // otherwise, ask the next node what the length after it is, and add 1 return getNext().lengthFromHere() + 1; }

main

public static void main(String[] args) {Application.launch(args);

access modifier

public: the code can be used/accessed anywhere in the programprotected: the code can be used in this type and in any type that extends this type (or in any type in the same folder as this type)private: the code can only be used in the body of this type

class fields

the variable is stored in the class (one copy that all the objects share)- class fields exist for the duration of the program.

method parameters

the variable(s) that store an input to the method. It exists only in the body of the method.

this

this is a special variable that exists inside instance (non-static) methods.this stores the address to the object that the method is acting on.this acts a hidden parameter to the method.

handle exception

try { - code that could throw an exception} catch (ExceptionType e) { - code that is executed if an exception of type ExceptionType occurs inside the try block - e is a variable that stores the exception object address, and it exists inside this block } finally { - code that is always executed upon exit of the try and catch blocks} There may be 0 or more catch blocks with a try and at most one finally block. There must be at least one catch block or a finally block with the try statement. try { } catch (ExceptionType1 e) { } catch (ExceptionType2 e) { }

static methods and generics

use different generic. The generic is specified by the creating of an instance to the class, and there is no instance in a static method.Instead, we can declare a generic in a method by placing the generic declaration before the return type.In our example, I changed the generic to S to make it clear that we are not using the T generic declared in the LinkedList class header.

overriding

verriding is when we change the behavior of an inherited method by writing another version with exactly the same name and parameter signatureand the same (or narrower in the case of a non-primitive) return type.

while loop

while (condition) loop-body-statementloop-body-statement is a single statement, simple or compoundcondition is any boolean expression While loop behavior:1) the condition is evaluated2) if the condition is true:2a) the loop body statement is executed2b) repeat step 1if the condition is false, go to the next statement of the program

long

64-bits of data

double

64-bits of data.

instance fields

Instance fields are memory that is allocated inside each instance. just private. Every instance gets its own copy of the instance fields.

anonymous class

- A local class that is created at the same step as the "new" operator.

Bit

A bit is the smallest unit of information. A bit is two values, usually denoted as 0 and 1.

Byte

A byte is 8 bits. A byte has 2^8 = 256 different values.

constructor

A constructor is a special method that is called by the new operator to initialize a class.A constructor must have the same name as the class and no return type:So, a constructor has the form: public ClassName(inputs) {A constructor is not inherited by classes that extend this class. Each class must define its own constructors.Default Constructors:If you do not write a constructor, Java provides a default constructor that takes no input.

linked list

A data structure that stores values of the same typeBenefits: Can easily increase or decrease size as needed. Can easily insert or delete at any location.Downside: Fast access to only a few elements.

summary of non primitive rules

A summary of the rules:1) Every object is created as a specific type using the new operator. I call this type the "true type".The true type determines how the object will behave. It does this by determining what version of a method is run.The true type never changes.Ex: new MyFirstWindow() creates an instance whose true type is MyFirstWindow. new JFrame() creates an instance whose true type is JFrame.2) The object is not only its "true type". It is also the type of the super class of the true type, that class's super class, and so on up to Object. This property of being many types at the same time is called "polymorphism".3) A typecast does not change the object. The typecast does not change the true type of the object. Instead, the typecast determines which of the legal polymorphic types for the object is the object acting as at this line of code.I call the type that the object is acting as the "current type". The compiler uses the current type to determine what methods you are allowed to call and what fields you can access.You can only call methods and access fields that exist for that current type.The specific field or class method accessed will depend on the current type, but the instance method that is used will be the version of the true type.

threads

A thread is an execution on your computer. Usually your program is a single thread.If you break your program into multiple threads, each thread will run independently and concurrently.So each thread in your program is a piece of the program that can run independently and concurrently with the rest of your program.

non primitive typecast rules

A typecast that goes "up" the hierarchy (wider) is automatic, by a typecast that goes "down" the hierarchy (narrower) must be explicit.

variable

A variable is the name given to a location in memory. In Java, variable has a type associated with it.A variable is used to store data. In Java, you can only store values with the appropriate type into the variable.

polymorphism updated

An object is many types at the same time: its true type plus all types that the true type extendsor implements. all non-static methods must be public method stubs.

Polymorphism

An object is multiple types: every type from its true type up the hierarchy to Object. The stack is used to store information used by method calls.

binary search

Assumes that the array is sorted in a non-decreasing fashion Checks the middle element, if it's less than the value being searched for it looks in the first half of the array, if not, it looks at the second half of the array

Bottom-up design

In this technique, we do not worry about the entire program at first. Instead, we start by figuring out what piece of the program wecan code first.

overloading

Overloading is when we create another method of the same name. This is legal as long as the parameter signature is different in each method.

Overriding methods

Overriding methods is the technique of Java where we re-define the behavior of an inherited method.We override an inherited method by writing a method that has exactly the same access modifier, return type(*), name, and input types.(*) the return type can be narrower if the return type is a non-primitive

=

Storing a value. Assigning a value.

typecast

Typecasts (type conversions)Java allows the programmer to convert a value of one type into a value of a different type.

1 != true

illegal

3 < 4 < 5

illegal

int y = 3.0

illegal

int y y = 1.0

illegal

char c = 'A' + x

illegal no matter value of x

i++

increments i and then returns the original value of i

++i

increments i by 1 and then returns the new value of i

what does stack store

information used by method calls.

types of fields

instance fields, class fields


Ensembles d'études connexes

Interview Q&A- Cloud Solutions Architect, Cloud Engineer, DevOps

View Set

(Assignment)Properties Of Probability Distribution

View Set