Tuesday, August 21, 2012

Explain the difference between abstract class and interfaces with an example for each.


Explain the difference between abstract class and interfaces with an example for each.

The differences between abstract class and interface are as follows:
Abstract Class
Interface
Can have abstract methods and concrete methods
Can have only method signatures and static final members
All methods are not by default public
All methods by default abstract and public
An abstract class can extend another abstract class
An interface can extend another interface but not a class
The extended class can override the methods of its super class and its hierarchy
An implementing class can implement multiple interfaces
All abstract methods must have abstract access modifier
All methods in an interface must not have abstract access modifier
The following examples illustrate the differences:
abstract class Shape
{
       abstract void area();
       abstract void perimeter();
       void someMethod() // concrete method
       {
              ..
       }
}

interface Shape
{
       void area();
       void perimeter();
}


// amazon ebay shopbob.com hotels.com canon newegg.com 

Android Interview Questions and Answers


Android Interview Questions and Answers
Describe Android Application Architecture.
Android Application Architecture has the following components:
• Services – like Network Operation
• Intent – To perform inter-communication between activities or services
• Resource Externalization – such as strings and graphics
• Notification signaling users – light, sound, icon, notification, dialog etc.
• Content Providers – They share data between applications

Describe a real time scenario where android can be used?
Imagine a situation that you are in a country where no one understands the language you speak and you can not read or write. However, you have mobile phone with you.

With a mobile phone with android, the Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.
What’s the difference between file, class and activity in android?
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.

What is a resource?
A user-supplied XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.

How will you record a phone call in Android? How to get a handle on Audio Stream for a call in Android?
Permissions.PROCESS_OUTGOING_CALLS: Allows an application to monitor, modify, or abort outgoing calls.

How is nine-patch image different from a regular bitmap?
It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.

What is an action?
A description of something that an Intent sender desires.

What is activity?
A single screen in an application, with supporting Java code.

Can I write code for Android using C/C++?
Yes, but need to use NDK
Android applications are written using the Java programming language. Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.
Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.
Android only supports applications written using the Java programming language at this time.

What is an URIs?
Android uses URI strings both for requesting data (e.g., a list of contacts) and for requesting actions (e.g., opening a Web page in a browser). Both are valid URI strings, but have different values. All requests for data must start with the string “content://”. Action strings are valid URIs that can be handled appropriately by applications on the device; for example, a URI starting with “http://” will be handled by the browser.

What is a Service ?
A class that runs in the background to perform various persistent actions, such as playing music or monitoring network activity.

What is a Theme ?
A set of properties (text size, background color, and so on) bundled together to define various default display settings. Android provides a few standard themes, listed in R.style (starting with “Theme_”).

What is android?
Android is a stack of software for mobile devices which has Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM executes Java language?s byte code which later transforms into .dex format files.

What are the advantages of Android?
The following are the advantages of Android:

* The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like AT&T and Orange will be broken by Google Android.
* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized
* Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.
Components can be reused and replaced by the application framework.
*Optimized DVM for mobile devices
*SQLite enables to store the data in a structured manner.
*Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies
*The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.

Features of Android
 Application framework enabling reuse and replacement of components
§
 Dalvik virtual machine optimized for mobile devices
§
 Integrated browser based on the open source WebKit engine
§
 Optimized graphics powered by a custom 2D graphics library; 3D
§ graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
 SQLite for structured data storage
§
 Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
§
 GSM Telephony (hardware dependent)
§
 Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
§
 Camera, GPS, compass, and accelerometer (hardware dependent)
§
 Rich development environment including a device emulator, tools for
§ debugging, memory and performance profiling, and a plugin for the Eclipse IDE.
Explain about the exceptions of Android?
The following are the exceptions that are supported by Android
* InflateException : When an error conditions are occurred, this exception is thrown
* Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown
* SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS
* WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.

Describe the APK format.
The APK file is compressed the AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.

What is .apk extension?
The extension for an Android package file, which typically contains all of the files related to a single Android application. The file itself is a compressed collection of an AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.

What is .dex extension
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language

What is an adb ?
Android Debug Bridge, a command-line debugging application shipped with the SDK. It provides tools to browse the device, copy tools on the device, and forward ports for debugging.

What is an Application ?
A collection of one or more activities, services, listeners, and intent receivers. An application has a single manifest, and is compiled into a single .apk file on the device.

What is a Content Provider ?
A class built on ContentProvider that handles content query strings of a specific format to return data in a specific format. See Reading and writing data to a content provider for information on using content providers.

What is a Dalvik ?
The name of Android’s virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included “dx” tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.

What is an DDMS
Dalvik Debug Monitor Service, a GUI debugging application shipped with the SDK. It provides screen capture, log dump, and process examination capabilities.

What is Drawable?
A compiled visual resource that can be used as a background, title, or other part of the screen. It is compiled into an android.graphics.drawable subclass.

What is an Intent?
A class (Intent) that contains several fields describing what a caller would like to do. The caller sends this intent to Android’s intent resolver, which looks through the intent filters of all applications to find the activity most suited to handle this intent. Intent fields include the desired action, a category, a data string, the MIME type of the data, a handling class, and other restrictions.

What is an Intent Filter ?
Activities and intent receivers include one or more filters in their manifest to describe what kinds of intents or messages they can handle or want to receive. An intent filter lists a set of requirements, such as data type, action requested, and URI format, that the Intent or message must fulfill. For Activities, Android searches for the Activity with the most closely matching valid match between the Intent and the activity filter. For messages, Android will forward a message to all receivers with matching intent filters.

What is an Intent Receiver?
An application class that listens for messages broadcast by calling Context.broadcastIntent

What is a Layout resource?
An XML file that describes the layout of an Activity screen.

What is a Manifest ?
An XML file associated with each Application that describes the various activies, intent filters, services, and other items that it exposes.

What Virtual Machine Android runs on?
Dalvik virtual machine

What is a Broadcast receivers?
A broadcast receiver is a component that does nothing but receive and react to broadcast announcements.
For example, announcements that the timezone has changed, that the battery is low or that the user changed a language preference.
All receivers extend the BroadcastReceiver base class.
Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive,
or they may use the NotificationManager to alert the user like(flashing the backlight, vibrating the device, playing a sound)
How is nine-patch image different from a regular bitmap?
It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.
How to Translate in android
The Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.
What is a Sticky Intent?
sendStickyBroadcast() performs a sendBroadcast (Intent) known as 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).

Example for sticky broadcast
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.
Activity Lifecycle
Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.
An activity has essentially four states:
  • If an activity in the foreground of the screen (at the top of the stack), it is active or running.
  • If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
  • If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
  • If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.
The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.

Describe a real time scenario where android can be used

Imagine a situation that you are in a country where no one understands the language you speak and you can not read or write. However, you have mobile phone with you.
With a mobile phone with android, the Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.

What are the differences between a domain and a workgroup?

In a domain, one or more computer can be a server to manage the network. On the other hand in a workgroup all computers are peers having no control on each other. In a domain, user doesn’t need an account to logon on a specific computer if an account is available on the domain. In a work group user needs to have an account for every computer.
In a domain, Computers can be on different local networks. In a work group all computers needs to be a part of the same local network. 
How does the AOSP relate to the Android Compatibility Program?
AOSP stands for Android Open-source project that maintains Android software and keep track of the new versions. It can be used for any purpose including the devices that are not compatible with other devices. It is related to the Android Compatibility Program as it defines the implementation of Android that is compatible with the third party apps.
What are the different Storage Methods in android?
Android provides many options for storage of persistent data. It provides the solution according to your need. The storages which have been provided in Android are as follows:-
Shared Preferences: Store private primitive data in key-value pairs
Internal Storage: Store private data on the device memory.
External Storage: Store public data on the shared external storage.
SQLite Databases: Store structured data in a private database.
Network Connection: Store data on the web with your own network server.

What is localization and how to achieve?
Localization is a way of representing the products in different languages. Android is an operating system which runs in many regions, so to reach different users localization is a must. Localization in Android can be achieved by incorporating different languages in the application which you are using. To do this knowledge of Java, XML elements, Activity lifecycle and general principles of internationalization and localization are required.
Describe Briefly the Android Application Architecture.
Android application architecture allows the simplification and reuse of any application. It provides a better way to publish the capabilities of the application so that any other application can make good use of those capabilities. This architecture includes the following components:
Intent: perform some operation on some activity and service
Resource Externalization - such as strings and graphics
Notification signaling users - light, sound, icon etc.
Content Providers – sharing of data between various applications
What dialog boxes are supported in android?
There are 4 dialog boxes which have been supported by Android. These are as follows:
AlertDialog: it supports 0 to 3 buttons with a list of selectable elements that includes check boxes and radio buttons.
-ProgressDialog: it displays the progress of any dialog or application. It is an extension of AlertDialog and supports adding buttons.
-DatePickerDialog: it is used to give provision to the user to select the date
- TimePickerDialog: it is used to give provision to the user to select the time

What is APK format in Android? How to make an APK file?
APK termed as Application package file is a format that is used to distribute and install the application software for android, and middleware on the android operating system. To make an APK file, first android is compiled and then all of its parts are grouped in one file termed as package. The package consists of the entire program’s code (.dex files), resources, manifest file etc. The file is saved with .apk extension.
What is a Sticky Intent?
Intent is basically an abstract description of an operation that has to be performed for communication. Sticky Intent is also a type of intent which allows the communication between a function and a service. For example: sendStickyBroadcast() performs send Broadcast(Intent) which stays even after the broadcast is complete. It helps in retrieving the data quickly. The message ACTION_BATTERY_CHANGED of an operating system is an example of it.
How to Translate in Android?
Android uses Google translator to translate data from one language into another language using XAMPP. XAMPP is used to transmit the data. The steps which have to be followed are: Type the message in your language, go to the language setting, a list will be displayed there, select the language from the list to convert your text.

Does android support jar applications?

You can't install jar files on Andriod devices but you can include jar as library in your application.

What is the TTL (Time to Live)? Why is it required?

Time to live (TTL) is a mechanism that limits the lifespan of data in a computer or network. TTL may be implemented as a counter or timestamp attached to or embedded in the data. Once the prescribed event count or timespan has elapsed, data is discarded. In computer networking, TTL prevents a data packet from circulating indefinitely. In computing applications, TTL is used to improve performance of caching or improve privacy.
Bundle
A mapping from String values to various Parcelable types.
AsyncTask
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.An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
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 orthere 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().
Context
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
Notification
A class that represents how a persistent notification is to be presented to the user using the NotificationManager. The Notification.Builder has been added to make it easier to construct Notifications.

Hello world in eclipse Or How to create class file in eclipse


Right click on the source folder then select new, then click class then next popup will be show.

Type package name just like com.swain.cell.java.example.
Type class name just like Hello(Class name should be stating with capital letter).
Then finish.  

// amazon ebay shopbob.com hotels.com canon newegg.com 

Hello.java

package com.swain.cell.java.example;

public class Hello {

       /**
        * @param args
        */
       public static void main(String[] args) {
              // TODO Auto-generated method stub
              System.out.println("hello world");

       }

}

Right click on the programme then popup will be show then select run as then java Application.


Output

Hello world




How to create java project in eclipse


Select file menu then select new then select project then another popup will be show.  

// amazon ebay shopbob.com hotels.com canon newegg.com 



Type project name then click finish.


This is a java project folder structure.



Monday, August 20, 2012

String palindrome


Output:

StringPalindrome.java

package com.swain.cell;

public class StringPalindrome {
       public static void main(String args[])
          {
             String original="Himanshu";
             String rev="";
                      
             int length = original.length();
        
             for ( int i = length - 1 ; i >= 0 ; i-- )
                rev = rev + original.charAt(i);
        
             if (original.equals(rev))
                System.out.println(original+" is a palindrome.");
             else
                System.out.println(original+" is not a palindrome.");
        
          }
}



// amazon ebay shopbob.com hotels.com canon newegg.com 

how to count selected Character from a sentence in java


Output:

C contents  3 times.

DuplicateCharacter.java

package com.swain.cell;

import java.util.HashMap;

public class DuplicateCharacter {

       /**
        * @param args
        */
       public static void main(String[] args) {
              // TODO Auto-generated method stub

        String str = "Character duplicate word example java";
        char selectedchar='C';
        char ch1[]=str.toUpperCase().toCharArray();
        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        for(int i=0; i<ch1.length; i++)
        {
            char ch=ch1[i];
            hm.put(ch,(hm.get(ch)==null?1:hm.get(ch)+1));
        }
      
        System.out.println(selectedchar+" contents  " + hm.get(selectedchar)+ " times.");
       
       
   
       }

}


// amazon ebay shopbob.com hotels.com canon newegg.com  Google

how to count selected word in string using java


Output:

java contents  3 times.

package com.swain.cell;

import java.util.HashMap;
import java.util.StringTokenizer;

public class DuplicateString {

       /**
        * @param args
        */
       public static void main(String[] args) {
              // TODO Auto-generated method stub

        String str = "java java android android java example";
        String selectedword="java";
        
        StringTokenizer t = new StringTokenizer(str);
        HashMap<String,Integer> hms=new HashMap<String,Integer>();
       
              while(t.hasMoreTokens())
              {
                    
                     String word = t.nextToken();
                      hms.put(word,(hms.get(word)==null?1:hms.get(word)+1));
             
              }
              System.out.println(selectedword+" contents  " + hms.get(selectedword)+ " times.");
       
   
       }

}


Check here video.




How to count duplicate characters from a sentence in java



Output :

DuplicateCharacter.java

package com.swain.cell;

import java.util.HashMap;

public class DuplicateCharacter {

       /**
        * @param args
        */
       public static void main(String[] args) {
              // TODO Auto-generated method stub

        String str = "Character duplicate word example java";
        char ch1[]=str.toCharArray();
        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        for(int i=0; i<ch1.length; i++)
        {
            char ch=ch1[i];
            hm.put(ch,(hm.get(ch)==null?1:hm.get(ch)+1));
        }
      
        System.out.println("No of Characters are : "+hm.toString());
       
       
   
       }

}

How to Calculate the Future Investment Value of Investment.

Below java program for calculate future investment value. Here calculate s using the formula futureInvestmentValue =investmentAmount x (...