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 8

Published in the Random EN group
Practice or theory? What's more important? Many will say that, of course, practice is more important. Like, practice all the way and you will be happy. I dare not agree with this. Analysis of questions and answers from interviews for a Java developer.  Part 8 - 1In interviews, no one will know how cool you are in practice. You will be asked to your full height precisely according to theory. And only then, when you go through all the circles of interviews and get on the project, you will apply your practical skills. You can object: sometimes they give a test task and practice is still needed. I do not argue, they are sometimes given, but the fact of the matter is that SOMETIMES, but the theoretical interview is ALWAYS. Feel the difference? Therefore, you must have a solid theoretical foundation under your feet, the strengthening of which we will continue to work on today. Namely, we will continue the analysis of questionsthat are often asked in interviews.

71. What happens if we don't override the toString() method for Enum?

Let's say we have the following enum :
public enum Role {
   STUDENT,
   TEACHER,
   DIRECTOR,
   SECURITY_GUARD;
}
Display the student in the console by calling toString() :
System.out.println(Role.STUDENT.toString());
Result in console:
STUDENT
That is, by default, toString() for enum is the name of the constant itself.

72. Is it possible to specify a constructor inside an Enum?

Yes, sure. It is through the constructor that the values ​​of the internal enum variables are set. As an example, add two fields to the previous enum - ageFrom and ageTo - to indicate the age range for each role:
public enum Role {
   STUDENT(5,18),
   TEACHER(20,60),
   DIRECTOR(40,70),
   SECURITY_GUARD(18,50);

   int ageFrom;
   int ageTo;

   Role(int ageFrom, int ageTo) {
       this.ageFrom = ageFrom;
       this.ageTo = ageTo;
   }
}

73. What is the difference between == and equals()?

This is one of the most common Java developer interview questions. Let's start with the fact that when we compare simple values ​​( int , char , double ...), we do it through == , since variables contain specific values ​​and we can compare them. And primitive variables are not full-fledged objects - they are not inherited from Object and do not have an equals() method . When we talk about comparing variables that refer to objects, then == will only compare the value of the references - whether they refer to the same object or not. And even if one object is identical to another, comparison through == will give a negative result (false ) because it's a different object. As you understand, the equals() method is used to compare reference variables . This is one of the standard methods of the Object class , which is needed for proper comparison of objects. But it’s worth clarifying right away: for this method to work correctly, it must be overridden, writing exactly how objects of this class should be compared. If you don't override the method, by default it will compare objects by == . In IntelliJ IDEA , you can override it automatically (using IDEA tools) -> alt + insert , in the window that appears, select equals() and hashCode()-> choose which fields of the class should participate -> and voila, the automatic implementation of the methods is done. Here is an example of what an auto-generated equals method would look like for a simple Cat class with two fields, int age and String name :
@Override
public boolean equals(final Object o) {
   if (this == o) return true;
   if (o == null || this.getClass() != o.getClass()) return false;
   final Cat cat = (Cat) o;
   return this.age == cat.age &&
           Objects.equals(this.name, cat.name);
}
If we talk about the difference between == and equals for enum s, there is not much of it. Analysis of questions and answers from interviews for a Java developer.  Part 8 - 2After all, enum stores constants, and even comparing similar values ​​​​through == , we will get true , since the references will always be to the same objects. Well, when using equals, we will also work out the functionality correctly, especially if you go into the body of the equals method for enum , you will see that the implementation of the method in the Enum class is as follows: Analysis of questions and answers from interviews for a Java developer.  Part 8 - 3That is, inside - the good old reference comparison! To sum up: for enum comparison and through ==, and through equals is correct.Analysis of questions and answers from interviews for a Java developer.  Part 8 - 4

74. What does the ordinal() method in Enum do?

When calling the int ordinal() method on an enum element , we will get the ordinal number from zero of this value in the general series of enumerations. Let's use this method on one element from the previous enum considered - Role :
System.out.println(Role.DIRECTOR.ordinal());
Accordingly, the following will be displayed in the console:
2

75. Is it possible to use Enum with TreeSet or TreeMap in Java?

The use of enum types in TreeSet and TreeMap is legal. And we can write:
TreeSet<Role> treeSet = new TreeSet<>();
treeSet.add(Role.SECURITY_GUARD);
treeSet.add(Role.DIRECTOR);
treeSet.add(Role.TEACHER);
treeSet.add(Role.STUDENT);
treeSet.forEach(System.out::println);
And the console will output:
STUDENT TEACHER DIRECTOR SECURITY_GUARD
We got the output not alphabetically. The point is that if we use enum 's elements for TreeSet values ​​or as keys for TreeMap , the elements are sorted in their natural order (the order in which they are given in enum ). Understanding these features helps us write better code.Analysis of questions and answers from interviews for a Java developer.  Part 8 - 5

76. How are ordinal() and compareTo() methods related in Enum?

As mentioned earlier, ordinal() returns the ordinal of the value in the general list of enums. Also, in the analysis of the previous question, you saw that the elements of enumerations, when they get into, for example, a TreeSet (sorted set) take the order in which they are declared in enum . And as we know, TreeSet and TreeMap sort elements by calling their compareTo() method of the Comparable interface . From this we can assume that the Enum class implements the Comparable interface , implementing it in the compareTo() method , inside which ordinal() is usedto set the sort order. Going into the Enum class , we see confirmation of this: Analysis of questions and answers from interviews for a Java developer.  Part 8 - 6And the body of the method itself: The ordinal()Analysis of questions and answers from interviews for a Java developer.  Part 8 - 7 method is not called here. Instead, the variable ordinal is used - the ordinal number of the element in the enumeration. The ordinal() method itself is nothing more than a getter for the ordinal variable .Analysis of questions and answers from interviews for a Java developer.  Part 8 - 8

77. Write an EnumM example

In the questions discussed above, I have already given examples of enums and I see no reason to duplicate the code (for example, question number 72 about the constructor in enum).

78. Is it possible to use Enum in switch case?

It is possible and necessary! Looking back at my practice, I note that one of the most common places to use enum is logical constructs like switch . In this case, you can provide for all possible variations of case , and after writing the logic for all enum values, the use of the default statement may not even be necessary! After all, if you use a String or a numeric value, for example, of type int , you may receive an unintended value, which in turn is impossible using enum . What switch would look like for the example discussed earlier:
public void doSomething(Role role) {
   switch (role) {
       case STUDENT:
           // некая логика для STUDENT
           break;
       case TEACHER:
           // некая логика для TEACHER
           break;
       case DIRECTOR:
           // некая логика для DIRECTOR
           break;
       case SECURITY_GUARD:
           // некая логика для SECURITY_GUARD
           break;
   }
}

79. How to get all the values ​​in an Enum instance?

If you want to get all instances of an enum, there is the values() method , which returns an array of all available values ​​of a given enum in natural order (in the order given in the enum ). Example:
Role[] roles = Role.values();
for (Role role : roles) {
   System.out.println(role);
}
The console will output:
STUDENT TEACHER DIRECTOR SECURITY_GUARD

Stream API

80. What is a Stream in Java?

Java Stream is a relatively new way of interacting with a data stream, which in turn allows you to more conveniently and compactly process large data, as well as parallelize data processing between a certain number of threads, which can increase performance in the using functionality. I can’t tell you more deeply about this topic in a nutshell, so I will leave here a link to an article that you can dive into this topic.Analysis of questions and answers from interviews for a Java developer.  Part 8 - 9

81. What are the main properties of transactions

The topic is called - Stream API, but the question is about the transaction. Hmm... First of all, let's understand what a transaction is. A transaction is a group of sequential operations with a database, which is a logical unit of work with data. A transaction can either complete and complete successfully, respecting data integrity and regardless of other concurrent transactions, or not complete at all, in which case it has no effect. So, transactions have four main properties, which are abbreviated as ACID . Let's look at how each letter of this abbreviation is deciphered: A - Atomicity - atomicity- this property guarantees that no transaction will be partially committed in the system. Either all of its sub-operations will be executed, or none of them will be executed ( all or nothing ). C - Consistency - consistency - a property that guarantees that each successful transaction will commit only valid results. That is, it is a guarantee that during a successful transaction all the rules that the system imposes on specific data will be fulfilled, otherwise the transaction will not be completed and the data in the system will return to its previous state. I - Isolation - isolation- a property that says that during the execution of a transaction, parallel transactions should not affect its result. This property is resource-intensive, so it is typically only partially implemented, allowing certain levels of isolations that solve certain isolation problems. We will discuss this in more detail in the next question. Analysis of questions and answers from interviews for a Java developer.  Part 8 - 10D - Durability - durability - this property ensures that if the user has received confirmation from the system that the transaction has been completed, he can be sure that the changes he has made will not be canceled due to any failure. That is, you can be sure that some kind of operating system failure will not do anything to your data if you have already received confirmation of the successful completion of your transaction.

82. What are the transaction isolation levels?

As I said earlier, providing an ACID isolation point is a resource-intensive process. Therefore, this property is partially fulfilled. There are various levels of isolation, and the higher the level, the greater the performance hit. Before moving on to transaction isolation levels, we need to consider the various problems of insufficient transaction isolation :
  • phantom reading - when the same selection (the same query) is called again within the same transaction, the received data differs, which occurs due to data insertions by another transaction;

  • non-repeating reading - when the same selection (the same query) is called again within one transaction, the received data differs, which occurs due to changes (update) and deletions of data by another transaction;

  • dirty read is the process of reading data added or modified by a transaction, which will not be subsequently confirmed (rolled back), i.e. reading invalid data;

  • lost update - when the same data is changed by different transactions at the same time, all changes are lost except the last one (reminiscent of the “race condition” problem in a multithreaded environment).

Transaction isolation levels are characterized by what kind of isolation problems they protect against. Let's consider in the form of a table the isolation levels and what problems they protect against:
isolation level phantom reading Non-repeating read Dirty Reading Lost update
SERIALIZABLE + + + +
REPEATABLE READ - + + +
READ COMMITTED - - + +
READ UNCOMMITTED - - - +
NONE - - - -
And do not forget the other side of the coin: the greater the isolation level, the longer it will take for transactions to process (when several transactions are executed in parallel). If you'd like to dig deeper into this topic, here's a great article to get you started.

83. What is the difference between Statement and PreparedStatement?

And here is not a very smooth transition to the features of JDBC technology . So, for starters, let's figure out what a Statement is . This is an object that is used to generate SQL queries. JDBC uses three of its types - Statement , PreparedStatement and CallableStatement . We will not consider CallableStatement today: let's talk about the difference between Statement and PreparedStatement .
  1. Statement is used to execute simple SQL queries without incoming, dynamically inserted parameters. PrepareStatement is used with the ability to dynamically insert input parameters.

  2. To set parameters in a PreparedStatement, the input parameters in the query are written as question marks, so that later they can be replaced with some value using various setters, such as setDouble() , setFloat() , setInt() , setTime() .... As a result, you will not insert data of the wrong type into the query.

  3. A PreparedStatement is "precompiled" and uses caching, so it may run slightly faster than a query from Statement objects . As a result, frequently executed SQL statements are created as PreparedStatement objects to improve performance .

  4. Statement is vulnerable to SQL injections, while PreparedStatement prevents them. Read more about SQL injection and other Java security best practices in this article .

If you have made a start in studying the technology of connecting a Java application to the Database - JDBC, I advise you to start with this article . Well, at this point, we will stop today.Analysis of questions and answers from interviews for a Java developer.  Part 8 - 11Analysis of questions and answers from interviews for a Java developer.  Part 8 - 12
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION