What is thread in Java.

What is thread in Java.

Thread is a program in execution. All Java programs have at least one thread, known as the main thread, which is created by the JVM at the program’s start, when the main() method is invoked with the main thread. In Java, creating a thread is accomplished by implementing an interface and extending a class. Every Java thread is created and controlled by the java.lang.Thread class.

When a thread is created, it is assigned a priority. The thread with higher priority is executed first, followed by lower-priority threads. The JVM stops executing threads under either of the following conditions:
  • If the exit method has been invoked and authorized by the security manager

  • All the daemon threads of the program have died
Explanation of oops concepts

Explanation of oops concepts

Object means a real word entity such as pen, chair, table etc.Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:
  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
How to load pdf file in your android application

How to load pdf file in your android application

WebView webview = (WebView) findViewById(R.id.webview);

webview.getSettings().setJavaScriptEnabled(true);

webview.getSettings().setBuiltInZoomControls(true);
webview.loadUrl("https://docs.google.com/gview?embedded=true&url=<PDF_COMPLETE_URL>");

webview.setWebViewClient(new WebViewClient() {
           @Override
           public void onPageFinished(WebView view, String url) {
                            
            }
});
Webview in android

Webview in android

WebView is a view that display web pages inside your application. You can also specify HTML string and can show it inside your application using WebView. WebView makes turns your application to a web application.

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/webview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
/>
WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("http://www.google.com");

If you click on any link inside the webpage of the webview, that page will not be loaded inside your webview so in that case we need to extend our class from WebViewClient and override its method.

private class MyBrowser extends WebViewClient {
   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String url) {
      view.loadUrl(url);
      return true;
   }
}
What is intent?

What is intent?

It is a kind of message or information that is passed to the components. It is used to launch an activity, display a web page, send sms, send email etc. There are two types of intents in android:
  1. Implicit Intent : It is used to invoke the system components.
  2. Explicit Intent : It is used to invoke the activity class.
Java 7 Features

Java 7 Features

1. Strings in Switch:

public void testStringInSwitch(String param){
       final String JAVA5 = "Java 5";
       final String JAVA6 = "Java 6";
       final String JAVA7 = "Java 7";
       switch (param) {
           case JAVA5:
               System.out.println(JAVA5);
               break;
           case JAVA6:
               System.out.println(JAVA6);
               break;
           case JAVA7:
               System.out.println(JAVA7);
               break;
       }
   }
 
2. Binary Literals:

public void testBinaryIntegralLiterals(){
        int binary = 0b1000; //2^3 = 8
        if (binary == 8){
            System.out.println(true);
        } else{
            System.out.println(false);
        }
}

3. Underscore Between Literals:

public void testUnderscoresNumericLiterals() {
    int oneMillion_ = 1_000_000; //new
    int oneMillion = 1000000;
    if (oneMillion_ == oneMillion){
        System.out.println(true);
    } else{
        System.out.println(false);
    }
}

4. Diamond Syntax:

public void testDinamond(){
    List list = new ArrayList<>();
    Map> map = new HashMap<>();
}


5. Multi-Catch Similar Exceptions:

public void testMultiCatch(){
    try {
        throw new FileNotFoundException("FileNotFoundException");
    } catch (FileNotFoundException | IOException fnfo) {
        fnfo.printStackTrace();
    }
}


6. Try with Resources:

public void testTryWithResourcesStatement() throws FileNotFoundException, IOException{
    try (FileInputStream in = new FileInputStream("java7.txt")) {
        System.out.println(in.read());
    }
}  

Difference between path band classpath in Java

Difference between path band classpath in Java

1).Path is an environment variable which is used by the operating system to find the executables.

Classpath is an environment variable which is used by the Java compiler to find the path, of classes.ie in J2EE we give the path of jar files.


2).PATH is nothing but setting up an environment for operating system. Operating System will look in this PATH for executables.

Classpath is nothing but setting up the environment for Java. Java will use to find compiled classes

3).Path refers to the system while classpath refers to the Developing Envornment.

In path we set the path of executables while in
classpath we set path of jars for compiling classes.
Random String Generation in Java

Random String Generation in Java

import java.util.Random;

public class RandomStringGen {


private static final String CHAR_LIST =
       "1234567890";
   private static final int RANDOM_STRING_LENGTH = 4;
   
   /**
    * This method generates random string
    * @return
    */
   public String generateRandomString(){
       
       StringBuffer randStr = new StringBuffer();
       for(int i=0; i<RANDOM_STRING_LENGTH; i++){
           int number = getRandomNumber();
           char ch = CHAR_LIST.charAt(number);
           randStr.append(ch);
       }
       return randStr.toString();
   }
   
   /**
    * This method generates random numbers
    * @return int
    */
   private int getRandomNumber() {
       int randomInt = 0;
       Random randomGenerator = new Random();
       randomInt = randomGenerator.nextInt(CHAR_LIST.length());
       if (randomInt - 1 == -1) {
           return randomInt;
       } else {
           return randomInt - 1;
       }
   }
   

}

Run task periodically in Java

Run task periodically in Java

Schedular Task :

For this functionality,

You should create a class extending TimerTask(available in java.util package). TimerTask is a abstract class.
Write your code in public void run() method that you want to execute periodically.
Insert below code in your Main class.

import java.util.TimerTask;
import java.util.Date;
/**
 * 
 * @author Dhinakaran P.
 */
// Create a class extends with TimerTask
public class ScheduledTask extends TimerTask {

Date now; // to display current time

// Add your task here
public void run() {
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}

Run Scheduler Task :

A class to run above scheduler task.

Instantiate Timer Object Timer time = new Timer();
Instantiate Scheduled Task class Object ScheduledTask st = new ScheduledTask();
Assign scheduled task through Timer.shedule() method.
import java.util.Timer;

/**
 * 
 * @author Dhinakaran P.
 */

//Main class
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {

Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create Repetitively task for every 1 secs

//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
Output:

Execution in Main Thread....0
Time is :Tue Jun 19 14:21:42 IST 2012
Time is :Tue Jun 19 14:21:43 IST 2012
Execution in Main Thread....1
Time is :Tue Jun 19 14:21:44 IST 2012
Time is :Tue Jun 19 14:21:45 IST 2012
Execution in Main Thread....2
Time is :Tue Jun 19 14:21:46 IST 2012
Time is :Tue Jun 19 14:21:47 IST 2012
Execution in Main Thread....3
Time is :Tue Jun 19 14:21:48 IST 2012
Time is :Tue Jun 19 14:21:49 IST 2012
Execution in Main Thread....4
Time is :Tue Jun 19 14:21:50 IST 2012
Time is :Tue Jun 19 14:21:51 IST 2012
Application Terminates
Time is :Tue Jun 19 14:21:52 IST 2012
Concurrency API in Java

Concurrency API in Java

The Concurrency API introduces the concept of an ExecutorService as a higher level replacement for working with threads directly. Executors are capable of running asynchronous tasks and typically manage a pool of threads, so we don't have to create new threads manually. All threads of the internal pool will be reused under the hood for revenant tasks, so we can run as many concurrent tasks as we want throughout the life-cycle of our application with a single executor service.

This is how the first thread-example looks like using executors:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
    String threadName = Thread.currentThread().getName();
    System.out.println("Hello " + threadName);
});

// => Hello pool-1-thread-1

The class Executors provides convenient factory methods for creating different kinds of executor services. In this sample we use an executor with a thread pool of size one.

The result looks similar to the above sample but when running the code you'll notice an important difference: the java process never stops! Executors have to be stopped explicitly - otherwise they keep listening for new tasks.

An ExecutorService provides two methods for that purpose: shutdown() waits for currently running tasks to finish while shutdownNow() interrupts all running tasks and shut the executor down immediately.

This is the preferred way how I typically shutdown executors:

try {
    System.out.println("attempt to shutdown executor");
    executor.shutdown();
    executor.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
    System.err.println("tasks interrupted");
}
finally {
    if (!executor.isTerminated()) {
        System.err.println("cancel non-finished tasks");
    }
    executor.shutdownNow();
    System.out.println("shutdown finished");
}
Android Permission with detailed description

Android Permission with detailed description

A basic Android application has no permissions associated with it by default, meaning it cannot do anything that would adversely impact the user experience or any data on the device. To make use of protected features of the device, you must include one or more <uses-permission> tags in your app manifest.

List of android permission:


StringACCESS_CHECKIN_PROPERTIESAllows read/write access to the "properties" table in the checkin database, to change values that get uploaded.
StringACCESS_COARSE_LOCATIONAllows an app to access approximate location.
StringACCESS_FINE_LOCATIONAllows an app to access precise location.
StringACCESS_LOCATION_EXTRA_COMMANDSAllows an application to access extra location provider commands.
StringACCESS_NETWORK_STATEAllows applications to access information about networks.
StringACCESS_NOTIFICATION_POLICYMarker permission for applications that wish to access notification policy.
StringACCESS_WIFI_STATEAllows applications to access information about Wi-Fi networks.
StringACCOUNT_MANAGERAllows applications to call into AccountAuthenticators.
StringADD_VOICEMAILAllows an application to add voicemails into the system.
StringBATTERY_STATSAllows an application to collect battery statistics
StringBIND_ACCESSIBILITY_SERVICEMust be required by an AccessibilityService, to ensure that only the system can bind to it.
StringBIND_APPWIDGETAllows an application to tell the AppWidget service which application can access AppWidget's data.
StringBIND_CARRIER_MESSAGING_SERVICEThis constant was deprecated in API level 23. Use BIND_CARRIER_SERVICES instead
StringBIND_CARRIER_SERVICESThe system process that is allowed to bind to services in carrier apps will have this permission.
StringBIND_CHOOSER_TARGET_SERVICEMust be required by a ChooserTargetService, to ensure that only the system can bind to it.
StringBIND_DEVICE_ADMINMust be required by device administration receiver, to ensure that only the system can interact with it.
StringBIND_DREAM_SERVICEMust be required by an DreamService, to ensure that only the system can bind to it.
StringBIND_INCALL_SERVICEMust be required by a InCallService, to ensure that only the system can bind to it.
StringBIND_INPUT_METHODMust be required by an InputMethodService, to ensure that only the system can bind to it.
StringBIND_MIDI_DEVICE_SERVICEMust be required by an MidiDeviceService, to ensure that only the system can bind to it.
StringBIND_NFC_SERVICEMust be required by a HostApduService or OffHostApduService to ensure that only the system can bind to it.
StringBIND_NOTIFICATION_LISTENER_SERVICEMust be required by an NotificationListenerService, to ensure that only the system can bind to it.
StringBIND_PRINT_SERVICEMust be required by a PrintService, to ensure that only the system can bind to it.
StringBIND_REMOTEVIEWSMust be required by a RemoteViewsService, to ensure that only the system can bind to it.
StringBIND_TELECOM_CONNECTION_SERVICEMust be required by a ConnectionService, to ensure that only the system can bind to it.
StringBIND_TEXT_SERVICEMust be required by a TextService (eg SpellCheckerService) to ensure that only the system can bind to it.
StringBIND_TV_INPUTMust be required by a TvInputService to ensure that only the system can bind to it.
StringBIND_VOICE_INTERACTIONMust be required by a VoiceInteractionService, to ensure that only the system can bind to it.
StringBIND_VPN_SERVICEMust be required by a VpnService, to ensure that only the system can bind to it.
StringBIND_WALLPAPERMust be required by a WallpaperService, to ensure that only the system can bind to it.
StringBLUETOOTHAllows applications to connect to paired bluetooth devices.
StringBLUETOOTH_ADMINAllows applications to discover and pair bluetooth devices.
StringBLUETOOTH_PRIVILEGEDAllows applications to pair bluetooth devices without user interaction, and to allow or disallow phonebook access or message access.
StringBODY_SENSORSAllows an application to access data from sensors that the user uses to measure what is happening inside his/her body, such as heart rate.
StringBROADCAST_PACKAGE_REMOVEDAllows an application to broadcast a notification that an application package has been removed.
StringBROADCAST_SMSAllows an application to broadcast an SMS receipt notification.
StringBROADCAST_STICKYAllows an application to broadcast sticky intents.
StringBROADCAST_WAP_PUSHAllows an application to broadcast a WAP PUSH receipt notification.
StringCALL_PHONEAllows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call.
StringCALL_PRIVILEGEDAllows an application to call any phone number, including emergency numbers, without going through the Dialer user interface for the user to confirm the call being placed.
StringCAMERARequired to be able to access the camera device.
StringCAPTURE_AUDIO_OUTPUTAllows an application to capture audio output.
StringCAPTURE_SECURE_VIDEO_OUTPUTAllows an application to capture secure video output.
StringCAPTURE_VIDEO_OUTPUTAllows an application to capture video output.
StringCHANGE_COMPONENT_ENABLED_STATEAllows an application to change whether an application component (other than its own) is enabled or not.
StringCHANGE_CONFIGURATIONAllows an application to modify the current configuration, such as locale.
StringCHANGE_NETWORK_STATEAllows applications to change network connectivity state.
StringCHANGE_WIFI_MULTICAST_STATEAllows applications to enter Wi-Fi Multicast mode.
StringCHANGE_WIFI_STATEAllows applications to change Wi-Fi connectivity state.
StringCLEAR_APP_CACHEAllows an application to clear the caches of all installed applications on the device.
StringCONTROL_LOCATION_UPDATESAllows enabling/disabling location update notifications from the radio.
StringDELETE_CACHE_FILESAllows an application to delete cache files.
StringDELETE_PACKAGESAllows an application to delete packages.
StringDIAGNOSTICAllows applications to RW to diagnostic resources.
StringDISABLE_KEYGUARDAllows applications to disable the keyguard if it is not secure.
StringDUMPAllows an application to retrieve state dump information from system services.
StringEXPAND_STATUS_BARAllows an application to expand or collapse the status bar.
StringFACTORY_TESTRun as a manufacturer test application, running as the root user.
StringFLASHLIGHTAllows access to the flashlight.
StringGET_ACCOUNTSAllows access to the list of accounts in the Accounts Service.
StringGET_ACCOUNTS_PRIVILEGEDAllows access to the list of accounts in the Accounts Service.
StringGET_PACKAGE_SIZEAllows an application to find out the space used by any package.
StringGET_TASKSThis constant was deprecated in API level 21. No longer enforced.
StringGLOBAL_SEARCHThis permission can be used on content providers to allow the global search system to access their data.
StringINSTALL_LOCATION_PROVIDERAllows an application to install a location provider into the Location Manager.
StringINSTALL_PACKAGESAllows an application to install packages.
StringINSTALL_SHORTCUTAllows an application to install a shortcut in Launcher.
StringINTERNETAllows applications to open network sockets.
StringKILL_BACKGROUND_PROCESSESAllows an application to call killBackgroundProcesses(String).
StringLOCATION_HARDWAREAllows an application to use location features in hardware, such as the geofencing api.
StringMANAGE_DOCUMENTSAllows an application to manage access to documents, usually as part of a document picker.
StringMASTER_CLEARNot for use by third-party applications.
StringMEDIA_CONTENT_CONTROLAllows an application to know what content is playing and control its playback.
StringMODIFY_AUDIO_SETTINGSAllows an application to modify global audio settings.
StringMODIFY_PHONE_STATEAllows modification of the telephony state - power on, mmi, etc.
StringMOUNT_FORMAT_FILESYSTEMSAllows formatting file systems for removable storage.
StringMOUNT_UNMOUNT_FILESYSTEMSAllows mounting and unmounting file systems for removable storage.
StringNFCAllows applications to perform I/O operations over NFC.
StringPACKAGE_USAGE_STATSAllows an application to collect component usage statistics
Declaring the permission implies intention to use the API and the user of the device can grant permission through the Settings application.
StringPERSISTENT_ACTIVITYThis constant was deprecated in API level 9. This functionality will be removed in the future; please do not use. Allow an application to make its activities persistent.
StringPROCESS_OUTGOING_CALLSAllows an application to see the number being dialed during an outgoing call with the option to redirect the call to a different number or abort the call altogether.
StringREAD_CALENDARAllows an application to read the user's calendar data.
StringREAD_CALL_LOGAllows an application to read the user's call log.
StringREAD_CONTACTSAllows an application to read the user's contacts data.
StringREAD_EXTERNAL_STORAGEAllows an application to read from external storage.
StringREAD_FRAME_BUFFERAllows an application to take screen shots and more generally get access to the frame buffer data.
StringREAD_INPUT_STATEThis constant was deprecated in API level 16. The API that used this permission has been removed.
StringREAD_LOGSAllows an application to read the low-level system log files.
StringREAD_PHONE_STATEAllows read only access to phone state.
StringREAD_SMSAllows an application to read SMS messages.
StringREAD_SYNC_SETTINGSAllows applications to read the sync settings.
StringREAD_SYNC_STATSAllows applications to read the sync stats.
StringREAD_VOICEMAILAllows an application to read voicemails in the system.
StringREBOOTRequired to be able to reboot the device.
StringRECEIVE_BOOT_COMPLETEDAllows an application to receive the ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting.
StringRECEIVE_MMSAllows an application to monitor incoming MMS messages.
StringRECEIVE_SMSAllows an application to receive SMS messages.
StringRECEIVE_WAP_PUSHAllows an application to receive WAP push messages.
StringRECORD_AUDIOAllows an application to record audio.
StringREORDER_TASKSAllows an application to change the Z-order of tasks.
StringREQUEST_IGNORE_BATTERY_OPTIMIZATIONSPermission an application must hold in order to useACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS.
StringREQUEST_INSTALL_PACKAGESAllows an application to request installing packages.
StringRESTART_PACKAGESThis constant was deprecated in API level 8. The restartPackage(String) API is no longer supported.
StringSEND_RESPOND_VIA_MESSAGEAllows an application (Phone) to send a request to other applications to handle the respond-via-message action during incoming calls.
StringSEND_SMSAllows an application to send SMS messages.
StringSET_ALARMAllows an application to broadcast an Intent to set an alarm for the user.
StringSET_ALWAYS_FINISHAllows an application to control whether activities are immediately finished when put in the background.
StringSET_ANIMATION_SCALEModify the global animation scaling factor.
StringSET_DEBUG_APPConfigure an application for debugging.
StringSET_PREFERRED_APPLICATIONSThis constant was deprecated in API level 7. No longer useful, seeaddPackageToPreferred(String) for details.
StringSET_PROCESS_LIMITAllows an application to set the maximum number of (not needed) application processes that can be running.
StringSET_TIMEAllows applications to set the system time.
StringSET_TIME_ZONEAllows applications to set the system time zone.
StringSET_WALLPAPERAllows applications to set the wallpaper.
StringSET_WALLPAPER_HINTSAllows applications to set the wallpaper hints.
StringSIGNAL_PERSISTENT_PROCESSESAllow an application to request that a signal be sent to all persistent processes.
StringSTATUS_BARAllows an application to open, close, or disable the status bar and its icons.
StringSYSTEM_ALERT_WINDOWAllows an app to create windows using the type TYPE_SYSTEM_ALERT, shown on top of all other apps.
StringTRANSMIT_IRAllows using the device's IR transmitter, if available.
StringUNINSTALL_SHORTCUTAllows an application to uninstall a shortcut in Launcher.
StringUPDATE_DEVICE_STATSAllows an application to update device statistics.
StringUSE_FINGERPRINTAllows an app to use fingerprint hardware.
StringUSE_SIPAllows an application to use SIP service.
StringVIBRATEAllows access to the vibrator.
StringWAKE_LOCKAllows using PowerManager WakeLocks to keep processor from sleeping or screen from dimming.
StringWRITE_APN_SETTINGSAllows applications to write the apn settings.
StringWRITE_CALENDARAllows an application to write the user's calendar data.
StringWRITE_CALL_LOGAllows an application to write (but not read) the user's contacts data.
StringWRITE_CONTACTSAllows an application to write the user's contacts data.
StringWRITE_EXTERNAL_STORAGEAllows an application to write to external storage.
StringWRITE_GSERVICESAllows an application to modify the Google service map.
StringWRITE_SECURE_SETTINGSAllows an application to read or write the secure system settings.
StringWRITE_SETTINGSAllows an application to read or write the system settings.
StringWRITE_SYNC_SETTINGSAllows applications to write the sync settings.
StringWRITE_VOICEMAILAllows an application to modify and remove existing voicemails in the system.