Android and Java Interview questions----All the Best

JAVA QUESTIONS
###############
Q) . What is the interface,whr we can use interface and abstract class ,what is the limitation of interface
A)
Advantages:

    Interfaces are mainly used to provide polymorphic behavior.
    Interfaces function to break up the complex designs and clear the dependencies between objects

Disadvantange:
Java interfaces are slower and more limited than other ones.
One disadvantage of interfaces is that one you publish them to other coders outside your own control, they represent a public commitment which can be difficult to change later. You don't know who else is using the interface and you don't know how, so you can't just add a new method to the interface without risking breaking the code of existing clients (if/when they upgrade). In comparison, if you'd used an abstract or concrete class, you could just add a new concrete method with no problems (usually).
This disadvantage isn't a reason to abandon interfaces, but it is a reason to design your interfaces carefully

1.what is theread.how we can use theread,which one is beter one,what will happen if a resoursae is in sleep and i called notify,how come a resource will be theread save.
A :  Thread is nothing but a unit of execution.
we can use theread in 2 way one by extending thread and implementing runnable
Implementing runnable is the better option as it according to OOPs.

2.what is serialization how to use this.

3.what is the difference bet hasmap and hastable , how to sort a sorted list in beter way.

4.how to make out 4 liter from 3lit and 5lit

5.which one used in java pass by value or pass by reference

6.what is final, finalize and finally. how to use finalize.

7.is finally work after return.
A: yes.

8.what is the diff between block syncronization and method syncronization.

A: if you go for synchronized block it will lock a specific object.
    if you go for synchronized method it will lock all the objects.
    if we want to invoke a critical method which is in a class whose access is not available then synchronized block is used. Otherwise synchronized method can be used.
   Synchronized methods are used when we are sure all instance will work on the same set of data through the same function Synchronized block is used when we use code which we cannot modify ourselves like third party jars etc
 
//Synchronized block

class A
{ public void method1() {...} }
class B
{
public static void main(String s[])
{ A objecta=new A();
A objectb=new A();
synchronized(objecta){objecta.method1();}
objectb.method1(); //not synchronized
}
}


//synchronized method
class A
{ public synchronized void method1() { ...}
}
class B
{
public static void main(String s[])
{
A objecta=new A();
A objectb =new A();
objecta.method1(); objectb.method2();

}
}


9.what are the methods present in object class.

10.how to store object kind of data in array list

11. what are the types of exception and what is compile time and run time
========================
1: How many constructors created by compilers,
 
Ans: 2 constructors, 1 is default constructor
     & another is copy constructor.

2: If you you call destroy() method inside init()
   method what'll happen ?

3: what are the join operations in database ?

4: if we can't create an instance of abstract class
   then why we need constructor of abstract class ?

5: if u have declared try block & finally block,
   how u block ur control not to execute finally block ?

Ans: System.exit();

6: Singleton class hw works , describe why we need it ?
   read the doc.
A : This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.
The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.
Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application.
Example:
To implement this design pattern we need to consider the following 4 steps:
Step 1: Provide a default Private constructor

public class SingletonObjectDemo {

// Note that the constructor is private
private SingletonObjectDemo() {
// Optional Code
}
}

Step 2: Create a Method for getting the reference to the Singleton Object

public class SingletonObjectDemo {

private static SingletonObject singletonObject;
// Note that the constructor is private
private SingletonObjectDemo() {
// Optional Code
}
public static SingletonObjectDemo getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonObjectDemo();
}
return singletonObject;
}
}

We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized SingletonObjectDemo getSingletonObject()

It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.

