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 6

Published in the Random EN group
Hello World! Keeping evolving is very important for any developer. After all, if you stop, there is a risk of becoming unclaimed and completely leaving the market: the IT world is constantly developing and moving forward, and you need to move along with it. But even at the same time, one cannot only focus on new and fresh technologies, so as not to forget, so to speak, about the classics (classical topics). Today I want to continue my analysis of questions on “classic” topics for a Java developer. Analysis of questions and answers from interviews for a Java developer.  Part 6 - 1I note that my answers are not the last resort - this is just how I see the correct answers to these questions, and you may not agree with something. It will be quite normal, so feel free to share your opinion in the comments. Links to parts of the analysis are at the end of the article.Analysis of questions and answers from interviews for a Java developer.  Part 6 - 2

Libraries and Standards

52. What is Hibernate? What is the difference between JPA and Hibernate?

I think to answer this question, we first need to understand what JPA is . JPA is a specification that describes the object-relational mapping of simple Java objects and provides an API for storing, retrieving, and manipulating such objects. That is, as we remember, relational databases (DB) are presented as a set of interrelated tables. And JPA is an accepted standard that describes how objects can interact with relational databases. As you can see, JPA is something abstract and intangible. It's like the idea itself, the approach. Analysis of questions and answers from interviews for a Java developer.  Part 6 - 3At the same time, Hibernate is a specific library that implements JPA paradigms. That is, with the help of this library you can work with a relational database through objects that represent data from the database (Entity). This library is said to be very close to the JPA ideals , and perhaps that is why it has become popular. And as you understand, the popularity of use is a good argument for further development and improvements. In addition, there is a huge community behind the frequent use, which has already sorted out all the possible and impossible issues related to this tool. Here is an example of a book , which analyzes in detail all the dark nooks and crannies of this technology. That is, Hibernate is studied as much as possible and, it turns out, reliable. Actually, it’s not in vain that even the ideal implementation of JPA by Spring usually uses Hibernate under the hood.

53. What is cascading? How is it used in Hibernate?

As I said earlier, in Hibernate interaction is done through data objects called entities . These entities represent some specific tables in the database, and as you remember, in Java, classes can contain references to other classes. These relationships are reflected in the database as well. In a database, as a rule, these are either foreign keys (for OneToOne, OneToMany, ManyToOne) or intermediate tables (for ManyToMany). You can read more about the relationship between entities in this article . When your entity has links to other related entities, annotations are placed above these links to indicate the type of connection: @OneToOne, @OneToMany, @ManyToOne, @ManyToMane, in whose parameters you can specify the property value - cascade - the cascade type for this connection . AtJPA has specific methods for interacting with entities (persist, save, merge…). Cascading types are just used to show how related data should behave when using these methods on a target entity. So, what are the cascading strategies (cascading types)? The JPA standard implies the use of six types of cascading:
  • PERSIST - save operations will cascade (for save() and persist() methods ). That is, if we save an entity associated with other entities, they are also stored in the database (if they are not already there)

  • MERGE - update operations will cascade (for the merge() method )

  • REMOVE - removal operations cascade ( remove() method )

  • ALL - contains three cascading operations at once - PERSIST - MERGE - REMOVE

In JPA , there is the concept of persistent ( persistence ) entity - an entity associated with its data in the database, which is controlled by the current session (connection). If you change it, but do not save the changes in the database, all the same, its data in the database will be changed.
  • DETACH - related entities will not be managed by the session ( detach() method ). That is, when they change, their data in the database will not be automatically changed - they are transferred from the persistence state to detached (an entity not managed by JPA)

  • REFRESH - each time an entity is updated with data from the database ( refresh() - updates detached objects), related entities are updated in the same way. For example, you have somehow changed the data taken from the database, and you want to return their original values. In this case, this operation is useful to you.

Analysis of questions and answers from interviews for a Java developer.  Part 6 - 4Hibernate supports all of these standard cascading operations, but also brings three of its own:
  • REPLICATE - used when we have more than one data source and we want the data to be synchronized (Hibernate - replicate method). All entities must have identifiers (id) so that there are no problems with their generation (so that for different databases the same entity does not have different id)

  • SAVE_UPDATE - cascading save/delete (for Hibernate method - saveOrUpdate )

  • LOCK is the opposite of DETACHED : puts the detached entity back into the persistence state , i.e. entity will become the tracked current session again

If no cascading type is selected, no operation on an entity will have an effect on other entities associated with it.

54. Can an Entity class be abstract?

In the JPA specification in paragraph 2.1 The Entity Class there is a line: “ Both abstract and concrete classes can be entities ”. So the answer is yes, an abstract class can be an entity and can be annotated with @Entity.

55. What is an entity manager? What is he responsible for?

First of all, I would like to note that EntityManager is one of the key components of JPA , which is used to interact with entities with the database. In general, the methods of interaction between the entity and the database are called from it (persist, merge, remove, detach) ... But I also note that this component, as a rule, is not the only one for the entire application: most often it is lightweight, often deleted and a new one is created using EntityManagerFactory . If we draw a parallel with JDBC , where EntityManagerFactory will be an analogue of DataSource , then EntityManager, in turn, will be an analogue of Connection. Earlier, I mentioned persistence as an entity that is managed by the current connection. So: this entity is managed by the EntityManager , which is closely related to the current connection and TransactionManager , which is responsible for opening / closing transactions. Further in the figure below, you can see the life cycle of an entity:Analysis of questions and answers from interviews for a Java developer.  Part 6 - 5EntityManager manages an entity when it is in the Managed stage (at this time it is persistent, because it has a relationship with the EntityManager). That is, it is no longer new and has not yet been removed. We can say that when an entity is new or removed, it is also detached, because it is not managed by the EntityManager. There are different strategies for EntityManager. That is, there can be one singleton EntityManager for the entire application, or a new one can be created each time, for each connection. If you use Spring, then the management of the creation / deletion of the EntityManager occurs automatically under the hood (but this does not mean that you cannot customize it for yourself ^^). It is worth saying that one or more EntityManagers also form a persistence context . Persistence contextis an environment in which entity instances are synchronized with similar entities in the database (as I said, this only works for persistent entities). If you delve into the study of JPA (which I highly recommend), then you will come across these concepts very, very often.

56. What is the Assert class? Why use it?

In JPA , I have not heard of such a class, so I will assume that this refers to the JUnit class of the library, which is used for unit testing code. The class of this library, Assert , is used to check the results of code execution ( assert is an assertion that you have a certain state / data in a certain place). For example, you are testing a method that should create a cat. You run a method and get some result:
Cat resultOfTest = createCat();
But you need to make sure that it was created correctly, right? Therefore, you previously created a certain cat - expectedCat - manually with exactly the parameters that you expect from the cat received from the createCat() method . Next, you use the Assert class to verify the results:
Assert.assertEquals(resultOfTest, expectedCat);
If the cats are different, an AssertionError exception will be thrown , which tells us that the expected results do not converge. The Assert class has many different methods that cover many tasks for checking expected results. Here are some of them:
  • assertTrue(<boolean>) - the expected value received as an argument must be true

  • assertFalse(<boolean>) - the expected value received as an argument should be false

  • assertNotEquals(<object1>, <object2>) - objects received as arguments must be different when compared using equals ( false )

  • assertThrows(<ClassNameOfException>.class, <exceptionObject>) - the second argument is expected to be an exception of the class specified by the first argument (i.e., as a rule, a method is called instead of the second argument, which should throw an exception of the desired type)

String

57. Characterize a String in Java

String - a standard class in Java, responsible for storing and manipulating string values ​​(sequences of characters), is an immutable class ( I wrote about immutable earlier ), i.e. the data of objects of this class cannot be changed after creation. I would like to immediately note that the StringBuilder and StringBuffer classes are actually two identical classes with the only difference being that one of them is intended for use in a multi-threaded environment (StringBuffer). These classes are analogous to String , but unlike String , they are mutable. That is, objects, once created, allow modification of the string they represent without creating a new object. Actually, the methods differ from the standard String methods and are aimed at satisfying the needs of changing the string (it’s not for nothing that they called the builder). Read more about String , StringBuffer and StringBuilder in this article .

58. What are the ways to create a String object? Where is it created?

The most common way to create a string is to simply set the value we need in double brackets:
String str = "Hello World!";
You can also do it directly with new :
String str = new String("Hello World!");
You can create a string and start from an array of characters:
char[] charArr = {'H','e','l','l','o',' ', 'W','o','r','l','d','!'};
String str = new String(charArr);
As a result of the toString method on some object:
String str = someObject.toString();
Returns a string representation as the result of any other method. For example:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str =  reader.readLine();
As you understand, there can be very, very many ways to create a string. When a String object is created, it is stored in the string pool , which we will discuss in more detail in one of the questions below.

59. How to compare two strings in Java and how to sort them?

Java uses the double equal sign == to compare values . If we needed to compare some simple values ​​like int , we would use it. But this method is not applicable for comparing full-fledged objects. In this case, it will only be a comparison of references - whether they point to the same object or not. That is, when comparing two objects with exactly the same values ​​of internal fields, comparison through == will give the result false : despite the same fields of objects, the objects themselves occupy different memory cells. And objects of the String class , despite their deceptive simplicity, are still objects. And comparison via ==for them is also not applicable (even despite the presence of a string pool). Here, the standard method of the Object class , equals , comes into play , which must be overridden in the class for it to work correctly (otherwise, by default, it compares through == ). In the String class , it is overridden, so we just take and use it:
String firstStr = "Hello World!";
String secondStr = "Hello World!";
boolean isEquals = firstStr.equals(secondStr);
Analysis of questions and answers from interviews for a Java developer.  Part 6 - 6We talked about comparison for matching, and now we will analyze the comparison for sorting. After all, in order to sort something, we need to know by what principle to sort. To do this, you can use the standard sorted set - TreeSet . You can read more about different collections in Java in this article . This list works on the basis of the red-black tree algorithm and sorts the set according to the specified sorting principle. As I said earlier, you need to understand how to sort objects of a certain type. Comparators are used to specify the comparison method for sorting . As a rule, they need to be implemented for the classes that you want to sort, but in the case of Stringthey have already been implemented. Therefore, we simply add the lines we need to TreeSet , and it will sort them:
TreeSet<String> sortedSet = new TreeSet<>();
sortedSet.add("B");
sortedSet.add("C");
sortedSet.add("A");
sortedSet.forEach(System.out::println);
Console output:
A B C

60. Give the algorithm for translating a string into a character. Write the appropriate code

As I said earlier, String class objects have a lot of different useful methods. One of these is toCharArray . This method converts a string to an array of characters:
String str = "Hello world";
char[] charArr = str.toCharArray();
Next, we have an array of characters that we can call by index:
char firstChar = charArr[0]; // H

61. How to translate a string into an array of bytes and back? Write the appropriate code

Similar to the toCharArray method , the String class has a getBytes method that returns a byte array of the string:
String str = "Hello world";
byte[] byteArr = str.getBytes();
byte firstChar = byteArr[6]; // 119
Today's part of the analysis has come to a logical end. Thank you for your attention!Analysis of questions and answers from interviews for a Java developer.  Part 6 - 7Analysis of questions and answers from interviews for a Java developer.  Part 6 - 8
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION