Removing white spaces

Method 1:
String s = "This is a sentence";
String s2 = s.trim();


Method 2:
String s = "This is a sentence";
String s2 = s.replaceAll("\\s", "");

Find Factorial of a number

public static int factorial(int number){
//base case
if(number == 0){
return 1;
}
return number*factorial(number -1);
}

(OR)

public static int factorial(int number){
int result = 1;
while(number != 0){
result = result*number;
number--;
}

return result;
}
}

Print Fibonacci Series

public static int fibonacci2(int number)
{
 if(number == 1 || number == 2)
{ return 1; }

 int fibo1=1, fibo2=1, fibonacci=1; 

for(int i= 3; i<= number; i++)
 fibonacci = fibo1 + fibo2;  //Fibonacci number is sum of previous two Fibonacci number 
 fibo1 = fibo2;
 fibo2 = fibonacci; 
}

 return fibonacci; //Fibonacci number 
}
}

(OR)

public static int fibonacci(int number)
{
 if(number == 1 || number == 2)
{ return 1; } 
return fibonacci(number-1) + fibonacci(number -2); //tail recursion 
}

Check if String Palindrome

We can check palindrome string by reversing string and checking whether it is equal to the original string or not.

checkIfPalindrome(String s)
{

StringBuilder s2 = new StringBuilder(s);
s2.reverse();

String rev_s2 = s2.toString();

if(s.equals(rev_s2))
{ return true; }
else
{ return false; }


}

(OR)

public class Palindrome {
public static void main(String[] args) {
String str = "OOLOO";
StringBuffer newStr =new StringBuffer();
for(int i = str.length()-1; i >= 0 ; i--) {
newStr = newStr.append(str.charAt(i));
}
if(str.equalsIgnoreCase(newStr.toString())) {
System.out.println("String is palindrome");
} else {
System.out.println("String is not palindrome");
}
}

}

Handler vs AsyncTask vs Thread

Handlers are background threads that provide you to communicate with the UI. Updating a progressbar for instance should be done via Handlers. Using Handlers you have the advantage of MessagingQueues, so if you want to schedule messages or update multiple UI elements or have repeating tasks.

AsyncTasks are similar, infact they make use of Handlers, but doesn't run in the UI thread, so its good for fetching data, for instance fetching webservices. Later you can interact with the UI.

Threads however can't interact with the UI, provide more "basic" threading and you miss all the abstractions of AsyncTasks. But ff you see the source code of AsyncTask and Handler, you will see their code purely in Java.

What does it mean ? It means no magic in AsyncTask or Handler. They just make your job easier as a developer. For example: If Program A calls method A(), method A() would run in a different thread with Program A.You can easily test by:

Thread t = Thread.currentThread();
int id = t.getId();

So, what is the difference ? AsyncTask and Handler are written in Java (internally use a Thread), so everything you can do with Handler or AsyncTask, you can achieve using a Thread too.

What Handler and AsyncTask really help you with? The most obvious reason is communication between caller thread and worker thread. (Caller Thread: A thread which calls the Worker Thread to perform some task.A Caller Thread may not be the UI Thread always). And, of course, you can communicate between two thread by other ways, but there are many disadvantages, for eg: Main thread isn't thread-safe (in most of time), in other words, DANGEROUS.

That is why you should use Handler and AsyncTask. They do most of the work for you, you just need to know what methods to override.

Difference Handler and AsyncTask:

Use AsyncTask when Caller thread is a UI Thread. This is what android document says:

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

I want to emphasize on two points:

1) Easy use of the UI thread (so, use when caller thread is UI Thread). 2) No need to manipulate handlers. (means: You can use Handler instead of AsyncTask, but AsyncTask is an easier option). There are many things in this post I haven't said yet, for example: what is UI Thread, of why it easier.

When you read Android document, you will see: Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue

They may seem strange at first.Just understand that, each thread has each message queue. (like a Todo List), and thread will take each message and do it until message queue empties. So, when Handler communicates, it just gives a message to caller thread and it will wait to process. (Handler can communicate with caller thread in safe-way)

Codes

Toast:
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),Toast.LENGTH_SHORT).show();
------------------------
Intents:
Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
startActivity(intent);
------------------------

Service

Most confusion about the Service class actually revolves around what it is not:

-A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
-A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Thus a Service itself is actually very simple, providing two main features:
A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.

When a Service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call its onCreate() and any other appropriate callbacks on the main thread. It is up to the Service to implement these with the appropriate behavior, such as creating a secondary thread in which it does its work.

Service Lifecycle :
There are two reasons that a service can be run by the system.

If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them. See the linked documentation for more detail on the semantics.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder). Usually the IBinder returned is for a complex interface that has been written in aidl. A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().