Interview may ask some questions from below String related programs?


package pack;
public class StringComparision {
	public static void main(String[] args) {
		String s1 = new String("I am unique!");
		String s2 = new String("I am unique!");
		String s3 = "I am unique!";
		String s4 = "I am unique!";
		System.out.println(s1 == s2);
		System.out.println(s2 == s3);
		System.out.println(s3 == s4);
		System.out.println(s1.equals(s2));
		System.out.println(s3.equals(s4));
	}
}			


Check the String is Anagram or Not?


package pack;
import java.util.Arrays;
public class AnagramCheck { 
	
	public static boolean isAnagramOption1(String firstWord, String secondWord) {
		
		if (firstWord.length() != secondWord.length()) {
			return false;
		}
		char[] chars = firstWord.toCharArray();
		for (char c : chars) {
			int index = secondWord.indexOf(c);
			if (index != -1) {
				secondWord = secondWord.substring(0, index)
						+ secondWord.substring(index + 1, secondWord.length());
			} else {
				return false;
			}
		}
		return secondWord.isEmpty();
	}
	public static boolean isAnagramOption2(String firstWord, String secondWord) {
		char[] charFromWord = firstWord.toCharArray();
		char[] charFromAnagram = secondWord.toCharArray();
		Arrays.sort(charFromWord);
		Arrays.sort(charFromAnagram);
		return Arrays.equals(charFromWord, charFromAnagram);
	}
	public static void main(String[] args) {
	    // Option 1 
		System.out.println("Anagram Check Option 1 ::"+AnagramCheck.isAnagramOption1("test", "stet"));
		// Option 2
		System.out.println("Anagram Check Option 2 :: "+AnagramCheck.isAnagramOption2("example","pleexam"));
	}	  
}			


How do you reverse a string without using string builtin functions?


package pack;
public class StringReverseWithoutFunction {
	static String reverseString(String s) {
		StringBuilder stringBuilder = new StringBuilder();
		for (int j = s.length() - 1; j >= 0; j--) {
			stringBuilder.append(s.charAt(j));
		}
		return stringBuilder.toString();
	}
	static String recursiveFun(String s) {
		if (s.length() == 0)
			return "";
		return s.charAt(s.length() - 1)
				+ recursiveFun(s.substring(0, s.length() - 1));
	}
	public static void main(String[] args) {
		System.out.println("StringReverseWithoutFunction ="
				+ StringReverseWithoutFunction.reverseString("Welcome"));
		System.out
				.println("StringReverseWithoutFunction Using Recursive Method="
						+ StringReverseWithoutFunction.recursiveFun("Welcome"));
	}
}			


Write a Prime Number Program in Java?


package pack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PrimeNumber {
	public static void main(String[] args) {
		
		int i,m=0,flag = 0;
		
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
		try {
			String s = bufferedReader.readLine();
			int n = Integer.parseInt(s);
			m = n/2;
			
			for (int j = 2; j <= m; j++) {
				
				if(n%2 == 0)
				{
					System.out.println("Given number is not PrimeNumber");
					flag = 1;
					break;
				}
				
			}
			
			if(flag == 0)
			{
				System.out.println("Given number is PrimeNumber");
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}			


Learn about Inheritance in Java & Selenium

How do you remove alternate element from arraylist?


package pack;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RemoveAlternateElementFromArrayList {
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add("A");
		list.add("B");
		list.add("C");
		list.add("D");
		list.add("E");
		list.add("F");
		list.add("G");
		int i = 0;
		for (Iterator<String> it = list.iterator(); it.hasNext();) {
			it.next(); 
			if (i % 2 != 0) {
				it.remove();
			}
			i++;
		}
		System.out.println("After ArrayList" + list);
	}
}			


Write a Simple MultiThread Program in Java?


	package pack;
	
	class Runnable1 implements Runnable {
	
		public Runnable1() {
			
		}
	
		@Override
		public void run() {
	
			for (int i = 0; i < 10; i++) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("Runnable1 = " + i);
			}
	
		}
	
	}
	
	class Runnable2 implements Runnable {
		public Runnable2() {
	
		}
	
		@Override
		public void run() {
			for (int i = 0; i < 10; i++) {
				System.out.println("Runnable2 = " + i);
				try {
				     
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
	
		}
	
	}
	
	public class MultiThread {
	
		/**
		 * @param args
		 * @throws InterruptedException
		 */
		/**
		 * @param args
		 * @throws InterruptedException
		 */
		public static void main(String[] args) throws InterruptedException {
	
			Runnable1 thread1 = new Runnable1();
	        Thread threadObj = new Thread(thread1);
	        threadObj.start();
	        threadObj.join();
			Runnable2 thread2 = new Runnable2();
			Thread threadObj2 = new Thread(thread2);
	        threadObj2.start();
		}
	}			


How do you find second largest number in an Array?


package pack;
import java.util.Arrays;
public class FindSecondLargestNumberInArray {
	public static void main(String[] args) {
		int[] array = { 56, 78, 90, 23, 123, 11, 77, 51 };
		// Option1
		findSecondLargestNumber(array);
		// Option2 - Using Arrays
		findSecondLargestNumberUsingArrays(array);
	}
	private static void findSecondLargestNumberUsingArrays(int[] array) {
		Arrays.sort(array);
		System.out.println("[OPTION 2] Second Largest Number is = "
				+ array[array.length - 2]);
	}
	private static void findSecondLargestNumber(int[] array) {
		int firstLargest = array[0];
		int secondLargest = array[0];
		for (int i = 0; i < array.length; i++) {
			System.out.print(+array[i] + "\t");
		}
		System.out.print("\n");
		for (int i = 0; i < array.length; i++) {
			if (array[i] > firstLargest) {
				secondLargest = firstLargest;
				firstLargest = array[i];
			} else if (array[i] > secondLargest) {
				secondLargest = array[i];
			}
		}
		System.out.println("[OPTION 1] Second Largest Number is = " + secondLargest);
	}
}			


How do you create own or custom ArrayList in java?


package pack;
import java.util.Arrays;
public class CustomArrayList {
	private Object[] arrayElements;
	private int listSize = 0;
	public CustomArrayList() {
		arrayElements = new Object[10];
	}
	public int size() {
		return listSize;
	}
	public Object get(int index) {
		if (index < listSize) {
			return arrayElements[index];
		} else {
			throw new ArrayIndexOutOfBoundsException();
		}
	}
	public static void main(String[] args) {
		CustomArrayList customArrayList = new CustomArrayList();
		customArrayList.addItem(new Integer(11));
		customArrayList.addItem(new Integer(12));
		customArrayList.addItem(new Integer(13));
		customArrayList.addItem(new Integer(14));
		customArrayList.addItem(new Integer(15));
		customArrayList.addItem(new Integer(16));
		customArrayList.addItem(new Integer(17));
		customArrayList.addItem(new Integer(18));
		customArrayList.addItem(new Integer(19));
		customArrayList.remove(2);
		for (int i = 0; i < customArrayList.size(); i++) {
			Integer intObj = (Integer) customArrayList.get(i);
			System.out.println("Array Element " + i + " index = " + intObj);
		}
	}
	private void addItem(Object object) {
		if (arrayElements.length - listSize <= 5) {
			increaseArraySize();
		}
		arrayElements[listSize++] = object;
	}
	private void increaseArraySize() {
		arrayElements = Arrays.copyOf(arrayElements, arrayElements.length * 2);
		System.out.println("Array Size = " + arrayElements.length);
	}
	private Object remove(int index) {
		if (index < listSize) {
			Object object = arrayElements[index];
			arrayElements[index] = null;
			int tmp = index;
			while (tmp < listSize) {
				arrayElements[tmp] = arrayElements[tmp + 1];
				arrayElements[tmp + 1] = null;
				tmp++;
			}
			listSize--;
			return object;
		} else {
			throw new ArrayIndexOutOfBoundsException();
		}
	}
}			


Prime Number Program

This program will determine whether a number entered by user is a prime number or not?


import java.util.*;
public class PrimeNumber {
	 public static void main(String args[]) {
		 PrimeNumber primeNumber = new PrimeNumber();
		 Scanner sc = new Scanner(System.in);
		 System.out.println("Enter any number :"); 
		 int i = 2; 
		 int num = sc.nextInt();
		 if (num <= 1) {
			 System.out.println(num + " is not a prime number"); 
			 System.exit(1); 
		 }
		 while(i <= Math.sqrt(num)) {
			 if (num % i == 0) {
				 System.out.println(num + " is not a prime number");
				 System.exit(1);
			 }
			 i++;
		 }
		 System.out.println(num + " is a prime number"); 
	 } 
}			


READ AND WRITE A TEXT FILE IN JAVA


import java.io.*;
public class ReadWrite{
    public static void main(String [] s){
        try {
            File f1 = new File("D:\\Test\\test1.txt");
            File f2 = new File("D:\\Test\\test2.txt");
            FileReader fr = new FileReader(f1);
            BufferedReader br = new BufferedReader(fr);
            FileWriter fw = new FileWriter(f2);
            BufferedWriter bw = new BufferedWriter(fw);
	    String line = "";
	    while((line = br.readLine())!=null) {
	    	System.out.println(line);
		bw.write(line);
		bw.newLine();
	    }
      	    bw.close();
 	}
	catch (IOException e){
            e.printStackTrace();
	}
    }
}			


JAVA CODE TO CHECK A STRING IS PALINDROME OR NOT?


public static boolean checkPalindrome(String str) {
		char [] charArray = str.toCharArray();
		int len = charArray.length;
		boolean flag = false;
 
  		for(int i=0; i<len/2; i++){
			if(charArray[i]==charArray[len-1-i]) {
				flag = true;
			} else {
				flag = false;
				break;
			}
		}
		return flag;
	}			


HOW TO IMPLEMENT CACHE MECHANISM IN JAVA?


import java.util.LinkedHashMap;
import java.util.Map;
 
public class MyCache{
 
	public static void main(String... c){
		LRUCache lru = new LRUCache<>(4);
		lru.put(1,23);
		lru.put(2,23);
		lru.put(3,23);
		lru.put(4,23);
		lru.put(5,23);
 
		for(Map.Entry entry : lru.entrySet()){
			System.out.println("Key : " + entry.getKey() + ",  Value : " + entry.getValue());
		}
	}
 
}
 
class LRUCache extends LinkedHashMap {
  private int cacheSize;
 
  public LRUCache(int cacheSize) {
    //super(16, 0.75, true);
    this.cacheSize = cacheSize;
  }
 
  protected boolean removeEldestEntry(Map.Entry eldest) {
    return size() > cacheSize;
  }
}			


HOW TO DOWNLOAD MP3 FILES IN JAVA?


 URLConnection connection = new 	URL("https://maudioshare.pw/download/40985").openConnection();
  	InputStream is = connection.getInputStream();
 
	OutputStream outstream = new FileOutputStream(new File("D:\\MohitData\\mysong.mp3"));
 
    	byte[] buffer = new byte[4096];
    	int length;
    	while ((length = is.read(buffer)) > 0) {
        	outstream.write(buffer, 0, length);
    	}
	System.out.println("mp3 download completed.");
    	outstream.close();			


HOW TO SEND AN E-MAIL VIA GMAIL IN JAVA?


import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class TestEmail {
	public static void main(String[] args) {
		final String userName = "mohit21sep@gmail.com";
		final String pwd = "*********";
		Properties properties = new Properties();
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.port", "587");
		Session session = Session.getInstance(properties,
		  new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userName, pwd);
			}
		  });
		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(userName));
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("tyagi_mohit143@yahoo.co.in"));
			msg.setSubject("Test Subject");
			msg.setText("Hello,"+ "\n\n This is my first email sent by Java application." + "\n\n\n Regards, \n Mohit");
			Transport.send(msg);
			System.out.println("Sent Successful.");
		} catch (MessagingException me) {
			me.printStackTrace();
		}
	}
}			


HOW TO FIND IF A GIVEN STRING HAS ALL UNIQUE CHARACTER?


 String str = "qwerty";
		boolean flag = true;
		boolean [] b = new boolean[256];
                int _s = str.length();
		
                for(int i=0; i < _s; i++){
			int val = str.charAt(i);
			if(b[val]){
				flag = false;
			}
			b[val] = true;
		}
		if(flag){
			System.out.println("Duplicate character does not exist in String");
		}
		else {
			System.out.println("Duplicate character exist in String");
		}			


WRITE A PROGRAM TO SPLIT A STRING BY CHARACTERS AND NUMBERS.


class SplitByCharAndNum {
 
	public static void main(String ... v) {
		String str = "ABC123DEF456GHI";
 
		String [] strArray = str.split("[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])");
		
		for(String s : strArray) {
			System.out.println(s);
		}
	}
 
} 			


Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions