Java Questions

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

Explain the JVM, JDK, and JRE

- A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a Java program. There are three notions of the JVM: specification, implementation, and instance. The specification is a document that formally describes what is required of a JVM implementation. Having a single specification ensures all implementations are interoperable. A JVM implementation is a computer program that meets the requirements of the JVM specification. An instance of a JVM is an implementation running in a process that executes a computer program compiled into Java bytecode. - Java Runtime Environment (JRE) is a software package that contains what is required to run a Java program. It includes a Java Virtual Machine implementation together with an implementation of the Java Class Library. The Oracle Corporation, which owns the Java trademark, distributes a Java Runtime environment with their Java Virtual Machine called HotSpot. - Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers, e.g. a javac compiler. The Java Development Kit is provided free of charge either by Oracle Corporation directly, or by the OpenJDK open source project, which is governed by Oracle.

What does the static keyword mean?

- A member variable or method can be used without instantiating the class to which it belongs to. Static is typically used when there is a variable which all members of some class need to share. This variable is only created once and behaves like a global variable with a scope of the class. Users cannot override static methods because overriding depends on dynamic binding at run whereas static methods are statically bound at compile time. - Methods can also be declared as static...use className.staticMethod() to invoke it; no need for object instance to use static method.

What is the difference between ArrayList and LinkedList?

- An ArrayList is an index based data structure backed by an Array. It provides random access to its elements with a performance equal to O(1). On the other hand, a LinkedList stores its data as list of elements and every element is linked to its previous and next element. In this case, the search operation for an element has execution time equal to O(n). - The Insertion, addition and removal operations of an element are faster in a LinkedList compared to an ArrayList, because there is no need of resizing an array or updating the index when an element is added in some arbitrary position inside the collection. - A LinkedList consumes more memory than an ArrayList, because every node in a LinkedList stores two references, one for its previous element and one for its next element.

What is an enumerated type?

- An enumerated type has values that are different from each other, and that can be compared and assigned, but are not specified by the programmer as having any particular concrete representation in the computer's memory enum Cardsuit { CLUBS, DIAMONDS, SPADES, HEARTS }; ... Cardsuit trump; - Enum types can have instance methods and a constructor. All enum types implicitly extend the Enum abstract class. An enum type cannot be instantiated directly. Internally, each enum value contains an integer, corresponding to the order in which they are declared in the source code, starting from 0. The programmer cannot set a custom integer for an enum value directly, but one can define overloaded constructors that can then assign arbitrary values to self-defined members of the enum class. - The internal integer can be obtained from an enum value using the ordinal() method, and the list of enum values of an enumeration type can be obtained in order using the values() method.

What is an unbounded generic type? What is the difference between List<? extends T> and List<? super T>?

- An unbounded generic type is of the form <?> which represents any object. This can be useful as List<String> is not a subtype of List<Integer> so List<?> will take care of this problem. - The ? represents a wildcard. Here's an example of its use: List<Integer extends Number> whereas List<Number super Integer>

How do arrays differ from generic types?

- Arrays are covariant which means if Sub is a subtype of Super then Sub[] is subtype of Super[], whereas generics are invariant which means that List<Sub> is not subtype of List<Super> which allows us to find out we made a mistake at compile time instead runtime like with arrays. - Arrays are reified meaning they know and enforce their element types at runtime whereas generics are implemented by erasure which means they enforce their type constraints only at compile time and discard (or erase) their element type information at runtime

What is the difference between Comparator and Comparable interface?

- Comparable is meant for objects with natural ordering which means the object itself must know how it is to be ordered. Can only sort on basis of single element such as id. When we make a collection element comparable we get only one chance to implement the compareTo() method Collections.sort(list); - Unlike Comparable, Comparator is external to the element type we are comparing. We create multiple separate classes (that implement Comparator) to compare by different members. Comparator can sort on basis of multiple elements such as id, name, price, etc. class RatingCompare implements Comparator<Movie> { public int compare(Movie m1, Movie m2) { if (m1.getRating() < m2.getRating()) return -1; if (m1.getRating() > m2.getRating()) return 1; else return 0; } } // Class to compare Movies by name class NameCompare implements Comparator<Movie> { public int compare(Movie m1, Movie m2) { return m1.getName().compareTo(m2.getName()); } } We could say: Collections.sort(list, new RatingCompare()) or Collections.sort(list, new NameCompare());

Explain the differences between TreeMap, HashMap, and LinkedHashMap. Provide an example of when each one would be best.

- HashMap is O(1) lookup and insertion but arbitrary ordering. Useful in most situations - TreeMap is O(logn) lookup and insertion but keys are ordered and implement Comparable interface..Useful when need keys in natural order like if you were creating mapping of names to Person objects and wanted to output people in alphabetical order - LinkedHashMap offers O(1) lookup and insertion. Useful when you need ordering of keys to match ordering of insertion (like in LRU cache situations)

