Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, November 7, 2012

Java Program to find GCD , LCM of two numbers


Greatest common divisor (gcd)

The greatest common divisor (gcd)( also known as the greatest common factor (gcf), or highest common factor(hcf)) of two or more non-zero integers, is the largest positive integer that divides the numbers without a remainder.
For example, the GCD of 8 and 12 is 4.


Euclid's algorithm 

Euclid's algorithm uses a division algorithm such as long division in combination with the observation that the gcd of two numbers also divides their difference.
Formally the algorithm can be described as,

  gcd(a,0) = a (1)
gcd(a,b) = gcd(b, a mod b) (2)

Tuesday, November 6, 2012

URI in Java

Before starting with Java.net.URI let us understand first what does URI means in general.

URI (Uniform Resource Identifier) in General

A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource.
The generic URI syntax consists of a hierarchical sequence of components referred to as the scheme, authority, path, query, and fragment.

   The following are two examples URIs and their component parts:



Friday, October 21, 2011

Shutdown Hook

Sometimes it is necessary to perform some cleanup before your java application shuts down. But problem is user may not always exit properly. User may terminate by pressing Ctrl + C or may simply logoff or shutdown the Operating system while application is still running.

How to ensure that cleanup code executes in such scenario?

Well! Java provides an elegant way to execute cleanup code in the middle of shutdown process. We will discuss it in this article.

Let’s start by understanding what happens when JVM (Java Virtual Machine) shuts down!

Friday, September 23, 2011

Singleton pattern


Sometimes it’s important for classes to have exactly one instance.
For example: Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager.

In such scenario Singleton Design Pattern comes to help.

Singleton pattern ensures a class only has one instance, and provides a global point of access to it.

Implementing Singleton

To implement singleton we need do following two things.
1.    Ensure a class only has one instance:
 This can be achieved by making constructor of a class private ( or protected: In case you want to extend this class.).
2.    Provides a global point of access to instance:
This can be achieved by keeping static reference to unique instance and having method to get that instance.