Thursday, November 1, 2012

Best Practices for JAVA Programming

If you are a java programmer and not following java best practices, you are not java professional in real world because only programming doesn't important but how you write optimized code is more important.

So here are some of the points which i thought to be publish which can help help to java beginners.

1) Don't create objects unnecessarily

 Creation of object is one of the most expensive operation if we talk about memory utilization and performance as well.

Look @ the below code :

public class States{

 private List states;
 
 public List getStates() {
  
  //initialize only when required
  if(null == states) {
   States= new ArrayList();
  }
  return states;
 }
}

2) Never declare class instance as a public

To declaring a class instance public, there might be security problem with your application.
Let say we are creating a array of some months which is fixed and if we declare as a public, it could be easily access by someone and can change those values which cause security problem.

So instead of declaring public you can use private modifier and can access by defining getter method but again this array can be accessible so what you can do is, you can return a clone of array.

Look @ the below code:

Bad practice :
public String[] months={"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov", "Dec"};
Good Practice :
private String[] months={"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov", "Dec"};
 public String[] getMonths() 
 {
 return months.clone(); 
 }

Tuesday, October 16, 2012

Extract img using regex

Hi All

If you want to extract image from HTML code and want to separate text with html ,
I am sure below code help you a lot :

 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ImgTest {

    public static void main(String[] args) {

            String s = "This is a jignesh<img src=\"test.html\" /> text";

            Pattern p = Pattern.compile("[<](/)?img[^>]*[>]");

            Matcher m = p.matcher(s);

            if (m.find()) {

              String src = m.group();

              System.out.println(src);

            }

            s = s.replaceAll("[<](/)?img[^>]*[>]", "");

            System.out.println(s);

    }

} 
OUTPUT :

<img src="test.html" />

This is a jignesh text  



Cheers !!!!

Tuesday, July 31, 2012

JDBC - MS SQL possible problem

Here in this post I am writing about some possible solutions of JDBC – MS SQL server connection problem. During my work I had faced this problem and tried a little hard to findout the solution. In our project when we tried to connect to MSSQL Server, through its default port 1433 it thrown an exception as follows. Hope this will be helpful to you.
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: “Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.”.
  1. Enable SQL Server Network Configuration
    • For this, go to Start Menu => Microsoft SQL Server 2008 => Configuration Tools => SQL Server Configuration Manager
    • Go to SQL Server Network Configuration => Protocols for [Instance Name] => TCP/IP
    • Instance name is the one in which you have created your database. By default it will be SQLEXPRESS
    • Make it enable (if disabled)
  2. Check the port on which SQL server is running
    • For this, go to Start Menu => Microsoft SQL Server 2008 => Configuration Tools => SQL Server Configuration Manager
    • Go to SQL Server Network Configuration => Protocols for [Instance Name] => TCP/IP
    • Instance name is the one in which you have created your database. By default it will be SQLEXPRESS
    • Right click on that and Go to Properties => IP Addresses tab => IP All section
    • There you will find TCP Dynamic Ports property and we have to consider that port number instead of default port 1433
  3. If you still facing the issue then please check Registry
    • Go to Start Menu => run => regedit
    • Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.[Instance Name]\MSSQLServer\SuperSocketNetLib\Tcp\IPAll and check the value of key TcpDynamicPorts. we have to consider that port number instead of default port 1433

Friday, May 18, 2012

Some basics about java

  1. Real-world objects contain state and behavior.
  2. A software object's state is stored in fields.
  3. A software object's behavior is exposed through methods.
  4. Hiding internal data from the outside world, and accessing it only through publicly exposed methods is known as data encapsulation.
  5. A blueprint for a software object is called a class.
  6. Common behavior can be defined in a superclass and inherited into a subclass using the extends keyword.
  7. A collection of methods with no implementation is called an interface.
  8. A namespace that organizes classes and interfaces by functionality is called a package.
  9. The term API stands for Application Programming Interface.

Reverse string in java

Simplest Example of making reverse string using java

public class StringReverse
{
  public static void main(String[] args)
  {
  String string=args[0];
  String reverse = new StringBuffer(string).
reverse
().toString();
  System.out.println("\nString before reverse:
"
+string);
  System.out.println("String after reverse:
"
+reverse);
  
}

Thursday, January 19, 2012

immutability in Java

Summary:  Immutable objects have a number of properties that make working with them easier, including relaxed synchronization requirements and the freedom to share and cache object references without concern for data corruption. While immutability may not necessarily make sense for all classes, most programs have at least a few classes that would benefit from being immutable.

An immutable object is one whose externally visible state cannot change after it is instantiated. The String, Integer, and BigDecimal classes in the Java class library are examples of immutable objects -- they represent a single value that cannot change over the lifetime of the object.

Benefits of immutability
Immutable classes, when used properly, can greatly simplify programming. They can only be in one state, so as long as they are properly constructed, they can never get into an inconsistent state. You can freely share and cache references to immutable objects without having to copy or clone them; you can cache their fields or the results of their methods without worrying about the values becoming stale or inconsistent with the rest of the object's state. Immutable classes generally make the best map keys. And they are inherently thread-safe, so you don't have to synchronize access to them across threads.

Freedom to cache
Because there is no danger of immutable objects changing their value, you can freely cache references to them and be confident that the reference will refer to the same value later. Similarly, because their properties cannot change, you can cache their fields and the results of their methods.
If an object is mutable, you have to exercise some care when storing a reference to it. Consider the code in Listing 1, which queues two tasks for execution by a scheduler. The intent is that the first task would start now and the second task would start in one day.

When to use immutable classes

Immutable classes are ideal for representing values of abstract data types, such as numbers, enumerated types, or colors. The basic numeric classes in the Java class library, such as Integer, Long, and Float, are immutable, as are other standard numeric types such as BigInteger and BigDecimal. Classes for representing complex numbers or arbitrary-precision rational numbers would be good candidates for immutability. Depending on your application, even abstract types that contain many discrete values -- such as vectors or matrices -- might be good candidates for implementing as immutable classes.



Another good example of immutability in the Java class library is java.awt.Color. While colors are generally represented as an ordered set of numeric values in some color representation (such as RGB, HSB, or CMYK), it makes more sense to think of a color as a distinguished value in a color space, rather than an ordered set of individually addressable values, and therefore it makes sense to implement Color as an immutable class.
Should we represent objects that are containers for multiple primitive values, such as points, vectors, matrices, or RGB colors, with mutable or immutable objects? The answer is. . . it depends. How are they going to be used? Are they being used primarily to represent multi-dimensional values (like the color of a pixel), or simply as containers for a collection of related properties of some other object (like the height and width of a window)? How often are these properties going to be changed? If they are changed, do the individual component values have meaning within the application on their own?

Events are another good example of candidates for implementation with immutable classes. Events are short-lived, and are often consumed in a different thread than they were created in, so making them immutable has more advantages than disadvantages. Most AWT event classes are not implemented as being strictly immutable, but could be with small modifications. Similarly, in a system that uses some form of messaging to communicate between components, making the message objects immutable is probably sensible.


Guidelines for writing immutable classes
Writing immutable classes is easy. A class will be immutable if all of the following are true:
  • All of its fields are final
  • The class is declared final
  • The this reference is not allowed to escape during construction
  • Any fields that contain references to mutable objects, such as arrays, collections, or mutable classes like Date:
    • Are private
    • Are never returned or otherwise exposed to callers
    • Are the only reference to the objects that they reference
    • Do not change the state of the referenced objects after construction