Posts

Showing posts with the label Java Core

Generics in Java

Image
Generics is a technical term for a set of language properties that allow generic types and methods to be defined and used. Generic types or methods differ from ordinary types in that they have typed parameters. An example of using generic types is the Java Collection Framework. For example, the LinkedList<E> class is a typical generic type. It contains the parameter E, which represents the type of items that will be stored in the collection. Objects of generic types are created by replacing parameterized types with real data types. Instead of just using LinkedList, without saying anything about the type of the item in the list, it is suggested to use the exact type indication LinkedList<String>, LinkedList<Integer>, etc. Read also: Errors of the Error class in Java Work of try-catch-finally block in Java Exceptions in Java

Work of try-catch-finally block in Java

Image
try - this keyword is used to mark the beginning of a block of code that could potentially lead to an error. catch is a keyword to mark the beginning of a block of code to catch and handle exceptions if they occur. finally is a keyword to mark the start of a block of code that is optional. This block is placed after the last catch block. Control is passed to the finally block in any case, whether an exception was thrown or not. The general view of the construction for handling an exception is as follows: try { // code that can potentially lead to an exception } catch(SomeException e) { // the class of the specific expected error is indicated in parentheses // exception handling code } finally { // optional block, the code of which is executed anyway } Mechanism try-with-resources This construct, which appeared in Java 7, allows you to use a try-catch block without worrying about closing resources used in a given code segment. Resources are declared in parent...

Errors of the Error class in Java

Image
Errors in the Error class are the most serious problems at the JVM level. For example, exceptions of this kind arise if the memory available to the virtual machine runs out. It is not prohibited to handle such errors, but it is not recommended to do so. OutOfMemoryError An OutOfMemoryError is thrown when the Java virtual machine cannot create (allocate) an object due to insufficient memory and the garbage collector cannot reclaim enough memory. The memory area occupied by a java process consists of several parts. The OutOfMemoryError type depends on which one ran out of space: java.lang.OutOfMemoryError: Java heap space: There is not enough space on the heap, namely, in the area of ​​memory into which objects created in the application programmatically are placed. Usually the problem lies in a memory leak. The size is specified by the -Xms and -Xmx parameters. java.lang.OutOfMemoryError: PermGen space: (prior to Java 8) This error occurs when there is not enough space in the Perm...

Exceptions in Java

Image
Hierarchy of exceptions Exceptions are divided into several classes, but they all have a common ancestor - the Throwable class, of which the Exception and Error classes are descendants. Errors are more serious problems that, according to the Java specification, should not be handled in a native program, as they are related to JVM-level problems. For example, exceptions of this kind arise if the memory available to the virtual machine runs out. Exceptions are the result of problems in the program that are, in principle, solvable, predictable, and the consequences of which can be eliminated within the program. For example, an integer was divided by zero. Checked and unchecked exceptions In Java, all exceptions are of two types: checked must be handled by a catch block or described in the method signature (for example, throws IOException). The presence of such a signature handler/modifier is checked at compile time; unchecked, which include Error errors (for example, OutOfMemoryEr...

Shallow and deep cloning in Java

Image
Difference between shallow and deep cloning Shallow Copy copies as little information about an object as possible. By default, Java cloning is shallow, i.e. the Object class is unaware of the structure of the class it is copying. Cloning of this type is carried out by the JVM according to the following rules: If the class has only members of primitive types, then a completely new copy of the object will be created and a reference to that object will be returned. If a class, in addition to members of primitive types, contains members of reference types, then references to objects of these classes are copied. Hence, both objects will have the same references. Deep copying duplicates absolutely all object information: There is no need to copy primitive data separately; All reference type members in the original class must support cloning. For each such member, super.clone() must be called when overriding clone(); If any member of the class does not support cloning, then in the c...

Cloning objects in Java

Image
Using the assignment operator does not create a new object, it only copies the reference to the object. Thus, the two references point to the same area of memory, to the same object. To create a new object with the same state, clone the object is used. The Object class contains a protected clone() method that performs a bitwise copy of a derived class object. However, you must first override the clone() method as public to be able to call it. In the overridden method, call the base version of the super.clone() method, which does the actual cloning. To make an object permanently clonable, the class must implement the Cloneable interface. The Cloneable interface contains no methods related to marker interfaces, and its implementation ensures that the clone() method of the Object class will return an exact copy of the object that called it with reproduction of the values of all its fields. Otherwise, the method throws a CloneNotSupportedException exception. Note that when using this...

Method hashCode() in Java

Image
What is the hashCode() method for The hashCode() method is required to calculate the hash code of the object passed as an input parameter. In Java, it is an integer, in a broader sense, a fixed-length bit string obtained from an array of arbitrary length. This method is implemented in such a way that for the same input object, the hash code will always be the same. It should be understood that in Java the set of possible hash codes is limited to the int type, and the set of objects is not limited by anything. Because of this, it is quite possible that the hash codes of different objects may coincide: if the hash codes are different, then the objects are guaranteed to be different; if the hash codes are equal, then the objects may not necessarily be equal. Rules for overriding the Object.hashCode() method. Is there any guidance on what fields to use when counting hashCode()? General advice: choose fields that are likely to be different. To do this, you must use unique, best of al...

Method equals() in Java

Image
Why equals() is needed Equals() method - defines an object equivalence relation. How is it different from the == operation When comparing objects with ==, the comparison only occurs between references. When comparing by equals() overridden by the developer, by the internal state of objects. If you want to override equals(), what conditions should be met? What are the properties of an equivalence relation generated by equals()? Reflexivity: for any reference to a value x, x.equals(x) will return true; Symmetry: for any references to x and y values, x.equals(y) must return true if and only if y.equals(x) returns true. Transitivity: for any references to x, y, and z values, if x.equals(y) and y.equals(z) return true, then x.equals(z) will return true; Consistency: for any references to x and y values, if x.equals(y) is called multiple times, it will always return true, or it will always return false, provided that no information used in comparing the objects has changed. For an...

What is Reflection in Java

Image
Reflection is a mechanism for obtaining data about a program during its execution (runtime). In Java, Reflection is implemented using the Java Reflection API, which consists of the package classes java.lang and java.lang.reflect. Java Reflection API features: Object class definition; Getting information about class modifiers, fields, methods, constructors and superclasses; Defining the interfaces implemented by the class; Creating an instance of the class; Getting and setting values of object fields; Calling object methods; Creation of a new array. Read also: Object class in Java Classes loaders and dynamic loading of classes in Java Constructor in Java

Classes loaders and dynamic loading of classes in Java

Image
The basis for working with classes in Java is loader classes, ordinary Java objects that provide an interface for finding and creating a class object by its name while the application is running. At the beginning of the program, 3 main class loaders are created: basic bootloader (bootstrap/primordial). Loads the core JDK system and inner classes Core API - java.* packages (rt.jar and i18n.jar). It is important to note that the base loader is "Initial" or "Root" and is part of the JVM, so it cannot be created in-code programs. extension loader (extention). Loads various extension packages that are located in the <JAVA_HOME>/lib/ext directory or another directory described in the java.ext.dirs system parameter. This allows you to update and add new extensions without having to modify the settings of the applications you are using. The extension loader is implemented by the sun.misc.Launcher$ExtClassLoader class. system loader (system/application). Loads cla...

Constructor in Java

Image
A constructor is a special method that has no return type and has the same name as the class in which it is used. The constructor is called when a new class object is created and determines the actions required to initialize it. Default constructor If a constructor is not defined for a class, the compiler will generate a constructor with no arguments - the so-called "default constructor". public class ClassName() {} If the class already has a defined constructor, then the default constructor will not be created and, if necessary, it must be described explicitly. Difference between a default constructor, a copy constructor, and a constructor with parameters The default constructor has no arguments. The copy constructor accepts an already existing class object as an argument for the subsequent creation of its clone. A constructor with parameters has in its signature arguments (usually required to initialize class fields). Private constructor A private (marked with ...

Object class in Java

Image
Object is the base class for all other objects in Java. Any class inherits from Object and, accordingly, inherits its methods: public boolean equals(Object obj) - is used to compare objects by value; int hashCode() - returns the hash code for the object; String toString() - returns the string representation of the object; Class getClass() - returns the class of the object at runtime; protected Object clone() - creates and returns a copy of the object; void notify() - resumes the thread waiting for the monitor; void notifyAll() - resumes all threads waiting on the monitor; void wait() - stopping the thread that called the method until another thread calls the notify() or notifyAll() method for this object; void wait(long timeout) - stopping the thread that called the method for a certain time or until another thread calls the notify() or notifyAll() method for this object; void wait(long timeout, int nanos) - stopping the thread that called the method for a certain time or un...

Class String in Java

Image
What are the features of the String class It is an immutable and finalized data type; The JVM stores all String objects in a string pool; An object of the String class can be obtained using double quotes; You can use the + operator to concatenate strings; Since Java 7, strings can be used in a switch statement. Why is String an immutable and finalized class There are several advantages to strings being immutable: A string pool is only possible because the string is immutable, so the VM saves more free space in the Heap, since different string variables point to the same variable in the pool. If the string were mutable, then interning the strings would not be possible, because changing the value of one variable would also affect the rest of the variables referring to that string. If the string is mutable, then it becomes a serious security risk for the application. For example, the database username and password are passed as a string to get a database connection, and in soc...

Autoboxing in Java and rules for wrapping primitive types in wrapper classes

Image
Autoboxing is a mechanism for implicitly initializing objects of wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, Boolean) with the values ​​of their corresponding original primitive types (byte, short, int ...), without explicitly using the class constructor. Autoboxing occurs when the primitive is directly assigned to the wrapper class (using the = operator), or when the primitive is passed to the method parameters (of the wrapper class type). Both primitive variables and compile-time constants (literals and final primitives) can be autoboxed into wrapper classes. In this case, literals must be syntactically correct to initialize a variable of the original primitive type. Autoboxing of variables of primitive types requires an exact match of the type of the original primitive to the type of the wrapper class. For example, an attempt to package a variable of type byte into Short without first explicitly casting byte into short will cause a compilation error. ...

Type casting in Java

Image
Java is a strongly typed programming language, which means that every expression and every variable has a strictly defined type already at the time of compilation. However, a casting mechanism is defined - a way to convert the value of a variable of one type to a value of another type. There are several types of casting in Java: Identity Conversion of an expression of any type to exactly the same type is always allowed and happens automatically. Widening primitive. Indicates that a transition from a less capacious type to a more capacious one is taking place. For example, from byte (1 byte long) to int (4 bytes long). Such conversions are safe in the sense that the new type is always guaranteed to contain all the data that was stored in the old type, and thus no data loss occurs. This type of casting is always allowed and happens automatically. Narrowing (downcasting) a primitive type (narrowing primitive). Means that the transition is made from a more capacious type to a less cap...

What is the difference between final, finally and finalize() in Java

Image
Final modifier: The class cannot have descendants; The method cannot be overridden in inherited classes; The field cannot change its value after initialization; Local variables cannot be changed once a value has been assigned to them; Method parameters cannot change their value inside a method. The finally statement guarantees that the specified section of code will be executed regardless of what exceptions were thrown and caught in the try-catch block. The finalize() method is called before the garbage collector performs object disposal. Example: public class MainClass { public static void main(String args[]) { TestClass a = new TestClass(); System.out.println("result of a.a() is " + a.a()); a = null; System.gc(); // Forcibly call the garbage collector a = new TestClass(); System.out.println("result of a.a() is " + a.a()); System.out.println("!!! done"); } } public class...

Method finalize in Java, exceptions

Image
What happens to the garbage collector if the finalize() method takes a significant amount of time to execute, or if an exception is thrown during execution? Finalize() is called directly in a separate Finalizer thread (java.lang.ref.Finalizer.FinalizerThread), which is created when the virtual machine starts (in the static section when loading the Finalizer class). Finalize() methods are called sequentially in the order in which they were added to the list by the garbage collector. Accordingly, if some finalize() hangs, it hangs the Finalizer thread, but not the garbage collector. This means, in particular, that objects that do not have a finalize() method will be properly deleted, but those that do not have a finalize() method will be added to the queue until the Finalizer thread is free, the application ends, or memory runs out. The same applies to exceptions thrown during finalize(): the runFinalizer() method of the Finalizer thread ignores all exceptions thrown at the time of fin...

Method finalize in Java

Image
By calling the finalize() method (which inherits from Java.lang.Object), the JVM implements functionality similar to the C++ destructors used to clear memory before returning control to the operating system. This method is called when the object is destroyed by the garbage collector and by overriding finalize(), you can program the actions necessary for the correct deletion of the class instance - for example, closing network connections, database connections, unlocking files, etc. After executing this method, the object must be re-collected by the garbage collector (and this is considered a serious problem with the finalize() method as it prevents the garbage collector from freeing memory). This method is not guaranteed to be called because the application can be terminated before garbage collection starts. The object will not necessarily be immediately available for assembly - the finalize() method can store a reference to the object somewhere. Such a situation is called "revi...

String pool in Java

Image
A String pool is a collection of strings stored in Heap. String pooling is possible thanks to Java's immutability of strings and the implementation of the idea of string interning; Pooling of strings helps save memory, but for the same reason, string creation takes longer; When "is used to create a string," is first searched for a string in the pool with the same value, if found, then a link is simply returned, otherwise a new string is created in the pool, and then a link to it is returned; Using the new operator creates a new String object. Then, using the intern() method, this string can be put into the pool, or you can get from the pool a reference to another String object with the same value; The string pool is an example of the Flyweight pattern. Read also: How Serial Garbage Collector works in the HotSpot virtual machine What flavors of garbage collectors are implemented in the HotSpot virtual machine How does the garbage collector work in Java

What is a garbage collector for in Java

Image
The Garbage Collector only needs to do two things: Find garbage - unused objects. (An object is considered unused if none of the entities in the code currently executing contains references to it, or the chain of links that could connect the object with some application entity is broken); Free memory from garbage. There are two approaches to detecting garbage: Reference counting; Tracing Reference counting . The essence of this approach is that each object has a counter. A counter stores information about how many references are pointing to an object. When the link is destroyed, the counter is decremented. If the counter value is zero, the object can be considered garbage. The main disadvantage of this approach is the difficulty of ensuring the accuracy of the meter. Also, with this approach, it is difficult to detect circular dependencies (when two objects point to each other, but no living object refers to them), which leads to memory leaks. The main idea of the Tracing a...