Monday, July 26, 2021

Difference Between equals and hashCode in Java

Key Difference – equals vs hashCode in Java

The equals is similar to the == operator, which is to test for object identity rather than object equality. The hashCode is a method by which a class implicitly or explicitly break down the data stored in an instance of the class into a single hash value, which is a 32 bit signed integer. The key difference between equals and hashCode in Java is that the equals is used to compare two objects while the hashCode is used in hashing to decide which group an object should be categorized into.

What is equals in Java?

The equals method is used to compare two objects. The default equals method is defined in the object class. That implementation is similar to the == operator. The two object references are equal only if they are pointing to the same object. It is possible to override the equals method.

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career
Figure 01: Java Program with equals

The statement System.out.println(s1.equals(s2)) will give the answer false because s1 and s2 are referring to two different objects. It was similar to the statement, System.out.println(s1 == s2);

The statement System.out.println(s1.equals(s3)) will give the answer true because s1 and s3 are referring to the same object. It was similar to the statement, System.out.println(s1 == s3);

There is no equals method in the Student class. Therefore, the equals in the Object class is called. True is displayed only if the object reference is pointing to the same object.

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career
Figure 02: Java Program with Overridden equals

According to the above program, the equals method is overridden. An object is  passed to the method, and it is type casted to Student. Then, the id values are checked. If the id values are similar, it will return true. If not, it will return false. The ids of s1 and s2 are similar. So, it will print true. The ids of s1 and s3 are also similar, so it will print true.

What is hashCode in Java?


The hashCode is used in hashing to decide to which group an object should be categorized into. A group of objects can share the same hashCode. A correct hashing function can evenly distribute objects into different groups.

A correct hashCode can have properties as follows. Assume that there are two objects as obj1 and obj2. If obj1.equals(obj2) is true, then the obj1.hashCode() is equal to obj2.hashCode(). If obj1.equals(obj2) is false, it is not necessary that obj1.hashCode() is not equal to obj2.hashCode(). The two unequal object might also have the same hashCode.

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career
Figure 03: Student class with equals and hashCode

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career
Figure 04: Main Program

The Student class contains the equals and hashCode methods. The equals method in the Student class will receive an object. If the object is null, it will return false. If the classes of the objects are not the same, it will return false. The id values are checked in both objects. If they are similar, it will return true. Else it will return false.

In the main program, objects s1 and s2 are created. When calling s1.equals(s2) will give true because the equals method is overridden and it checks the id values of the two objects. Even though they are referring to two objects, the answer is true because the id values of s1 and s2 are the same. As the s1.equals(s2) is true, the hashCode of s1 and s2 should be equal. Printing the hashCode of s1 and s2 gives the same value. The hashCode method can be used with Collections such as HashMap.

What is the Difference Between equals and hashCode in Java?


equals vs hashCode in Java 
equals is a method in Java that acts similar to the == operator, which is to test for object identity rather than object equality.   hashCode is a method by which a class implicitly or explicitly breaks down the data stored in an instance of the class into a single hash value. 
Usage 
The method equals is used to compare two objects.   The method is used in hashing to decide which group an object should be placed into.

Source: differencebetween.com

Friday, July 23, 2021

Difference Between Applets and Servlets

Oracle Java Applets, Oracle Java Servlets, Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Java Career

Applets vs Servlets

A program written in Java that can be embedded in a HTML page is called an applet. A Java enabled browser can be used to view the web page containing the applet. When the page containing an applet is viewed, the code of the applet is transferred to the user computer and executed on the Java Virtual Machine (JVM) of the browser. A Java program that is used to improve/ extend the functionalities of a server is called a servlet. The server should be accessed by the host applications using the request-response model. In simple terms, a servelt can be seen as an Java applet running on the server.

What is an Applet?

A program written in Java that can be embedded in a HTML page is called an applet. A Java enabled browser can be used to view the web page containing the applet. When the page containing an applet is viewed, the code of the applet is transferred to the user computer and executed on the Java Virtual Machine (JVM) of the browser. Applets allow providing the user with interactive features that might not be possible to provide using only HTML. Since the applet’s code is run on JVM, applets are platform independent (supports Microsoft Windows, UNIX, Mac OS, etc.) and can run in any browser that supports Java. Furthermore, applets are cached by most web browsers. Hence applets could be loaded quickly when returning to a web page. When it comes to security, there are two types of applets called signed applets and unsigned applets. Unsigned applets have some important restrictions like inability to access the local file system. They can only access the applet download site on the web. Signed applets can behave as a standalone application once its signature is verified.

What is a Servlet?

A Java program that is used to improve/ extend the functionalities of a server is called a servlet. The server should be accessed by the host applications using the request-response model. In simple terms, a servelt can be seen as an Java applet running on the server. Typically servlets are used for storing/ processing data that were submitted using an HTML form and to provide dynamic content in a web page. Furthermore, servlets are used for managing state information. Java servlets are efficient, easier to use and portable compared to other CGI (Common Gateway Interface) technologies.

What is the difference between Applets and Servlets?

A java program that can be embedded in a HTML page and viewed using a Java enabled browser is called an applet, while a Java program that is used to improve/ extend the functionalities of a server is called a servlet. Actually, a servlet can be seen as an applet running on the server. An applet is downloaded in to the client’s machine and run on the client’s browser, whereas a servlet runs on the server and transfers the results back to the client when it is done. When using applets, the entire code of the applet has to be transferred to the client. Therefore it consumes more network bandwidth than servlets, which transfers only the results to the client.

Source: differencebetween.com

Wednesday, July 21, 2021

Difference Between JSP and Servlets

JSP, Servlets, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career

JSP vs Servlets

A Servlet is a server side software component written in Java and runs in a compatible container environment known as a Servelt container (like Apache Tomcat). Servlets are predominantly used in implementing web applications that generate dynamic web pages. They can however generate any other content type like XML, text, images, sound clips, PDF, Excel files programmatically.

A Servlet written to generate some HTML may look like this:

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter w = response.getWriter();

w.write(“<html>”);

w.write(“<body>”);

Date d = new Date();

w.write(d.toString());

w.write(“</body>”);

w.write(“</html>”);

}

}

JSP, Servlets, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career
The code above contains a mixture of HTML and Java source code. Such is not very readable and maintainable. JSP which stands for JavaServer Pages provides a better alternative. For example, the following is a fragment of JSP code that results in identical output:

<%@page import=”java.util.Date”%>

<html>

<body>

<%= new Date().toString() %>

</body>

</html>

Web page authors find JSP easier to write and maintain. JSP files are however translated into Servlets by a Servlet container at the time JSP files are first accessed. However, business logic writers find Servlets to be easier to work with.

A request received by a web application should trigger the execution of some business logic and then generate a resultant web page as the response. In modern day web applications, controlling the overall request processing cycle is mostly handed by Servlets. As the last stage in processing a request, such a Servlet generally hands over the responsibility of generating the dynamic HTML to a JSP.

Monday, July 19, 2021

Set it up

Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Learning, Oracle Java Career, Oracle Java

In Java, we often have framework support for importing settings from the file system of our application. If we’re lucky, and we often are, these settings can be customized and overridden by system properties or environment variables.

However, there are a couple of situations where this doesn’t quite apply:

◉ Very lightweight applications that use no frameworks

◉ Loading custom settings based on business logic

Though we can shoe-horn heavier frameworks like Spring into the first, or try to force Spring to process properties for us, often we need a lighter solution.

Lightweight Config

I recently wrote and released Lightweight Config, an open source package to solve this with either .yaml or .properties files.

I’ve demonstrated its use in AWS Lambdas in an article on Baeldung.com.

I thought it might be nice to cover a different use case in this article, notably how it might be used to load settings up in a test.

At The Max

I wrote Lightweight Config from the ground up, but I’ve used its predecessors extensively. Originally, it was a test-helper library. Then I created one for loading settings for lambdas.

At full strength, you’d define a .yml file:

hardCoded: true

interpolated: ${SOME_ENV_VAR:-default}

partialInterpolation: Welcome to ${APP_NAME}

database:

   url: ${DB_URL}

   username: ${DB_USER}

   password: ${DB_PASSWORD}

Then a POJO to load the file into:

public class Settings {

    private boolean hardCoded;

    private String interpolated;

    private String partialInterpolation;

    private DatabaseSettings database;

    // getters and setters

}

Then it’s a one liner to load from the yaml into the Settings object – Settings settings = ConfigLoader.loadYmlConfigFromResource("settings.yaml", Settings.class)

There are also some hooks that can be applied to plug in custom tags if necessary.

Reading Per Environment Properties

Let’s flip to an example where we just want some Java .properties loaded into Properties. One might argue that the POJO approach gives us a better API, but let’s say we’re using something that’s already bound to Properties, such as an email client, or DB connection pool.

Here’s a snippet of some settings that relate to dev:

workers=12

sourceEmail=test@mytest.com

pdfFolder=/home/test/pdf

Let’s call this file profiles/dev.properties.

Now let’s create a parent file with all the global settings in:

#import profiles/${ENV_NAME}.properties

threadPoolSize=24

versionNumber=${BUILD_VERSION:-Unknown}

adminUser=admin

adminPassword=${ADMIN_PASSWORD}

Let’s call this file app.properties and put it in the same directory as contains the profiles directory mentioned above.

Now we can load both the above files into a Properties object by:

Path appPropertiesPath = PROPERTIES_DIR.resolve("app.properties");

Properties properties = ConfigLoader.loadProperties(appPropertiesPath);

What happens in this case is that the various placeholders are filled in from environment variables (or system properties if you prefer). Included in this is the #import statement, which not only describes how a child file is imported, but allows placeholder interpolation into the path of that file.

So, by setting a different ENV_NAME environment variable, the same loading code could import a different set of per-environment properties into the whole Properties object being loaded.

It’s a simple syntax/approach that’s flexible enough to use for a variety of things.

Source: javacodegeeks.com

Friday, July 16, 2021

Difference Between Abstract Class and Concrete Class

Oracle Java Abstract Class, Oracle Java Concrete Class, Oracle Java Exam Prep, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Material, Oracle Java Guides

Abstract Class vs Concrete Class

Most of the popular modern object oriented programming languages like Java and C# are class based. They achieve the object oriented concepts such as encapsulation, inheritance and polymorphism through the use of classes. Classes are an abstract representation of real world objects. Classes can be either concrete or abstract depending on the level of implementation of their method functionalities. A concrete class completely implements all its methods. An abstract class can be considered as a limited version of a regular (concrete) class, where it may contain partially implemented methods. Typically, concrete classes are referred to as (just) classes.

What is Concrete Class?

The default class is a concrete class. The class keyword is used to define classes (e.g. in Java). And usually they are simply referred to as classes (without the adjective concrete). Concrete classes depict the conceptual representation of real world objects. Classes have properties called attributes. Attributes are implemented as global and instance variables. Methods in the classes represent or define the behavior of these classes. Methods and attributes of classes are called the members of the class. Typically, encapsulation is achieved by making the attributes private, while creating public methods that can be used to access those attributes. An object is the instance of a class. Inheritance allows the user to extend classes (called sub classes) from other classes (called super classes). Polymorphism allows the programmer to substitute an object of a class in place of an object of its super class. Typically, the nouns found in the problem definition directly become classes in the program. And similarly, verbs become methods. Public, private and protected are the typical access modifiers used for classes.

What is Abstract Class?

Abstract classes are declared using Abstract keyword (e.g. in Java,). Typically, Abstract classes, also known as Abstract Base Classes (ABC), cannot be instantiated (an instance of that class cannot be created). So, Abstract classes are only meaningful to have if the programming language supports inheritance (ability to create subclasses from extending a class). Abstract classes usually represent an abstract concept or entity with partial or no implementation. Therefore, Abstract classes act as parent classes from which child classes are derived so that the child class will share the incomplete features of the parent class and functionality can be added to complete them.

Abstract classes may contain Abstract methods. Subclasses extending an abstract class may implement these (inherited) Abstract methods. If the child class implements all such Abstract methods, it becomes a concrete class. But if it does not, the child class also becomes an Abstract class. What all this means is that, when the programmer nominates a class as an Abstract, she is saying that the class will be incomplete and it will have elements that need to be completed by the inheriting subclasses. This is a nice way to create a contract between two programmers, which simplifies tasks in software development. The programmer, who writes code to inherit, needs to follow the method definitions exactly (but of course can have her own implementation).

What is the difference between Abstract Class and Concrete Class?

Abstract classes usually have partial or no implementation. On the other hand, concrete classes always have full implementation of its behavior. Unlike concrete classes, abstract classes cannot be instantiated. Therefore abstract classes have to be extended in order to make them useful. Abstract classes may contain abstract methods, but concrete classes can’t. When an abstract class is extended, all methods (both abstract and concrete) are inherited. The inherited class can implement any or all the methods. If all the abstract methods are not implemented, then that class also becomes an abstract class.

Source: differencebetween.com

Wednesday, July 14, 2021

Difference Between AOP and OOP

AOP vs OOP

AOP (Aspect-oriented programming) and OOP (Object-oriented programming) are two programming paradigms. A programming paradigm is a fundamental style of computer programming. Programming paradigms differ in how each element of the programs is represented and how each step is defined for solving problems. As the name suggests, OOP focuses on representing problems using real-world objects and their behavior, while AOP deals with breaking down the programs in to separate crosscutting concerns.

What is AOP?

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

AOP is a programming paradigm, which deals with breaking down a program in to cohesive areas of functionality (called concerns) that cut across multiple areas, in order to increase modularity. Support for abstractions (such as classes, methods, etc.) to group and encapsulate concerns in to unique entities is provided in many other programming paradigms. But concerns (such as “Logging”) are examples of crosscutting concerns, because every logged part of the system is affected by the strategy used for logging. The main focus of all AOP implementations is to have suitable crosscutting expressions to capture all concerns in a single location.

What is OOP?

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

In OOP, the focus is on thinking about the problem to be solved in terms of real-world elements, and representing the problem in terms of objects and their behavior. Classes depict the abstract representations of real world objects. Classes are like blueprints or templates, which gather similar items or things that can be grouped together. Classes have properties called attributes. Attributes are implemented as global and instance variables. Methods in the classes represent or define the behavior of these classes. Methods and attributes of classes are called the members of the class. An instance of a class is called an object. Therefore, an object is a data structure that closely resembles some real-world object.

There are several important OOP concepts such as Data abstraction, Encapsulation, Polymorphism, Messaging, Modularity and Inheritance. Typically, encapsulation is achieved by making the attributes private, while creating public methods that can be used to access those attributes. Inheritance allows the user to extend classes (called sub classes) from other classes (called super classes). Polymorphism allows the programmer to substitute an object of a class in place of an object of its super class. Typically, the nouns found in the problem definition directly become classes in the program. And similarly, verbs become methods. Some of the most popular OOP languages are Java and C#.

What is the difference between AOP and OOP?

The key difference between OOP and AOP is that the focus of OOP is to break down the programming task in to objects, which encapsulate data and methods, while the focus of AOP is to break down the program in to crosscutting concerns. In fact, AOP is not a competitor for OOP, because it emerged out of OOP paradigm. AOP extends OOP by addressing few of its problems. AOP introduces neat ways to implement crosscutting concerns (which might have been scattered over several places in the corresponding OOP implementation) in a single place. Therefore, AOP makes the program cleaner and more loosely coupled.