Java

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

How many objects on the heap if I cast?

Because casting an object won't create another object in the heap, there will only be that one object in heap plus whatever else was already existing in the heap.

Can I instantiate an Abstract class? Constructor?

Abstract classes can't be instantiated, but they can be subclassed. Abstract classes do have constructors, and those constructors are invoked when a concrete subclass is instantiated.

What are the 4 pillars of Object Oriented Programming?

Abstraction Encapsulation Inheritance Polymorphism

Can you override static methods?

No, static methods are not associated with class instances so overriding is not applicable. They cannot be accessed by its objects, only the implementing class.

Why would you choose Java?

- Large developer community - Huge amount of documentation - Great exception handling - Good for enterprise level applications - A lot of environments support java - Forwards compatible

What is Java?

- A OOP programming language - A Common programming language - A compiled programming language where the source code needs to be compiled into bytecode before it can run

What is a Queue?

- A Queue is an interface that implements Collection. It is for data structures that use the first-in-first-out (FIFO) principle, meaning that the first object put into a queue will the the first one removed. Dynamically sized. - Implementations of Queue are LinkedList, PriorityQueue, and Deque

What is a PriorityQueue?

- A data structure that is ordered according to natural ordering or using a comparator - Works via FIFO principle - A Priority Queue that uses natural ordering won't allow elements that cannot be compared

What is a LinkedList?

- A linear data structure - Not a contiguous location - Nodes are used to link elements by storing a reference to the next linked element

Stack vs Heap

- A stack refers to Java Stack Memory which is LIFO. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and references to objects. As soon as the method ends, the block becomes unused and available for the next method. Stack memory size is much less than heap memory. - A heap refers to the Java Heap Space which is used by Java runtime to allocate memory to Objects and JRE classes. Objects are always created in the Heap space. Garbage collection works on heap memory to free memory used by objects that don't have a reference. Objects on the heap have global access and can be referenced anywhere in the application.

How do you achieve Abstraction?

- Abstract class - Using a framework, such as Spring

What is a TreeSet?

- An implementation for the SortedSet interface - No duplicate values - Doesn't preserve the insertion order of elements but elements are sorted by keys - An implementation of a self-balancing binary search tree

What is a List?

- An interface that implements Collection -

Class vs Object

- An object is an instantiation of a class - The class is the blueprint that provides the states and behaviors its instantiated objects will have

Final vs Finally vs Finalize

- Final is a non-access modifier that marks your variable as a constant. Can be applied to a class to make it so that it cannot be extended. Can be applied to a method to prevent subclasses from overriding that method. - Finally refers to the finally clause in a try, catch, finally block. Finally will always execute, even when there is an exception. Only time it won't be called is during a System.exit. - Finalize - a method that the garbage collector invokes when the JVM figures out that a particular instance should be garbage collected. The purpose is to release resources used by objects before they're removed from memory.

What are the types of set?

- HashSet - LinkedSet - TreeSet

What is a HashSet?

- Implements the Set interface; also implements Serializable and Cloneable - Uses the HashTable as an underlying data structure - Duplicate values are not allowed - Objects that you insert in a HashSet aren't guaranteed to be inserted in the same order. - Objects are inserted based on their hash code. - Hash refers to how you go and find the value - HashSet - only values, set of hashed values - HashMap - key/values, map where the keys are hashed - Collisions - update the older one

What is an ArrayList?

- Inherits AbstractList class and implements List interface - Increases by half its size - Constant time access - Dynamically sized arrays - Not thread safe - Can only contain objects; not used for primitive types, but you can use a wrapper class for such cases

What are the class members?

- Instance variables - Methods - Constructors - Inner class - Static/Instance blocks

JDK vs JRE vs JVM

- Java Development Kit (JDK) contains compiler and debugger tools to compile the Java source code, also includes the Java Runtime Environment (JRE) and Java Virtual Machine (JVM) - The JRE provides an environment and in that environment the JVM runs the compiled byte code. It contains both the library and the JVM - The JVM creates a layer of abstraction from the Java Code and the computer environment. It is used to convert the java bytecode into machine readable code.

What is a SortedSet

- Ordered using their natural ordering, or by a comparator provided at creation time - Implements the Comparable interface - All elements must be mutually comparable - compared elements accept each other as the argument to their compareTo method - Can be sorted in a natural order with Comparable interface or using a Comparator

What is Polymorphism?

- Polymorphism is the concept that in Java, objects can have the same states and behaviors, so they are interchangeable. The program's intentions are determined at runtime or compile time. - Runtime polymorphism aka dynamic polymorphism: achieved by method overriding. - Compile-time polymorphism aka static polymorphism: achieved by method overloading

Difference between the run and start methods?

- Run is a method of an object implementing runnable - Start is a method of an object inheriting from the Thread class - When you call run it executes the run method - When you call start it instantiates a new thread and calls run.

What is Serialization?

- Serialization is the process where java objects are converted to byte streams - Serialization is for transferring from Java to Java applications only. - Serialization (object to stream) and deserialization (stream to object) Must use the serializable interface to be marked for serialization

Stack vs Vector?

- Stack is a data structure which extends Vector, and it stores its objects in a last-in-first-out (LIFO) manner. The last object to be added will be the first one to be removed. - Vector is a resizable data structure that allows duplicate elements to be inserted and preserves insertion order. Synchronized and thread safe. Implements RandomAccess interface, so retrieval methods are very fast. Increases in size by double. Includes five methods which allows it to be treated like a stack (push, pop, peek, empty, and search).

State vs Behavior

- States are properties of an object - Behaviors are actions that an object can take

Abstract Class vs Interface

- Typically a programmer would use an abstract class to denote a kind of hierarchy between the abstract class and the classes that extend it. An interface is just implemented, so the interface can be used across a variety of classes that may not be related at all. - Can only extend one abstract class - Can implement as many interfaces as you would like - If a programmer wants to have method definitions or contain variables that aren't static and final, they would use an abstract class. The methods in an abstract class can also be overridden, while in an interface, all the methods must be implemented by the class that implements the interface.

What are the types of lists?

ArrayList LinkedList Vector Stack

== vs .equals()

== operator - Strict comparison by value and identity; used for both primitive and objects comparison equals Method - Comparison by value only; method can be overridden; used for objects comparison

What is an Array?

A Data structure containing like-typed variables that is initialized with a certain block of memory that use indexes which allow for consistent access.

What is a Generic?

A Generic is a template which enables programmers to specify Generic methods and classes with single method declarations, a set of related methods, or with a single class declaration An example of a generic is using the diamond syntax where you create a reference to a List of some object type with the type specified between angle brackets and initialize an ArrayList

Bean vs POJO

A POJO is a plain old java object A bean is a POJO but with more restrictions - Must have a no-args constructor - Must have private instance variables -Must have getters and setters

What is a Singleton?

A Singleton is a class that can only have one instance of that class at a time. Its purpose is to limit the number of objects of that class to one. Example is a Factory. If we try to create another instance, it will point to the first instance created. To design a Singleton class, you make the constructor private and write a static accessor method that gets your singleton.

Is a catch block needed?

A catch block is needed if you have a checked exception otherwise the JVM won't compile the code, but if you throw the exception in the method signature, you can also simply have a try-finally block.

What is a Deque?

A double ended Queue (pronounced deck) is a data structure that can be accessed from both ends, meaning that it can be used as a FIFO or a LIFO data structure.

What is a hashcode?

A hashcode is an identifier for an object that has been converted to an integer. Should be unique, although collisions happen. A hash collision is when two different objects share a hashcode.

What is a Constructor?

A method that creates an instance of a class based on the parameters defined in the constructor's signature

What is a Process?

A program in execution is often referred to as a process. It can consist of multiple threads, and a thread is the smallest part of the process that can execute concurrently with other threads of the process.

How do you invoke a static method?

A static method can be invoked within the class that it is declared without needing to create an instance of that class to invoke the method. Outside of the defining class, a static method is called by prefixing it with its class name. It can also be qualified with an object, which will be ignored, but the class of the object will be used.

What is a Thread?

A thread is a part of the process that runs a path of the program in execution. It runs asynchronous to the main method thread. When your program starts up, at least one thread is created by the JVM (main method thread). Another example of a thread is the garbage collector.

What is a Try-Catch-Finally block?

A try-catch-finally block is used to handle checked exceptions so that the JVM will compile the code. In the try block, the programmer handles the potential exception or exceptions. In the catch block, the programmer handles the potential exception or exceptions. The finally block will execute after the catch block always, unless the system method is called or the power fails or any other exceptional states.

What is a Wrapper class?

A wrapper class is meant to encapsulate primitive data types to turn them into objects using an operation of the JVM called autoboxing. You can also unbox an object to a primitive. Can use object methods. Can be used with Generics.

What is Abstraction?

Abstraction is focused on the concept of reusability which is achieved using generalization or specialization. In abstraction, the programmer's focus is what happens, rather than the implementation. An example of abstraction is using abstract classes. To reiterate the point of generalization and specialization, an abstract class provides general states and behaviors that can be overridden by classes that extend it, thus creating a unique implementation of that abstract class.

How do you achieve Encapsulation?

Access modifiers

Why would you use an Abstract class over an Interface?

An abstract class, unlike an interface, doesn't work like a contract, so all of the inherited methods don't have to be implemented, and those that you want to use can be used using the parent's definition or by overriding. Abstract classes allow yo to inherit class variables, as long as they aren't static. Abstract classes are used when the relationship between the abstract class and the class extending it is hierarchical, when you want to inherit states, and when you want to define a method definition. (Interfaces can actually also provide default methods without affecting implementing classes, as it includes an implementation) An implementing class can override the default implementation provided by the interface

What is an Interface?

An interface is an abstract type that other classes can implement. It is a contract which includes method signatures (but not method definitions) and sometimes static final variables which must all be implemented by classes that use that interface. An interface is helpful for providing semantic meaning across a number of classes without implying them to be related via inheritance extension.

What is a Set?

An interface which extends collections. A set is an unordered collection of objects which can only contain unique values.

ArrayList vs Vector

ArrayList and Vectors can both be dynamically sized, but a Vector increases by double its size while an ArrayList increases by half of its size. Both Vectors and ArrayLists implement List, and they both allow RandomAccess. A vector is thread safe and ArrayLists are not.

What are data types in Java?

Boolean - true or false, default false (number of bits can vary between platforms) Char - character type whose values are 16-bit Unicode characters, default \u0000, 16 bits Byte - default 0, 8 bits Short - default 0, 16 bits Int - default 0, 32 bits Long - default 0, 64 bits Float - default 0.0, 32 bits Double - default 0.0 64 bits

TreeSet vs HashSet

Both implement the Set interface. TreeSets also implement the SortedSet interface. TreeSet is an implementation of a binary self-balancing tree, whereas HashSets are sets but with their values hashed.

What is casting?

Casting is the process of taking an object of a particular type and turning it into another type, which gives you access to that type's methods. Casting is used when going from a more general to a specific type. For example, Integer inherits from Number, so if you want to store an Integer as a Number, that's okay, since all Integers are Numbers. But if you want to go the other way around, you need a cast, since not all since not all Numbers are Integers.

Checked vs Unchecked Exceptions

Checked Exceptions - fall under exceptions; must be thrown or surrounded in a try/batch block otherwise the JVM won't compile the code. Outside resource failing. - Exception, IOException, FileNotFoundException, SQLException - Unchecked Exceptions - fall under RuneTimeExceptions, which is a subclass of Exception. Unchecked Exceptions can be compiled and will throw an exception at runtime. Unchecked Exceptions can be caught or handled with logic. -RunTimeException, ArrayIndexOutOfBoundsException, ArithmeticException

What are the scopes of the variables?

Class - inside class Method - inside method Block - inside for or if statements

What is a Collection?

Collection is an interface. Collections is a utility class that has static methods for doing operations on objects of classes that implement the Collection interface.

What is the difference between 'Collection' vs 'Collections'?

Collection is the interface that implements Iterable. It marks a class as a Collection and therefore also Iterable. Collections is the java utility class that provides static methods available to Collection classes

Comparable vs Comparator

Comparable is an interface that compares an object based on natural ordering (numbers and letters). It uses a convention of positive number for greater than the compared element, negative number for less than the compared element, and 0 for equal. Comparator is an interface that implements Comparable and implements its compareTo method for custom ordering. Comparator allows you to implement your own rules.

RunTime vs CompileTime

Compile time is when the JVM compiles your java source code into bytecode Runtime is when your compiled Java code is run when a user uses your application

What are the types of Polymorphism ?

Compile-time polymorphism (static) Runtime polymorphism (dynamic)

What is a deadlock?

Deadlock is another component of the producer consumer problem when two or more threads are waiting for resources that the others have.

What are the types of Constructors?

Default (created by the JVM for you if no constructor is specified) No Args (constructor with no arguments/parameters) Parameterized (constructor with arguments/parameters)

What is Encapsulation?

Encapsulation is a technique to control an object's accessibility to its states. Achieved using access modifiers which are public, protected, default, and private. These access modifiers are used for info hiding or data hiding.

What are some types of errors, exceptions, and runtime exceptions?

Errors: StackOverflow, VirtualMachineError, OutOfMemoryError Exceptions: FileNotFoundException, IOException, SQLException RuntimeException: ArrayIndexOutOfBounds, NullPointerException, RuntimeException

What is an Exception? What class does it extend?

Exception extends Throwable, which has Exception and Errors as subclasses, and RuntimeException which is a subclass of Exception. Exceptions are events in execution that deviate or interrupt from the normal flow of execution. You can throw and catch exceptions.

How do you achieve Inheritance?

Extend class

Which is the fastest FileIO available and why?

File Input Reader - reads your file line by line

What is File I/O?

File Input/Output Java uses the concept of a stream to speed I/O. Streams can be used to read/write from and to the console, files, data, and more.

What is the final key word used for.

Final is a non-access modifier and it is used on objects and variables to make them immutable. When used on a class it makes it uninheritable. When used on methods it makes them non-overridable.

What are Generics for?

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. They are used for type-checking at compile time, so that code will be more type-=safe. Using generics also eliminates the use of casts. An example of using Generics is specifying the type of a Collection using diamond syntax.

What are some concrete implementations of Set?

HashSet, TreeSet, and LinkedHashSet

Hashtable vs Hashmap

Hashtable - synchronized; doesn't allow null values for keys. Legacy class that has been re-engineered to implement the Map interface. Extends from Dictionary, an abstract class Hashmap - not synchronized (better for non-threaded applications; allows one null key and any number of null values). Subclass of the AbstractMap class and a member of the Java Collection Framework from the beginning of its introduction. Doesn't guarantee the order of the map will remain constant over time

How do you go about starting a thread?

If implementing runnable, invoke the method run. If extending a thread, invoke the method start, which will invoke the method run.

What is Inheritance?

Inheritance is the concept that classes can share states and behaviors through extension. This relationship between classes is made between the parent or super class and the child or subclasses.

Which are the scopes of a variable?

Instance - declared inside a class and outside any method, constructor, or block. Visible to all methods, constructors, and blocks in a class. Local - variables declared within methods constructors, or blocks of code have instance scope. Can only be accessed inside that method or block of code. Static - declared using the static keyword in a class and outside any method, constructor or block. All instances of a class share the same copy of a static variable.

What are the three kinds of variables?

Instance variable - declared in a class but outside a method Local variable - declared in a method, constructor, or block Static variable - declared with the static keyword in a class but outside a method

How do I start a thread implementing Runnable?

Invoke the run method to start a thread implementing Runnable. The runnable object needs to be passed through the thread constructor and have invoke start.

How do you achieve Polymorphism?

Method overriding Method overloading

What is Multithreading? How do you do it?

Multithreading is when your threads are running concurrently and handling different tasks. The OS divides processing time among different applications and also among each thread within an application.

Is Java 100% Object Oriented Programming? Why or why not?

No because of primitives which are not objects

Can I force garbage collection?

No, you can't force the garbage collector to scan the heap. The garbage collector starts when the first user thread is started by the JVM, and it is terminated when the last user thread terminates. You can invoke the method System.gc to run the garbage collector, but it does not guarantee that the garbage collector will run. The JVM is in charge of when a thread will run, and the garbage collector is a thread.

What is the difference between protected and default?

Protected locks access of resources to class and subclass instances of the class in question. Default locks the access of resources to the package.

What are the Access Modifiers?

Public - globally accessible Protected - accessible within the package and its subclasses Default - accessible only within the package Private - accessible only within that class

What are Reflections?

Reflections refer to the accessing and manipulating of a class at runtime. When the JVM compiles code, it will leave the names of methods and data and leave executable machine code, so that another method can take an object and read its method names and data names. Reflection is generally used in frameworks to operate on objects without having those objects be of any particular class

What are the thread methods?

Run - starts the thread of execution Start - creates a new thread and calls run() Sleep - static method of a thread, doesn't release resource locks Wait - method of an object, releases resource locks Notify - wakes up only a single thread from a wait state to use a resource NotifyAll - wakes up all threads waiting for a resource Join - causes the current thread to wait for another thread to finish

What is the difference between a List and a Set?

Set values need to be unique

What is shadowing?

Shadowing is when two variables or objects with the same name and type have overlapping scopes. When this happens the field with the larger scope is hidden.

What is varargs used for?

Short for variable length arguments. When a method can hve any number of parameters and overloading the method would cause too much ambiguity. So you can pass ellipses into the parameter of your method after the first argument and then access the varargs array. Varargs is an array of arguments that is an array of data passed when a method is called, args is the array containing all the parameters passed into a function.

What are the Non-Access Modifiers?

Static - variable of function is shared between all instances of that class as it belongs to the type, not the actual objects themselves Final - define an entity that can only be assigned once. Once a final variable has been assigned it always contains the same value Abstract - purpose of extending Synchronized - used for threads; accessed by only one thread at a time Volatile - used for threads; lets JVM know that a thread accessing a variable must merge its own private copy with the master copy in memory Transient - used in serialization; a field that is transient won't be sent at all and will appear as null on the other end

What does the keyword "Static" mean?

Static is a non-access modifier that means you can use that method or variable from a class without instantiating that class. Static also means that it belongs to the class itself an not an instance of a class. For static variables there's 1 shared copy of the variable among all instances of the class and static method can only use static variables.

String vs StringBuilder vs StringBuffer

String - Immutable (cannot be changed or extended); stored in string pool; thread safe StringBuilder - Mutable; for strings changing rapidly; do not extend string because string is final StringBuffer - mutable; synchronized, much slower; do not extend string because string is final; thread safe, useful for threads/strings being manipulated by multiple threads.

What is the difference between StringBuilder and StringBuffer?

String builder is unsyncrhonized and faster while string buffer is synchronized and slower.

What is synchronization?

Synchronization is the process of making resources thread-safe. Done using the synchronize keyword which makes an object only accessible by one thread.

What is the finally block?

The finally block is the block that executes after a try-batch block. A finally block will always execute, even if an exception is thrown. A finally block won't execute when the system exit method is invoked, if the power goes out, or any other extreme circumstances occur.

Which method does the garbage collector call?

The garbage collector calls finalize() before destroying the object which is eligible for garbage collection. This method shouldn't be overridden. You can trick the garbage collector by letting it think the object was already collected. User threads will be frozen. The finalize method was also deprecated in Java 9.

What is the Garbage Collector

The garbage collector is a long running thread (daemon thread) which gets rid of objects that no longer hold a reference in the heap to free up space.

Throw vs Throws

Throw - method body to invoke an exception; act of throwing an exception explicitly; throw is followed by an instance variable. Throws - method signature; used to declare an exception; throws is followed by exception class names

What is Varargs?

VarArgs is short for variable arguments, which consist of a number of variable arguments. VarArgs are used when an indeterminate amount of arguments could be included. They are array like and can be only one type and one per method and also be used as the last parameter

What are the Data Structures in Java?

Various structures for holding data Array - one block of memory; constant access time ArrayList - dynamically resizeable; object Vector - dynamically resizable; object LinkedList - uses nodes Set - unique values; sortable Queue - FIFO Tree - binary search tree Map - key value; not sortable Deque - accessible from both ends Stack - LIFO

What is the main purpose of Version Control Software?

Version Control Software is software that is responsible for the management of changes to your files, documents, programs, etc. It records changes so that you can recall specific versions later. An example of a VCS is Git, which we us to store individual and collaborative projects. Git is used for versioning static files, text files, but it can't version binary files.

What are wrapper classes?

Wrapper classes in java are classes built to add functionality to primitives. Primitives can be turned into a wrapper object that has its own methods that can be used. Wrappers: Byte, Short, Integer, Long, Float, Double, Character, Boolean Handy for generics since generics don't work on primitive types

Can constructors be private?

Yes. A private constructor is needed to create a Singleton.


Ensembles d'études connexes

Chapter 21: Title, Risk and Insurable Interest

View Set

Properties of Matter Study Guide

View Set

Types of Observations (Strengths & Weaknesses)

View Set

The 거야/거예요 Ending in Korean - How does it work?

View Set

Chapter 6: Variable Costing and Segment Reporting: Tools for Management

View Set

Ch 2: Methods for Describing Sets of Data

View Set

Chapter 5 - Job Based Structures and Job Evaluation

View Set