class SingletonClass {

private static SingletonClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private SingletonClass() {
// Optional Code
}
public static synchronized SingletonClass getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonClass();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

public class SingletonObjectDemo {

public static void main(String args[]) {
// SingletonClass obj = new SingletonClass();

                //Compilation error not allowed
SingletonClass obj = SingletonClass.getSingletonObject();
// Your Business Logic
System.out.println("Singleton object obtained");
}
}




7: Write Algorithm for LinkedList operaations ?

8: See all the Searching & Sorting Algorithms ?

9: JIT compiler in java ? read the doc.

10: Rest question are common as u'll prepare for
    those.


ANDROID QUESTIONS
#################
11. what is the diff bet JVM and DVM.
A. JVM executes in interpreter formate and DVM in case register formate.

12.Why work with worker thread is not fit to android?
A.
public void onClick(View v) {
  new Thread(new Runnable() {
    public void run() {
      Bitmap b = loadImageFromNetwork();
      mImageView.setImageBitmap(b);
    }
  }).start();
}
it violates the single-threaded model for the UI: the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread. In this piece of code above, the ImageView is manipulated on a worker thread, which can cause really weird problems

13.
1: if u hv declared 3 Activities , thn hw u move from 3rd activity 2 1st , without thro 2nd activity ?

Ans: call activity 'A' with FLAG_ACTIVITY_CLEAR_TOP. startActivity(new Intent(this, UI.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

2: If you press a number hw it's calls to the destination,describe ?

Ans: for SMS:
SmsManager sman = SmsManager.getDefault();sman.sendTextMessage(num, null, msg, null, null);
other way:
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse( "sms:" + num ));//if num we will not provide then it will give the dial with out number.
startActivity(intent);
For CALL:
//call dial program
Intent it = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:xxxxxx"));
startActivity(it);

3: how media player works in android, for that what u'll, do describe ?

Ans:  using the MediaPlayer or JetPlayer APIs. You can also record audio, video and take pictures using the MediaRecorder and Camera APIs if supported by the device hardware.

4: Hw to maintain session in android ?read the doc.

5: Hw to make android apps secured ?

Ans: by maintaing session & send data using encription.read the doc.

6: why we use AndroidManifest.xml file ?read the doc.

7: Hw we use Handler & Asynctask in Android, describe ? read the doc .

8: Hw u use a Progressbar & Progress dialog in android, describe ? read the doc .

9: If your screen orientation changed while viewing a dialog ?

Ans: the activity'll restarted, for that u hv 2 save the activity state by overriding onRetainNonConfigurationInstance() method.& get the data by overriding getLastNonConfigurationInstance() method. & if u don't want 2 restart ur activity then u hv 2 Override onConfigurationChanged() method.& in Manifest file declare a tag.

10: Hw activity maintains it's stack, say details ? read the doc.

11: describe hw IPC works in android ? read the doc .

12: Why serialization needs  & hw it works ? read the doc.

11: what are the diff parsing used in android ? what is sax and dom and android pullparser and what is the difference between them.

A : SAX is an event based parser, whereas DOM is a tree model parser.
-SAX
• Parses node by node
• Doesn’t store the XML in memory
• We cant insert or delete a node
• SAX is an event based parser
• SAX is a Simple API for XML
• doesn’t preserve comments
• SAX generally runs a little faster than DOM

DOM
• Stores the entire XML document into memory before processing
• Occupies more memory
• We can insert or delete nodes
• Traverse in any direction.
• DOM is a tree model parser
• Document Object Model (DOM) API
• Preserves comments
• SAX generally runs a little faster than DOM

12: Hw you create a custom listview in android ?

13: Back button handle in android ?
   Ans: override the onKeyBack() or onBackPressed() method  .

14: describe android lifecycle methods? read the doc.

15: Hw to create custom Broadcast Receiver in android ?

17: what is ndk. what is the comands in ndk. how to use ndk in java
..Make a folder called jni in the root of the project (right-click the project node, New – Folder). Create a file called Android.mk (New – File) within that folder with the following contents:


LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

# Here we give our module name and source file(s)
LOCAL_MODULE    := ndkfoo
LOCAL_SRC_FILES := ndkfoo.c

include $(BUILD_SHARED_LIBRARY)

Except the module name (ndkfoo), treat everything in that file as magic. You can go deeper into Unix Makefiles later if you want.

The Android.mk file is important for the NDK build process to recognize your NDK modules. In our case we named our module ndkfoo and told the build tool that it consists of one source file named ndkfoo.c. Let’s create it in the same jni folder:

Here’s the content for you to copy and paste:

#include <string.h>
#include <jni.h>

jstring Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
  return (*env)->NewStringUTF(env, "Hello from native code!");
}

Android actually uses the standard Java way to communicate with native code called JNI (Java Native Interface). It defines conventions and mechanisms that Java code and C/C++ code use to interact. You can read more about JNI in the official Sun docs, but for now you might notice that the name of the C function is not just random – it matches the Java class name. In addition, what the function does is it uses the JNIEnv object to create a Java string from a literal, and returns the string to the caller.
As you can notice, a successful run of the ndk-build tool will create an .so file in a new folder called libs that will be created in your project root (if it’s not there yet). The .so file is the binary library that will be included into the application .apk package and will be available for the Java code of the app to link to. You just need to hit F5 in Eclipse after selecting the project root to update the Eclipse project with the changes you did in the Cygwin console.

You have to repeat the ndk-build command every time you modify the C/C++ source of your NDK code. Eclipse ADT does not support NDK so you need to do it from the Cygwin console. Don’t forget to refresh Eclipse every time!

Anyway, the NDK part is actually finished. What we need to do now is to change the Java code of the NdkFooActivity class to use the NDK code:

package com.mindtherobot.samples.ndkfoo;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

public class NdkFooActivity extends Activity {

  // load the library - name matches jni/Android.mk
  static {
    System.loadLibrary("ndkfoo");
  }

  // declare the native code function - must match ndkfoo.c
  private native String invokeNativeFunction();

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // this is where we call the native code
        String hello = invokeNativeFunction();

        new AlertDialog.Builder(this).setMessage(hello).show();
    }
}


18: what is the difference between file, class and activity.

A : File - It is a block of arbitrary information, or resource for storing information. It can be of any type

    Class - Its a compiled form of .Java file . Android finally used this .class files to produce an executable apk

    Activity - An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view


19:what are process by which we can move from one activity to another activity.

20:what is the difference between theread and service and async task

A : A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class.

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.


22: how to sync with google the contacts?

23: what is shared preference ?? can we acess from other application the shared pereference
A : Store private primitive data in key-value pairs
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);

24: if we start parent theread and 2 chield theread as parent theread dead is the child theread will dead.
A : yes the main thread in java killed all other thread before destoy.. and demon thread is the thread which deals with back gound work it associated with the user normal thread and as normal thread works finished it also remove.Garbage collector runs as a daemon thread to recalim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly.

25: what is the difference between single top ,single task , single instance and standard.
A : standard - always create multiple instance instance of the activity.
singleTop - conditionally create ,if the activity is not in the top of the stack.
singleTask - its not create the multiple instance . instead it will always create the root activity and othes will intent throught it.
singleInstance - its not create the multiple instance . but create the new instance in the stack whre no other activity is allowed.

27: if in ur application net work failed what ucan do for sync?

28: how to use json in android?

29: what is ddms and what are the tools available in ddms

30: what is life cycle of  UI thread.

31: waht are the types of intents are there??

32: what happen on configuration change??

33: what is ANR
A: In Android, the system guards against applications that are insufficiently responsive for a period of time by displaying a dialog to the user, called the Application  Not Responding (ANR) dialog.Generally, the system displays an ANR if an application cannot respond to user input.

In Android, application responsiveness is monitored by the Activity Manager and Window Manager system services. Android will display the ANR dialog for a particular application when it detects one of the following conditions:

    No response to an input event (e.g. key press, screen touch) within 5 seconds
    A BroadcastReceiver hasn't finished executing within 10 seconds


34: what are the api used in gps collector.
A :

35: how u are syncing the chat .

36: What is the Sticky Intent?

A : sendStickyBroadcast() performs a sendBroadcast (Intent) that is "sticky," i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver (BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast (Intent).

One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver () for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

37 : What is pending intent and its use ??

A : By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself (with the same permissions and identity). As such, you should be careful about how you build the PendingIntent: often, for example, the base Intent you supply will have the component name explicitly set to one of your own components, to ensure it is ultimately sent there and nowhere else.

A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it. If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token if that is still valid, and can thus call cancel() to remove it.

=====================================================
Explane the different life times of an activity?
How will you pass one object from one activity to other?
conditions for considering a process is foreground?
How can you include code which is written in c to your android application?
Which all are the arguments in a JNI method and what is the use of each one.
Do you need to explicitely allocate memory for executing a method in JNI.
Which all are the data types in JNI and which all data types need memory allocation?
Gave some methode signature in Java and asked to give the JNI methode signature?
From where will you allocate memory , from Java or C?
From where will you release memory from Java or C?
Can you release a memory allocate in C from Java?
You have some data in your application youn want share that to another application Give me the steps will will follow?
List all the layouts and situations for each layouts to be used?
How will you give weigts in linear layout?
Gave linear layout components size in percentage and asked to give weights?
What is the difference of frame layout from other layouts?
Gave some UI and asked to select layout and list all the params for each components (button , text box ..etc) which you will provide to implement the puticular layout that should be positioned same in all the devices?
In which situations you will use thread AsyncTask and message handling. ?
What is the difference between Async task and message handling?
How will you parse xml file?
Which xml parser did you use inyour project
What all are the basic steps you need to follow for supporting multiple screens?
Which project management methedology you are following?
Have you ever created project designing diagram?

1.Activity life cycle
2.Asynctask
3Thread & Handlers
4.content provider & resolver
5.All project and Flow(High-level design)
6.Android architecture.
7.synclml protocols

Comments

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams

Core Java -----Question and Answers