Friday, December 13, 2024

[Solved] 3 Examples to reverse an Array in Java - Example Tutorial

Hello guys, today we are going to see another common coding question from interviews - how do you reverse an array in Java? This is a popular array-based coding problem and often asked programmers during the first few rounds of interviews to check if they can code or not. Well, there are multiple ways to solve this problem and we will see three common ways to ever an array in Java. This method applies to all kinds of arrays like string array or integer array or even with arrays of objects because it's not focused on data types. The first way to reverse an array is by reversing it in a brute force way, without using any additional data structure or library method. 

How to Find Even and Odd Number in Java - Program Tutorial Example

Even and Odd number check Java Example
There are many ways to find if a number is even or odd in Java but before moving into technical details on finding even and odd numbers in Java let's what is even and odd numbers in terms of Mathematics. Any number which is completely divisible by 2 is called an even number while a number that is not completely divisible by 2 is called an odd number. If you think in terms of remainder then in the case of even number, the remainder is zero while in the case of odd number remainder will be 1. zero is considered as an even number in maths. 

Wednesday, December 11, 2024

How to Find Missing Number in a Sorted Array in Java [Solved]

Today's coding problem is not very new, it's an age-old classic Programming interview Question. You have a sorted array containing n - 1 unique number starting from 0 to n - 1. There is only one number missing in this range and you need to find that out. I mean you need to write a Java method to find the missing number and print its value in the console. Some of you might have seen this question before, but if you have not been asked this question before, what is the first approach comes into your mind to solve this question? Since only one number is missing, many programmers come up with the approach of iterating over the array, and comparing each element with the expected one like the first element should be 0, the second element should be 1, and so on.

How to Count number of 1s (Set Bits) in a binary number in Java [Solved]

Good morning folks, In today's article, we are going to discuss one of the frequently asked bit manipulation-based interview questions, how do you count the number of set bits in a given bit sequence?  Bit Manipulation is an important topic in programming interviews and a good programmer should have sufficient knowledge and skill to work with binary numbers. This kind of question tests the skill of the programmer. Sometimes, it is also asked as to how to count the number of 1s (ones) in a given number? Both are the same question because 1 is also known as set bit.  For example, if the given input is 1000110010 then your program should return 4, as three are only four set bits in this bit sequence.

How to Print Pyramid Pattern in Java? Program Example

Pattern based exercises are a good way to learn nested loops in Java. There are many pattern based exercises and one of them is printing Pyramid structure as shown below:


* * 
* * * 
* * * * 
* * * * * 

You need to write a Java program to print the above pyramid pattern. How many levels the pyramid triangle would have will be decided by the user input. You can print this kind of pattern by using print() and println() method from System.out object. System.out.print() just prints the String or character you passed to it, without adding a new line, useful to print stars in the same line. 

Monday, December 9, 2024

Top 20 Machine Learning Libraries for AI Engineers in 2025 - Best of Lot

 Artificial Intelligence (AI) has emerged as a transformative technology, revolutionizing various industries and driving innovation. With the increasing accessibility of AI, numerous free tools have become available, enabling individuals and businesses to explore and leverage AI capabilities. In this article, we present the top 20 free Machine Learning libraries to try in 2025. These tools cover a wide range of AI applications, including machine learning, natural language processing, computer vision, and more. Let's dive into the exciting world of AI tools and discover how they can empower innovation and automation.

Sunday, December 8, 2024

How to call REST API an send HTTP GET and POST Request using cURL command in Linux? Example Tutorial

The curl or cURL command of Linux is a compelling and versatile command which allows you to send sophisticated HTTP requests right from your Linux command line window. You can use the cURL command to test your RESTful Web Services by sending GET and POST requests, doing authentication, saving a cookie in the file, etc. The curl command is, in fact, the go-to tool for many Java and Spring developers working in web applications and consuming data from the secured RESTful Web Services. Still, you can also use it to test your simple REST Web APIs without security. I have used it many times to check if our Web service is up or not, or is there any error while accessing those services.

Thursday, October 31, 2024

How to Create Config Server in Microservices Architecture with Spring Cloud Config Server

The ability of microservices architecture to deconstruct big monolithic programmes into smaller, independent, and controllable services has led to its enormous growth in popularity in recent years. It can be difficult to manage configuration across numerous microservices, though, as each service may call for a separate set of configurations. To solve this problem, configurations for microservices are centralised and managed by a separate Config Server. In this post, we'll examine what a Config Server is, why it's crucial for microservices, and how to use Spring Cloud Config Server to construct it.

Tuesday, October 29, 2024

Top 10 AI Tools for Bloggers and Writers in 2025

 Artificial Intelligence (AI) has revolutionized various industries, and the field of writing and blogging is no exception. AI-powered tools for bloggers and writers have emerged, offering innovative solutions to enhance creativity, streamline workflows, and improve content quality. In this article, we present the top 10 AI tools specifically designed for bloggers and writers. These tools leverage AI technologies such as natural language processing, machine learning, and data analytics to help writers generate ideas, improve grammar, enhance productivity, and optimize content for better engagement. Let's explore these cutting-edge AI tools and discover how they can empower bloggers and writers.

Monday, October 28, 2024

What is Payload in REST API? How to send Payload using HTTP Post Request and HttpClient

Hello and welcome to the blog post. In this comprehensive article we are going to take a look at an interesting topic. I’m sure you all are familiar with client-server architecture. If not let me recap it quickly for you. 

A Client is a machine (or a web-browser) that request for desired results from the  server. In other words, clients initiate requests for services or resources, while servers provide those services or resources upon request. The client-server model forms the foundation of many networked applications and systems, where clients and servers communicate and collaborate to fulfill various tasks and deliver services.

What is a Payload?

When a client sends a request to a server, the payload typically contains the data or parameters required by the server to process the request. For example, in a client-server architecture for a web application, the payload of an HTTP request sent by the client may include parameters for a form submission, JSON data for an API request, or a file to be uploaded.

On the server side, when the server sends a response back to the client, the payload contains the data or information requested by the client. This can include HTML content, JSON responses, file attachments, or any other data relevant to the specific request made by the client.

Payload in REST API

The information supplied in the body of an HTTP request is referred to as a payload in the RESTful API architecture. It represents the data that is being sent from the client to the server or the other way around. Depending on the content type supplied in the request headers, the payload may be in one of several forms, including JSON, XML, or plain text.

The payload carries the necessary data required to perform operations on the server or to retrieve specific resources. For example, when creating a new resource, the payload would typically contain the data that needs to be stored on the server. When updating an existing resource, the payload would include the modified data.

What is an HttpClient? 

HttpClient is a powerful Java package that offers quick and efficient way for submitting HTTP requests and receiving server responses. Starting with Java 11, it is a part of the Java SE standard library and offers a comprehensive API for interacting with HTTP-based services.

HttpClient's main objective is to make it easier for client applications to communicate with RESTful APIs, web services, and other HTTP-based endpoints. The low-level aspects of creating and managing connections, dealing with request and response bodies, modifying headers, controlling timeouts, and dealing with redirection are abstracted away.

You can perform various HTTP operations like GET, POST, PUT, DELETE by using HttpClient. It supports both synchronous and asynchronous request processing and offers a number of configuration options for customization.

Let’s take an example on how to send a POST request to REST API using HttpClient

import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;

import java.net.http.HttpClient;

import java.net.http.HttpRequest;

import java.net.http.HttpResponse;

import java.net.http.HttpHeaders;

import java.net.http.HttpResponse.BodyHandlers;


public class HttpClientExample {

    public static void main(String[] args) throws Exception {

        // Create an instance of HttpClient

        HttpClient httpClient = HttpClient.newHttpClient();


        // Define the URL of the REST API endpoint

        String url = "http://api.example.com/users";


        // Create a User object

        User user = new User("John Doe", 30);


        // Serialize the User object to JSON

        ObjectMapper objectMapper = new ObjectMapper();

        String requestBody = objectMapper.writeValueAsString(user);


        // Build the HTTP request

        HttpRequest request = HttpRequest.newBuilder()

                .uri(URI.create(url))

                .header("Content-Type", "application/json")

                .POST(HttpRequest.BodyPublishers.ofString(requestBody))

                .build();


        // Send the request and receive the response

        HttpResponse<String> response = httpClient.send(request, BodyHandlers.ofString());


        // Extract the User object from the response

        String responseBody = response.body();

        User responseUser = objectMapper.readValue(responseBody, User.class);


        // Print the response User object

        System.out.println("Response User: " + responseUser);

    }

}


class User {

    private String name;

    private int age;


    // Constructors, getters, and setters


    @Override

    public String toString() {

        return "User{" +

                "name='" + name + '\'' +

                ", age=" + age +

                '}';

    }

}


In this example, we have a User class representing the user object. We use the ObjectMapper from the Jackson library to serialize the User object to JSON format. 

We then create an HttpRequest object with the necessary details, including the URI, headers (in this case, "Content-Type" is set to "application/json"), and the request body containing the serialized User object. 

After sending the request using httpClient.send(), we receive the response as an HttpResponse object. We extract the response body as a JSON string. 

Finally, we deserialize the response JSON string back into a User object using objectMapper.readValue(). The resulting User object represents the response payload, which we can use as needed.


Sending Payload to REST API using HTTP POST Request and HttpClient in Java

import java.net.URI;

import java.net.http.HttpClient;

import java.net.http.HttpRequest;

import java.net.http.HttpResponse;

import java.net.http.HttpHeaders;

import java.net.http.HttpEntity;

import java.net.http.HttpHeaders;

import java.net.http.HttpRequest.BodyPublishers;

import java.net.http.HttpResponse.BodyHandlers;


public class HttpClientExample {

    public static void main(String[] args) throws Exception {

        HttpClient httpClient = HttpClient.newHttpClient();


        String jsonPayload = "{\"name\": \"Someone \", \"email\": \"someone@example.com\"}";


        HttpRequest request = HttpRequest.newBuilder()

                .uri(URI.create("http://example.com/api/resource"))

                .header("Content-Type", "application/json")

                .POST(BodyPublishers.ofString(jsonPayload))

                .build();


        HttpResponse<String> response = httpClient.send(request, BodyHandlers.ofString());


        int statusCode = response.statusCode();

        String responseBody = response.body();


        System.out.println("Status Code: " + statusCode);

        System.out.println("Response Body: " + responseBody);

    }

}


In the example above, we create a JSON payload using a sample data object. We set the HTTP method to POST, the request URL to "http://example.com/api/resource", and the content type to "application/json". The payload is then sent in the body of the request using the BodyPublishers.ofString() method. 

Finally, we retrieve and handle the response from the server.

Remember to replace "http://example.com/api/resource" with the actual endpoint URL of the REST API you want to send the payload to, and modify the payload data according to your requirements and the API's expected format.

Let me show you how to send other types of payloads from the following example.


1) Sending a Form-UrlEncoded Payload


import java.net.URI;

import java.net.http.HttpClient;

import java.net.http.HttpRequest;

import java.net.http.HttpResponse;

import java.net.http.HttpHeaders;

import java.net.http.HttpEntity;

import java.net.http.HttpHeaders;

import java.net.http.HttpRequest.BodyPublishers;

import java.net.http.HttpResponse.BodyHandlers;

import java.net.URLEncoder;

import java.nio.charset.StandardCharsets;


public class HttpClientExample {

    public static void main(String[] args) throws Exception {

        HttpClient httpClient = HttpClient.newHttpClient();


        String payload = "name=" + URLEncoder.encode("John Doe", StandardCharsets.UTF_8)

                + "&email=" + URLEncoder.encode("johndoe@example.com", StandardCharsets.UTF_8);


        HttpRequest request = HttpRequest.newBuilder()

                .uri(URI.create("http://example.com/api/resource"))

                .header("Content-Type", "application/x-www-form-urlencoded")

                .POST(BodyPublishers.ofString(payload))

                .build();


        HttpResponse<String> response = httpClient.send(request, BodyHandlers.ofString());


        int statusCode = response.statusCode();

        String responseBody = response.body();


        System.out.println("Status Code: " + statusCode);

        System.out.println("Response Body: " + responseBody);

    }

}


In this example, we are sending a form-urlencoded payload to the REST API endpoint "http://example.com/api/resource". The payload contains two fields, name and email, which are URL-encoded using the URLEncoder.encode() method. The Content-Type header is set to "application/x-www-form-urlencoded".



2) Sending a Plain Text Payload


import java.net.URI;

import java.net.http.HttpClient;

import java.net.http.HttpRequest;

import java.net.http.HttpResponse;

import java.net.http.HttpHeaders;

import java.net.http.HttpEntity;

import java.net.http.HttpHeaders;

import java.net.http.HttpRequest.BodyPublishers;

import java.net.http.HttpResponse.BodyHandlers;


public class HttpClientExample {

    public static void main(String[] args) throws Exception {

        HttpClient httpClient = HttpClient.newHttpClient();


        String textPayload = "This is a plain text payload.";


        HttpRequest request = HttpRequest.newBuilder()

                .uri(URI.create("http://example.com/api/resource"))

                .header("Content-Type", "text/plain")

                .POST(BodyPublishers.ofString(textPayload))

                .build();


        HttpResponse<String> response = httpClient.send(request, BodyHandlers.ofString());


        int statusCode = response.statusCode();

        String responseBody = response.body();


        System.out.println("Status Code: " + statusCode);

        System.out.println("Response Body: " + responseBody);

    }

}


In this example, we are sending a plain text payload to the REST API endpoint "http://example.com/api/resource". The payload simply contains the text "This is a plain text payload." The Content-Type header is set to "text/plain" to indicate that the payload is in plain text format.



Summary 

In summary, sending a payload to a REST API using an HTTP POST request and HttpClient in Java involves creating an HTTP request with the desired payload, specifying the necessary headers, and sending the request using the HttpClient instance. The server will process the payload and provide a response, which can be accessed and utilized accordingly.


Sunday, October 27, 2024

20 Examples of Git Commands in Linux and Windows

Version control is crucial in software development, and Git stands out as a powerful tool for managing source code. Whether you're working in a Linux or Windows environment, understanding Git commands is essential. This article explores 20 fundamental Git commands, demonstrating their application and significance. From initializing a repository to handling branches and commits, each command plays a pivotal role in maintaining a well-organized and collaborative development workflow. Whether you're a seasoned developer or a newcomer, mastering these Git commands will enhance your ability to track changes, collaborate seamlessly, and contribute effectively to software projects.

Friday, October 25, 2024

Is Frontend Master Worth It?

Frontend development has been growing rapidly in the last few years, as web applications have become more complex and interactive. Frontend Master is an online platform that provides courses and tutorials to learn front-end development. However, with so many resources available on the internet, it's difficult to know whether Frontend Master is worth investing your time and money. In this article, we'll take a closer look at what Frontend Master has to offer and whether it's worth the investment.

Saturday, October 19, 2024

Top 10 Programming Languages to Learn in 2025 [UPDATED]

Hello guys, we're just one week away from 2025. This is when most of us start making our goals like physical goals, educational goals, and financial goals. As a programmer, one of our goals is to learn new technologies and programming languages, but which languages should you learn? Since acquiring a programming language requires both time and patience, you should learn a language worth the effort; I mean., it can reward you with a better job and career growth. In this article, I will share with you the top 10 programming languages you can learn in 2025 to get a job in your favorite companies like Google, Microsoft, and Facebook.

Monday, October 14, 2024

5 Best DP-900 Certification Courses and Practice Test for Azure Data Fundamentals Exam in 2025

The DP-900 certification, also known as the Microsoft Azure Data Fundamentals Certification, is perfect for people who are just starting to work with data on the cloud. This certification will help you build foundational knowledge in cloud data services with Microsoft Azure. Taking the DP-900 certification exam will have many benefits. It will give you a broad overview of how data works in the cloud. It will also help you test your knowledge of cloud data within the ambit of Microsoft Azure services.

Wednesday, October 9, 2024

10 Tools Java Developers Should Learn in 2024 - (UPDATED)

Hello folks, we are in the first week of 2024, and many programmers have already started making a good process to their goals for 2024, which is very good, but if you are someone, who is still not sure what to learn in 2024, then you have come to the right place. In the past, I have shared 10 things Java developers to learn in 2024, and last week, I published the top 5 Java Frameworks to learn, but there is one topic that kept coming from my readers.  The question which I have received this week a couple of times from my fellow Java developers and readers is which tools Java programmers should learn in 2024? Or what are some excellent Java tools used in application development? And finally, what should I learn in 2024?

Wednesday, October 2, 2024

7 Free 1Z0-803 and 1Z0-804 Sample Questions - OCAJP 7 and OCPJP 7 Mock Exams (Oracle Certified Associate Java SE 7 Programmer 1 and 2 )

In this article, I am going to share some OCAJP 7 or 1Z0-803 exam and OCPJP 7 or 1Z0-804 certification sample questions and mock exam for practice which are completely free and available online. The sample questions are not good enough for thorough practice but you can use these mock tests to get an idea of what to expect in the actual exam. Many of the free mock questions are actually the samples questions provided by professional certification exam simulator provided e.g. Whizlabs, Enthuware, MyExamCloud etc, which are samples of their full-length exam simulators. 

Top 5 OCPJP7 books for 1Z0-804 and 1Z0-805 Exam - Java SE 7 II Certification

You may know that from Java SE 7 onwards, you need to pass two exams to become a certified Java developer e.g. OCAJP and OCPJP. The first one is an associate-level exam and it's rather easy to pass, but the second one OCPJP is a professional level exam and it's much harder than OCAJP. If you are giving the Oracle Java certification then you should know that you need to pass OCAJP before taking the OCPJP exam. This is also the second part of an article about books to prepare Java SE 7 certifications. In the first part, I have shared the best books for OCAJP7 and in this part, I am going to share the best books for the OCPJP7 exam.

Monday, September 30, 2024

When to use PUT or POST in a RESTful API and Web Service? Answer

Hello guys, if you are confused about whether to use PUT or POST for updating a resource using RESTful web service then you have come to the right place. In the past, I have shared the best RESTful web service books and courses and today, I am going to share some tips to choose between PUT and POST while designing your RESTful web services. Btw, you are not alone, one of the most common confusion among web developers is the choice of PUT or POST HTTP method for creating and updating a resource while developing RESTful Web Services. Since both can be used to submit data, you can use either POST or PUT to create or update a resource.
 

Thursday, September 19, 2024

Review - Is IT Fundamentals for Cybersecurity Specialization on Coursera Worth it?

Learning the information technology (IT) fundamentals in general and cyber security is a good investment in yourself since there is a massive demand for these skills. Companies need people to secure their infrastructure, such as their servers where they host the website and user's data, monitor their network for unauthorized access, and scan the employee computers for any trojan and viruses that could give hackers control over your system.

Tuesday, September 17, 2024

What is Backend for front-end Pattern? How to use it?

  In the realm of microservices architecture, designing efficient communication between front-end applications and the back-end services is crucial. The Backend for Front-End (BFF) pattern has emerged as a useful architectural pattern to streamline this communication. In this article, we will delve into what the Backend for Front-End pattern is, its benefits, and how to effectively implement and utilize it in your microservices ecosystem.

What is Backend for front-end Pattern? How to use it?

The Backend for Front-End pattern, also known as BFF, is an architectural pattern that involves creating a specialized backend service for a specific front-end application or client. The purpose of this pattern is to decouple the front-end from the complexities and intricacies of the backend services, providing tailored APIs that align with the needs of the front-end.

By employing the BFF pattern, you create an intermediary layer that acts as a bridge between the front-end and the various backend services. This allows for improved flexibility, enhanced user experience, and optimized performance.

How to Use the Backend for Front-End Pattern


Identify the Front-End Application

Start by identifying the front-end application or client that will benefit from the BFF pattern. It can be a web application, mobile application, or any other consumer of the backend services.




Understand the Front-End Requirements

Work closely with the front-end development team to understand the specific requirements of the application. This includes the data and functionality needed, performance considerations, and any other factors that may impact the user experience.


Design the Backend for Front-End Service

Based on the front-end requirements, design a specialized backend service that acts as the BFF for the front-end application. This service will serve as an intermediary between the front-end and the backend services, encapsulating the necessary logic and communication.

Define Tailored APIs

The BFF service should expose a set of tailored APIs that are optimized for the front-end application's needs. These APIs should provide the required data in an efficient and convenient format, minimizing unnecessary round trips and reducing data transfer.

Aggregate Data and Handle Complexity

The BFF service should handle the complexity of interacting with multiple backend services. It can aggregate data from different services, orchestrate workflows, and transform or filter the data to meet the front-end's specific requirements. This helps in reducing the complexity and network overhead on the front-end side.

Optimize Performance

One of the key benefits of the BFF pattern is the ability to optimize performance. The BFF service can leverage caching mechanisms, pre-fetching of data, or implementing tailored data retrieval strategies to enhance response times and improve the overall user experience.



Maintain Separation of Concerns

While the BFF service acts as an intermediary between the front-end and the backend services, it's important to maintain separation of concerns. The BFF should not contain business logic or data manipulation that belongs to the backend services. Instead, it should focus on providing the necessary data and functionality required by the front-end.

Handle Security and Authorization

Ensure that the BFF service implements proper security measures to protect sensitive data and enforce appropriate authorization rules. This may involve authentication mechanisms, token-based access control, or integration with a central authentication service.

Evolve and Scale

As the front-end application evolves, the BFF service should also adapt accordingly. Monitor the usage patterns, performance metrics, and user feedback to continuously enhance and optimize the BFF service. Additionally, ensure that the BFF service is designed to be scalable and can handle increased traffic and load as the application grows.



Benefits of the Backend for Front-End Pattern


Improved Front-End Development Experience: The BFF pattern allows front-end developers to work with a specialized backend service that caters specifically to their needs. This results in a more streamlined development process, as the front-end team can focus on building the user interface without being hindered by backend complexities.

Enhanced Performance: By tailoring APIs and optimizing data retrieval and caching strategies, the BFF service can significantly improve the performance of the front-end application. This reduces latency, minimizes unnecessary data transfer, and provides a more responsive user experience.

Flexibility and Adaptability: The BFF pattern promotes flexibility by enabling the front-end application to evolve independently from the backend services. As requirements change or new features are introduced, the BFF service can be updated accordingly without impacting the existing backend services.

Simplified Backend Integration: The BFF service acts as a single point of integration for the front-end application, abstracting away the complexities of multiple backend services. This simplifies the integration process and reduces the coordination efforts required between the front-end and backend teams.

Security and Authorization Control: The BFF service can handle security concerns and enforce authorization rules specific to the front-end application. This allows for a centralized approach to security, ensuring that the appropriate authentication and authorization mechanisms are applied consistently.

Considerations for Using the Backend for Front-End Pattern


Increased Complexity: Implementing the BFF pattern introduces an additional layer of complexity to the overall architecture. It requires careful design and coordination between the front-end and backend teams to ensure smooth communication and maintain separation of concerns.

Potential Performance Bottlenecks: While the BFF pattern can improve performance, improper implementation or inadequate scalability measures can introduce performance bottlenecks. It is important to monitor and optimize the BFF service to ensure it can handle the expected load and traffic.

Maintenance and Versioning: As the front-end application evolves, the BFF service may require updates and maintenance. It is crucial to manage versioning and compatibility between the front-end and BFF service to prevent disruptions and ensure seamless upgrades.




Overlapping Functionality: Care must be taken to avoid duplicating functionality between the BFF service and backend services. It is essential to clearly define the responsibilities and boundaries of each component to avoid unnecessary redundancy or inconsistency.

Conclusion


The Backend for Front-End pattern provides a powerful approach to improving the interaction between front-end applications and backend services in a microservices architecture. By creating a specialized backend service tailored to the needs of the front-end, the BFF pattern enhances performance, simplifies integration, and promotes flexibility.

When implementing the BFF pattern, it is important to consider the specific requirements of the front-end application, design tailored APIs, optimize performance, and handle security and authorization effectively. By maintaining separation of concerns and continuously monitoring and optimizing the BFF service, you can create a robust and scalable architecture that enhances the development experience and delivers a seamless user experience.

Utilize the Backend for Front-End pattern as a valuable tool in your microservices ecosystem to bridge the gap between front-end applications and backend services, providing a streamlined and optimized communication channel.