[go: up one dir, main page]

0% found this document useful (0 votes)
7 views7 pages

Reviewer (Basic-Threads)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Reviewer (Basic-Threads)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 7

BASIC JAVA

Linux Terminal == DOS Command

Access Modifiers:
public – accessible to everyone
private – accessible only within the class
protected – accessible only to subclasses
default – accessible to the whole package

Non-Access Modifiers:
static – used to create variables/methods that will exist independently of any instances.
- also known as class variables
final – can only be initialized once. However, data within a final object can be changed but not the
reference.
Abstract – cannot be instantiated. Basically empty method. Main purpose is for the class to be
extended.
Synchronized & Volatile – for threads

Primitive Data Types: stores the value directly


byte – 1 byte
short – 2 bytes
int – 4 bytes
long – 8 bytes
float – 4 bytes
double – 8 bytes
char – 2 bytes
boolean – 1 bit

Non-Primitive Data Types: only points to the object


all data types stored in java.lang.Object

**Class within a class is possible.

ADVANCED JAVA
OOP
Inheritance - subclass inherits the methods and fields of superclass
- superclass can't use methods from subclass
- subclass can't inherit constructors of superclass but can be invoked using super
Keywords:
1. extends – subclass inherits properties of superclass (IS-A)
2. super – to invoke the values of the superclass
3. implements – subclass inherits properties of the superclass interface
4. instanceof – returns boolean (HAS-A)

Types of Inheritance:
1. Single
public class A{...}
public class B extends A{...}
2. Multi-Level
public class A{...}
public class B extends A{...}
public class C extends B{...}
3. Hierarchical
public class A{...}
public class B extends A{...}
public class C extends A{...}
4. Multiple (ILLEGAL)
public class A{...}
public class B extends A{...}
public class C extends A, B{...}
*Java does not support multiple inheritance. A class can only extends one class.
*A class can implement more than one interface. Java did this to get rid of the impossibility of multiple
inheritance.

Override – overriding the functionality of an existing method


- subclass can implement a superclass method based on the need/requirement
Keyword: super

Rules:
1. Args and Return types must exactly be the same as the overriden method.
2. Access modifier must not be higher than the overriden method
3. Instance methods can only be overriden if inherited by subclass
4. constructors, uninheritable, final and static methods cannot be overriden but static can be re-
declared.
5. Subclass within same package (override anything except final)
6. Subclass with diff. package(override only public/protected)

Polymorphism – ability of an object to take on many forms


- most common occurrence is when parent class is used to refer to child class
public class Animal{...}
public class Dog extends Animal{...}
Animal a = new Dog();
*All Java objects are considered polymorphic bc they pass the IS-A test
Types:
1. Dynamic – also known as Run Time Polymorphism
- Overriding
2. Static – also known as Compile Time Polymorphism
- Overloading

Abstraction – process of hiding the implementation details from the user using abstract class/interfaces.
Keyword:
abstract – showing the funcionality instead of how it works

Rules:
1. Abstract classes may or may not contain abstract methods but if a class contains at least one, it
should be declared abstract.
2. Cannot be instantiated
ClassRef ref = new ClassRef(...) [INVALID]
3. Must be inherited to use. Must provide implementations for the methods inside the abstract class.
4. No curly braces and body when declaring.
public abstract datatype methodName();
5. When inheriting a class, override the abstract method/ declare itself abstract.

Encapsulation – variables of a class will be hidden from other classes and can be accessed through
access points(public getters & setters).
- also known as data hiding
Keyword: private – can only be accessed by the methods in the class

Benefits:
1. fields of a class can be made read-only or write-only.
2. class have total control over what is stored in the fields
3. class can change the data type of a field and users do not have to change the code.

Packages – prevent naming conflicts, access control, easier searching&usage of classes, interfaces,
enums, annotations, etc.
-a grouping of related types providing access protections & name space management.
- java.lang (fundamentals) & i.o (I/o functions)
Keyword: -d to create package
javac -d packageName fileName.java

DATA STRUCTURES (Ad Hoc Classes) *for specific purposes only


1. Enumeration – defines methods where you can enumerate elements in a collection of objects.
- superceded by Iterator but used by legacy classes(Vectors, Properties), API classes and widespread
use in application code.

2. BitSet – creates a special array that holds bit/flag values and is dynamic.
- a legacy class but re-engineered in Java 2, ver. 1.4
- helpful when storing boolean values

3. Vector – implements a dynamic array


- similar to ArrayList but synchronized and contains legacy classes that are not included in the
Collections framework

4. Stack – implements LIFO stack of elements


- subclass of Vector
- only defines constructor : Stack()

5. Dictionary – abstract class for mapping keys to values and operates like Map
- obsolete (not used anymore)

6. HashTable – originally part of java.util and concrete implementation of Dictionary


- re-engineered in Java 2 and is now part of the Collections framework
- similar to HashMap but synchronized

7. Properties – subclass of HashTable


- used to maintain lists of values where both key and value are String.

COLLECTIONS
Goals:
1. to be high-performance where the implementation for the collections are highly efficient
2. different collections work in a similar manner and with high interoperability (work with parts of
other systems)
3. extending/adapting must be easy

Collection Frameworks contain:


1. Interfaces – abstract data types that represent collections
- allows collections to be manipulated independently

2. Implementation (Classes) – concrete implementations of collection interfaces.


- reusable data structures

3. Algorithms – methods for computations (sorting, searching)


- considered polymorphic bc same method may be used by diff. Implementationsin the collection

Collection Interface
1. Collection – foundation of the collections framework
- contains the core methods that all collections will have

2. List – extends the Collection interface and declares behavior of a collection that stores a sequence of
elements
- elements are accessed given their position in the zero-based list

3. Set – extends Collection and restricts duplicate elements


- models mathematical set abstraction
- Set instances may be compared despite different implementations

4. SortedSet – extends Set and sort in ASC


- sorts as you add

5. Map – maps value to unique keys

6. Map.Entry – enables you to work with map entry


- entrySet() returns a Set containing the map entries and each element in the set is an object of
Map.Entry

7. SortedMap – extends Map and sorts keys in ASC

8. Enumeration – legacy interface where you can enumerate the elements


- superceded by Iterator and considered obsolete but not deprecated

Collection Classes
- implements Collection interface

1. AbstractCollection – implements most of the Collection interface


2. AbstractList – extends AbstractCollection and implements most of the List interface

3. AbstractSequentialList – extends AbstractList


- used by a collection with sequential elements

4. LinkedList – extends AbstractSequentialList and implements List interface


- provides linked-list data structure

5. ArrayList – extends AbstractList and implements List interface


- can only store Objects not primitives

6. AbstractSet – extends AbstractCollection and implements most of Set interface

7. HashSet – extends AbstractSet and implements Set interface.


- uses hash table for storage and stores info by hashing
- hash code is the informational content of a key to determine unique value

8. LinkedHashSet – extends HashSet and maintains a linked-list of the entries in which they were
inserted
- allows insertion-order iteration over the set which means the elements are returned in the order that
they were added.

9. TreeSet – implements the Set interface that uses tree for storage
- the objects are stored in ASC order

10. AbstractMap – implements most of the Map interface

11. HashMap – extends AbstractMap and uses hashtable for storage


- execution time of get() and put() are constant despite large sets
- not sorted in ASC

12. TreeMap – implements Map interface using tree storage


- stores key/value pairs in sorted order for rapid retrieval

13. WeakHashMap – implements Map interface with only weak references to the keys
- similar to HashMap but if the Java memory manager no longer has strong reference to the value
specified by key, it is removed from the map

14. LinkedHashMap – extends HashMap and maintains linked list of the entries in the order they were
inserted
- when iterating over the map, the elements are returned in the order they were inserted
- can also return elements in the order they were last accessed

15. IdentityHashMap – implements AbstractMap


- similar to HashMap but uses reference equality when comparing
- uses in rare cases where reference-equality semantics is required
- has expected max size parameter
16. Legacy Classes (Vector, Stack, Dictionary, Hashtable, Properties, BitSet)

**Threads: cannot modify collection at the same time (Exception)


Collections Algorithm
- static methods within collection class
- Immutable Static Variables: EMPTY_SET, EMPTY_LIST, EMPTY_MAP.

Exception Handling
1. try-catch
2. throw/throws
3. try-catch-finally

THREADS
- path of execution in Java
- 2 or more tasks executing concurrently (multithreading)

States:
1. New – not yet started
2. Runnable – currently executing
3. Blocked – waiting for the lock
4. Waiting – waiting for another thread to finish an action
5. Time_Waiting – waiting for another thread to finish an action within a specified time
6. Terminated – thread is dead

Ways to create a Thread:


1. Implement Runnable – more flexible than extending thread but cannot be instantiated.
2. Extend Thread – use this when the class extending thread will never be extended by another class

Characteristics of a Thread:
1. Priority – threads with higher priority will be executed first
(10) Thread.MAX_PRIORITY
(5) Thread.NORM_PRIORITY
(1) Thread.MIN_PRIORITY
2. Daemon flag – also called “service thread” e.g, garbage collection
- scans for variables that will not be accessed again and frees their resources
- must be set before the thread is started

Types of Thread Scheduler:


1. Preemptive – round-robin style of scheduling
- suspended() & resume()
2. Non-preemptive – finish current thread before going to the next.
- yield()
*The type of scheduler depends on the system Java is running on.
*Thread capacity depends on the CPU/platform.

Factors for Limit on Thread creation:


1. JVM invocation parameters
2. requested stack size in the thread constructor
3. limits on threads specified by the OS
* OutOfMemory Error when the limit is reached

Lambda
- block of code(expression) with parameter variables
- can be converted to functional interfaces
- can access final variables from the enclosing scope
- can now add default and static methods in interfaaces that provide concrete implementation
- can be passed around for later use
- use when an object of a functional interface(interface with single abstract method) is expected
Array.sort(words, Comparator(functional interface));
Array.sort(words, (first, second) → Integer.compare(first.length(), second.length()));
- If the body of a lambda throws a checked exception, either catch it in the lambda body or assign the
lambda to an interface whose abstract method can throw an exception like the call method in Callable
interface.
- can't assign a lambda to an Object variable because it is not a functional interface.
* Conversion to a functional interface is the only thing lambda can do in Java

Method reference Syntax:


1. object :: instanceMethod
2. Class :: staticMethod
3. Class :: instanceMethod

History:
Alonzo Church wanted to formalize what it means for a mathematical function to be effectively
computable. He used lambda(symbol) to mark parameters. The ^ was used by the Principia
Mathematica to denote free variables which inspired Church to use the uppercase version but later
switched to lowercase.

Syntax:
1. (parameters) → expression
2. (parameters) → {expression with long computation & return statement}
3. () → expression
4. If parameter type can be inferred, omit the identifier.
Comparator<String> comp = (first, second) → Integer.compare(first.length(), second.length());
|
Java can infer from this that variables first and second are Strings.
5. If expression has single parameter that can be inferred, omit the parentheses.
6. Annotations and final modifiers may be included in the parameters.
(final String name) → {expression}
(@Override String name) → {expression}
7. Never specify the result type. Java will infer it from the context.

You might also like