JavaRush /Java Blog /Random EN /Analysis of questions and answers from interviews for a J...

Analysis of questions and answers from interviews for a Java developer. Part 7

Published in the Random EN group
Hey everyone! Programming is full of pitfalls. And there is practically no topic in which you will not stumble and fill bumps. This is especially true for beginners. There is only one way to reduce the amount of this - to study. In particular, this applies to detailed analyzes of the most basic topics. Today I continue to analyze 250+ questions from interviews for a Java developer, which cover basic topics well. I note that the list also contains not quite standard questions that allow you to look at ordinary topics from a different angle.Analysis of questions and answers from interviews for a Java developer.  Part 7 - 1

62. What is a string pool and why is it needed?

In memory in Java (Heap, which we'll talk about later), there is an area - String pool , or string pool. It is designed to store string values. In other words, when you create a certain string, for example, through double quotes:
String str = "Hello world";
a check is made to see if the string pool has the given value. If it does, the variable str is assigned a reference to that value in the pool. If it doesn't, a new value will be created in the pool and a reference to it will be assigned to str . Consider an example:
String firstStr = "Hello world";
String secondStr = "Hello world";
System.out.println(firstStr == secondStr);
True will be displayed on the screen . We remember that == compares exactly references - it means that these two references refer to the same value from the string pool. This is done in order not to produce many identical objects of the String type in memory, because, as we remember, String is an immutable class, and if we have many references to the same value, there is nothing wrong with that. It is no longer possible for a change in a value in one place to change several other links at once. But still, if we create a string with new :
String str = new String("Hello world");
a separate object in memory will be created that will store the given string value (and it does not matter if we already have such a value in the string pool). As confirmation:
String firstStr = new String("Hello world");
String secondStr = "Hello world";
String thirdStr = new String("Hello world");
System.out.println(firstStr == secondStr);
System.out.println(firstStr == thirdStr);
We'll get two false s , which means we have three different referenced values. Actually, therefore it is recommended to create strings simply through double quotes. However, it is possible to add (or get a reference to) values ​​into the string pool when creating an object via new . To do this, we use the string class method - intern() . This method forcibly creates a value in the string pool, or gets a reference to it if it is already stored there. Here is an example:
String firstStr = new String("Hello world").intern();
String secondStr = "Hello world";
String thirdStr = new String("Hello world").intern();
System.out.println(firstStr == secondStr);
System.out.println(firstStr == thirdStr);
System.out.println(secondStr == thirdStr);
as a result, we will get three true values ​​in the console , which means that all three variables refer to the same string.Analysis of questions and answers from interviews for a Java developer.  Part 7 - 2

63. What GOF patterns are used in the string pool?

In the string pool, the GOF pattern is clearly traced - lightweight (flyweight), otherwise it is called a settler. If you see another template here, share it in the comments. Well, we'll talk about the lightweight template. Lightweight is a structural design pattern in which an object that presents itself as a unique instance in different places in the program, in fact, is not. Lightweight saves memory by sharing the common state of objects among themselves, instead of storing the same data in each object. To understand the essence, consider the simplest example. Suppose we have an employee interface:
public interface Employee {
   void work();
}
And there are some implementations like lawyer:
public class Lawyer implements Employee {

   public Lawyer() {
       System.out.println("Юрист взят в штат.");
   }

   @Override
   public void work() {
       System.out.println("Решение юридических вопросов...");
   }
}
And the accountant:
public class Accountant implements Employee{

   public Accountant() {
       System.out.println("Бухгалтер взят в штат.");
   }

   @Override
   public void work() {
       System.out.println("Ведение бухгалтерского отчёта....");
   }
}
Methods are very arbitrary: we just need to see that they are executed. The same situation is with the constructor. Thanks to the console output, we will see when new objects are created. We also have a department of employees, whose task is to issue the requested employee, if he is not there, to hire and issue in response to a request:
public class StaffDepartment {
   private Map<String, Employee> currentEmployees = new HashMap<>();

   public Employee receiveEmployee(String type) throws Exception {
       Employee result;
       if (currentEmployees.containsKey(type)) {
           result = currentEmployees.get(type);
       } else {
           switch (type) {
               case "Бухгалтер":
                   result = new Accountant();
                   currentEmployees.put(type, result);
                   break;
               case "Юрист":
                   result = new Lawyer();
                   currentEmployees.put(type, result);
                   break;
               default:
                   throw new Exception("Данный сотрудник в штате не предусмотрен!");
           }
       }
       return result;
   }
}
That is, the logic is simple: if there is a given unit, return it, if not, create it, put it in storage (something like a cache) and give it back. Now let's see how it all works:
public static void main(String[] args) throws Exception {
   StaffDepartment staffDepartment = new StaffDepartment();
   Employee empl1  = staffDepartment.receiveEmployee("Юрист");
   empl1.work();
   Employee empl2  = staffDepartment.receiveEmployee("Бухгалтер");
   empl2.work();
   Employee empl3  = staffDepartment.receiveEmployee("Юрист");
   empl1.work();
   Employee empl4  = staffDepartment.receiveEmployee("Бухгалтер");
   empl2.work();
   Employee empl5  = staffDepartment.receiveEmployee("Юрист");
   empl1.work();
   Employee empl6  = staffDepartment.receiveEmployee("Бухгалтер");
   empl2.work();
   Employee empl7  = staffDepartment.receiveEmployee("Юрист");
   empl1.work();
   Employee empl8  = staffDepartment.receiveEmployee("Бухгалтер");
   empl2.work();
   Employee empl9  = staffDepartment.receiveEmployee("Юрист");
   empl1.work();
   Employee empl10  = staffDepartment.receiveEmployee("Бухгалтер");
   empl2.work();
}
And in the console, respectively, there will be an output:
The lawyer is hired. Solving legal issues ... The accountant was hired. Maintaining an accounting report.... Solving legal issues... Maintaining an accounting report.... Solving legal issues... Maintaining an accounting report.... Solving legal issues... Maintaining an accounting report.... Solving legal issues. .. Book keeping...
As you can see, only two objects were created in total, which were reused many times. The example is quite simple, but it clearly demonstrates how applying this pattern can save our resources. Well, as you noticed, the logic of this pattern is painfully similar to the logic of the insurance pool. You can read more about the varieties of GOF patterns in this article .Analysis of questions and answers from interviews for a Java developer.  Part 7 - 3

64. How to split a string into parts? Please provide an example of relevant code

Obviously, this question is about the split method . The String class has two variations of this method:
String split(String regex);
And
String split(String regex);
regex is a line separator - some regular expression by which a string is divided into an array of strings, for example:
String str = "Hello, world it's Amigo!";
String[] arr = str.split("\\s");
for (String s : arr) {
  System.out.println(s);
}
The following will be output to the console:
Hello, world it's Amigo!
That is, our string value was split into an array of strings and a space served as a separator (for separation, you could use a non-space regular expression "\\s" and just a string expression " " ). The second, overloaded method has an additional argument - limit . limit - the maximum allowable value of the resulting array. That is, when the string has already been split into the maximum allowed number of substrings, there will be no further splitting, and the last element will have the “remainder” of a possibly unbroken string. Example:
String str = "Hello, world it's Amigo!";
String[] arr = str.split(" ", 2);
for (String s : arr) {
  System.out.println(s);
}
Console output:
Hello, world it's Amigo!
As we can see, if it were not for the limitation limit = 2 , the last element of the array could be split into three substrings.Analysis of questions and answers from interviews for a Java developer.  Part 7 - 4

65. Why is an array of characters better than a string for saving a password?

There are several reasons for preferring an array to a string when storing a password: 1. String pool and immutability of strings. When using an array ( char[] ) we can explicitly erase the data after we're done with it. We can also rewrite the array as much as we like, and there will be no valid password anywhere in the system, even before garbage collection (just change a couple of cells to invalid values). At the same time, String is an immutable class. That is, if we want to change its value, we will get a new one, while the old one will remain in the string pool. If we want to remove the String value of the password, this can be quite tricky, since we need the garbage collector to remove exactly the value from the String pool-a, and there is a good chance that this String value will stay there for a long time. That is, in this situation, String is inferior to the char array in terms of data storage safety. 2. If a String value is accidentally output to the console (or logs), the value itself will be displayed:
String password = "password";
System.out.println("Пароль - " + password);
Console output:
Password - password
At the same time, if you accidentally print an array to the console:
char[] arr = new char[]{'p','a','s','s','w','o','r','d'};
System.out.println("Пароль - " + arr);
in the console there will be an incomprehensible gibberish:
Password - [C@7f31245a
Actually, not abracadabra, but: [C - class name - array char , @ - separator, after which - 7f31245a - hexadecimal hashcode. 3. The white paper, Java Cryptography Architecture Guide explicitly points to storing passwords in char[] instead of String : “It would seem logical to collect and store the password in an object of type java.lang.String . However, there is a caveat here: String objects are immutable, that is, no methods are defined to allow the contents of a String object to be changed (overwritten) or nulled out after use. This function makes Stringobjects unsuitable for storing sensitive information such as user passwords. Instead, you should always collect and store sensitive security information in a character array.”Analysis of questions and answers from interviews for a Java developer.  Part 7 - 5

Enum

66. Briefly describe Enum in Java

Enum is an enumeration, a set of string constants united by a common type. Declared through the keyword - enum . Here is an example with enum - valid roles in some school:
public enum Role {
   STUDENT,
   TEACHER,
   DIRECTOR,
   SECURITY_GUARD
}
Words written in capital letters are the same enumeration constants that are declared in a simplified way, without using the new operator . Using enums greatly simplifies life, as they help to avoid errors and confusion in names (since there can only be a certain list of values). For me personally, they are very convenient when used in a Switch logic construct .

67. Can an Enum implement interfaces?

Yes. After all, enumerations should not just represent passive collections (like roles, for example). In Java, they can represent more complex objects with some functionality, so you may need to add extra functionality to them. It also allows you to use the possibilities of polymorphism, substituting the enum value in places where the type of the implemented interface is needed.

68. Can an Enum extend a class?

No, it cannot, because enum is a default subclass of the generic class Enum<T> , where T represents the generic enum type. It is nothing more than a common base class for all enum types in the Java language. The conversion of an enum to a class is done by the Java compiler at compile time. This extension is not explicitly specified in the code, but is always invisibly present.

69. Is it possible to create an Enum without object instances?

As for me, the question is a little strange, well, or I did not fully understand it. I have two interpretations: 1. Can there be an enum without values ​​- yes, of course, it will be something like an empty class - is meaningless:
public enum Role {
}
And calling:
var s = Role.values();
System.out.println(s);
We will get in the console:
[Lflyweight.Role;@9f70c54
(an empty array of Role values ) 2. Is it possible to create an enum without the new operator - yes, of course. As I said above, you do not need to use the new operator for enum values ​​(enumerations) , since these are static values.

70. Can we override the toString() method of an Enum?

Yes, of course, you can override the toString() method to define a specific way to display your enum when calling the toString method (when casting an enum to a regular string, for example, to output to the console or logs).
public enum Role {
   STUDENT,
   TEACHER,
   DIRECTOR,
   SECURITY_GUARD;

   @Override
   public String toString() {
       return "Выбрана роль - " + super.toString();
   }
}
That's all for today, until the next part!Analysis of questions and answers from interviews for a Java developer.  Part 7 - 6Analysis of questions and answers from interviews for a Java developer.  Part 7 - 7
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION