How to Compare two excel files in same format using java

How to Compare two excel files in same format using java


import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CompareTwoExcelSheets {
public Map getExcelDataInMap(String inputFileName, String sheetName)
throws IOException {
LinkedHashMap<Integer, List> rowWiseDetails = new LinkedHashMap<Integer, List>();
HashMap<String, LinkedHashMap<Integer, List>> outerMap = new LinkedHashMap<String, LinkedHashMap<Integer, List>>();
InputStream fis = getClass().getResourceAsStream(inputFileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetName);
Iterator<Row> rowIt = sheet.iterator();
while (rowIt.hasNext()) {
Row row = rowIt.next();
Iterator<Cell> cellIterator = row.cellIterator();
List data = new LinkedList();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
data.add(cell.toString());
}
rowWiseDetails.put(row.getRowNum(), data);
}
return rowWiseDetails;
}
private void syso() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
try {
Map ss = new CompareTwoExcelSheets().getExcelDataInMap(
"CVM_Submit_prof.xlsx", "Sheet1");
Map pp = new CompareTwoExcelSheets().getExcelDataInMap(
"CVM_Submit_prof.xlsx", "Sheet1");
if (ss.equals(pp)) {
System.out.println("success!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

HTTP Status 500 - java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

HTTP Status 500 - java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

Error Message: HTTP Status 500 - java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

Solution:

if you are using Maven web project, then add below dependencies to the pom.xml file.otherwise, download jstl-1.2.jar and standard-1.1.2.jar files and add them to your project library.


Maven Dependecies:

<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

if still reproducing the same issue, let us know by commenting.
Solved: Maven Build failure showing error the filename, directory name, or volume label syntax is incorrect

Solved: Maven Build failure showing error the filename, directory name, or volume label syntax is incorrect

Error: The filename, directory name, or volume label syntax is incorrect.Maven TestNG project build failure and showing below error message.


syntax is incorrect

Solution:

<configuration>
                                <from>builder@myhost.com</from>
                                <subject>a subject</subject>
                                <failonerror>true</failonerror>
                                <mailhost>mail.dummy.ch</mailhost>
                                <mailuser>XXXXX</mailuser>
                                <mailpassword>XXXXX</mailpassword>
                                <htmlMessageFile>src/main/MailContent.html</htmlMessageFile>
                                <receivers>
                                        <receiver>dani</receiver>
                                        <receiver>sam@any-company.com</receiver>
                                </receivers>
                                <fileSets>
                                        <fileSet>
                                                <directory>${basedir}/src/main</directory>
                                                <includes>
                                                        <include>**/*.pdf</include>
                                                </includes>
                                        </fileSet>
                                </fileSets>

                        </configuration>


check weather you are using htmlMessageFile or htmlMessage in configuration.if you are using htmlMessageFile then provide your html file name only.otherwise you should use html code.
Solution:welcome file not loading in spring maven

Solution:welcome file not loading in spring maven

Welcome file html not working with spring project,showing HTTP status-404 error message

welcome file
HTTP-404 resource not Found

You need to put the JSP file in /index.jsp instead of in /WEB-INF/jsp/index.jsp. This way the whole servlet is superfluous by the way.

 WebContent 
          |-- META-INF 
          |-- WEB-INF 
                 -- web.xml 
            -- index.jsp
Reading the all files inside the folder and writing the data into file

Reading the all files inside the folder and writing the data into file

Reading the all files inside the folder and writing the data that we need.


My file name: GOPS_Read_10042017.txt

GOPS_Read_10042017.txt contains the data below:
000000000HDRGAPS2017-04-2621.20.55000000296
TFIC260420175                           2017-04-26Test INDIA PRIVATE LIMITED      
TFIC9PUPP02178                         2017-04-26Test INDIA PRIVATE LIMITED      
IFIC267332                             2017-03-15GLOBAL BUSINESS SOLUTIONS I
L267332111
999999999TRLGAPS2017-04-2621.20.55000000296000029563



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;

public class InvoiceFinder {

/**
* @param args
*/

private static File[] getFileList(String dirPath) {
        File dir = new File(dirPath);  

        File[] fileList = dir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.startsWith("GOPS") &&name.endsWith(".txt");
            }
        });
        return fileList;
    }
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
try {

File[] matchingFiles = getFileList("C:\\files");
System.out.println(matchingFiles.length);
for (int i=0;i<matchingFiles.length;i++){

BufferedReader br = new BufferedReader(new FileReader(matchingFiles[i]));
BufferedWriter bw=new BufferedWriter(new      FileWriter("C:\\files\\output"+matchingFiles[i].getName().substring(14)+".txt"));
String sCurrentLine;
br.readLine();
while((sCurrentLine=br.readLine())!=null){

if ( !sCurrentLine.startsWith("L")&&(!sCurrentLine.startsWith("000000000")&&!sCurrentLine.startsWith("999999999"))){
bw.write("'"+sCurrentLine.substring(4, 28).trim()+"',");
bw.newLine();

}

}
br.close();
bw.close();
}



} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}

Prime number checking in java, checking the prime numbers from list of random numbers

Prime number checking in java, checking the prime numbers from list of random numbers

public class PrimeCheckerImpl {
/**
* @Srinivas Kumar
*/


public Map<Integer, Boolean> primeChecker(List<Integer> randList) {
int i,m=0,flag=0;  
Map<Integer,Boolean> primeCheckMap=new HashMap<>();
Iterator<Integer> itrList= randList.iterator();
if(itrList.hasNext()){
int randNum=itrList.next();
 m=randNum/2;  
 for(i=2;i<=m;i++){  
  if(randNum%i==0){  
  System.out.println("Number is not prime");  
  flag=1;
  primeCheckMap.put(randNum, false);
  break;  
  }  
 }  
 if(flag==0)  
 System.out.println("Number is prime");
 primeCheckMap.put(randNum, true);
}    
return primeCheckMap;
}
public static void main(String[] args) {

PrimeCheckerImpl   look_up=new PrimeCheckerImpl ();
                List<Integer>  posNumList=new ArrayList<Integer>();
               Random randomList=new Random();
Integer genNum=randomList.nextInt();
System.out.println(randomList.nextInt());
for (int i=0;i<10;i++){
IRandom randomnum=new Random();
if(randomnum>0){
posNumList.add(num);
}
                                   }

Map<Integer, Boolean> primeList=look_up.primeChecker(posNumList);
/
System.out.println(primeList);
}

}
Reverse the String without using the reverse method in JAVA

Reverse the String without using the reverse method in JAVA



Reverse the String without using the reverse method in JAVA

public class StringRev{

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

String s="SrinivasKumar";
char[] ch=s.toCharArray();
char[] rev=new char[ch.length];
for(int i=0;i<ch.length;i++){
rev[i]=ch[ch.length-(i+1)];

}
       System.out.println(rev);
}

}
While working with RSA or eclipse, if Unable to open the java file using editor?

If the above issue occurred, Please follow any of the one
Sol1:Just go to  Window>> reset perspective in eclipse, it may resolve the problem
Sol2: Otherwise go to C:\users\<username>\.Rational\IDE\IRuntime\3841673973(number may not be same for all user)


inner class inside interface

inner class inside interface

How to write the inner class inside the interface?

public interface MyInterface {

class  InsideInter{
int i=9, j=10;
public int add(int i,int j){
int tot=0;
tot=i+j;
return tot;
}
}
}
public class TestInterface implements MyInterface {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
        TestInterface ti=new TestInterface();
       MyInterface.InsideInter insider=new MyInterface.InsideInter();
       System.out.println(insider.add(20, 25));
     
}

}


ConcurrentHashmap vs HashTable, difference between ConcurrentHashmap and HashTable

ConcurrentHashmap vs HashTable, difference between ConcurrentHashmap and HashTable

Difference between ConcurrentHashmap and HashTable

ConcurrenthashMap is also threadsafe like Hashtable but it not fully locked like HashTable.
ConcurrentHashMap locked the only particular object that thread is working reamaning objects in the map is availble for all the threads.

and interoperable with Hashtable is possible.This class does not allow the null value as key or value.
Unlike Hastable it will not throw ConcurrentModificationException.  However, iterators are designed to be used by only one thread at a time. All the methods of map and Iterator interface are implemeted in this class. 
Interview  questions on Java coding 3 - output for below code

Interview questions on Java coding 3 - output for below code

1)what is the output for below code.

class Counter{  
static int count=0;//will get memory when instance is created  
  
Counter(){  
count++;  
System.out.println(count);  
 
public static void main(String args[]){  
  
Counter c1=new Counter();  
Counter c2=new Counter();  
Counter c3=new Counter();  
  
 }  

} 

Ans: 1
2
3

2)what is the output for below code.
 static class  Emp {
        int eno=10;
        public int getEmp(){
                return eno;
        }
}
 public class TestEmp
 {
         public static void main(String[] args) {
                Emp obj=new Emp();
                System.out.println(obj.getEmp());
        }

 }

Ans: we can't write the static class out side the class
Interview Questions on Java coding- 2

Interview Questions on Java coding- 2


1)What is the output for below code?

class Testing {
        {
                System.out.println(" block");
        
        }
        
    public static void main1(String[] args) {
                // TODO Auto-generated method stub
System.out.println("Main method");
        }
}
 Ans: Print notning as the no main method, but runs sucessfully witout error.

2) What is the output for below code?

class Testing {
        {
                System.out.println(" block");
        
        }
        
    public static void main(String[] args) {
                // TODO Auto-generated method stub
System.out.println("Main method");
        }
}

Ans: prints Main method in console as there is no chance to call instance block


3)What is the output for below code?
public class Test {
        Test(){
                System.out.println("Constructor");
        }
        static {
        
                System.out.println("static ");
        }
        static {
                
                System.out.println("static ");
        }
         {
                       System.out.println("instance ");
        }
     
        public static void main(String[] args) {
                // TODO Auto-generated method stub
                System.out.println("Main method");
        Test obj=new Test();
        }
}
Ans: we can any nuber of statis blocks, no structural issue, it prints 
static 
static
Main method
instance 
Constructor


Write code to schedule the meeting in outlook, outlook meeting schedule in java

Write code to schedule the meeting in outlook, outlook meeting schedule in java

outlook meeting schedule in java

package com.sree.test;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.MailcapCommandMap;
import javax.activation.MimetypesFileTypeMap;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;


public class JavaMeetingSch {
// attendee is who is going to attand the meeting, if group of people please use string array

public void sendMeeting(String attendee) {

try{
MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap)MimetypesFileTypeMap.getDefaultFileTypeMap();
   mimetypes.addMimeTypes("text/calendar ics ICS");
   MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap();
   mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain");
 
   Properties props = new Properties();
props.put("mail.smtp.host", "host name");
Session session = Session.getDefaultInstance(props, null);

 MimeMessage message = new MimeMessage(session);
 InternetAddress addr = new InternetAddress(attendee);
   message.setFrom(new InternetAddress("srini@org.com"));
   message.setSubject("Monthly meeting");
   message.addRecipient(Message.RecipientType.TO, addr);
       Multipart multipart = new MimeMultipart("alternative");
 
   BodyPart calendarPart = buildCalendarPart();
   multipart.addBodyPart(calendarPart);

   message.setContent(multipart);
   System.out.println("message:"+message);
   // send the message
   Transport.send(message);
   System.out.println("Meeting sent sucessfully");
}catch(Exception e){
System.out.println("Error while sending meeting req:"+e);
}
//    Transport transport = session.getTransport("smtp");
//    transport.connect();
//    transport.sendMessage(message, message.getAllRecipients());
//    transport.close();
}
private static SimpleDateFormat iCalendarDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmm'00'");

    private BodyPart buildCalendarPart() throws Exception {

        BodyPart calendarPart = new MimeBodyPart();

        Calendar cal = Calendar.getInstance();
       
        cal.add(Calendar.DAY_OF_MONTH, 1);
        Date start = cal.getTime();
       String inString= start.toString();
       Date today=null;
     
     
       today = new Date();
         if(inString!=null&inString!=""){
      String day= inString.substring(0, 3) ;
      System.out.println("Day is "+day);
      start=new Date(today.getYear(), today.getMonth(), today.getDate()+1, today.getHours()-4, today.getMinutes()) ;
      if(day.equalsIgnoreCase("Fri")||day.equalsIgnoreCase("Sat")){
   
      start=new Date(today.getYear(), today.getMonth(), today.getDate()+3, today.getHours()-4, today.getMinutes()) ;
     
   
      }
       }
              System.out.println("start: "+start);
              Date end = new Date(today.getYear(), today.getMonth(), today.getDate()+1, today.getHours()-3, today.getMinutes());
        System.out.println("end time:"+end);

        //check the icalendar spec in order to build a more complicated meeting request
        String calendarContent =
                "BEGIN:VCALENDAR\n" +
                        "METHOD:REQUEST\n" +
                        "PRODID: BCP - Meeting\n" +
                        "VERSION:2.0\n" +
                        "BEGIN:VEVENT\n" +
                        "DTSTAMP:" + iCalendarDateFormat.format(end) + "\n" +
                        "DTSTART:" + iCalendarDateFormat.format(start)+ "\n" +
                        "DTEND:"  + iCalendarDateFormat.format(end)+ "\n" +
                        "SUMMARY:test request\n" +
                        "UID:324\n" +
                        "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:srini@org.com\n" +
                        "ORGANIZER:MAILTO:srini@org.com\n" +
                        "LOCATION:Desk\n" +
                        "DESCRIPTION:Please attend the meeting\n" +
                        "SEQUENCE:0\n" +
                        "PRIORITY:1\n" +
                        "CLASS:PUBLIC\n" +
                        "STATUS:CONFIRMED\n" +
                        "TRANSP:OPAQUE\n" +
                        "BEGIN:VALARM\n" +
                        "TRIGGER:PT1440M\n" +
                        "ACTION:DISPLAY\n" +
                        "DESCRIPTION:REMINDER\n" +
                        "END:VALARM\n" +
                        "END:VEVENT\n" +
                        "END:VCALENDAR";

       
        calendarPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
        calendarPart.setHeader("Content-ID","calendar_message");
        calendarPart.setDataHandler(new DataHandler( new ByteArrayDataSource(calendarContent.toString(), "text/calendar")));
        return calendarPart;
    }



}

Interview Questions on Java coding

Interview Questions on Java coding

1)what is the output?
String s="Test";
s=s.substring(1,1);
syso(s)

Ans: print nothing

2)String s="Test";
s.contains("");

Ans: True

3)what is the output?
String s="Test";
String k=s.concats(null);
sysout(k)

Ans: NullPointerException

4)what is the output?
String sp="Java String Split";
                String sp1[]=sp.split("\\s",1);
                
                System.out.println(sp1[0]);

Ans:Java String Split

5) how to print the 2nd table or any table of maths in SQL?
2*1=2
2*2=4
2*3=6
.....
.....
2*10=20
Ans:SELECT '2*'||to_char(level)||'='||to_char(2*LEVEL) FROM dual CONNECT BY LEVEL < 11



critical java interview qustions

critical java interview qustions

  

 How can you determine if JVM is 32-bit or 64-bit from Java Program?
    Can you create an Immutable object that contains a mutable object?
    How can you mark an array volatile in Java?
    What will this return 5*0.1 == 0.5? true or false?
    What is the right data type to represent Money (like Dollar/Pound) in Java
    Is ++ operation thread-safe in Java?
    In Java, can we store a double value in a long variable without explicit casting?
    How can you do constructor chaining in Java?
    How can we find the memory usage of JVM from Java code?
    Can you catch an exception thrown by another thread in Java?
    How can you check if a String is a number by using regular expression?
Most frequently asked java interview questions

Most frequently asked java interview questions

comment your answer or questions
1.Difference between Abstract Class an Interface
2.Why we are using interface in java
3.Why we are using Abstract Class in java
4.Explain static Keyword.
5.Final,Finally, Finalize Keyword in java
6.What is meant by Abstraction
7.Given an example of Encapsulation
8.Difference & and && operators
9.Explain Assertion Keyword in java
10.What is mean serialization.
11.Default object of class in java
12.Default methods in java
13.Default Interfaces in java
14.What is the difference between String and String buffer
15.What is the difference between String Buffer and String Builder
16.what is meant String Tokenizer
17.Difference between Exception and Error with Example
18.Explain Exception Hirearchy
19.Difference between Checked and unchecked Exception with Example
20.Difference between ArrayList and vector
21.Difference between ArrayList and Array
22.Difference between ArrayList and Linked List
23.Define List, Map , Set
24.Difference between HashSet and TreeSet
25.Difference between HashMap and HashTable
26.Difference between HashMap and TreeMap
27.Difference between Comparable and Comparator
28.Difference collection and Collections
29.Explain Hashing alrogithm
30.Why we are using generic in java
31.Why we are using transien varaible in java
32.what is meant String literals in java
33.Difference between throw and throws keyword in java
34.Difference between Aggressition and composition in java
35.List and Map are synchronized in java explain with example
36.Why we are using arraylist in java
37.Why we are using Vector in java
38.Why we are using Linked List in java
39.What is meant fail fast in java
40.What is meant Singleton in java with example
41.Difference between static variable and instance variable
42.Difference between method overloading and overiding
43.Define this and Super keyword in java
44.Define Enum in java
45.Difference between List Iterator and Iterator
46.What is meant by Autoboxing
47.Difference between equals() and hashcode() method in java
48.Explain function of garbage collection in java
49.Difference between List and Set in java
50.Explain feature of Java 5 and Java 6 and Java 7

By:Vimal Kumar V(sr.software engineer,java)
Java Programming and Coding Questions

Java Programming and Coding Questions


1)    How to check if a String contains only numeric digits? (solution)

If you'll be processing the number as text, then change:
if (text.contains("[a-zA-Z]+") == false && text.length() > 2){
to:
if (text.matches("[0-9]+") && text.length() > 2) {
Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.
If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


2) How to write LRU cache in Java using Generics? (answer)

We need to keep a pointer to the LRU and MRU items. The entries' values will be stored in the list and when we we query the HashMap, we will get a pointer to the list. On get(), we need to put the item at the right-most side of the list. On put(key,value), if the cache is full, we need to remove the item at the left-most side of the list from both the list and the HashMap.
import java.util.LinkedHashMap;
import java.util.Iterator;

public class LRUCache {

    private int capacity;
    private LinkedHashMap<Integer,Integer> map;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.map = new LinkedHashMap<>();
    }

    public int get(int key) {
        Integer value = this.map.get(key);
        if (value == null) {
            value = -1;
        } else {
            this.set(key, value);
        }
        return value;
    }

    public void set(int key, int value) {
        if (this.map.containsKey(key)) {
            this.map.remove(key);
        } else if (this.map.size() == this.capacity) {
            Iterator<Integer> it = this.map.keySet().iterator();
            it.next();
            it.remove();
        }
        map.put(key, value);
    }
}


3) Write a Java program to convert bytes to long? (answer)

public byte[] longToBytes(long x) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.putLong(x);
    return buffer.array();
}

public long bytesToLong(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.put(bytes);
    buffer.flip();//need flip
    return buffer.getLong();
}

4) How to reverse a String in Java without using StringBuffer? (solution)

public class ReverseString {

private static String hello = "Hello World";

public static void main(String[] args)
{
System.out.println(reverseString(hello));
}

public static String reverseString(String s) {
char c[] = s.toCharArray();
int i = 0, j = c.length - 1;
while (i < j) {
char tmp = c[i];
c[i] = c[j];
c[j] = tmp;
i++;
j--;
}
return new String(c);
}

5) How to find the word with the highest frequency from a file in Java? (solution)

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
/**
 * Java program to find count of repeated words in a file.
 *
 * @author
 */
public class Problem {

    public static void main(String args[]) {
        Map<String, Integer> wordMap = buildWordMap("C:/temp/words.txt");
        List<Entry<String, Integer>> list = sortByValueInDecreasingOrder(wordMap);
        System.out.println("List of repeated word from file and their count");
        for (Map.Entry<String, Integer> entry : list) {
            if (entry.getValue() > 1) {
                System.out.println(entry.getKey() + " => " + entry.getValue());
            }
        }
    }

    public static Map<String, Integer> buildWordMap(String fileName) {
        // Using diamond operator for clean code
        Map<String, Integer> wordMap = new HashMap<>();
        // Using try-with-resource statement for automatic resource management
        try (FileInputStream fis = new FileInputStream(fileName);
                DataInputStream dis = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(new InputStreamReader(dis))) {
            // words are separated by whitespace
            Pattern pattern = Pattern.compile("\\s+");
            String line = null;
            while ((line = br.readLine()) != null) {
                // do this if case sensitivity is not required i.e. Java = java
                line = line.toLowerCase();
                String[] words = pattern.split(line);
                for (String word : words) {
                    if (wordMap.containsKey(word)) {
                        wordMap.put(word, (wordMap.get(word) + 1));
                    } else {
                        wordMap.put(word, 1);
                    }
                }
            }
        } catch (IOException ioex) {
            ioex.printStackTrace();
        }
        return wordMap;
    }

    public static List<Entry<String, Integer>> sortByValueInDecreasingOrder(Map<String, Integer> wordMap) {
        Set<Entry<String, Integer>> entries = wordMap.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<>(entries);
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });
        return list;
    }
}

Output:
List of repeated word from file and their count
its => 2
of => 2
programming => 2
java => 2
language => 2


6) How do you check if two given String are anagrams? (solution)

package miscellaneous;

/*
 * We increment the count of each character in the first array and
 * decrement the count of each character in the second array.
 *
 * If the resulting counts array is full of zeros, then strings are anagrams otherwise not.
 */
public class Find2StringAreAnagramsOfEachOther {

 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  System.out.println("Anagram?? :"+isAnagram(str1, str2));
 }

 private static boolean isAnagram(String a, String b){
 
  //if both string is null, then considering it as anagram.
  if(a==b){
   return true;
  }

  //if any one string is null, then they are not anagram.
  if(a==null || b==null)
   return false;
 
  //If length of both strings are not same then obviously they are not anagrams.
  if(a.length()!=b.length())
   return false;
 
  char[] aArr = a.toLowerCase().toCharArray();
  char[] bArr = b.toLowerCase().toCharArray();
 
  // An array to hold the number of occurrences of each character
  int[] counts = new int[26];
 
  for (int i = 0; i < aArr.length; i++){
   counts[aArr[i]-97]++;  // Increment the count of the character at respective position
   counts[bArr[i]-97]--;  // Decrement the count of the character at respective position
  }
 
  // If the strings are anagrams, then counts array will be full of zeros not otherwise
  for (int i = 0; i<26; i++){
   if (counts[i] != 0)
    return false;
  }
 
  return true;
 }
}


7) How to print all permutation of a String in Java? (solution)

package com.journaldev.string.permutation;

import java.util.HashSet;
import java.util.Set;

/**
 * Java Program to find all permutations of a String
 * @author pankaj
 *
 */
public class StringHelper {
    public static Set<String> permutationFinder(String str) {
        Set<String> perm = new HashSet<String>();
        //Handling error scenarios
        if (str == null) {
            return null;
        } else if (str.length() == 0) {
            perm.add("");
            return perm;
        }
        char initial = str.charAt(0); // first character
        String rem = str.substring(1); // Full string without first character
        Set<String> words = permutationFinder(rem);
        for (String strNew : words) {
            for (int i = 0;i<=strNew.length();i++){
                perm.add(charInsert(strNew, initial, i));
            }
        }
        return perm;
    }

    public static String charInsert(String str, char c, int j) {
        String begin = str.substring(0, j);
        String end = str.substring(j);
        return begin + c + end;
    }

    public static void main(String[] args) {
        String s = "AAC";
        String s1 = "ABC";
        String s2 = "ABCD";
        System.out.println("\nPermutations for " + s + " are: \n" + permutationFinder(s));
        System.out.println("\nPermutations for " + s1 + " are: \n" + permutationFinder(s1));
        System.out.println("\nPermutations for " + s2 + " are: \n" + permutationFinder(s2));
    }
}


8 How do you print duplicate elements from an array in Java? (solution)

public class DuplicatesInArray
{  
    public static void main(String[] args)
    {
        String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"};

        for (int i = 0; i < strArray.length-1; i++)
        {
            for (int j = i+1; j < strArray.length; j++)
            {
                if( (strArray[i].equals(strArray[j])) && (i != j) )
                {
                    System.out.println("Duplicate Element is : "+strArray[j]);
                }
            }
        }
    }   
}


9) How to convert String to int in Java? (solution)

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

There is a slight difference between these methods:
•    valueOf returns a new or cached instance of java.lang.Integer
•    parseInt returns primitive int.
The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.


10) How to swap two integers without using temp variable? (solution)


a = a + b;
b = a - b;
a = a - b;

For strings (by using a temporary variable for the length):
 int len1 = s1.length();
s1 = s1 + s2;
 s2 = s1.substring(0, len1);
s1 = s1.substring(len1);




JVM Internals and Garbage Collection Interview Questions

JVM Internals and Garbage Collection Interview Questions

Q1.  When are static variables loaded in memory ?

Ans. They are loaded at runtime when the respective Class is loaded. 

Q2.  What is a String Pool ?

Ans. String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

Q3.  how many objects are created with this code ?

String s =new String("abc"); 

Ans. Two objects will be created here. One object creates memory in heap with new operator and second in stack constant pool with "abc".

Q4.  Which are the different segments of memory ?

Ans. 

1. Stack Segment - contains local variables and Reference variables(variables that hold the address of an object in the heap)

2. Heap Segment - contains all created objects in runtime, objects only plus their object attributes (instance variables)

3. Code Segment -  The segment where the actual compiled Java bytecodes resides when loaded

Q5.  Which memory segment loads the java code ?

Ans. Code segment.

Q6.  Does garbage collection guarantee that a program will not run out of memory?

Ans. Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection

Q7.  Describe what happens when an object is created in Java ?

Ans. 

1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.

2. The instance variables of the objects are initialized to their default values.

3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.

4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

Q8.  Describe, in general, how java's garbage collector works ?

Ans. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected.

Q9.  Can I import same package/class twice? Will the JVM load the package twice at runtime?

Ans. One can import the same package or same class multiple times. Neither compiler nor JVM complains wil complain about it. And the JVM will internally load the class only once no matter how many times you import the same class.

Q10.  Different types of memory used by JVM ?

Ans. Class , Heap , Stack , Register , Native Method Stack.

Q11.  What is a class loader ? What are the different class loaders used by JVM ?

Ans. Part of JVM which is used to load classes and interfaces.

Bootstrap , Extension and System are the class loaders used by JVM.

Q12.  Explain java.lang.OutOfMemoryError ?

Ans. This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

Q13.  Is JVM, a compiler or interpretor ?

Ans. Its an interpretor.

Q14.  Difference between loadClass and Class.forName ?

Ans. loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the object after loading it.

Q15.  Should we override finalize method ?

Ans. Finalize is used by Java for Garbage collection. It should not be done as we should leave the Garbage Collection to Java itself.

Q16.  Which kind of memory is used for storing object member variables and function local variables ?

Ans. Local variables are stored in stack whereas object variables are stored in heap.

Q17.  Why do member variables have default values whereas local variables don't have any default value ?

Ans. member variable are loaded into heap, so they are initialized with default values when an instance of a class is created. In case of local variables, they are stored in stack until they are being used.

Q18.  Why Java don't use pointers ?

Ans. Pointers are vulnerable and slight carelessness in their use may result in memory problems and hence Java intrinsically manage their use. 

Q19.  What are various types of Class loaders used by JVM ?

Ans. 

Bootstrap - Loads JDK internal classes, java.* packages.

Extensions - Loads jar files from JDK extensions directory - usually lib/ext directory of the JRE

System  - Loads classes from system classpath. 

Q20.  How are classes loaded by JVM ?

Ans. Class loaders are hierarchical. The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running.