Revature Week 1 (Java)

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Logical Operators

! Not, ~ Bitwise Not, && logical AND, || logical OR, & bitwise AND (Will not short circuit), | bitwise OR, ^ exclusive OR (Returns true if both inputs are different), == comparison , != not equal to, >, <, >=, <=, Instanceof (returns a boolean if the object is an instance of a given class), Condition ? ifTrue : ifFalse

ArrayList

(Class) A resizable array that expands itself by 50%. Not synchronized.

Stack (Collection)

(Class) FILO

LinkedList

(Class) Has the same features as an ArrayList, but is structured differently. Each node only points to the previous and next node. Uses the deque interface, so looking at the first and last node is fast, but the inner nodes are slow.

PriorityQueue

(Class) Keeps everything organized by priority. The first out will have the highest priority, otherwise obeys FIFO.

TreeMap

(Class) Keys are sorted in their natural order, or by a provided comparator at creation time.

HashMap

(Class) Map that isn't synchronized but fast.

Vector

(Class) Nearly identical to ArrayList, but expands by 100% instead and is also synchronized.

HashSet

(Class) Organizes itself based on what's most efficient. Every item is unique. Uses an underlying hash table.

Hashtable

(Class) Same as HashMap, but synchronized and cannot take in null values.

Deque

(Interface) Double ended queue, can return from the other end.

TreeSet

(TreeSet) Organizes itself based on alphabetical/chronological. Uses a red black tree algorithm.

String methods (Know a few)

*.substring(int x, int y)* Returns the substring between the given indices, beginning is inclusive, end is exclusive *.toUpperCase()* and *.toLowerCase()* *.charAt(int x)* finds a character at a given location *.indexOf(char a)* returns the first index of a particular character *.length()*

Scopes of a variable (4)

*Static* (think classes) Declared at the beginning of the class, uses the static keyword *Instance* (think objects) Declared at the same place as static, but doesn't use any keywords *Method* Only accessible within the same piece of the class *Block* (local, loop) Only accessible within the {} it was created inside It's essentially asking "where does this variable die?"

Mathematical Operators

++pre, post++, --pre, post--, +, -, =, *, /, %, +=, -=, *=, /=, %=

Why are strings immutable in Java? (4)

1) *Security*: If a String is received from an untrustworthy source, there is no guarantee that they won't change its value later on. 2) *Synchronization*: Because strings cannot be changed during runtime, they are thread-safe. 3) *Performance*: The String pool exists because Strings are immutable, increasing performance. 4) *Caching*: The hashCode() method is overridden in the String class to facilitate caching, which improves the performance of collections that use hashes+Strings.

What are the differences between the Comparable and Comparator interfaces?

1) Comparable is implemented by the class itself (natural order), while Comparator is implemented by a separate class (any defined attribute of classes). 2) Comparable (and by extension compareTo) is used by default by the .sort method, while a Comparator can be taken in as an optional second parameter in .sort.

What can 'this' be used for? (5)

1) Invoke current class constructor 2) Invoke current class method 3) Return the current class object 4) Pass an argument in the method call 5) Pass an argument in the constructor call

What constraints are placed on Java constructors? (3)

1) Name must be the same as class name. 2) No explicit return type. 3) Cannot be abstract, static, final, or synchronized.

What is super() used for? (3)

1) To call the immediate parent. 2) Used with instance members (variables/methods). 3) Used within a constructor to call the constructor of the parent class.

Why do we use Java? (7)

1) WORA (Write once, run anywhere) 2) OOP, better reflects the real world 3) Strictly typed 4) Modular 5) Widely used 6) Strong backing from Oracle 7) Automatic garbage collection

== vs .equals

== compares references (addresses) .equals() checks values (content) instead of reference .equals() must be overridden in your custom classes so it knows what to compare for values

What is the difference between a static field, method, and class?

A *static field* is accessible by the rest of the program using className.fieldName. A *static method* can be called without an instance of the class. Use className.methodName. A *static class* may only exist within another class in java, but its purpose is currently beyond me. Something about memory efficiency?

