corejava_12

56. Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?
In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you’re done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.
In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.

57. If one needs a Set, how do you choose between HashSet vs. TreeSet?
At first glance, HashSet is superior in almost every way: O(1) add, remove and contains, vs. O(log(N)) for TreeSet.
However, TreeSet is indispensable when you wish to maintain order over the inserted elements or query for a range of elements within the set. Generally speaking, TreeSet is a good choice when order matters and when reads are balanced against the increased cost of writes.

58. How are Java enums more powerful than integer constants? How can this capability be used?
Enums are essentially final classes with a fixed number of instances. They can implement interfaces but cannot extend another class.
This flexibility is useful in implementing the strategy pattern, for example, when the number of strategies is fixed.
 Generally, the safety and flexibility of enums means they should be used in place of integer constants, and switch statements can be eliminated with liberal use of abstract methods.
  
59. When designing an abstract class, why should you avoid calling abstract methods inside its constructor?
Because  it restricts how those abstract methods can be implemented.

60. Why there are two Date classes; one in java.util package and another in java.sql?
A java.util.Date represents date and time of day, a java.sql.Date only represents a date (the complement of java.sql.Date is java.sql.Time, which only represents a time of day, but also extends java.util.Date).

No comments:

Post a Comment