Posts

Showing posts with the label Java

Java Constructor vs method

Functionally difference between constructors and methods is that constructors create and initialize objects that don't exist yet, while methods perform operations on objects that already exist. Constructors can't be called directly. They are invoked implicitly when the new keyword creates an object. Methods can be called directly on an object that has already been created with new. Constructors must be named with the same name as the class name. Constructors cannot  return anything, even void . Methods must be declared to return something ( or void). Constructor compiler provide default constructor where as method compiler does't provide. Constructor cannot be final since it cant be inherited. Constructor cannot be abstract since it is used to create and initialize object. Constructor cannot be static since it is used to create instance of object. Only public, protected & private modifiers are permitted.

Better ways to implement Singleton in Java

Singleton Design pattern restrict creation of only once instance of a Class. That means inside a single JVM only one instance of the Singleton Class will be created.  In java we have broadly two options to implement Singleton. 1) Early Creation of the Object Instance. 2) Lazy Creation of the Object Instance: Here the instance is created on first invocation. Following example demonstrate how to implement Singleton in Java. Method 1: Early Creation of Object Instance public class SingletonClass { private static final SingletonClass INSTANCE = new SingletonClass(); //Private Constructor private SingletonClass () { //Do nothing } public static SingletonClass getInstance () { return INSTANCE ; } } Here the instance is created ahead even before calling the Class. We need to provide a private constructor otherwise Java Compiler will add a default Constructor. Method 2: Lazy Creation of Object Inst...

Masking Credit Card number in Java

Sometimes we need to mask crucial information like Credit Card Numbers, CVV numbers etc before storing  or logging the information. This example mask Credit Card Number (Except last 4 Digit) from a Text which contains information along with Credit Card Number. The following example demonstrates how we can easily mask the credit card with Matcher and Pattern Classes. This Sample Code uses Matcher and Pattern. Pattern Used in this sample is not optimized for Credit Card Numbers, this pattern will get any numerical numbers in the String Content.  Based on the Credit Card Type a more efficient and Strict RegEx can be used to mask the Credit Card. /**Mask the Credit card number but last four digit value **/   Pattern PATTERN = Pattern.compile( "[0-9]+" ); String message = content; Matcher matcher = PATTERN.matcher(message); String maskingChar = "*"; StringBuilder finalMask = new StringBuilder(maskingChar...

Shift operator in java

Shift operator in java Java supports two types of shift operator (Logical Shift and Arithmetic shift). Logical Shift : In logical shift simply all the bits except the extreme left or right bit is moved by one place. and The extra bit from the other end is replaced with zero. For Example for The number 4 (binary = 0000 0100) Logical Shift ( >>>, << )                              original number        0 000 0100              (Decimal 4)                              after left shift           000 0100 0              (Decimal 8)                              original number         ...

JSON Manipulation in Java

JSON stands for Java Script Object Notation, in which essentially we represent data in name:value pair in a string. Example of JSON strin is as follows {    "lastName":"Smith",    "suffix":"Jr",    "city":"Foster City",    "country":"US",    "postalCode":"94404",    "firstName":"John" } Which represent the Data about a user. JSON is a standard notation to exchange data. To process Json String , like converting from Json String to Java or vice versa we have so many different libraries in Java.One of the Most prominent being Jackson, Bellow are the example or Some Use cases for Handling Json in Java. Converting JSON String to Java Object Using Jackson We can use ObjectMapper to convert a JSON String to java Object. ObjectMapper mapper = new ObjectMapper(); UserInfo userInfoObj = mapper.readValue(JSONStringSrc,  UserInfo.class); Where UserInfo Obje...

String Manipulation in Java

Working with String like things in java is very common, and one of the common uses case. While we need to replace a substring inside a long String, we have couple of options in java. Java "String" itself has methods like replace and replaceAll which we can use to replace a substring from the main string. The other option is using StringBuilder  which has method like replace(start, end,str);   Which is better then the formar and we will see the difference in details next. We can also use Pattern and Matcher to replace substring from String like bellow. Pattern p = Pattern.compile(" \\$\\{USERNAME\\ }"); Matcher m = p.matcher(ORIGINAL_STRING); p = Pattern.compile(" \\$\\{USERNAME\\ }"); m = p.matcher(ORIGINAL_STRING); m.replaceAll(USERNAME_VALUE); But the for most of the cases much better and efficient way to replace substring is to use Apache StringUtils Utility Class. I have created some test methods which utilizes the above mentioned dif...

When to User Interface and When Abstract Class

This discussion is very common , when to use interface and when to use Abstract Class. Before deciding we should know properties of Abstract Class and Interface in details ::Abstract Class:: It contains both abstract methods and non abstract methods Classes Extend Abstract Class Abstract Classes cannot be instantiated. Abstract can't be declared with Final Synchronised Native. It can have static and instance initialise block. Abstract Class has constructor. Abstract Class may not contain any method(any abstract method) ::Interfaces:: Interface contains all abstract methods. Classes implements Interface. all methods compulsory implemented by particular class which implement interface. Interface variables are implicitly public static and final. Interface variables are constants that cannot be overridden. They are inherited by any class that implements an interface. Interface may not contain any method(Marker Interface). Interface does not contain Constructor. I...

Java Annotation

Annotations on Annotations(Meta Annotation) J2SE 5.0 provides four annotations in the java.lang.annotation package that are used only when writing annotations:     @Documented—Whether to put the annotation in Javadocs     @Retention—When the annotation is needed     @Target—Places the annotation can go     @Inherited—Whether subclasses get the annotation These four annotations are used while creating custom Annotations and are called Meta Annotations. The Target annotation The target annotation indicates the targeted elements of a class in which the annotation type will be applicable. It contains the following enumerated types as its value:      @Target(ElementType.TYPE)—can be applied to any element of a class      @Target(ElementType.FIELD)—can be applied to a field or property      @Target(ElementType.METHOD)—can be applied to a method level annotat...

Java Annotation

Annotation in Java is there to make programmers life a bit easy. Annotation-based development relieves Java developers from the pain of cumbersome configuration. Advantages of using Annotations Annotations are attached to Classes and can be processed via reflection. It is much easier to see the Annotations as they are defined in Java code and no need to refer external configurations (like XML). Compiler will do static type checking for Annotation uses. Compile time the proper uses of annotation will be done. Here are some rules-of-thumb when defining an annotation type: Annotation declaration should start with an 'at' sign like @, following with an interface keyword, following with the annotation name. Method declarations should not have any parameters. Method declarations should not have any throws clauses. Return types of the method should be one of the following: primitives String Class enum array of the above types The following shows example of decel...

Difference between volatile and synchronized

volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords: int i1; int geti1() {return i1;} volatile int i2; int geti2() {return i2;} int i3; synchronized int geti3() {return i3;} geti1() accesses the value currently stored in i1 in the current thread . Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main...

What is the difference between an application server and a Web server

A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols. Web server's delegation model is fairly simple. When a request comes into the Web server, the Web server simply passes the request to the program best able to handle it. The Web server doesn't provide any functionality beyond simply providing an environment in which the server-side program can execute and pass back the generated responses. The server-side program usually provides for itself such functions as transaction processing, database connectivity, and messaging. A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scrip...

What is Serialization

Serialization is the process of persisting the state of an object. Lets say for example you create a dog object and instantiate all its various members, size, age, height etc. Serialization allows you to 'save' this object persisting all its state. Its kind of like saving anything, this can then be restored at a later date and the object reused. To make a class suitable for serialization the class needs to implement the Serializable interface. Serializable is a marker interface, it doesnot have any methods defined.

How To Avoid Deadlock In java

How to avoid deadlocks One of the best ways to prevent the potential for deadlock is to avoid acquiring more than one lock at a time, which is often practical. However, if you have to acquire more then one lock for some purpose then acquire multiple locks in a consistent, defined order. Depending on how your program uses locks, it might not be complicated to ensure that you use a consistent locking order. You can define a lock acquisition ordering on the set of locks and ensure that you always acquire locks in that order. Once the lock order is defined, it simply needs to be well documented to encourage consistent use throughout the program. Following are the zest about how we can avoid deadlock in the context of java, Narrow down the synchronization's scope to as small a block as possible. Try to avoid locking multiple objects if possible.  Use a consistent lock order, by which if multiple locks need to be acquired will be acquired in a p...

What Is Deadlock In java

A condition that occurs when two processes are each waiting for the other to complete before proceeding. The result is that both processes hang . Deadlocks occur most commonly in multitasking and client/server environments. Ideally, the programs that are deadlocked, or the operating system , should resolve the deadlock, but this doesn't always happen. The Following examples depicts how we can have deadlock in java. p ublic class MyDeadlockTest {   public static void main(String[] args)   {     final Object object1 = "object1" ;     final Object object2 = "object2" ;     // t1 tries to lock object1 then object2     Thread t1 = new Thread()     {       public void run()       {         // Lock resource 1         synchronized (object1)         {           System...

How Equals and == Works in Java

The "Object" Class in Java provides a method with name "equals" which is used to test if two objects are equal. And the "==" is a operator. This operator when used for primitives, returns true if two primitive values are equal. And for Object references, this "==" operator returns true when they are referring to the same object. The object "Object" which all other Java objects extend has an equals method which allows you to check to see if two objects are equal, which means you call equals on any object you want. Objet's implementation of equals does the following ( The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values xand y, this method returns true if and only if x and y refer to the same object ( x==y has the value true ). When you compare two instances using ==, you are actually comparing their memory addresses to see if they are ref...

Working With JDBC

Connecting to a database In order to connect to a database, you need to perform some initialization first. Your JDBC driver has to be loaded by the Java Virtual Machine classloader, and your application needs to check to see that the driver was successfully loaded. We'll be using the ODBC bridge driver, but if your database vendor supplies a JDBC driver, feel free to use it instead. // Attempt to load database driver try { // Load Sun's jdbc-odbc driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); } catch (ClassNotFoundException cnfe) // driver not found { System.err.println ("Unable to load database driver"); System.err.println ("Details : " + cnfe); System.exit(0); } We try to load the JdbcOdbcDriver class, and then catch the ClassNotFoundException if it is thrown. This is important, because the application might be run on a non-Sun virtual machine that doesn't include the ODBC bridge, such as Microsoft's J...