What kind of compiler does the JVM use?

A Just in time compiler (JIT) whose job is to convert byte code to native machine code. This compiler will first compile code to C, then to 1's and 0's.

Collection Framwork

A collection is an object that represents a group of objects, and the framework architecture offers a unified way to represent and manipulate these collections.

Constructors

A method for creating an object in a class. When an object is created, the compiler makes sure that constructors for all its members and inherited objects are called. Java will create default constructors if your class doesn't have any.

Heap

A region of your computer's memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger).

What is a stack trace?

A report of the active stack frames at a certain point in time during the execution of a program. Each time a function is called in a program, a block of memory is allocated on top of the runtime stack. At a high level, an activation record allocates memory for the function's parameters and local variables declared in the function.

Stack

A special region of your computer's memory that stores temporary variables. Is managed and optimized by the CPU quite closely. Every time a function declares a new primitive variable, it is "pushed" onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are deleted. Because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.

Class

A template used to create an object, and to define object data types and methods. When declaring a class, you are creating a new data type.

Final keyword

A variable whose value cannot be reassigned. Field - Constants Method - Cannot be overridden Class - Cannot be extended Note that a final object can still have its attributes modified through getters and setters

What's the difference between abstraction and encapsulation?

Abstraction solves issues at the design level, and is all about hiding unwanted details while only showing essential info. Focuses on what info an object should contain. Encapsulation solves issues at the implementation level, and binds code and data into a single unit. Usually means hiding internal details of an object for security reasons.

Downcasting

Also know as narrowing casting, this process must be addressed specifically by the programmer. When a larger type is converted to a smaller type.

Upcasting

Also know as widening casting, this process is done automatically by java in most cases. When a smaller type is transformed into a larger type. If done with classes, we cannot access the child class members not shared with the parent, but we can still access overridden members.

What is an exception in Java? Is it a class?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. Exceptions are classes in java, but checked/unchecked exceptions are merely categories.

Checked Exceptions (Know 3)

An exception notified by the compiler at compilation-time. The programmer should take care of these. FileNotFoundException IOException SQLException

Object

Any entity that has a state and behavior. Can be defined as an instance of a class.

API

Application Program Interface

Primitive Variables (8)

Byte (8 bits) Boolean (True/false, 1 bit, depending on the jvm) Char (single character, 16 bits) Float (32 bits) Double (64 bits) Int (32 bits) Short (16 bits) Long (64 bits)

What does super() mean within a constructor?

Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass. super(1,2,3);

Scanner

Class meant to gather input from the console and files.

StringBuilder and StringBuffer

Classes for storing and manipulating changeable data composed of multiple characters. Both have identical methods, but StringBuffer is synchronized and slower. Most of the time we will use StringBuilder.

Collection vs Collections

Collection is an interface, Collections is a class. Collection provides the standard functionality for the interfaces that extend it. The collections class sorts and synchronizes collection elements via its provided static methods.

Interfaces

Contracts with your classes. The classes that implement these must provide functionality for all provided methods. Interfaces also always have implicitly public and abstract methods, and public static final fields.

Generic Methods

Enables programmers to specify, with a single declaration, a set of related methods. Allows for more adaptive code. class Student<T>{ T age; Student(T age){ this.age = age; } } Student<Float> std = new Student<Float>(25.5f);

Generic Classes

Encapsulate operations that are not specific to a particular data type. public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } }

Why do we use generics in Java?

Generics are used to enforce type safety, meaning that your class is able to dynamically act on any datatype.

OOP Abstraction

Hiding implementation details from the user and only providing functionality. In Java, is accomplished by setting instance variables to private and using getters/setters. We can also use abstract classes+interfaces.

List Interface

Implemented by classes that represent an ordered collection of element such as numbers or strings. Allows duplicates.

(Extra) Which sorting algorithm does Arrays.sort(...) and Collections.sort(...) use in Java 8?

In Java 8, primitive Arrays are sorted using Insertion Sort for small Arrays and Quick Sort for large Arrays, though this varies slightly depending on a few factors, like the type of primitive being used. Collections of objects are sorted via Merge Sort. Insertion Sort is used for arrays shorter than 47, while Quick Sort is used for the rest.

Comparable Interface

Interface mainly used to sort arrays/lists of custom objects. It contains a single method, public int compareTo(), which must be overridden in your custom class. class Student implements Comparable<Student> {...} Used by .sort for a lot of different classes, such as Arrays and Collections.

Comparator Interface (2)

Interface that is used to order objects of a user-defined class in a customized way. It contains 2 methods: compare(obj1, obj2) and equals(obj). Steps: 1) We first create a class that implements comparator and overrides compare(...): *public class myComparator implements Comparator<Student> {...}* 2) We may now use our comparator as an optional parameter in Arrays and Collections: *Arrays.sort(a, new myComparator());*

Map Interface

Involves the storage of key/value pairs. Does not allow for duplicate keys. They keys can be taken away and stored as a separate set. Maps are the most efficient way to store data.

Iterable and Iterator

Iterable is at the top of the Collection hierarchy and doesn't do much. Iterator comes next, and allows iteration over a collection.

Abstract Classes

Meant to be the beginning of the inheritance tree for all your classes. It lays out the minimum for what all your classes will need and share. Doing this allows for abstraction, because we cannot tell how the method is being implemented, especially if it is being up-casted to the abstract class. The only reason for a constructor in an abstract class is to link it back to the object class.

Annotations

Metadata that tells the compiler and the developer the purpose of something, denoted with an @ in Java. We can create custom annotations that perform some kind of action.

Compile Time Polymorphism

Method overloading. Can change either the type, number, or order of parameters.

Run Time Polymorphism

Method overriding. We cannot reduce the visibility of a method, and if we change the return type, it must be a related variable to the return type of the parent's return type (called a *covariance*). Can also change the throws declaration to a subtype of the parent's.

Methods and parameters

Methods are used to expose the behavior of an object. They optionally can take in or return any data type.

Abstract Methods

Methods that have only a method header and will be extended or implemented in another class.

What does the String[] args portion of the main method mean?

Most important when running a Java application from the command line. The 'args' is a String array in the command line and applies to all words that appear after the class name, e.g. "java classname [args]". This allows the user to specify configuration information when the application is launched.

Errors (Know 3)

Not exceptions at all, but instead problems that arise beyond control of the user or the programmer. StackOverflowError OutOfMemoryError CompilationError

Reference Variable

Objects where the reference variable is held in the stack and the actual object is stored in the heap. The variable holds a reference to where the object is held.

Unchecked Exceptions (Know 3)

Occurs at the time of execution, also called RuntimeExceptions. Ignored at the time of compilation. IllegalArgumentException ArrayIndexOutOfBounds NullPointerException

(Extra) Naming conventions in java (6)

Package: Reverse of an address, lowercase Class: noun, TitleCase Method: verb, camelCase field: noun, camelCase Interface: adjective, TitleCase Final field/Constants: noun, UPPERCASE

Packages and Imports

Packages are how classes are organized. Imports are how classes can access classes in other packages.

What do developers use stack traces for?

Programmers commonly use stack tracing during interactive and post-mortem debugging. A stack trace allows tracking the sequence of nested functions called - up to the point where the stack trace is generated. In a post-mortem scenario this extends up to the function where the failure occurred (but was not necessarily caused).

Access Modifiers (4)

Public - Accessible from anywhere Protected - Same class, package, subclass Default - Same class, package Private - Same class only

Set Interface

Represents a collection of objects with no duplicates and no order. As a tradeoff, it's faster than a list.

Queue Interface

Represents an ordered collection based on some know order, usually FIFO

OOP Encapsulation

Restricting direct access to data. In java, usually accomplished through access modifiers.

.hashCode()

Returns a hash of the object, override this method whenever the equals method is overridden.

.toString()

Returns a string representation of an object. By default, returns java.lang.Object@memoryaddresshere

What is the difference between scope and encapsulation?

