Tuesday, 4 July 2017

Interview Programs

Simple Android thread and handler example

onCreate()
{
//layout and progress bar we have
//thread creation
thread = new Thread(new Mythread())
thread.start();
handler = new Handler()
{
handleMessage(Message msg)
{

//set value to progress bar

}
};



}

class Mythread implements Runnable
{


run()
{
//create Message object

for(int i =0;i<10;i++)
{
Message msg = Message.obtain();
msg.arg1 = i;
handler.sendMesahe(mg);

}

}


}

Download an image and send it to UI android httpurlconnection

private void downloadImage(String urlStr) {
      progressDialog = ProgressDialog.show(this, "", "Downloading Image from " + urlStr);
      final String url = urlStr;

      new Thread() {
         public void run() {
            InputStream in = null;

            Message msg = Message.obtain();
            msg.what = 1;

            try {
               in = openHttpConnection(url);
               bitmap = BitmapFactory.decodeStream(in);
               Bundle b = new Bundle();
               b.putParcelable("bitmap", bitmap);
               msg.setData(b);
               in.close();
            }catch (IOException e1) {
               e1.printStackTrace();
            }
            messageHandler.sendMessage(msg);
         }
      }.start();
   }

  private Handler messageHandler = new Handler() {
      public void handleMessage(Message msg) {
         super.handleMessage(msg);
         ImageView img = (ImageView) findViewById(R.id.imageView);
         img.setImageBitmap((Bitmap) (msg.getData().getParcelable("bitmap")));
         progressDialog.dismiss();
      }

   };

Fibonacci series


class FibExample{  
public static void main(String args[])  
{    
 int n1=0,n2=1,n3,i,count=10;    
 System.out.print(n1+" "+n2);//printing 0 and 1    
    
 for(i=2;i<count;i++)//loop starts from 2 because 0 and 1 are already printed    
 {    
  n3=n1+n2;    
  System.out.print(" "+n3);    
  n1=n2;    
  n2=n3;    
 }    
  
}}  

Find duplicates in array


public class DuplicateArray {


public static void main(String[] args) {
int sample [] = {1,2,3,4,5,2,3,4,2,2,2};
HashMap<Integer ,Integer> testMap = new HashMap<Integer,Integer>();
for(int  num : sample)
{
int i = 1;
if(!testMap.containsKey(num))
{
testMap.put(num, i);
}else
{
testMap.put(num, testMap.get(num)+1);
}
//System.out.println("print"+num);
}
for (HashMap.Entry<Integer, Integer> entry : testMap.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}

}
}

Reverse a String


public class ReverseString {

public static void main(String[] args) {

String test ="ABCD";
StringBuffer sb = new StringBuffer();
for(int i = test.length()-1 ;i>=0;i--)
{
sb.append(test.charAt(i));
}

System.out.println("print rev"+sb.toString());
}
}

Java Simple CallBack Example


public interface EventInterface {



public void notifyEventExample();

}

public class CallBack {

public EventInterface eI;
public CallBack(EventInterface eventInt)
{
this.eI = eventInt;
sendEvent();
}
public void sendEvent()
{
eI.notifyEventExample();
}
}



public class CallBackreceiver implements EventInterface {
public CallBackreceiver() { CallBack testCallBack = new CallBack(this); }
/* * public void testMethod() { testCallBack.sendEvent(); } */ public static void main(String args[]) {
CallBackreceiver receicer = new CallBackreceiver(); // receicer.testMethod();
}
public void notifyEventExample() { System.out.println("I'm Called"); }
}

Download an image from web service and load into an image view

@Override
    protected Bitmap doInBackground(String... params) {
     Bitmap bitmap = null;
     try {
         URL url = new URL(params[0]);
                bitmap = BitmapFactory.decodeStream((InputStream)url.getContent());
 } catch (IOException e) {
  Log.e(TAG, e.getMessage());
 }
        return bitmap;
    }
@Override
    protected void onPostExecute(Bitmap bitmap) {
  imageView.setImageBitmap(bitmap);
    }

Reverse a string with out using String Buffer and String builder

public static String reverse(String source){
        if(source == null || source.isEmpty()){
            return source;
        }       
        String reverse = "";
        for(int i = source.length() -1; i>=0; i--){
            reverse = reverse + source.charAt(i);
        }
      
        return reverse;
    }



Alternate thread printing odd and even




public class PrintOddEvenInSequence {


private boolean isOddPrinting = false;

private boolean isEvenPrinting = false;

private int oddNum = 0;
private int evenNum = 0;
public static void main (String args[]) {
final PrintOddEvenInSequence oddEvenInSequence = new PrintOddEvenInSequence();
Thread printOddNumThread = new Thread(new Runnable() {
public void run() {
oddEvenInSequence.printOddNumber();
}
});
printOddNumThread.start();
Thread printEvenNumThread = new Thread(new Runnable() {
public void run() {
oddEvenInSequence.printEvenNumber();
}
});
printEvenNumThread.start();
}
private void printOddNumber() {
synchronized (this) {
while (true) {
while (isEvenPrinting) {
try {
System.out.println("Waiting to print odd number");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isOddPrinting = true;
System.out.println(++oddNum);
isOddPrinting = false;
notify();
}
}
}
private void printEvenNumber() {
synchronized (this) {
while (true) {
while (isOddPrinting) {
try {
System.out.println("Waiting to print even number");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isEvenPrinting = true;
System.out.println(++evenNum);
isEvenPrinting = false;
notify();
}
}
}

}



Find number of repeating characters in a string



public class Testmain {

public static void main(String args[])throws Exception{
int  count = 0;
String s = "ABCDABD";
for(int i = 0;i<s.length();i++)
{
for(int j = i+1;j<s.length();j++)
{
if(s.charAt(i)==s.charAt(j))
{
count++;
System.out.println("repeated character is "+s.charAt(i));
}
}
}

System.out.println("count "+count);
}


}

Remove Specific character from string


 public static String removeCharInString (String string, char charToBeRemoved) {

        if (string == null)
             return "";

       
         StringBuilder strBuild = new StringBuilder ();

        for (int i = 0; i < string.length (); i++) {
            char chr = string.charAt (i);
            if (chr == charToBeRemoved)
                continue;
            strBuild.append (chr);
        }
        return strBuild.toString ();
    }
}

No comments:

Post a Comment

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...