What is the factory pattern and why is it useful?

- In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface. - Factory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-class. - Factory design pattern provides approach to code for interface rather than implementation. - Factory pattern removes the instantiation of actual implementation classes from client code. Factory pattern makes our code more robust, less coupled and easy to extend. For example, we can easily change PC class implementation because client program is unaware of this. Factory pattern provides abstraction between implementation and client classes through inheritance.

Explain the difference between Iterator and Enumeration interface

- Interator has extra method remove which allows for modification of elements in underlying collection - Enumeration is twice as fast as compared to an Iterator and uses very less memory. However, the Iterator is much safer compared to Enumeration, because other threads are not able to modify the collection object that is currently traversed by the iterator.

Explain what object reflection is in Java and why it's useful.

- Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. Class myObjectClass = MyObject.class; Method[] methods = myObjectClass.getMethods(); Field[] fields = myObjectClass.getFields(); - Reflection can be useful for the following reasons: you can observe or manipulate the runtime behavior of applications; you can debug or test programs as you have direct access to methods, constructors, and fields; you can call methods by name when you don't know the method in advance

Method overloading vs method overriding

- Overloading is compile time polymorphism, in which you can different parameters in multiple definitions of method signature and you can have the same parameters but with different types or order. It may or may not need inheritance. - Overriding is runtime polymorphism and needs inheritance to operate. Has the same name and exactly the same types and order but changes superclass' existing behavior.

What is the difference between pass by reference and pass by value?

- Pass by reference refers to changing value of original object - Pass by value refers to making changes to copy of original object so no damage is done globally.

Why is String class in Java immutable?

- Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed. - Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues. - Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object). - Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state)

What are the differences between Heap and Stack memory?

- Stack: Stack memory is used only by one thread of execution. Stack memory can't be accessed by other threads. Follows LIFO manner to free memory. Exists until the end of execution of the thread. Stack memory only contains local primitive and reference variables to objects in heap space. - Heap: Heap memory is used by all the parts of the application. Objects stored in the heap are globally accessible. Memory management is based on generation associated to each object. Heap memory lives from the start till the end of application execution. Whenever an object is created, it's always stored in the Heap space.

What is the difference between using new() operator to create String and using "" to create String?

- String pool helps in saving a lot of space for Java Runtime although it takes more time to create the String. - When we use double quotes to create a String, it first looks for String with same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference. - However using new operator, we force String class to create a new String object in heap space.

Why is saving passwords in char array more secure than in a String?

- Strings are immutable. That means once you've created the String, if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before garbage collection kicks in. - With an array, you can explicitly wipe the data after you're done with it. You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection. - So yes, this is a security concern - but even using char[] only reduces the window of opportunity for an attacker, and it's only for this specific type of attack. - It's possible that arrays being moved by the garbage collector will leave stray copies of the data in memory. I believe this is implementation-specific - the garbage collector may clear all memory as it goes, to avoid this sort of thing. Even if it does, there's still the time during which the char[] contains the actual characters as an attack window

What kind of reference types exist in Java?

- Strong: default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. The object is garbage collected only when the variable which was strongly referenced points to null. - Soft: even if the object is free for garbage collection then also its not garbage collected, until JVM is in need of memory badly. The objects gets cleared from the memory when JVM runs out of memory. - Weak: used in WeakHashMap to reference the entry objects. If JVM detects an object with only weak references (i.e. no strong or soft references linked to any object object), this object will be marked for garbage collection. - Phantom: eligible for garbage collection. But, before removing them from the memory, JVM puts them in a queue called 'reference queue' . They are put in a reference queue after calling finalize() method on them.

What is the difference between errors, checked exceptions and unchecked exceptions?

- Unchecked exceptions (like IndexOutOfBounds or NullPointerException) extend RuntimeException and are not expected to be dealt with at compile time - Checked exceptions must be dealt with by either using a try-catch or by throwing the exceptions within the method definition or within block in the method (examples include IO exceptions or SQL exception). - Error is unrecoverable condition occurring at runtime such as outofmemory error - Both exception and error inherit from the class throwable which inherits from object

What are the data types supported by Java? How many bytes are each?

- byte is 8 bits - short is 2 bytes - int is 4 bytes - long is 8 bytes similar to in but "longer" - float is 4 bytes - double is 8 bytes higher precision than float

What is the difference between throw and throws clause?

- throw keyword: Throw is used to explicitly throw an exception. Checked exceptions can not be propagated with throw only. Throw is followed by an instance. Throw is used within the method. You cannot throw multiple exception -throws keyword: Throws is used to declare an exception. Checked exception can be propagated with throws. Throws is followed by class. Throws is used with the method signature. You can declare multiple exception e.g. public void method()throws IOException,SQLException

What is the difference between abstract classes and interfaces? When should you use one over the other?

-Neither an abstract class nor interface can be instantiated. An abstract class can have state and behavior whereas an interface has no state or behavior. - An abstract class can provide complete, default code and/or just the details that have to be overridden. In case of abstract class, a class may extend only one abstract class. An abstract class can have non-abstract methods. An abstract class can have instance variables. An abstract class can have any visibility: public, private, protected. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. An abstract class can contain constructors. - An interface cannot provide any code at all,just the signature. A Class may implement several interfaces. All methods of an Interface are abstract. An Interface cannot have instance variables. An Interface visibility must be public (or) none. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. An Interface cannot contain constructors. - Multiple inheritance is not supported in Java so if you need have plenty of functionality from a variety sources, interfaces are the way to go. Abstract are better from a maintenance perspective as concrete methods are defined for each subclass whereas any changes to an interface require updates to each class that implements the interface. Abstract classes are preferable if you want to encapsulate an Is-A entity like Shape or Car whereas interfaces are better to capture capabilities like Runnable or Flyable. Interfaces provide more decoupling than abstract classes because interfaces don't contain any implementation detail, whereas abstract classes' children may be couple with each other.

Can you access non static variable inside static context?

A static variable belongs to its class and is the same for all instances. Static variables are initialized by the jvm upon start up whereas non static variables rely on instances to initialize them hence non static variables without a calling object will make the compile complain as they have not been initialized yet.

Can an abstract class be instantiated? Does it have a constructor?

An abstract class cannot be instantiated; it must be extended, but it does have a constructor to take care of the situation where it's subclass' constructor will always explicitly or implicitly calls super which would be the abstract class' constructor.

What is the difference between ArrayList and Vector?

Arraylist is fast as it is not synchronized whereas vector is thread safe and slow and synchronized; arraylist can only use iterator to traverse list whereas vector can use both enumeration and iterator.

What differences exist between java.util's HashMap and HashTable?

Both implement the map interface. A HashMap allows the existence of null keys and values, while a Hashtable doesn't allow neither null keys, nor null values. A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in single-threaded environments, while a Hashtable is suitable for multi-threaded environments. A HashMap provides its set of keys and a Java application can iterate over them. Thus, a HashMap is fail-fast. On the other hand, a Hashtable provides an Enumeration of its keys. The Hashtable class is considered to be a legacy class.

What a singleton class and how can we make a class singleton?

Class whose only instance can be created at given time and ensures global access to this instance through the application. It can be useful when there is a unique identifier to ensure only instance instance exists; also it cuts down overhead when calling implements equals() with a == b. To make a singleton, have all the following conditions be met: a) Private constructor to restrict instantiation of the class from other classes; b) Private static variable of the same class that is the only instance of the class; c) Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.

What is SimpleDateFormat class and how would you use it?

Commonly used to parse and fomat dates. Use followoing syntax: SimpleDateFormat s = new SimpleDateFormat("yyy/MM/DD HH:mm:ss"); s.format(new Date());

What is Polymorphism?

Described as one interface, many implementations. You can assign a different meaning to something in different contexts. There are two types of polymorphism: compile time polymorphism (method overloading) and runtime polymorphism.

Why doesn't Collection interface extend Serializable or Cloneable interfaces?

Each implementation of collection varies and should decide whether it should implement Cloneable or Serializable on its own terms

What is the difference between fail-fast and fail-safe when talking about iterators?

Fail-safe throws CME as it works with a clone of underlying collection whereas fail-fast does not and is allowed to modify the underlying collection

What are the benefits of object-oriented programming?

Modular development of code which leads to easy maintenance and modification (you can change one module without affection other modules), reusabiltiy of code, improved reliability and flexibility, increased understanding of code.

What makes Java platform independent?

Platform independence means write once run anywhere which is true for Java since its byte codes can run on any system (because of the jvm which is aware of the specific instruction lengths and other particularities of the underlying hardware platform) regardless of underlying os

What is dynamic method dispatch?

Runtime polymorphism in which a call to an overridden method is resolved at runtime rather than compile time. The method is called through reference variable of superclass.

What is a copy constructor?

Similar to cloning an existing object of the same class: public Galaxy(Galaxy existingGalaxy){this(existingGalaxy.getName());}

What is method hiding?

When a subclass writes definition of a superclass' private method, java will hide the superclass' method though it is not technically being overridden.


Ensembles d'études connexes

Anatomy 1 Chapter 13 - The Spinal Cord and Spinal Nerves

View Set

Comprehensive Exam Study Set - History of Christianity

View Set

CHAPTER 9: INTERPERSONAL ATTRACTION

View Set

Cognitive Psychology Exam 3 (Quizzes 9, 11, & 12)

View Set

Principles of Real Estate II: Ch. 9

View Set

Node.js Interview Questions - Beginner Level

View Set

Policy provisions and contract laws

View Set

C++ CPT-232 Chapter 4 Review questions (1-30 & 42-58)

View Set

7th Grade - Ratios and Proportional Reasoning Review

View Set