Scope is about defining the lifetime of objects, whereas encapsulation is all about controlling who can access those objects during that lifetime.

Var-args

Short for variable-length arguments. Use ellipses to create a method that can take in multiple arguments. public static void fun(int ... a) { // method body }

What is a static import?

Static imports allow us to access the static members of a class directly without using a class name or object. Without static import: Math.sqrt(4) import static java.lang.Math.*; sqrt(4)

Strings

Strings are a special class in java. They are immutable, and are kept track of in a pool of Strings in the heap. Under the hood, they are a final char array.

JVM vs JRE vs JDK

The *Java Virtual Machine* allows java to be converted into bytecode and will run on any machine. The *Java Runtime Environment* holds the JVM and its core libraries, minimum needed to run a program. The *Java Development Kit* holds both the JRE and JVM, and is the minimum needed to write code.

OOP Polymorphism

The ability for a child to change its abilities from others. Java achieves this through method overloading and method overriding.

Main Method

The method that is first called when a java program executes. public static void main(String[] args)

How do we determine the min and max value of a primitive data type?

The min and max of a particular data type is -2^(number of bits - 1) to 2^(number of bits -1)-1

Wrapper Classes

The object representation of primitive data types. They allow us to perform operations on primitives.

Try/Catch/Finally

To handle exceptions, the code that throws exceptions is placed inside a try block, and the code that handles the exceptions is placed inside a catch block, and the code that needs to be executed regardless of whether or not an exception is thrown is placed inside the finally block.

What is a 2D array?

Two-dimensional arrays form a tabular, two-dimensional arrangement. You access elements with an index pair a[i][j].

Static keyword

Used to declare members that do not belong to individual objects but to a class itself.

Control flow statements

We can control our application's decision making during runtime by using control flow statements. If, if-else, if-else if-else, and switches. Remember fall-through logic for switches, and that default will always come last. In for-loops and while-loops, remember that you can use break; to exit the loop entirely, or continue; to immediately jump to the next iteration.

Stack vs. Heap

When a program is run, memory is often dynamically allocated in two places; the stack and the heap. The stack stores method calls, primitive variables, and reference variables. The heap stores the actual objects. Memory is continuously allocated on a stack but not on a heap. Technically, once a block of memory has been allocated on the stack, it cannot be easily removed as there can be other blocks of memory that were allocated before it.

OOP Inheritance

When classes inherit traits and properties from their parents.

Bounded Type Parameters

When you want to restrict what can be passed into a type parameter. public static <T extends Comparable<T>> T maximum(T x, T y, T z) { return max;}

'this' keyword

Within an instance method or a constructor, *this* is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Often used in constructors and setters to eliminate the confusion between class attributes and parameters with the same name.

Casting

Works for both primitive and reference variables. When a variable is transformed into the type of another.

Can interfaces have methods with bodies?

Yes, through the use of *default/static methods*. These are mainly used for backwards compatibility involving lambdas.

What else can 'this' be used for in constructors?

You can also use the *this* keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. public Rectangle() { this(1, 1); } public Rectangle(int width, int height) { this.width = width; this.height = height; }

Arrays

a collection of items stored in a contiguous memory location and addressed using one or more indices.

What are some useful methods of StringBuilder? (5ish)

append(Str/Char/Int) charAt(int) deleteCharAt(int) indexOf(Str) length()

How could I use super() to refer to a method of a parent class?

class Person { void message() { System.out.println("This is person class"); } } class Student extends Person { void message() { System.out.println("This is student class"); } void display() { super.message(); } } Will display the method from the parent class.

How could I use super() to refer to a field in a parent class?

class Vehicle { int maxSpeed = 120; } class Car extends Vehicle { int maxSpeed = 180; void display() { System.out.println(super.maxSpeed); } } super.maxSpeed will output *120*, not 180.

Short circuit operators

|| and && are known as short circuit operators because the second condition is never read if the first is satisfied


Kaugnay na mga set ng pag-aaral

Work and Energy Practice Questions

View Set

Systems of Linear Equations in Three Variables

View Set