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

Tuesday, April 15, 2014

How to check if my string is equal to null?

How to check if my string is equal to null?


Solution:

public static boolean isEmpty(String string) {
    return string == null || string.length() == 0;
}
Usage:
if (isEmpty(string)) {
  // do something
}
Explanation:
As noted above, the || and && operators short circuit. That means as soon as they can determine their value they stop. So if (string == null) is true, the length part does not need to be evaluated, as the expression would always be true. Likewise with &&, where if the left side is false, the expression is always false and need not be evaluated further.
As an additional note, using length is generally a better idea than using .equals. The performance is slightly better (not much), and doesn't require object creation (though most compilers might optimize this out).

Thursday, November 22, 2012

Difference between "==" operator and equals() method


Difference between "==" operator and equals() method

The “==” operator:

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:

By definintion, the objects are all created on the heap. When you create an object, say,

Object ob1 = new SomeObject();
Object ob2 = new SomeObject();

We have 2 objects with exactly the same contents, lets assume. We also have 2 references, lets say ob1 is at address 0x1234 and ob2 is at address 0x2345. Though the contents of the objects are the same, the references differ.

Using == compares the references. Though the objects, ob1 and ob2 are same internally, they differ on using this operation as we comare references. ob1 at address 0x1234 is compared with ob2 at address 0x2345. Hence, this comparison would fail.

object.equals() on the other hand compares the values. Hence, the comparison between ob1 and ob2 would pass. Note that the equals method should be explicitly overridden for this comparison to succeed.

The equals() method: 

The equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the '==' operator is expected to check the actual object instances are same or not.

The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal. Here is an example that will help clarify this:

String obj1 = new String("xyz");

String obj2 = new String("xyz");

if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Java’s String class overrides the equals() method to compare the characters in a string. This means that the comparison between the 2 String objects returns true since they both hold the string “xyz”.

Monday, October 3, 2011

Arrays in Java

Background:

Suppose we have here three variables of type int with different identifiers for each variable.
int number1;
int number2;
int number3;

number1 = 1;
number2 = 2;
number3 = 3;

As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose.

Definition:
  • An array is a systematic arrangement of objects, usually in rows and columns.
  • An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
  • An array is a very common type of data structure where in all elements must be of the same data type. Once defined , the size of an array is fixed and cannot increase to accommodate more elements. The first element of an array starts with zero.
  • In Java and other programming languages, there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently. This type of variable is called an array. An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots.
Declaring Arrays:

Like all other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. One array cannot store both ints and Strings, for instance.

Like all other variables in Java an array must be declared. To declare an array, write the data type, followed by a set of square brackets[], followed by the identifier name.

Syntax:

<elementType>[] <arrayName>;
                   or
<elementType> <arrayName>[];

Here are some examples:

int[] k;
float[] yt;
String[] names;

This says that k is an array of ints, yt is an array of floats and names is an array of Strings. In other words you declare an array like you declare any other variable except that you append brackets to the end of the type.

You also have the option to append the brackets to the variable instead of the type.

int k[];
float yt[];
String names[];

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

byte[] rowvector, colvector, matrix[];
This declaration is equivalent to:
byte rowvector[], colvector[], matrix[][];
Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.
However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Array Instantiation:

After declaring, we must create the array and specify its length with a constructor statement. Declaring arrays merely says what kind of values the array will hold. It does not create them. Java arrays are objects, and like any other object you use the new keyword to create them. When you create an array, you must tell the compiler how many components will be stored in it.

Note:
Instantiation: In Java, this means creation
Constructor: In order to instantiate an object, we need to use a constructor for this. A constructor is a method that is called to create a certain object.

Arrays can be created using the new operator or by declaring a static initializer. The new operator specifies the size of the array.

Syntax:

<arrayName> = new <elementType>[<noOfElements>];

Example:

intArray = new int[10];     // Defines that intArray will store 10 integer values
int[] c, d;         // declare references to array c and d
c = new int [ 4 ];         // allocate memory for the 4 elements in array c
d = new int [ 125 ];     // allocate memory for the 125 elements in array d
byte[] b = new byte [ 100 ]; // declare and allocate memory for array b

An array intializer may be any arbitrary expression.

int c = 15;
int[] primes = { 1, 2, 3, 5, 7, 9, 11 };
int[] a = { 1, primes[2], c, (int)Math.pow(2,2) };

When memory is allocated for an array, the elements are automatically initialized to their default values: zero for all numeric primitive data types, false for boolean variables and null for references.

As with all objects, if the array reference (object reference) is assigned a null value, then the garbage collector will reclaim the dereferenced (unused) memory.

    Wednesday, February 23, 2011

    Introduction to Java

    What is Java:

    • Java is a computer programming language originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform.
    • It enables programmers to write computer instructions using English based commands, instead of having to write in numeric codes. 
    • It’s known as a “high-level” language because it can be read and written easily by humans. 
    • Like English, Java has a set of rules that determine how the instructions are written. 
    • These rules are known as its “syntax”. Once a program has been written, the high-level instructions are translated into numeric codes that computers can understand and execute.
    • The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities.
    • Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture.
    •  Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible.
    •  It is intended to let application developers "write once, run anywhere". Java is currently one of the most popular programming languages in use, and is widely used from application software to web