7 tips for beginners in Java

7 tips for beginners in Java

Good day DevBattles users!  In this not big article I want to give several tips for beginners,  who started studying Java.

1.Avoid unnecessary objects and always prefer “lazy” initialization.

As you know, create objects in Java is expensive, in terms of performance and memory usage. hus, you need to create or initialize objects only when needed. Like in example:

 

public class Human {

    private List friends;

    public List getFriends () {

        //initialization only when necessary
        if(null == friends) {
            friends = new ArrayList();
        }
        return friends;
    }
}

2. To check string empty always to use

Allow several different ways to checking string empty and one of them is abc.equals(“”). Never do this. The best way to check empty string is isEmpty(). This method simply compares the length of line with 0 using length() method. Because this operation is less costly. To be sure, just compare source code equals() and isEmpty():

 

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

public boolean isEmpty() {
        return value.length == 0;
}

 

3) Turn the empty collection instead of null.

If function return empty collection what don’t have value, then make sure what returning empty collection, not null. This will save you additional checks on null.

 

public List<User> getUsers() {
    return ( null == users ? new ArrayList<User>(0) : users);
}

 

4.Using your line carefully

If two lines combined by using “+” in “for” loop, then each time creating new object   String. This causes loss of memory  and increases the performance. Also, avoid using constructor when creating the line.

 

//slower initialization
String str1 = new String("slower initialization");

//Faster initialization
String str2 = "Faster initialization";

 

5.Try to use primitives instead of classes-wrappers.

Class-wrapper working slower by primitives, because they retain more information, primitives – just value. Sometimes the programmer can make a mistake in the code using the class-wrapper.

Consider the following example:

int x = 10;
int y = 10;

Integer x1 = new Integer(10);
Integer y1 = new Integer(10);

System.out.println(x == y);
System.out.println(x1 == y1);

 

First sysout, prints true, while the second will print false. The problem is that to compare two objects of class-wrappers we can use the == operator because it compares the reference and not the actual value.

6. Never drop  “java.lang.Exception”.

Never dispose immediately java.lang.Exception. This contradicts the intended use of these exceptions. Throw more specific exclusion or create your own, unless found necessary for the particular situation.

7.Processing NullPointerException

NullPointerException, is a common exception in Java. This exception arises when we try to apply the method to a field object that is a reference to null. Never treat NullPointerException using try-catch-finally. More appropriate would be the test field on the null.

int noOfStudents = 0;
if(school.listStudents() != null) {
     noOfStudents = school.listStudents().count;
}

Thanks for attention!