Revature Week 2 Notes
3. What does polymorphism mean? Hiding implementation details through a higher-level construct, like abstract classes and interfaces, thereby decreasing coupling and increasing cohesion Restricting access to data members by using access modifiers and getter/setter methods Receiving state and behavior from other classes, thereby reducing boilerplate and duplicate code and allowing for hierarchies of classes Allowing the implementation of a given behavior to vary, whether between subclasses or within the same class
Allowing the implementation of a given behavior to vary, whether between subclasses or within the same class
2. When extending the RuntimeException class in Java, what is created? An unchecked exception A checked exception No new exceptions A hybrid exception
An unchecked exception
1. Which of these implements the List interface? ArrayList Set Queue Heap
ArrayList
4. What is the Java process that implicitly converts a primitive to its wrapper class? Autoboxing Boxing Wrapping Unwrapping
Autoboxing
1. Select the false statement regarding inheritance Base classes are usually more specific than derived classes. A derived class can be the base class for other derived classes. A derived class can contain more attributes and behaviors than its base class. Some derived classes can have multiple base classes.
Base classes are usually more specific than derived classes.
2. What is the process of converting a primitive to its wrapper class? Boxing Unboxing Wrapping Unwrapping
Boxing
1. Custom exceptions in Java...? Can be created by extending any exception class Can only be created by extending certain exception classes Can be created by creating a whole new exception class Cannot be created
Can be created by extending any exception class
2. What is the difference between classes and objects? Classes are read-only, objects are dynamic Objects are the templates from which classes are instantiated Classes are the templates from which objects are instantiated Classes are dynamic, objects are read-only
Classes are the templates from which objects are instantiated
1. What is the correct name for the wrapper class for the int type? Integer int integer Int
Integer
1. Garbage collection can be forced by Using the <code>System.gc()</code> method Calling the <code>finalize()</code> method It can never be forced. None of the options
It can never be forced.
2. Which of these is NOT a characteristic of the List interface? It does not preserve the order in which elements are inserted. Duplicate entries are allowed. Elements are accessed by index List inherits operations from Collections as well as adding some of its own.
It does not preserve the order in which elements are inserted.
Dynamic Polymorphism
It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime. It is otherwise known as runtime polymorphism class Animal{ public void animalSound(){ System.out.println("Default Sound"); } } public class Dog extends Animal{ public void animalSound(){ System.out.println("Woof"); } public static void main(String args[]){ Animal obj = new Dog(); obj.animalSound(); } }
2.Access to stack memory can best be described as...? FIFO; First In First Out LIFO; Last In First Out. Random access to some elements in the stack. Full access to all elements in the stack.
LIFO; Last In First Out.
1. The _____ class is a special class in Java which is the root class from which all other classes inherit, either directly or indirectly. Object Base Root Fundamental
Object
2. Exception handling is done via...? A try-catch block An if-then block A for loop A do-while block
A try-catch block
5.Which is <b>not</b> a feature of heap memory? If heap space is full, Java throws java.lang.OutOfMemoryError. This memory, in contrast to stack, isn't automatically deallocated. Unlike stack, a heap isn't threadsafe and needs to be guarded by properly synchronizing the code.. Access to this memory is faster compared to stack memory.
Access to this memory is faster compared to stack memory.
Implementing Pop
Adding items to the Stack is great, but we'll also need to be able to remove items so that we can do a little bit of testing of our code. You'll find that our current approach to a Stack may be challenging to support. - For instance we have a reference to the last item, but we can't simply return that? We need to remove it entirely from the array. - Arrays are fixed-sized objects in Java, so that means we'll have to copy over all of the elements to a new array and get rid of the old one. Add the following code to your class: public int pop(){ int tempItem = lastItem; //store the last item into a variable //copy a new array but remove last item int[] newArray = new int[items.length-1]; for(int i = 0; i < newArray.length; i++){ newArray[i] = items[i]; } items = newArray; //update the items array lastItem = items[items.length-1]; //update lastItem //return our 'popped' element return tempItem; }
3. ____ is a type of inheritance where there is one Parent class and one Child class. One child class extends one parent class. Single inheritance Multi-level inheritance Hierarcihal inheritance Multiple inheritance
Single inheritance
4. Why would we want to extend the RuntimeException class? So that we write the code that handles the exception To let the JVM handle the exception To let the computer operating system to handle the exception Do not extend the RuntimeException class or it will create more exceptions
So that we write the code that handles the exception
Key Features of Java Heap Memory
Some other features of heap space include: - It's accessed via complex memory management techniques that include the Young Generation, Old or Tenured Generation, and Permanent Generation. - If heap space is full, Java throws java.lang.OutOfMemoryError. Access to this memory is comparatively slower than stack memory This memory, in contrast to stack, isn't automatically deallocated. It needs Garbage Collector to free up unused objects so as to keep the efficiency of the memory usage. Unlike stack, a heap isn't threadsafe and needs to be guarded by properly synchronizing the code.
1. Which is not a rule for which you can create a custom class in Java? Syntax rules Validation rules Mapping rules Processing rules
Syntax rules
equals()
The Object class defines both the equals() and hashCode() methods, which means that these two methods are implicitly defined in every Java class, including the ones we create: class Money { int amount; String currencyCode; } Money income = new Money(55, "USD"); Money expenses = new Money(55, "USD"); boolean balanced = income.equals(expenses) The default implementation of equals() in the Object class says that equality is the same as object identity, and income and expenses are two distinct instances. Overriding equals() Let's override the equals() method so that it doesn't consider only object identity, but also the value of the two relevant properties: @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Money)) return false; Money other = (Money)o; boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null) || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode)); return this.amount == other.amount && currencyCodeEquals; } equals() conditions Java defines the conditions that our implementation of the equals() method must fulfill. Most of the criteria are common sense. The equals() method must be: - reflexive: an object must equal itself - symmetric: x.equals(y) must return the same result as y.equals(x) - transitive: if x.equals(y) and y.equals(z), then also x.equals(z) - consistent: the value of equals() should change only if a property that is contained in equals() changes (no randomness allowed)
1. If an exception is NOT handled anywhere in the program, what will occur? The exception propogates up through the call stack until it is handled by the JVM which will then terminate the program. The computer's operating system will handle the exception. The compiler will correct the code before it finishes compiling. Nothing occurs.
The exception propogates up through the call stack until it is handled by the JVM which will then terminate the program.
3.When a method is finished executing, which of the following does <b>not</b> happen with the stack? The flow goes back to the calling method. Its corresponding stack frame is flushed. The memory allocated for the stack is lost until the machine is reset. Space becomes available for the next method.
The memory allocated for the stack is lost until the machine is reset.
Example
public class BasicExceptionExample { public static void main(String[] args) { try { // try/catch blocks allow you to try out risky code and handle any exceptions that are thrown throwManyExceptions(3); } catch(FileNotFoundException e) { System.out.println("FileNotFoundException caught"); } catch (IOException e) { System.out.println("IOException caught"); } catch (Exception e) { // if you have multiple catch blocks, broader exception classes must come after more specific ones System.out.println("Other exception caught"); } finally { System.out.println("The finally block will always run! (unless System.exit(0) is called or power is lost)"); } } public static void throwManyExceptions(int i) throws Exception { // throws declaration in the method signature means you are "ducking" the exception switch(i) { case 1: throw new IOException(); case 2: throw new ClassNotFoundException(); case 3: throw new FileNotFoundException(); default: throw new Exception(); } } }
Autoboxing
the automatic conversion of primitive types to an object of their corresponding wrapper classes. // Java program to demonstrate Autoboxing import java.util.ArrayList; class Autoboxing { public static void main(String[] args) { char ch = 'a'; // Autoboxing- primitive to Character object conversion Character a = ch; ArrayList<Integer> arrayList = new ArrayList<Integer>(); // Here, autoboxing of the int 25 takes place because arrayList only stores Integer objects. arrayList.add(25); // printing the values from object System.out.println(arrayList.get(0)); } }
Implementing Push
used to add an item to the stack and update the lastItem to the one we're pushing. To add an item to the array we'll simply add the new item (defined by the parameter) to the end of the items array. public void push(int newItem){ int index = items.length; //get current length to store as index items = new int[items.length + 1]; //increase the array by 1 so that we can add our new item items[index] = newItem; //store the value in the index lastItem = newItem; //update lastItem }
3. The _____ method returns a Class object that represents this object's runtime class clone getClass toString finalize
getClass
Advantages Of Linked List
- Dynamic data structure: A linked list is a dynamic arrangement so it can grow and shrink at runtime by allocating and deallocating memory. So there is no need to give the initial size of the linked list. - No memory wastage: In the Linked list, efficient memory utilization can be achieved since the size of the linked list increase or decrease at run time so there is no memory wastage and there is no need to pre-allocate the memory. - Implementation: Linear data structures like stack and queues are often easily implemented using a linked list. - Insertion and Deletion Operations: Insertion and deletion operations are quite easier in the linked list. There is no need to shift elements after the insertion or deletion of an element only the address present in the next pointer needs to be updated.
Key Features of Stack Memory
- It grows and shrinks as new methods are called and returned, respectively. - Variables inside the stack exist only as long as the method that created them is running. - It's automatically allocated and deallocated when the method finishes execution. - If this memory is full, Java throws java.lang.StackOverFlowError. - Access to this memory is fast when compared to heap memory. - This memory is threadsafe, as each thread operates in its own stack.
Disadvantages Of Linked List
- Memory usage: More memory is required in the linked list as compared to an array. Because in a linked list, a pointer is also required to store the address of the next element and it requires extra memory for itself. - Traversal: In a Linked list traversal is more time-consuming as compared to an array. Direct access to an element is not possible in a linked list as in an array by index. For example, for accessing a node at position n, one has to traverse all the nodes before it. - Reverse Traversing: In a singly linked list reverse traversing is not possible, but in the case of a doubly-linked list, it can be possible as it contains a pointer to the previously connected nodes with each node. For performing this extra memory is required for the back pointer hence, there is a wastage of memory. - Random Access: Random access is not possible in a linked list due to its dynamic memory allocation.
Unchecked Exceptions
- Predictable but unpreventable: The caller did everything within their power to validate the input parameters, but some condition outside their control has caused the operation to fail. For example, you try reading a file but someone deletes it between the time you check if it exists and the time the read operation begins. By declaring a checked exception, you are telling the caller to anticipate this failure. - Reasonable to recover from: There is no point telling callers to anticipate exceptions that they cannot recover from. If a user attempts to read from an non-existing file, the caller can prompt them for a new filename. On the other hand, if the method fails due to a programming bug (invalid method arguments or buggy method implementation) there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time. - Unless the exception you are throwing meets all of the above conditions it should use an Unchecked Exception. Reevaluate at every level: Sometimes the method catching the checked exception isn't the right place to handle the error. In that case, consider what is reasonable for your own callers. If the exception is predictable, unpreventable and reasonable for them to recover from then you should throw a checked exception yourself. If not, you should wrap the exception in an unchecked exception. If you follow this rule you will find yourself converting checked exceptions to unchecked exceptions and vice versa depending on what layer you are in. - For both checked and unchecked exceptions, use the right abstraction level. For example, a code repository with two different implementations (database and filesystem) should avoid exposing implementation-specific details by throwing SQLException or IOException. Instead, it should wrap the exception in an abstraction that spans all implementations (e.g. RepositoryException).
Object class methods
- The toString() method is automatically called if you print an Object. Usually, this is overridden to provide human-readable output. Otherwise, you will print out fully.qualified.ClassName@memoryAddress - The equals(Object o) method compares two Objects. The == operator also compares objects, but only the memory address (i.e. will return true if and only if the variables refer to the exact same object in memory). By default, and unless you explicitly override it, the equals method simply calls the == operator. - The hashCode() method returns a hash code - a number that puts instances of a class into a finite number of categories. There are a few rules that the method follows: You are expected to override hashCode() if you override equals() - The result of hashCode() should not change in a program if .equals() returns true, the hash codes should be equal if .equals() returns false, the hash codes do not have to be distinct. However, doing so will help the performance of hash tables. - Finally, the .finalize() method is called by the garbage collector when it determines there are no more references to the object. It can be overriden to perform cleanup activities before garbage collection, although it has been deprecated in newer versions of Java.
Checked exceptions
Exceptions that require mandatory handling. Exceptions can be used to help write robust programs. Checked exceptions generally represent conditions that are outside the control of the programmer. Checked Exceptions should be used for predictable, but unpreventable errors that are reasonable to recover from. The compiler will check that such exceptions are handled by the program. Suppose that some statement in the body of a subroutine can generate a checked exception, one that requires mandatory handling. The statement could be a throw statement, which throws the exception directly, or it could be a call to a subroutine that can throw the exception. In either case, the exception must be handled. This can be done in one of two ways: - The first way is to place the statement in a try statement that has a catch clause that handles the exception; in this case, the exception is handled within the subroutine, so that no caller of the subroutine can ever see the exception. - The second way is to declare that the subroutine can throw the exception.This is done by adding a "throws" clause to the subroutine heading, which alerts any callers to the possibility that the exception might be generated when the subroutine is executed.The caller will, in turn, be forced either to handle the exception in a try statement or to declare the exception in a throws clause in its own header.
3. If you want to require your custom exception to be handled...? Extend any existing exception class Do not extend an existing exception class Create your own exception class Extend any class but the Exception class
Extend any existing exception class
2. Custom classes cannot be created in Java since Java is not object-oriented. False True
False
4. A Java programming language developer must write memory management into their programs. False True
False
4. Since Java has exception handling capability, programmers do not need to write code to handle exceptions. False True
False
4.Which of the following is <b>not</b> true about heap space? Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space. References to objects in heap space are stored in stack memory. Heap space uses static memory allocation.
Heap space uses static memory allocation.
4. ____ is a type of inheritance where there is one super class and more than one sub class extend the super class. Single inheritance Multi-level inheritance Hierarcihal inheritance Multiple inheritance
Hierarcihal inheritance
Violating equals() Symmetry With Inheritance
If the criteria for equals() is such common sense, then how can we violate it at all? Well, violations happen most often if we extend a class that has overridden equals(). Let's consider a Voucher class that extends our Money class: class WrongVoucher extends Money { private String store; @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof WrongVoucher)) return false; WrongVoucher other = (WrongVoucher)o; boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null) || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode)); boolean storeEquals = (this.store == null && other.store == null) || (this.store != null && this.store.equals(other.store)); return this.amount == other.amount && currencyCodeEquals && storeEquals; } // other methods } At first glance, the Voucher class and its override for equals() seem to be correct. And both equals() methods behave correctly as long as we compare Money to Money or Voucher to Voucher. But what happens, if we compare these two objects: Money cash = new Money(42, "USD"); WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon"); voucher.equals(cash) => false // As expected. cash.equals(voucher) => true // That's wrong. This violates the symmetry criteria of the equals() contract.
1.Which is <b>not</b> a feature of stack memory? If the memory is full, the program proceeds as normal. It grows and shrinks as new methods are called and returned, respectively. Variables inside the stack exist only as long as the method that created them is running. It's automatically allocated and deallocated when the method finishes execution.
If the memory is full, the program proceeds as normal.
Errors, Exceptions, and Compilation Errors
In Java, both errors and exceptions are the subclasses of java.lang.Throwable class. Error refers to an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. Errors can be classified into three types: - Compile-time - Run-time - Logical On the other hand, exceptions in java refer to an unwanted or unexpected event, which occurs during the execution of a program (run-time) that disrupts the normal flow of the program's instructions. // Java Program to Illustrate Error // Stack overflow error via infinite recursion // Class 1 class StackOverflow { // method of this class public static void test(int i) { // Incorrect as base condition leads to non-stop recursion. if (i == 0) return; else { test(i++); } } } // Class 2 // Main class public class GFG { // Main driver method public static void main(String[] args) { // Testing for error by passing // custom integer as an argument StackOverflow.test(5); } }
Covariant return types
Overriding and overridden methods have same signature but different return types if the return types are class types, and the return type of the overriding method in the derived class is a descendent class of the return type of the overridden method in the base/ancestor class. When overriding a method, we also have the option of changing the return type - provided that the overridden return type is a subtype of the original type. This is called covariant return types. We can also choose to change the access modifier of an overridden method - provided that the new modifier for the overriding method provides more, not less, access than the overridden method.
Static Polymorphism
Polymorphism that is resolved during compile time is known as static polymorphism. Method overloading can be considered as static polymorphism example. Method Overloading: This allows us to have more than one methods with same name in a class that differs in signature. class DisplayOverloading { public void disp(char c) { System.out.println(c); } public void disp(char c, int num) { System.out.println(c + " "+num); } } public class ExampleOverloading { public static void main(String args[]) { DisplayOverloading obj = new DisplayOverloading(); obj.disp('a'); obj.disp('a',10); } }
2. Which of the following is not a good example of a hierarchy likely to be modeled by inheritance? Prime numbers Airplanes Animals Geometric shapes
Prime numbers
1.What does object-oriented programming mean? Programming constructs are objects which model real-world concepts and can be put into hierarchies, and the relationship between objects are managed Functions are first-class objects and can be passed as parameters Variables are statically typed and not allowed to change types once declared Any piece of software which operates at an enterprise-level scale
Programming constructs are objects which model real-world concepts and can be put into hierarchies, and the relationship between objects are managed
2. Subclasses of the class Exception which are not subclasses of ______ are checked exceptions. RuntimeException IOException ArithmeticException NullPointerException
RuntimeException
Violating the Consistency of hashCode() and equals()
The second criteria of the hashCode conditions has an important consequence: If we override equals(), we must also override hashCode(). This is by far the most widespread violation regarding the equals() and hashCode() methods contracts. class Team { String city; String department; @Override public final boolean equals(Object o) { // implementation } } The Team class overrides only equals(), but it still implicitly uses the default implementation of hashCode() as defined in the Object class. And this returns a different hashCode() for every instance of the class. This violates the second rule.
1. The _____ class represents all possible objects that can be thrown by a throw statement and caught by a catch clause in a try..catch statement. Throwable ExceptionHandler ErrorHandler Catchable
Throwable
Fixing equals() Symmetry With Composition
To avoid this pitfall, we should favor composition over inheritance. Instead of subclassing Money, let's create a Voucher class with a Money property: class Voucher { private Money value; private String store; Voucher(int amount, String currencyCode, String store) { this.value = new Money(amount, currencyCode); this.store = store; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Voucher)) return false; Voucher other = (Voucher) o; boolean valueEquals = (this.value == null && other.value == null) || (this.value != null && this.value.equals(other.value)); boolean storeEquals = (this.store == null && other.store == null) || (this.store != null && this.store.equals(other.store)); return valueEquals && storeEquals; } // other methods }
Defining Validation Classes
To customize validation of an internal/external message field/section, you have to write a class that implements the IFieldValidation interface and plug it to the validation rule of the corresponding field/section.
2. Variable references are stored in the Stack. True False
True
3. Custom classes are more flexible than the built-in Java language. True False
True
3. If an error is predicatble but unpreventable and reasonable to recover from, a checked exception should be used True False
True
3. What is the process of converting a wrapper class to its primitive? Boxing Unboxing Wrapping Unwrapping
Unboxing
Exceptions
When an exceptional condition occurs in the course of a Java program, a special class called an Exception can be thrown, which indicates that something went wrong during the execution of the program. If the exception is not handled anywhere in the program, it will propagate up through the call stack until it is handled by the JVM which then terminates the program. Exceptions Handling / Declaring Exceptions: - When risky code is written that has the possibility of throwing an exception, it can be dealt with in one of two ways: - Handling means that the risky code is placed inside a try/catch block - Declaring means that the type of exception to be thrown is listed in the method signature with the throws keyword. This is also called "ducking" the exception - you let the code which calls the method deal with it.
Custom Exceptions
You can create custom exceptions in Java by extending any exception class. If you extend RuntimeException, however, you will be creating an unchecked exception. This is a good idea if you do not want other code to have to handle your exception being thrown. If you do always want to require your exception to be handled, then create a checked exception by extending any existing one, or the Exception class itself. public class MyCheckedException extends Exception {} public class MyUncheckedException extends RuntimeException {} public class ExceptionThrower { public static void main(String[] args) { try { throw new MyCheckedException("uh oh"); } catch(MyCheckedException e) {} // we're just ignoring it here if ( 100 > 1) { throw new MyUncheckedException("you're not required to handle me!"); } } public static void declareChecked() throws MyCheckedException { throw new MyCheckedException("this one is declared!"); } }
3. What is the easiest way to immediately force Java garbage collection? Call System.gc() in code Invoke a Java heap dump Use the Java diagnostic command and run jcmd GC.run You cannot force Java garbage collection
You cannot force Java garbage collection
List
a collection that is ordered and preserves the order in which elements are inserted into the list. Contrary to sets, duplicate entries are allowed. Also, elements are accessed by their index, which begins with 0 for the first element in the list.
ArrayList
a concrete class which implements List. It is a data structure which contains an array within it, but can resize dynamically. Once it reaches maximum capacity, an ArrayList will increase its size by 50% by copying its elements to a new (internal) array. Traversal is fast (constant time) because elements can be randomly accessed via index, just like an array. Insertion or removal of elements is slow, however (linear time, since there is a risk of having to resize the underlying array).
Object class
a special class in Java which is the root class from which all other classes inherit, either directly or indirectly. Any class that doesn't have an extends clause implicitly inherits Object. If a subclass has an extends clause that specifies a superclass other than Object, the class still inherits Object. Since all objects inherit from the Object class, they have at least the methods defined in the Object class: - Object clone() : Returns a copy of this object. boolean equals(Object o) - Indicates whether this object is equal to the o object. - void finalize() : Called by the garbage collector when the object is destroyed. - Class<?> getClass() : Returns a Class object that represents this object's runtime class - int hashCode() : Returns this object's hash code. - void notify() : Is used with threaded applications to wake up a thread that's waiting on this object. - void notifyAll() : Is used with threaded applications to wake up all threads that are waiting on this object. - String toString() : Returns a String representation of this object. - void wait() : Causes this object's thread to wait until another thread calls notify or notifyAll. - void wait(long timeout) : Is a variation of the basic wait method. - void wait(long timeout, int nanos) : Another variation of the wait method.
Custom Class
adds flexibility to standard mechanism provided by Designer for defining message processing. A custom class is more flexible compared to the formula language
Vector
an older class which implements List - it is essentially a thread-safe implementation of an ArrayList.
Wrapper Classes
are classes that let you treat primitives as Objects. This is necessary for certain methods which only accept objects and not primitives. Wrapper classes have static helper methods like .parseX() and .valueOf() for explicit primitive conversion. public class AutoboxingExample { public static void main(String[] args) { int n = 5; // We start by declaring an int for a primitive type. someMethod(n); // autoboxing is done here to wrap the Integer class around int n. // 8 } public static void someMethod(Integer i) { System.out.println(i + 3); } }
Example of Stack and Heap
class Person { int id; String name; public Person(int id, String name) { this.id = id; this.name = name; } } public class PersonBuilder { private static Person buildPerson(int id, String name) { return new Person(id, name); } public static void main(String[] args) { int id = 23; String name = "John"; Person person = null; person = buildPerson(id, name); } }
LinkedList
implements both the List and Queue interfaces, so it has all methods in both interfaces. The data structure is composed of nodes internally, each with a reference to the previous node and the next node - i.e. a doubly-linked list. Because of this structure, insertion or removal of elements is fast (no risk to resize, just change the nearest references), but traversal is slow for an arbitrary index.
Programming with Exceptions
class ShipDestroyed extends RuntimeException { Ship ship; // Which ship was destroyed. int where_x, where_y; // Location where ship was destroyed. ShipDestroyed(String message, Ship s, int x, int y) { // Constructor creates a ShipDestroyed object // carrying an error message plus the information // that the ship s was destroyed at location (x,y) // on the screen. super(message); ship = s; where_x = x; where_y = y; } } A throw statement can be used in a program to throw an error of type ParseError. The constructor for the ParseError object must specify an error message. For example: throw new ParseError("Encountered an illegal negative number."); Since ParseError is defined as a subclass of Exception, it is a checked exception. If the throw statement does not occur in a try statement that catches the error, then the subroutine that contains the throw must declare that it can throw a ParseError by adding the clause "throws ParseError" to the subroutine heading. A routine that wants to handle ParseErrors can use a try statement with a catch clause that catches ParseErrors. For example: try { getUserData(); processUserData(); } catch (ParseError pe) { . . . // Handle the error }
2. The _____ method returns a copy of this object. clone getClass toString finalize
clone
Unboxing
converts an object of a wrapper class to its corresponding primitive data type. // Java program to demonstrate Unboxing import java.util.ArrayList; class Unboxing { public static void main(String[] args) { Character ch = 'a'; // unboxing - Character object to primitive conversion char a = ch; ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(24); // unboxing because get method returns an Integer object int num = arrayList.get(0); // printing the values from primitive data types System.out.println(num); } }
3. Which of these is not an additional operation provided by the List interface? eliminate() get() set() addAll()
eliminate()
4. Code that executes at the end of a try-catch block is designated with which keyword? finally try catch throws
finally
4. Which of these is not an additional operation provided by the List interface? firstIndexOf() indexOf() lastIndexOf() remove()
firstIndexOf()
What is inheritance?
is all about inheriting the common state and behavior of parent class (super class) by its derived class (sub class or child class). A sub class can inherit all non-private members from super class, by default. - Inheritance can be one of four types - depending on classes hierarchy. Let's learn about all four types of inheritances. - Single inheritance: There is one Parent class and one Child class. One child class extends one parent class Multi-level inheritance: In multilevel inheritance, there will be inheritance between more than three classes in such a way that a child class will act as parent class for another child class. - Hierarchical inheritance: In hierarchical inheritance, there is one super class and more than one sub classes extend the super class. - Multiple inheritance: In multiple inheritance, a class can inherit the behavior from more than one parent classes as well.Note: Not all programming languages support Multiple Inheritance. For instance, Java does not support multiple inheritance from Classes. This means that any given class can only have one direct parent or super class.
Method Overriding
is when a method in a child class has the same method signature as a method in the parent class, but with a different implementation. Overriding methods makes class hierarchies more flexible and dynamic.
Method Overloading
is when there exist two or more methods in a class with the same method name, but different method signatures by changing the parameter list. method overloading is a type of compile-time - or static - polymorphism.
Polymorphism
means "taking on many forms". In the realm of programming, it describes how objects can behave differently in different contexts. The most common examples of polymorphism are method overloading, method overriding, upcasting and downcasting.
hashCode()
returns an integer representing the current instance of the class. hashCode() conditions: - Java also defines a set of conditions for the hashCode() method. A thorough look at it shows how closely related hashCode() and equals() are. - All three criteria for hashCode() mention the equals() method in some way: - internal consistency: the value of hashCode() may only change if a property that is in equals() changes - equals consistency: objects that are equal to each other must return the same hashCode - collisions: unequal objects may have the same hashCode
Upcasting
the process of casting an object of a subclass to an object of its superclass. It is a safe operation because it does not involve any loss of data. In other words, when you upcast an object, you can access only the members of the superclass, but you do not lose any members of the subclass. Upcasting is done automatically by the Java compiler, so you do not need to explicitly cast the object.
Downcasting
the process of casting an object of a superclass to an object of its subclass. It is a risky operation because it may result in a ClassCastException at runtime if the object being cast is not actually an instance of the subclass. To avoid this, it is recommended to use the instanceof operator to check if the object can be safely downcasted.
Boxing
the process of converting a primitive to its wrapper class.
3. "Ducking" or declaring an exception is done with which keyword? throws try catch if
throws
4. The _____ method returns a String representation of this object. clone getClass toString finalize
toString
Stack Memory in Java
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 referred from the method that are in a heap. - Access to this memory is in Last-In-First-Out (LIFO) order. Whenever we call a new method, a new block is created on top of the stack which contains values specific to that method, like primitive variables and references to objects. - When the method finishes execution, its corresponding stack frame is flushed, the flow goes back to the calling method, and space becomes available for the next method.
Heap Space in Java
used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, and the references to these objects are stored in stack memory. - These objects have global access and we can access them from anywhere in the application. - We can break this memory model down into smaller parts, called generations, which are: - Young Generation - this is where all new objects are allocated and aged. A minor Garbage collection occurs when this fills up. - Old or Tenured Generation - this is where long surviving objects are stored. - When objects are stored in the Young Generation, a threshold for the object's age is set, and when that threshold is reached, the object is moved to the old generation. - Permanent Generation - this consists of JVM metadata for the runtime classes and application methods.
