Revature Review Questions
How many interfaces can interface extend in Java?
Any number of interfaces. An interface can extend another interface, in a similar way as a class can extend another class.
What is the version control?
-Maintains the integrity of source code -Flexibilitiy (large and small scale/efficiency ) -widely accepted -Quality Open Source project
What are some of the benefits of using Git?
-Perfomance
What is a wrapper class?
Are classes that let you treat primitives as objects. The wrapper classes in java servers two primary purposes. To provide a mechanism to 'wrap' primitive values in an object so that primitives can do activities reserved for the objects like being added to ArrayList, Hashset, HashMap etc. collection. To provide an assortment of utility functions for primitives like converting primitive types to and from string objects, converting to various bases like binary, octal or hexadecimal, or comparing various objects.
What is the Maven lifecycle?
1) Validate: Validates if the project is correct and if all necessary information is available 2) Compile: Source code compilation is done in this phase 3) Test: Tests the compiled source code suitable for testing framework 4) Package: This phase creates the JAR/WAR as mentioned in the packaging in the POM.xml 5) Install: This phase installs the package in local/remote maven repository 6) Deploy: Copies the final package to the remote repository Also note these steps need to go in order. Maven will not test before compiling, or package before testing ect...
What is autoboxing?
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on.
What is garbage collection?
Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.
What are the differences between a checked exception and an unchecked exception?
Checked exceptions are those which are caught by your compiler, or at compile time. • If some code with a method throws a checked exception, the method must either handle the exception, or must request that the exception is handled later. • Unchecked exceptions are exceptions that are not checked at compile time. Technically, you do not have to handle them...but you still should! • Runtime exceptions are unchecked exceptions (because the code was able to compile and run).
What are the different control statements, and how are they different?
If/else/else if for- loop: Are used to iterate over data structures. Includes 3 statements in ( ) --> Declaration, Condition, Increment/Decrement while loop: test a condition - if the condition evaluates to true the block of code is run, otherwise it is skipped do -while loop: An alternative to the while loop. Guarantees that the block will always run at least once Switch- attempts to match some variable to the value it contains
What is the difference between comparator and comparable?
Comparable: 1) provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price. 2) affects the original class, i.e., the actual class is modified. 3) provides compareTo() method to sort elements. 4) present in java.lang package 5) We can sort the list elements of Comparable type by Collections.sort(List) method. Comparator: 1) provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc. 2) doesn't affect the original class, i.e., the actual class is not modified. 3) provides compare() method to sort elements. 4) is present in the java.util package 5) We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.
How do I create a custom exception?
Custom Exception can be created by extending any Exception Class, or the Throwable Class. Typically, this is done by extending the Exception class to provide more structure to the newly created exception. public class EvenNumberException extends Exception{ public EvenNumberException(String message) { super(message); } public EvenNumberException(){} }
What is a marker interface? What is an example of a marker interface?
It is an empty interface with no field or methods. Examples: Serializable, Cloneable, and Remote Interface.
How is an iterator different from a ListIterator?
Iterators are used in Collection framework in Java to retrieve elements one by one. It can be applied to any Collection object. VS ListIterator is only applicable for List collection implemented classes like arraylist, linkedlist etc. It provides bi-directional iteration. ListIterator must be used when we want to enumerate elements of List. This cursor has more functionality(methods) than iterator.
Can an abstract class implement an interface in Java?
Java Abstract class can implement interfaces without even providing the implementation of interface methods.
What is the difference between the stack and the heap?
Java automatically. The JVM divides the memory into two parts: stack memory and heap memory. Stack memory is used to store the order of method execution and local variables. Heap memory stores the objects and it uses dynamic memory allocation(allows the programmer to allocate or release memory as needed) and deallocation.
How many abstract classes can a class extend in Java?
Java has a rule that a class can extend only one abstract class
What is a Lambda expression?
Java lambda expressions are Java's first step into functional programming. A Java lambda expression is thus a function which can be created without belonging to any class. Functional programming is very often used to implement event listeners. Event listeners in Java are often defined as Java interfaces with a single method. (parameter1, parameter2) -> { code block }
What is deadlock, livelock, and thread starvation?
Deadlock - describes a situation where 2 or more threads are blocked trying to access the same resource , waiting for the other. Neither thread can continue execution so program is halted indefinitely Livelock - situation where a request for an exclusive lock is denied repeatedly. Thread Starvation - when a thread is in waiting state for a long period because it is not getting access of shared recourse or higher priority threads
Common HTML tags <div> <p> <span> <b> <i> <h1><h2>..<h6> <br> <table> <img src="URL"> <ol> <ul> <a href="">
<div> defines a "division of the page' <p> defines a paragraph <span> - an online tag for grouping text or elements <b> bold text <i> italicized text <h1> <h2> ..<h6> - these are headings from largers to smallest <br> line break <table> - defines a table <img src="URL"> <ol> - an ordered list <ul> an unordered list <a href=""> makes a hyperlink
Semantic elements that help define the element's purpose on the webpage l
<section> <article> <header> <footer> <nav> <aside> <figure> <figcaption> <details> <mark> <summary> <time>
How to create a table using markups
<tr> table row <td> table cell <th> is used for table headers
What is the difference between == and .equals?
== checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
What are the differences between FileinputStream, FileReader, and BufferedReader?
A BufferedReader accepts any type of Reader and is capable of reading from any character input stream. (Faster, more efficient Better option) FileReader is capable reading characters from files only. FileInputStream read raw streams of bytes from files or sockets (BufferedReader and FileReader or for characters FileInputStream is for bytecode)
How are the List, Set, and Queue interfaces different from each other?
List: implementations maintain the order of the elements placed inside them, which can be accessed by their index, and can contain duplicate elements. Set: implementations do not maintain the order of elements, does not support random access, and can not contain duplicate elements Queue: implementations order elements in a FIFO(first-in-first-out) manner, all new elements are inserted at the tail(ex end of line), usually do not allow for the insertion of null elements
What is multithreading? Why do we use it?
Multithreading extends the idea of multitasking into application where you can subdivide operations in a single application into individual, parallel threads. The benefit of multithreaded applications is better performance due to non-blocking execution
What are the different ways to create a thread? What is different about them?
Multithreading is achieved via the Thread class and/or the Runnable interface. 1. Create a class that extends Thread 2. implement the run() method 3. instantiate your class 4. call the start() method ______________________________ 1. Create a class that implements the Runnable functional interface 2. implement the run() method 3. pass an instance of your class to a Thread constructor 4. Call the start() method on the thread ______________________________ Since Runnable is a functional interface you can also use a lambda expression passed as a runnable type required in a thread constructor
What are the JVM recognized states of thread?
New: Newly created thread that has not started executing Runnable: either running or ready for execution but waiting for its resource allocation Blocked: waiting to acquire a monitor lock to enter or re-enter a synchronized block/method Waiting: waiting for some other thread to perform an action without any time limit Timed_waiting: waiting for some other thread to perform a specific action for a specified time period Terminated: has completed its execution
Do generics support primitive data types?
No you have to use the wrapper classes.
What is synchronization?
Synchronization is the capability to control the access of multiple threads to any shared resource. Meaning when 2 or more threads attempt to access the same resource by using the synchronized keyword on a piece of logic enforces that only one thread can access the resource at any given time.
What is the difference between a Singleton and Factory?
The purpose of the singleton design pattern is where you want all calls to go through the same instance. Singleton design pattern ensures that no matter how many times a client (or multiple clients) ask for an instance of this specific Type to be created (instantiated) for them, they will always get the exact same one and only one instance of the type. It guarantees that only one instance of the type can ever be instantiated. The purpose of the Factory method is to provide a new instance of the object whenever the Factory method is being called. When you are dealing with lot of different interrelated classes, it is better to use the Factory to streamline the object creational.The Factory pattern defines an interface for creating objects (no limitation on how many) and usually abstracts the control of which class to instantiate.
What are packages and imports?
The first (non-commented) line in a .java file. Packages are a way of organizing classes, interfaces, and enums in a hierarchical manner. --> lowercase characters separated by periods in reverse web domain format --> We use import statement after our package declaration to pull in other classes (Keeps the code less verbose)
What is the difference between git init and git clone?
Using git init, you can initialize and empty git repository in your local and using git clone, you can clone an existing git repository to your system
What is a static import?
With the help of static import, we can access the static members of a class directly without class name or any object. For Example: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but by using static import we can access sqrt() method directly.
Can finally be skipped? How?
You cannot skip the execution of the final block. Still if you want to do it forcefully when an exception occurred, the only way is to call the System.exit(0) method, at the end of the catch block which is just before the finally block.
How do I prevent some data from getting serialized?
You cannot unimplement an interface so if your superclass implements Serializable your new class will as well. To stop automatic serialization use private methods to throw the NotSerializableException
How many interfaces can a class implement in Java?
Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
Explain the difference between Hashmap and Hashtable.
a HashTable is an older, thread-safe implementation of a HashMap. It does not allow null keys or null values
How do I iterate through a HashMap?
entrySet() method to iterate over the set of Map.Entry keySet( ) method to iterate over the set of keys values( ) method to return a Collection of values which can then be iterated over
What is the difference between final, finally, and finalize?
final - is the keyword and access modifier which is used to apply restrictions on a class, method or variable. finally - is the block in Java Exception Handling to execute the important code whether the exception occurs or not. finalize - is the method in Java which is used to perform clean up processing just before object is garbage collected.
What is the purpose of hashcode?
hashCode() is used for bucketing in Hash implementation like HashMap, HashTable, HashSet. the value received is used as the bucket number for the storing elements of the set/map. It is the address of this element inside the set/map
What is the difference between implicit and explicit casting?
implicit casting is when you are assigning(or converting) a smaller type to a larger type explicit casting is when you are assigning(or converting) a larger type to a smaller type (You tend to want to stay away from this because it causes you to loose some data)
What is Java?
is a high-level, compiled, strongly typed object-oriented programming (OOP) language.
What are generics? Why use them?
is a type of method to operate on objects of various types while providing compile time safety. Generics help to enforce compile time safety.
<nav>
is for major navigation blocks that specify a set of navigation links
<aside>
is used to identify content that is related to the primary content of the web page. The content inside <aside> does not constitute the primary content of the page.
what non semantic elements? some examples ?
mean elements are not related to the content on the web page ex: <div> <span>
what are the two options for making lists in HTML
ordered lists are defines with <ol> unordered lists are defines with <ul> and the list items within either are denoted with <li>
<articlce>
represents a section of content that forms an independent part of a document or site such as Forum post, Blog post, Newspaper article
What is the difference between the JRE, JDK, and JVM?
the JRE - Java Runtime Environment --> contains all the runtime libraries that your code will be calling and using. JRE contains JVM JVM - Java Virtual Machine --> Java code is compiled to bytecode and runs on JVM. The JVM reads the compiled bytecode and translates it to machine code to be executed. JDK - Java Development Kit provides developer tools like a compiler, debugger, documentation tools(javadoc), and other command line utilities
What are semantic elements? what are some examples
these elements are used to define the content on the webpage ex: <form> <table> <article>
How to make a hyperlink in a webpage ?
use <a> tag example: <p> Here is a <a href="www.google.com">link to Google!</a><p>
What is a no args constructor?
when we create our own constructor with no arguments - Can have all four modifiers - can have logic including super call- by default first statement is a super call
What is a default constructor?
when we write a class without any constructor then at compilation time java compiler creates a default constructor - Access modifer same as class (Public or Default) -has super() call ----------------------------------- Extra Piece of information: -Every default constructor is a 0 argument constructor but every 0 argument constructor is not a default constructor
What are Strings?
• Most commonly used class • Immutable constant objects derived from the String Class • Can be created through two notations, both behave differently: - String str1 = "hello world"; // string literals - String str2 = new String("hello world"); // object • String literals are "pooled", no two String literals have the same value. References to duplicate literals are shared. Object-notation Strings are not pooled.
What are some string methods?
• char charAt(int index) - Returns the character at the specified position in the String. • int indexOf(String str) - Returns the position of the first occurrence of the specified substring • int length() - Returns the number of characters in the string • String substring(int beginIndex) - Returns a substring starting from the given index of the parent String. • boolean equals(String str) - Returns whether the two strings have the same sequence of characters.
What are some basic Git commands?
$git add $git clone url $git init $git commit -m "message" git push -u origin main
What does the static modifier do?
- static means that the variable or method "belongs to" the class, instead of each object of the class. - Variables declared with the static keyword reside in the static or class scope. - Static variables persist throughout the lifetime of your entire program. - static methods can be invoked from the class, instead of an object.
What are the annotations of JUnit?
@Test @BeforeClass @Before @After @AfterClass
What is a functional interface?
A functional interface in Java is an interface that contains only a single abstract (unimplemented) method. A functional interface can contain default and static methods which do have an implementation, in addition to the single unimplemented method.
What is the string pool?
A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored. When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap.
What is an iterator?
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping.
How many interfaces can an interface implement in Java?
An interface cannot implement another interface in Java.
What is the difference between Collection and Collections?
Collection is the parent interface of all other child interfaces and classes of the Java Collection framework Collections is a utility class of Java Collection framework that consists of static utility functions
What are the different wrapper classes?
Each Java primitive has a corresponding wrapper: (Primitive) boolean, byte, short, char, int, long, float, double (Wrapper classes) Boolean, Byte, Short, Character, Integer, Long, Float, Double
What is Git?
Git is an open source version control system that enables you to manage your website source code.
How many classes can a class extend in Java?
In Java, classes may extend only ONE superclass.
What is JUnit?
JUnit is a unit testing framework for Java Programming language.
What are some of the subinterfaces of the Collection interface?
List, Set and Queue
What is the Scanner class?
Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings
What is serialization and deserialization?
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.
What is the purpose of the Object class?
The Object class is the parent class of all the classes in java by default.
What is Maven?
Maven is a project management and comprehension(Build-automation) tool that provides developers a complete build lifecycle framework
What is the purpose of using Maven?
Maven is an automation and management tool developed by Apache Software Foundation. It allows developers to create projects, dependency, and documentation using Project Object Model and plugins. Maven can also build any number of projects into desired output such as jar, war, metadata.
What is the producer and consumer problem?
The producer should produce data only when the queue is not full if it is full the producer shouldn't be allowed to put any data in the queue. the consumer should only consume data when the queue is not empty if it is empty the consumer shouldn't be allowed to take any data from the queue.
What are some methods that are inherited from the Object class?
The toString() Method, The equals() Method, hashCode().
How do you create an Array in java?
They are: 1. declared with square brackets after the type of the array 2. followed by the name of the Array 3. Assignment Operator 4. Curly Brackets with elements inside
How do I perform garbage collection?
No way to explicitly force garbage collection but we can request it by Calling the System. gc() command.
<section>
defines a thematic grouping of content sections like chapters, headers, footers, introduction , etc
What is the first line of a java application?
public class FirstJavaProgram { This is the first line of our java program. Every java application must have at least one class definition that consists of class keyword followed by class name
<header>
specifies a header for a document or section
Under what circumstances does a class have a default constructor?
when there is no constructor implemented by the programmer -It is inserted during compilation and will appear only in .class file and not the source code
When can you upcast a variable? Downcast a variable?
you can upcast a variable when more memory space is needed. Vice-versa you would downcast when you want to save up more memory space.
<audio>
element defines sound content and it has a controls attribute that adds audio like play, pause, and volume.
<footer>
element used to define the footer for a document or section. It contains information about the author of the document
What are the scopes of a variable in java?
- Instance, or object scope - Class, or static scope - Method Scope - Block scope
What are various methods that threads have?
- getters and setters for id, name, and priority interrupt( ) isAlive( ) isInterrupted( ) isDaemon( ) join( ) start( ) Thread.currentThread( ) Thread.sleep(long millis)
What are the risks of synchronization?
- may prevent the performance of compiler and runtime -may not get benefit of concurrency --> this effects the scalability
<video>
element used to embed a video on a web page
How do I serialize an object?
1. We implement the Java.io.Serializable interface 2. ObjectOutputStream has a writeObject( ) that serializes an object 3. ObjectInputsream has a readObject( ) method that deserializes an object
What are some Scanner methods?
1.nextInt() 2.hasNext() 3. Scanner.toString() 4.Scanner.ioException() 5.Scanner.close()
What is a constructor?
A constructor declares how an object is to be instantiated and initialized from the class "blueprint". Like a method but: 1. the signature does not contain a return type 2. Constructor always has the same name as the class
What is the first line of a constructor?
A super() call (or a this() call) must be the first line of any constructor
How many catch blocks can be used in a try catch? (min and max)?
A try block can be followed by any number of catch blocks
What are the different ways in which we can handle an exception?
A try statement that catches the exception. The try must provide a handler for the exception.(Handling) A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception.(Declaring)
What is the difference between an abstract class and an interface ?
Abstract class vs Interface Type of methods: Interface can have only abstract methods. An abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also. Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables. Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables. Implementation: Abstract class can provide the implementation of the interface. Interface can't provide the implementation of an abstract class. Inheritance vs Abstraction: A Java interface can be implemented using the keyword "implements" and an abstract class can be extended using the keyword "extends". Multiple implementations: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc.
What are the pillars of object oriented programming? Explain them.
Abstraction: The process of hiding implementation and processes of an entity to reduce complexity or increase understanding of a system's properties. Polymorphism: The ability for objects, classes, variables and/or methods to alter functionality while maintaining structure. Inheritance: The ability for entities to adopt variables (fields) and/or methods (behavior) from a parent (super) class, allowing for instantiation of child objects from said parent class. Encapsulation: The act of wrapping code into a single unit and then selectively exposing and restricting access to that code based on functionality or use within classes.
What are the benefits of using Java?
Advantages: -free - Platform Independent (Write once Run Everywhere)(can run on any OS) - C-language inspired syntax - automatic memory language -Extensive built-in runtime library -Supported by Oracle -Rich Open Source community
What is the difference between an exception and an error?
An Error "indicates serious problems that a reasonable application should not try to catch." VS An Exception "indicates conditions that a reasonable application might want to catch."
What is an exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
What does it mean to be a "pass-by-value" language? How is this different from "pass-by-reference"?
By definition, pass by value means you are making a copy in memory of the actual parameter's value that is passed in, a copy of the contents of the actual parameter is accessed/modified. VS pass by reference (also called pass by address), a copy of the address of the actual parameter is passed to the function.
How do I create a test case and test suite in JUnit?
File>New> Other> Java>JUnit>JUnit Test Suite
What happens during the compilation process?
First, the source '.java' file is passed through the compiler (JDK) then encodes the source code into Bytecode(JVM) The content of each class contained in the source file is stored in a separate class file -Parse -Enter -Process Annotations -Flow -Desugar -Generates
What goes on the heap?
Heap space in Java is used for dynamic memory allocation for Java objects and JRE classes at the runtime. New objects are always created in heap space and the references to this objects are stored in stack memory. These objects have global access and can be accessed from anywhere in the application.
What is auto-unboxing?
If the conversion goes from wrapper classes to primitive types this is called unboxing.
Why would I choose one method of creating a thread over another?
If the design requires multiple inheritance using the interface is preferred
What is the difference between a Java Bean and a POJO?
POJO: stands for Plain Old Java Object. It is an ordinary Java object, not bound by any special restriction other than those forced by the Java Language Specification and not requiring any classpath. POJOs are used for increasing the readability and re-usability of a program Beans: are special type of Pojos. There are some restrictions on POJO to be a bean. 1) All JavaBeans are POJOs but not all POJOs are JavaBeans. 2) Serializable i.e. they should implement Serializable interface. Still, some POJOs who don't implement Serializable interface are called POJOs because Serializable is a marker interface and therefore not of much burden. 4) Fields should be private. This is to provide the complete control on fields. 5) Fields should have getters or setters or both. A no-arg constructor should be there in a bean. 6) Fields are accessed only by constructor or getter setters.
What is the purpose of the pom.xml?
POM is an XML file which contains the project configuration details used by Maven. It provides all the configuration required for a project. POM means project object model, and, as the name suggests, it defines the model of the project as well.
What are the different access modifiers? What does each one do?
Public - Available anywhere Protected - Within the same package, and this class' sub-classes default - within the same package private - Only within the same class
What are the various input/delete/get methods for List, Set, and Queue?
Queue - add(E e), remove( ), poll( ) List - hashCode( ) Set - iterator ( )
What is the Reflection API?
Reflection is an API which is used to examine or modify the behavior of methods, classes, interfaces at runtime. The required classes for reflection are provided under java.lang.reflect package. Reflection gives us information about the class to which an object belongs and the methods of that class which can be executed by using the object. Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.
What goes on the stack?
Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects that are in a heap, referred from the method. Access to this memory is in Last-In-First-Out (LIFO) order.
What are the different no-access modifiers? What do they do?
Static - denotes class scope/method can be invoked with an instance of a class /Variables accessed through the class final -Variable can't be reassigned/ class can't be extended /method can't be overridden Abstract - class can't be instantiated instead inherited/ only method signature defined/subclasses implement the abstract method Synchronized -relevant to threads (thread safe) Transient -makes variable non-serializable Volatile- marks a variable to never be cached Strictfp- restricts floating point calculations. For portability
What is the difference between String, StringBuilder, and StringBuffer?
String Is immutable and the slowest StringBuffer and StringBuilder(fastest) are mutable StringBuffer and String is synchronized(thread safe) VS StringBuilder is non-synchronized i.e. not thread safe. StringBuffer is less efficient VS StringBuilder is more efficient.
What does finally do?
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. This allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
What is the Map interface's relationship to the Collection interface?
does not implement the Collection interface but is considered part of the Collections Framework
What is varargs?
an alternative notation. We use the varargs construct (...) which replaces the [] array notation
What are the different assert methods of JUnit?
assertTrue( ) assertFalse( ) assertEquals( ) assertNotEquals( ) assertThat( )
What are the primitive data types?
byte short char int long double float boolean
<source>
defines the media resources for the audio files and it has attributes such as src and type
<figure>
describes some flow content optionally with a caption that is self contained and referenced as a single unit from the main flow of the document <img>(inserts and image) and <figcaption> (visual explanation of image) are grouped in <figure>