Advertisement

Ads

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, October 2, 2021

How to calculate Large Factorials using Big Integer in Java?

Calculate Large Factorials using Big Integer in Java Program


Factorials of numbers greater or equivalent to 13 cannot be discovered using the primitive int data types as demonstrated in our earlier factorial method due to overflow. The factorials are too big to be contained in the size of an integer variable and its maximum value is only 2147483647 (2^31 1). 

Calculate Large Factorials using Big Integer



If we employ longer data types, any factorials higher in or greater than 21 can result in an overflow. To find the factorial for anything greater than 21 you have to make use of the BigInteger class in the java.math package.

Like the name suggests, the BigInteger class was intended to hold a massive integer value, something that is larger than the value of a lengthy primitive e.g. 2^63 -1 or 9223372036854775807L.

It is also necessary to change the method we calculate the factorial to accommodate a smaller number. Recursion is not a suitable method in order to compute the factorial for a larger number. Instead, we have to utilize for loops to calculate it.

It is also worth noting that, in common with java.lang.String and the other wrapper classes, BigInteger is also immutable in Java This means that it is essential to save the result in the same variable. If not the results of the calculation is lost.

BigInteger stores numbers as a 2's complement numbers, similar to int primitive and supports operation that is that is supported by int variables as well as all the necessary methods in java.lang.Math class.

In addition, it provides the capability to use modular arithmetic primality testing, bit manipulation as well as prime generation GCD calculation, as well as other diverse operations.

A basic understanding of the fundamental Java ideas and APIs is crucial and is the reason I would recommend everyone Java programmers take a comprehensive Java online course such as The Complete Java Masterclass on Udemy to increase their Java knowledge and API abilities.

Monday, January 28, 2019

A Beginners Guide to Java JDBC

Introduction to JDBC in Java

Java Database Connectivity is a standard Java API used to connect Java application with Database. Java JDBC is used to communicate with the different type of Databases like Oracle, MS Access, My SQL and SQL Server. JDBC can also define as the platform-independent interface between a relational database and Java programming. It allows a java program to execute the SQL statement and retrieve the result from the database. JDBC uses drivers to connect with database. 

Different Types of JDBC Driver in Java 

Java JDBC

1. JDBC-ODBC Bridge Driver
2. Natïve Driver
3. Network Protocol Driver
4. Thin Driver

Why should we use JDBC?

There is some critical point which explains why we should use JDBC.

1. JDBC API is Standard API. We can communicate with any Database without
revising our Application, i.e. it is Database Independent API.
2. JDBC Drivers developed in Java, and hence JDBC Concept is applicable for any
Platform. i.e., JDBC is Platform Independent Technology.
3. By using JDBC API, we can perform basic CRUD Operations very efficiently.
C ➔ Create (Insert)
 R ➔ Retrieve (Select)
 U ➔ Update (Update)
 D ➔ Delete (Delete)
4. We can also perform Complex Operations like inner joins, Outer joins, calling
Stored Procedures, etc. very quickly by using JDBC API.
5. JDBC API supported by many vendors and they developed multiple Products
based on JDBC API.

Advantages of JDBC:

1. Provide present enterprise information.
2. Automatically Creates an XML structure of data from the database.
3. No content conversion required.
4. Query and Stored procedure supported.
5. We can use JDBC for both Synchronous and Asynchronous processing.
6. Supports modules.
7. Zero Configuration for Network Computers.
8. Full Access to Metadata.
9. Database Connection Identified by URL.
10. It does not require an installation.

Monday, January 21, 2019

How Java Servlet Works?

Features of Java Servlet

There are 5 Features of Servlet are as Follow:
Portable: Servlet uses Java Programming language, and as we know java is portable language, so servlet is also portable.
Efficient: Servlets invocation is highly skilled as compared to any CGI programs.
Robust: JVM manages Servlet. That’s why Servlet is robust.
Performance: Servlet creates a thread for each request, so the performance of servlet is better than CGI.
Secure: Because it uses java language, so servlet is safe.

How Servlet Works?

Whenever a request comes, it received by the servlet, and then they forward the request to the web container. A Web container is responsible for handling the request by creating the new thread. Container creates multiple threads to execute various requests.

How Java Servlet Works?


Let’s understand the working of Servlet –
1. The User sends a request by clicking a link for a servlet.
2. Then, the container finds the servlet and Create two instances.
  a.HttpServletRequest
  b.HttpServletResponse
3. After this, the container creates a thread for executing the request. So they call the servlet’s service() method and passes the instances as arguments.
4.Based on the HTTPRequest method sent by client, service( ) method decides which servlet method, doGet() or doPost() to call. 
5. Then, to respond to the client, servlet uses response instance to write the response.
6.After the service( ) method is completed, container call the destroy( ) method. And the request and response instance are prepared for garbage collection.

Servlet API

there are 2 packages of java servlet API are as follow:

1.javax.servlet

This package contains several classes and interfaces that describe and define bonds between a class and environment for an object.

Interface: -

ServletResponse
ServletRequest
RequestDispatcher
ServletConfig
Servlet

Class: -

GenericServlet
ServletRequestWrapper
ServletResponseWrapper
ServletInputStream
ServletOutputStream

Exception

ServletException
UnavailableException

2.javax.servlet.http

This package contains several classes and interfaces that describe and define bonds between a servlet class running under HTTP protocol and environment for an object.

Interface:- 

HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionContext
HttpSessionListener

Class: -

Cookie
HttpServlet
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent




Monday, December 17, 2018

An Ultimate Guides to Garbage Collection in Java

What is Garbage Collection in Java?


Java garbage collection is the method by that Java programs accomplishes automatic memory management. Java programs compile to bytecode which will be run on a Java Virtual Machine. Once Java programs run on the JVM, objects are created on the heap, which is a share of memory dedicated to the program. Ultimately, some objects cannot be required. The garbage collector finds these unused objects and deletes them to liberate memory.

Java garbage collection

When there are not any references to an object, it is assumed to be now not required, Also, the memory, obtained by the purpose can be rescued. There is no specific necessity to destroy an object as Java handles the de-allocation by itself.
The technique that accomplishes this is often called Garbage Collection. Programs that don’t de-allocate memory will eventually crash once there’s no memory left within the system to assign. These programs are said to have memory escapes.

Why we perform Garbage Collection in Java?

The purpose of garbage collection is to spot and discard objects that are not any longer required by a program, so their resources are saved and reused. A Java object is a focus to garbage collection once it becomes inaccessible to the program within which it’s used.

How Java Garbage Collection Works?

Many people assume garbage collection collects and discards dead objects. But, in Java garbage collection is doing the differing! Live objects are followed and everything else chosen garbage. As you will see, this basic misunderstanding will result in several performance issues.

Let's begin with the heap that is that the space of memory used for dynamic allocation. In most configurations, the package allocates the heap in before to be managed by the JVM whereas the program is running. 

This includes several important complications:
Object creation is quicker as a result of world synchronization with the package isn’t required for every single object. An allocation claims some area of a memory array and transfers the offset pointer forward. The next assignment starts at this offset and requests the next portion of the array.
When an object is not any longer used, the garbage collector retrieves the underlying memory and recycles it for future object allocation. This implies there is no specific deletion and no memory is given back to the operating system.

All objects are allotted on the heap area managed by the JVM. Every item that the uses by the developer is treated in this manner, organized with class objects, variables, and even the code itself. If an object is being documented, the JVM considers it active. Once an object is no longer documented and therefore is not approachable by the application code, the garbage collector removes it and retrieves the unused memory.

Garbage Collection Example in Java:

public class Example1{   
   public static void main(String args[]){  
        /* Here we are purposely assigning a nullvalue to a reference*/
Example1 obj=new Example1();  
obj=null; 
        /* Here we are purposely assigning reference a to another reference b*/
Example1a = new Example1();
Example1b = new Example1();
b = a;
System.gc();  /* representing garbage collection by calling this*/
   }  
   protected void finalize() throws Throwable
   {
        System.out.println("Garbage collection is performed by JVM");
   }
}
Output:
Garbage collection is performed by JVM
Garbage collection is performed by JVM

In this example, we are representing the garbage collection by calling System.gc(). During this example, we have overridden a finalize() method. This method is invoked directly before an object is destroyed by java garbage collection method. This is often the motive you would see within the output that this technique has been invoked double.