Tuesday, September 20, 2016

Send Email and Attache Text or Image file in Java tutorial

I am going to give you a brief about how it send email in java programs. Sending emails is one of the common tasks in real life applications and that’s why Java provides robust JavaMail API that we can use to send emails using SMTP server. JavaMail API supports both TLS and SSL authentication for sending emails.

we will learn how to use JavaMail API to send emails using SMTP server with no authentication, TLS and SSL authentication and how to send attachments and attach and use images in the email body. For TLS and SSL authentication, I am using GMail SMTP server because it supports both of them.

JavaMail API is not part of standard JDK, so you will have to download it from it’s official website i.e JavaMail Home Page. Download the latest version of the JavaMail reference implementation and include it in your project build path. The jar file name will be javax.mail.jar.

If you are using Maven based project, just add below dependency in your project.

<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>

1)Creating javax.mail.Session object

2)Creating javax.mail.internet.MimeMessage object, we have to set different properties in this object such as recipient email address, Email Subject, Reply-To email, email body, attachments etc.

3)Using javax.mail.Transport to send the email message.

The logic to create session differs based on the type of SMTP server, for example if SMTP server doesn’t require any authentication we can create the Session object with some simple properties whereas if it requires TLS or SSL authentication, then logic to create will differ.

So I will create a utility class with some utility methods to send emails and then I will use this utility method with different SMTP servers.

Here is the sample code:

EmailUtil.java:

import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
 * @author Abhinaw.Tripathi
 *
 */
public class EmailUtil
{
/**
* Utility method to send simple HTML email
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
   {
     MimeMessage msg = new MimeMessage(session);
     //set message headers
     msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
     msg.addHeader("format", "flowed");
     msg.addHeader("Content-Transfer-Encoding", "8bit");
     msg.setFrom(new InternetAddress("Abhinaw. Tripathi@igt.com", "NoReply-JD"));
     msg.setReplyTo(InternetAddress.parse("abhinawtripathi34@gmail.com", false));
     msg.setSubject(subject, "UTF-8");
     msg.setText(body, "UTF-8");
     msg.setSentDate(new Date());
     msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
     System.out.println("Message is ready");
         Transport.send(msg);
     System.out.println("EMail Sent Successfully!!");
   }
   catch (Exception e)
{
     e.printStackTrace();
   }
}
/**
* Utility method to send email with attachment
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendAttachmentEmail(Session session, String toEmail, String subject, String body)
{
try
{
        MimeMessage msg = new MimeMessage(session);
        msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");  
    msg.setFrom(new InternetAddress("Abhinaw.Tripathi@igt.com", "NoReply-JD"));
    msg.setReplyTo(InternetAddress.parse("abhinawtripathi34@gmail.com", false));
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));    
        // Create the message body part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Fill the message
        messageBodyPart.setText(body);
        // Create a multipart message for attachment
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Second part is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "abc.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
        msg.setContent(multipart);
        // Send message
        Transport.send(msg);
        System.out.println("EMail Sent Successfully with attachment!!");
     }
catch (MessagingException e)
{
        e.printStackTrace();
   }
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}

/**
* Utility method to send image in email body
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendImageEmail(Session session, String toEmail, String subject, String body)
{
try
{
        MimeMessage msg = new MimeMessage(session);
        msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");    
    msg.setFrom(new InternetAddress("Abhinaw.Tripathi@igt.com", "NoReply-JD"));
    msg.setReplyTo(InternetAddress.parse("abhinawtripathi34@gmail.com", false));
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));    
        // Create the message body part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);      
        // Create a multipart message for attachment
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Second part is image attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "image.png";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        //Trick is to add the content-id header here
        messageBodyPart.setHeader("Content-ID", "image_id");
        multipart.addBodyPart(messageBodyPart);
        //third part for displaying image in the email body
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent("<h1>Attached Image</h1>" +"<img src='cid:image_id'>", "text/html");
        multipart.addBodyPart(messageBodyPart);      
        //Set the multipart message to the email message
        msg.setContent(multipart);
        // Send message
        Transport.send(msg);
        System.out.println("EMail Sent Successfully with image!!");
     }
catch (MessagingException e)
{
        e.printStackTrace();
   }
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}


Now if you wish to send simple email do something like this:

SimpleEmail.java:

import java.util.Properties;
import javax.mail.Session;
/**
 * @author Abhinaw.Tripathi
 *
 */
public class SimpleEmail
{
   public static void main(String[] args)
   {
   System.out.println("SimpleEmail Start");
   String smtpHostServer = "smtp.gmail.com";
   String emailID = "abhinawtripathi34@gmail.com";
   Properties props = System.getProperties();
   props.put("mail.smtp.host", smtpHostServer);
   Session session = Session.getInstance(props, null);
   EmailUtil.sendEmail(session, emailID,"SimpleEmail Testing Subject", "SimpleEmail Testing Body");
   }
 

}

if  you wish to send email with SSL Authentication do something like this:

SSLEmail.Java:

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

public class SSLEmail
{
/**
  Outgoing Mail (SMTP) Server
  requires TLS or SSL: smtp.gmail.com (use authentication)
  Use Authentication: Yes
  Port for SSL: 465
*/
public static void main(String[] args)
{
final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id
final String password = "mypassword"; // correct password for gmail id
final String toEmail = "myemail@yahoo.com"; // can be any email id

System.out.println("SSLEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port

Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};

Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
       EmailUtil.sendEmail(session, toEmail,"SSLEmail Testing Subject", "SSLEmail Testing Body");
       EmailUtil.sendAttachmentEmail(session, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");
       EmailUtil.sendImageEmail(session, toEmail,"SSLEmail Testing Subject with Image", "SSLEmail Testing Body with Image");
}


}

TLSEmail.java:

/**
 * 
 */
package com.advanceemail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
/**
 * @author Abhinaw.Tripathi
 *
 */
public class TLSEmail 
{
/**
  Outgoing Mail (SMTP) Server
  requires TLS or SSL: smtp.gmail.com (use authentication)
  Use Authentication: Yes
  Port for TLS/STARTTLS: 587
*/
public static void main(String[] args)
{
final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id
final String password = "mypassword"; // correct password for gmail id
final String toEmail = "myemail@yahoo.com"; // can be any email id 
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
       //create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() 
{
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);
EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body");
}
}



In above all code i have shown you how to send email .however you can also attache text file and image file also.very simple code.in fact you can also design the email in HTML format.



Wednesday, September 14, 2016

How are Java objects stored in memory?

Very frequent question on java that how java objects are stored in memory.

Ans: 

In Java, all objects are dynamically allocated on Heap.
In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on heap.

For example, following program fails in compilation. Compiler gives error “Error here because t is not initialed”.

class Test {
    // class contents
    void show() {
        System.out.println("Test::show() called");
    }
}

public class Main {
    public static void main(String[] args) {
        Test t;
        t.show(); // Error here because t is not initialed
    }
}

Allocating memory using new() makes above program work.

class Test {
    // class contents
    void show() {
        System.out.println("Test::show() called");
    }
}
 
public class Main {
    public static void main(String[] args) {
        Test t = new Test(); //all objects are dynamically allocated
        t.show(); // No error
    }
}

in java basically there are different section where jvm allocate memory either loading time of class or run time.

1.) class area or method area -> here static data member gets memory at loading time of class.
2.) heap area -> here object get memory and it initialize all instance data member
at run time of class.
3.) stack area -> here local variable gets memory .

Maximize number of 0s by flipping a subarray in java

Maximize number of 0s by flipping a sub-array

Given a binary array, find the maximum number zeros in an array with one flip of a sub-array allowed. A flip operation switches all 0s to 1s and 1s to 0s.

Examples:

Input :  arr[] = {0, 1, 0, 0, 1, 1, 0}
Output : 6
We can get 6 zeros by flipping the sub-array {1, 1}

Input :  arr[] = {0, 0, 0, 1, 0, 1}
Output : 5

The idea is very simple just count the original zero and find the largest sum in the sub-array.
i would provide a solution for it which will work in o(n) complexity.

Solution:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class FlipZeroApp
{
public static void main(String[] args)
{
//int[] arr={0, 1, 0, 0, 1, 1, 0};  output should 6
int[] arr={0, 0, 0, 1, 0, 1};   // here output should be 5
int size=arr.length;
int count=findMaxZeroCount(arr, size);
System.out.println(count);
}
public static int findMaxZeroCount(int arr[], int n)
{
   int orig_zero_count = 0;
   int max_diff = 0;
   int curr_max = 0;

   for (int i=0; i<n; i++)
   {
       if (arr[i] ==0)
          orig_zero_count++;
       // Value to be considered for finding maximum sum
       int val = (arr[i] ==1)? 1 : -1;

       // Update current max and max_diff
       curr_max = Math.max(val, curr_max + val);
       max_diff = Math.max(max_diff, curr_max);
   }
   max_diff = Math.max(0, max_diff);

   return orig_zero_count + max_diff;
}


}

Complexity= o(n) where as any other solution would work in o(n^2).

Output: 5

Non Fibonacci Numbers in Java

Given a positive integer n, the task is to print the n'th non Fibonacci number. The Fibonacci numbers are defined as:

Fib(0) = 0
Fib(1) = 1
for n >1, Fib(n) = Fib(n-1) + Fib(n-2)

First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141,....

Examples:

Input : n = 2
Output : 6

Input : n = 5
Output : 10

There are basically two solutions for it,

Naive Approach: First Approach is to find find Fibonacci numbers and then print first n numbers not present in the found Fibonacci numbers.

Better Solution: A better solution is to use the formula of Fibonacci numbers and keep adding of gap between two consecutive Fibonacci numbers. Value of sum of gap is count of non-Fibonacci numbers seen so far.

Solution:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class FibonaciNumber
{
public static int nonFibonaciNumber(int n)
{
int prevprev=1,prev=2,current=3;

while(n>0)
{
prevprev=prev;
prev=current;
current=prevprev + prev;
n=n-(current-prev-1); //it can be negative
}
n=n+(current-prev-1); //make it positive

return prev+n;
}

public static void main(String[] args)
{
int count=nonFibonaciNumber(5);
System.out.println(count);
}

}

Output: 10

Tuesday, September 13, 2016

Android TV App Building Concept

Building TV Apps

Android offers a rich user experience that's optimized for apps running on large screen devices, such as high-definition televisions. Apps on TV offer new opportunities to delight your users from the comfort of their couch.


  • TV apps use the same structure as those for phones and tablets.
  • This approach means you can create new TV apps based on what you already know about building apps for Android, or extend your existing apps to also run on TV devices. 
  • However, the user interaction model for TV is substantially different from phone and tablet devices. In order to make your app successful on TV devices, you must design new layouts that can be easily understood from 10 feet away, and provide navigation that works with just a directional pad and a select button.

There are few points you can note while TV app development such as
  1. Handling TV Hardware
  2. Building TV Layouts
  3. Creating TV Navigation
Each of them plays a very vital role in Android Tv app development.Lets see how they
impact on the development but before that you must have understanding about few things
such as

1)Supported Media Formats
2)DRM
3)android.drm
4)ExoPlayer
5)android.media.MediaPlayer

And Android TV app uses lean back support.

1)Declare Leanback support for TV:

Declare that your app uses the Leanback user interface required by Android TV. If you are developing an app that runs on mobile (phones, wearables, tablets, etc.) as well as Android TV, set the required attribute value to false. If you set the required attribute value to true, your app will run only on devices that use the Leanback UI.

<manifest>
    <uses-feature android:name="android.software.leanback"
        android:required="false" />
</manifest>

So there are few things also which are not required at TV app development.

2)Declare touchscreen not required:

Applications that are intended to run on TV devices do not rely on touch screens for input. In order to make this clear, the manifest of your TV app must declare that a the android.hardware.touchscreen feature is not required. This setting identifies your app as being able to work on a TV device, and is required for your app to be considered a TV app in Google Play. The following code example shows how to include this manifest declaration:

<manifest>
    <uses-feature android:name="android.hardware.touchscreen"
              android:required="false" />
</manifest>

3)Provide a home screen banner:

An application must provide a home screen banner image for each localization if it includes a Leanback launcher intent filter. The banner is the app launch point that appears on the home screen in the apps and games rows. When designing your banner, follow the design requirements described in Banners. To add the banner to your app, describe the banner in the manifest as follows:

<application
    android:banner="@drawable/banner" >
</application>

4)Add TV Support Libraries:

The Android SDK includes support libraries that are intended for use with TV apps. These libraries provide APIs and user interface widgets for use on TV devices. The libraries are located in the <sdk>/extras/android/support/ directory. Here is a list of the libraries and their general purpose:

a)v17 leanback library - Provides user interface widgets for TV apps, particularly for apps that do media playback.

b)v7 recyclerview library - Provides classes for managing display of long lists in a memory efficient manner. Several classes in the v17 leanback library depend on the classes in this library.

c)v7 cardview library - Provides user interface widgets for displaying information cards, such as media item pictures and descriptions.
Note: You are not required to use these support libraries for your TV app. However, we strongly recommend using them, particularly for apps that provide a media catalog browsing interface.

If you decide to use the v17 leanback library for your app, you should note that it is dependent on the v4 support library. This means that apps that use the leanback support library should include all of these support libraries:

v4 support library
v7 recyclerview support library
v17 leanback support library
The v17 leanback library contains resources, which require you to take specific steps to include it in app projects. For instructions on importing a support library with resources, see Support Library Setup.


5)Declaring hardware requirements for TV:

<uses-feature android:name="android.hardware.touchscreen"
        android:required="false"/>
<uses-feature android:name="android.hardware.faketouch"
        android:required="false"/>
<uses-feature android:name="android.hardware.telephony"
        android:required="false"/>
<uses-feature android:name="android.hardware.camera"
        android:required="false"/>
<uses-feature android:name="android.hardware.nfc"
        android:required="false"/>
<uses-feature android:name="android.hardware.location.gps"
        android:required="false"/>
<uses-feature android:name="android.hardware.microphone"
        android:required="false"/>
<uses-feature android:name="android.hardware.sensor"
        android:required="false"/>

Android apps can declare hardware feature requirements in the app manifest to ensure that they do not get installed on devices that do not provide those features. If you are extending an existing app for use on TV, closely review your app's manifest for any hardware requirement declarations that might prevent it from being installed on a TV device.

If your app uses hardware features (such as a touchscreen or camera) that are not available on TV, but can operate without the use of those features, modify your app's manifest to indicate that these features are not required by your app. The following manifest code snippet demonstrates how to declare that your app does not require hardware features which are unavailable on TV devices.

So, These are few things which are basic requirement for Android TV App Development and must
be taken care while Android TV app Development. Now,So if we can not use touch screen and so how we will navigate within the Application.Will tell you in next tutorial.



Monday, September 12, 2016

Android Request Run-Time Permission Example

Although Android is being keep developed but the latest update to Android M is totally different since there is some major change that would change everything like new Run-time Permission. Surprisingly it is not much talked about in Android Developer community even though it is extremely important and may cause some big trouble in the near future.

The New Runtime Permission
Android's permission system is one of the biggest security concern all along since those permissions are asked for at install time. Once installed, the application will be able to access all of things granted without any user's acknowledgement what exactly application does with the permission.

No surprise why there are so many bad guys trying to collect user's personal data through this security weakness and use it in the bad way.

Android team also know this concern. 7 year passed, finally permission system is redesigned. In Android 6.0 Marshmallow, application will not be granted any permission at installation time. Instead, application has to ask user for a permission one-by-one at runtime.

Note: Please note that permission request dialog shown above will not launch automatically. Developer has to call for it manually. In the case that developer try to call some function that requires a permission which user has not granted yet, the function will suddenly throw an Exception which will lead to the application crashing.

What happened to the application that has already been launched?
This new permission system may cause you some panic right now. "Hey ! What's about my application that launched 3 years ago. If it is installed on Android 6.0 device, does this behavior also applied? Will my application also crash?!?"

Don't worry. Android team has already thought about it. If the application's targetSdkVersion is set to less than 23. It will be assumed that application is not tested with new permission system yet and will switch to the same old behavior: user has to accept every single permission at install time and they will be all granted once installed !

As a result, application will run perfectly like previous. Anyway please note that user still can revoke a permission after that ! Although Android 6.0 warn the user when they try to do that but they can revoke anyway.

Very Simple Code Solution:

Manifest.xml: 


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myandrioid.abhinaw">
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application 
       android:allowBackup="true" 
       android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" 
       android:supportsRtl="true"  
      android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



MainActivity.java :

package com.myandrioid.abhinaw;
import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
{
    private Button buttonRequestPermission;
    private int STORAGE_PERMISSION_CODE = 23;

    @Override    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermisssion();
    }

    private  void requestPermisssion()
    {
        buttonRequestPermission = (Button) findViewById(R.id.buttonRequestPermission);
        buttonRequestPermission.setOnClickListener(new View.OnClickListener()
        {
            @Override            public void onClick(View v)
            {
                if(isReadStorageAllowed())
                {
                    Toast.makeText(MainActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
                    return;
                }
                requestStoragePermission();
            }
        });
    }

    private boolean isReadStorageAllowed()
    {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED)
            return true;
        return false;
    }

    private void requestStoragePermission()
    {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE))
        {
           // do nothing
        }
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
    }

    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if(requestCode == STORAGE_PERMISSION_CODE)
        {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
            }
            else            {
                Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
            }
        }
    }
}

activity_main.xml :

<Button  
  android:layout_width="match_parent" 
   android:layout_height="wrap_content" 
   android:text="Request Storage Permission"  
  android:id="@+id/buttonRequestPermission"  
  android:layout_centerVertical="true"  
  android:layout_below="@+id/button" />

Result: 







Nagarro Coding Questions for Experienced Interview Android

1)Given an unsorted list of repeated elements in an array, Find the element with maximum frequency.
Solution:

There are two approaches for this:
1)Naive Approach: Need two loop,outer-inner and outer loop will pick element and will traverse and inner loop will just count the duplicate.

Time Complexity: o(n^2)

2)Better Approach: 

Time Complexity: o(n) and o(k) for space where k=size;
/*
 * @author Abhinaw.Tripathi
 *
 */
public class MaxRepeatingApp
 {
public static void main(String[] args)
{
int arr[] = {2, 3, 3, 5, 3, 4, 1, 7};
                int n = arr.length;
                int k=8;
                System.out.println("Maximum repeating element is: " +maxRepeating(arr,n,k));
}
public static int maxRepeating(int[] arr,int n,int k)
{
for(int i=0;i<n;i++)
arr[(arr[i])%k] +=k;

int max=arr[0],result=0;
for(int i=0;i<n;i++)
{
if(arr[i] > max)
{
max=arr[i];
result=i;
}
}
return result;
}
}
Result: Maximum repeating element is: 3

2) Given a string containing characters and brackets, find if the brackets are paired in the string.

Solution: 
public static boolean pairedNotpaired(String str)
{
Stack stack=new Stack();
boolean result=true;
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i);
switch (c) 
{
 case ')':
 if((Character)stack.pop()!=null)
 {
 return false;
 }
 
 case '}':
 
 if((Character)stack.pop()!=null)
 {
 return false;
 }
 
break;
 case ']' :
 {
 if((Character)stack.pop()!=null)
 {
 return false;
 }
 }

default:
stack.push(c);
break;
}
}
return result;

}


3) Given a set of integers, find the third maximum sum of two elements from the set.
Solution:
/**
 * @author Abhinaw.Tripathi
 *
 */
public class ThirdlargestSumApp {

public static int swap(int a, int b)
{
return a;
}
public static void main (String[] args) throws java.lang.Exception
{
   int k = 3;                            //Finding kth largest pair sum in array "a".
   int []a = {-2, 3, 4, -1, 5, 7, 8};   //input array
   int []b = new int[k]; //Holds the calculated pair sum. Not more than k highest pair-sum arerequired at any moment.  
   
   for(int i = 0; i < k; i++) 
    b[i] = Integer.MIN_VALUE;
   
   for(int i = 0; i < a.length-1; i++)
   {
       int pair = a[i] + a[i+1];
       if(pair > b[0]) 
       {                                //Compare with the Min Value i.e. b[0].
           b[0] = pair;
           System.out.println("All Sum:" +b[0]);                                                      
           if(b[1] < b[0]) 
           {
               b[1] = swap(b[0], b[0]=b[1]); // To satisfy parent(b[0]) <= left_child(b[1]) constraint for MinHeap
           }
           if(b[2] < b[0])
           {
               b[2] = swap(b[0], b[0]=b[2]); // To satisfy parent(b[0]) <= right_child(b[1]) constraint for MinHeap
           }
       }
   }
   System.out.println( "\n" +"3rd Sum:" +b[0]);
}
}

4)Find middle element efficiently of a Circular Linked List.
Solution:

class LinkedList
{
Node head; 
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}

void printMiddle()
{
Node slow_ptr = head;
Node fast_ptr = head;
if (head != null)
{
while (fast_ptr != null && fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
System.out.println("The middle element is [" +
slow_ptr.data + "] \n");
}
}

public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}

public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+"->");
tnode = tnode.next;
}
System.out.println("NULL");
}

public static void main(String [] args)
{
LinkedList llist = new LinkedList();
for (int i=5; i>0; --i)
{
llist.push(i);
llist.printList();
llist.printMiddle();
}
}
}

5) Given a string ,find the longest sub-string with all distinct characters in it.If there are multiple such strings,print them all.

Solution:
/**
 * 
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
import java.util.*;
 
public class UniqueSubStringApp
  static boolean isValid(int count[],int k)
   {
int val = 0;
    for (int i=0; i<26; i++)
        if (count[i] > 0)
            val++;
 
    return (k >= val);
   }
static int uniquesubstring(String s,int k)
{
int u=0;
int max=0,max_start=0;
int cur_start=0;
int cur_end=0;
int n=s.length();
int count[]=new int[27];
Arrays.fill(count,0);
for(int i=0;i<n;i++)
{
if(count[s.charAt(i)-'a']==0)
{
u++;
}
count[s.charAt(i)-'a']++;
}
if(u<k)
{
System.out.printf("k is greater than no of characters");
return 0;
}
Arrays.fill(count,0);
count[s.charAt(0)-'a']++;
for(int i=1;i<n;i++)
{
count[s.charAt(i)-'a']++;
cur_end++;
while(!isValid(count,k))
{
count[s.charAt(cur_start)-'a']--;
cur_start++;
}
 
if(cur_end-cur_start+1>max)
{
max=cur_end-cur_start+1;
max_start=cur_start;
}
 
}
 
System.out.println("Max substring "+s.substring(max_start,cur_end+1));
System.out.println("length "+max);
return 0;
}
public static void main (String[] args) throws java.lang.Exception
{
String s="aabacbebebe";
int k=3;
uniquesubstring(s,3);
}
}