Skip to content

brenelz/java-basicstestusersnew

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

98 Commits
 
 
 
 
 
 

Repository files navigation

Core-Java

  1. Difference between Heap and Stack in java?
  2. What are the important features of Java 8 release?
  3. What is JVM and is it platform independent?
  4. What is JIT compiler?
  5. What is Classloader in Java? What are different types of classloaders?
  6. Java Compiler is stored in JDK, JRE or JVM?
  7. What is the difference between factory and abstract factory pattern?
  8. What are the methods used to implement for key Object in HashMap?
  9. Difference between Serialization and Deserialization in Java.
  10. What is SerialVersionUID?
  11. Difference between the Inner Class and Sub Class.
  12. What are the advantages of JSON over XML?
  13. Can we import same package/class two times? Will the JVM load the package twice at runtime?
  14. Distinguish between static loading and dynamic class loading?
  15. How can we find the actual size of an object on the heap?
  16. Why we use Vector class?
  17. What is the difference between transient and volatile variable in Java?
  18. Mention the uses of Synchronized block
  19. What is the default size of load factor in hashing based collection?
  20. Write a code to make Collections readOnly?
  21. Distinguish between a predicate and a function?
  22. What is Nashorn in Java8?
  23. How many types of memory areas are allocated by JVM?
  24. What will be the initial value of an object reference which is defined as an instance variable?
  25. How can constructor chaining be done using this keyword?
  26. Can you declare the main method as final?
  27. Can we declare a constructor as final?
  28. Can we declare an interface as final?
  29. What is the difference between the final method and abstract method?
  30. What is the difference between compile-time polymorphism and runtime polymorphism?
  31. Can you achieve Runtime Polymorphism by data members?
  32. Can you have virtual functions in Java?
  33. What is covariant return type?
  34. What is the difference between abstraction and encapsulation?
  35. Can there be an abstract method without an abstract class?
  36. Can you declare an interface method static?
  37. What is a marker interface?
  38. Can we define private and protected modifiers for the members in interfaces?
  39. When can an object reference be cast to an interface reference?
  40. How the metacharacters are different from the ordinary characters?
  41. Give the hierarchy of InputStream and OutputStream classes.
  42. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
  43. What is the purpose of the finalize() method?
  44. What is difference between CyclicBarrier and CountDownLatch in Java ?
  45. What will be the problem if you don't override hashcode() method
  46. Can you access non static variable in static context?
  47. What is the purpose of the Runtime class and System class?
  48. What are FilterStreams?
  49. What are assertions in Java?
  50. Can we have multiple public classes in a java source file?
  51. What is Java Package and which package is imported by default?
  52. What is static keyword?
  53. What is final, finally and finalize in java?
  54. What is the difference between abstract class and interface?
  55. What are Wrapper classes?
  56. What is Java Annotations?
  57. What is Java Reflection API?
  58. What is anonymous inner class?
  59. What is default constructor?
  60. Java is Pass by Value or Pass by Reference?
  61. What is singleton class and how can we make a class singleton?
  62. What is the numeric promotion?
  63. Which API is provided by Java for operations on a set of objects?
  64. Is delete, next, main, exit or null keyword in java?
  65. What is the default value of the local variables?
  66. How many types of constructors are used in Java?
  67. What do you understand by copy constructor in Java?
  68. What are the restrictions that are applied to the Java static methods?
  69. What is the difference between aggregation and composition?
  70. What is object cloning?
  71. What is method overloading with type promotion?
  72. Can we override the private methods?
  73. Can we change the scope of the overridden method in the subclass?
  74. What is the final variable, final class, and final blank variable?
  75. How to make a read-only and write-only class in Java?
  76. What are the advantages of Encapsulation in Java?
  77. What is the static import?
  78. Name some classes present in java.util.regex package.
  79. What is a nested class? Is there any difference between nested classes and inner classes?
  80. What is the nested interface?
  81. How will you invoke any external process in Java?
  82. What do you understand by an IO stream?
  83. What are the super most classes for all the streams?
  84. What is the purpose of using BufferedInputStream and BufferedOutputStream classes?
  85. How to set the Permissions to a file in Java?
  86. In Java, How many ways you can take input from the console?
  87. How can you avoid serialization in child class if the base class is implementing the Serializable interface?
  88. Can a Serialized object be transferred via network?
  89. What is the difference between Serializable and Externalizable interface?
  90. How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
  91. What is the purpose of using java.lang.Class class?
  92. What are the ways to instantiate the Class class?
  93. What is the purpose of using javap?
  94. What are autoboxing and unboxing? When does it occur?
  95. What is a native method?
  96. What comes to mind when someone mentions a shallow copy in Java?
  97. What is Locale?
  98. What is the right data type to represent a price in Java?
  99. What will happen if you put return statement or System.exit () on try or catch block? Will finally block execute?
  100. What will happen if we put a key object in a HashMap which is already there?
  101. If a method throws NullPointerException in the superclass, can we override it with a method which throws RuntimeException?
  102. What is immutable object? Can you write immutable object?

Java OOPS

  1. What is runtime polymorphism or dynamic method dispatch?
  2. What is difference between dependency injection and factory design pattern?
  3. Difference between Adapter and Decorator pattern?
  4. Difference between Adapter and Proxy Pattern?
  5. What is Template method pattern?
  6. When do you use Visitor design pattern?
  7. When do you use Composite design pattern?
  8. The difference between Inheritance and Composition?
  9. Difference between Abstract factory and Prototype design pattern?
  10. What is Adapter pattern? When to use it?
  11. The difference between nested public static class and a top level class in Java?
  12. Give me an example of design pattern which is based upon open closed principle?
  13. Can you explain Liskov Substitution principle?
  14. What is Law of Demeter violation? Why it matters?
  15. When do you use Flyweight pattern?
  16. The difference between nested static class and top level class?
  17. The difference between DOM and SAX parser in Java?
  18. What is the difference between an object-oriented programming language and object-based programming language?
  19. Difference between Static binding and Dynamic binding in java ?

Multithreading

  1. What is difference between Executor.submit() and Executer.execute() method?
  2. Can we make array volatile in Java?
  3. What are practical uses of volatile modifier?
  4. What are the different ways of implementing thread? Which one is more advantageous?
  5. What kind of thread is the Garbage collector thread?
  6. What is the difference between Process and Thread?
  7. What are the benefits of multi-threaded programming?
  8. What is difference between user Thread and daemon Thread?
  9. How can we pause the execution of a Thread for specific time?
  10. What do you understand about Thread Priority?
  11. What is Thread Scheduler and Time Slicing?
  12. What is context-switching in multi-threading?
  13. How does thread communicate with each other?
  14. Which is more preferred – Synchronized method or Synchronized block?
  15. What is Deadlock? How to analyze and avoid deadlock situation?
  16. What is Java Timer Class? How to schedule a task to run after specific interval?
  17. What is Thread Pool? How can we create Thread Pool in Java?
  18. Why must wait() method be called from the synchronized block?
  19. What are the states in the lifecycle of a Thread?
  20. What is the difference between wait() and sleep() method?
  21. What is shutdown hook?
  22. Can Java object be locked down for exclusive use by a given thread?
  23. What is static synchronization?
  24. How is the safety of a thread achieved?
  25. Difference between start() and run() method of thread class.
  26. How do you call wait() method? using if block or loop? Why?
  27. What is false sharing in the context of multi-threading?
  28. What is Thread Group? Why it’s advised not to use it?
  29. What best practices you follow while writing Multi-threading and Concurrency code in Java?
  30. How do you stop a thread in java?
  31. Can we call run() method of a Thread class?
  32. How can we make sure main() is the last thread to finish in Java Program?
  33. Why Thread sleep() and yield() methods are static?
  34. What is ThreadLocal?
  35. What is Java Thread Dump, How can we get Java Thread dump of a Program?
  36. What will happen if we don’t override Thread class run() method?
  37. Differentiate between the Thread class and Runnable interface for creating a Thread?
  38. What does join() method?
  39. Can we make the user thread as daemon thread if the thread is started?

Concurrency

  1. What is race-condition?
  2. What is the difference between ScheduledExecutorService and ExecutorService interface?
  3. What does yield method of the Thread class do?
  4. What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?
  5. What are Concurrent Collection Classes?
  6. What is the difference between the Runnable and Callable interfaces?
  7. What is the Thread’s interrupt flag? How can you set and check it? How does it relate to the InterruptedException?
  8. What is Java Memory Model (JMM)? Describe its purpose and basic ideas.
  9. Describe the conditions of livelock, and starvation.
  10. How ReadWritelock can help in reducing contention among multiple threads?
  11. What is the Difference between ReentrantLock and Synchronized?
  12. What is SynchronousQueue in Java?
  13. Why ConcurrentHashMap is faster than Hashtable in Java?
  14. How do you share data between two threads in Java?
  15. Describe the purpose and use-cases of the fork/join framework
  16. What is Phaser in Java concurrency?
  17. What is Exchanger in Java concurrency?
  18. What is Semaphore in Java concurrency?
  19. What is lock striping in concurrent programming?
  20. What is blocking method in Java?
  21. What is Callable and Future in Java concurrency?
  22. What is atomic variable in Java?
  23. What is Busy Spinning? Why will you use Busy Spinning as wait strategy?
  24. What is Executors Framework?
  25. What is FutureTask class?
  26. What are the available implementations of ExecutorService in the standard library?
  27. What are the main components of concurrency API?

Collections

  1. What is Java Collections Framework? List out some benefits of Collections framework?
  2. What is the benefit of Generics in Collections Framework?
  3. Why Collection doesn’t extend Cloneable and Serializable interfaces?
  4. Why Map interface doesn’t extend Collection interface?
  5. What is difference between Enumeration and Iterator interface?
  6. What is different between Iterator and ListIterator?
  7. What are different ways to iterate over a list?
  8. What is the difference between fail-fast and fail-safe iterator?
  9. How to avoid ConcurrentModificationException while iterating a collection?
  10. Why there are no concrete implementations of Iterator interface?
  11. What are different Collection views provided by Map interface?
  12. What is difference between HashMap and Hashtable?
  13. What are similarities and difference between ArrayList and Vector?
  14. What is difference between Array and ArrayList?
  15. What is difference between ArrayList and LinkedList?
  16. Which collection classes provide random access of it’s elements?
  17. What is EnumSet?
  18. What are concurrent Collection Classes?
  19. What is BlockingQueue? How to implement producer-consumer problem by using BlockingQueue?
  20. What is Queue and Stack, list their differences?
  21. What is difference between Comparable and Comparator interface?
  22. How can we sort a list of Objects?
  23. While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?
  24. How can we create a synchronized collection from given collection?
  25. What are common algorithms implemented in Collections Framework?
  26. What are best practices related to Java Collections Framework?
  27. What is Java Priority Queue?
  28. What is LinkedHashMap in Java?
  29. Which kind of tree is used to implement TreeMap in Java?
  30. What is default size of ArrayList and HashMap in Java?
  31. What is the difference between HashSet and TreeSet?
  32. What is the difference between Set and Map?
  33. What is the difference between HashSet and HashMap?
  34. What is the difference between HashMap and TreeMap?
  35. What is the difference between Collection and Collections?
  36. What is the advantage of the generic collection?
  37. What is hash-collision in Hashtable and how it is handled in Java?
  38. What is the Dictionary class?
  39. How to synchronize ArrayList?
  40. What are all the Classes and Interfaces that are available in the collections?
  41. What is meant by Ordered and Sorted in collections?
  42. Explain about the different lists available in the collection.
  43. Explain about Map and their types.
  44. What is the difference between List and Set?
  45. What is the difference between peek(), poll() and remove() method of the Queue interface?
  46. What is the difference between HashMap and ConcurrentHashMap?
  47. What is CopyOnWriteArrayList? How it is different from ArrayList in Java?
  48. What are concurrentCollectionClasses?
  49. How to make Java ArrayList Read-Only?
  50. How to remove duplicates from ArrayList?
  51. How to reverse ArrayList?
  52. How to sort ArrayList in descending order?
  53. Which design pattern followed by Iterator ?
  54. What is difference between IdentityHashMap and HashMap in Java?
  55. What is CompareAndSwap approach?
  56. Why there is not method like Iterator.add() to add elements to the collection?
  57. What is ConcurrentLinkedQueue in Java?
  58. What is ConcurrentLinkedDequeue in Java?
  59. What is difference between ArrayBlockingQueue & LinkedBlockingQueue in Java Concurrency?
  60. What is PriorityBlockingQueue in Java Concurrency?
  61. What is DelayQueue in Java Concurrency?

Servlets

  1. What is a Server Side Include (SSI)?
  2. What is the difference between doGet() and doPost()?
  3. What is a servlet? What is the life-cycle of a servlet?
  4. What are the differences between Get and Post methods?
  5. What is Request Dispatcher?
  6. What are the differences between forward() method and sendRedirect() methods?
  7. How does cookies work in Servlets?
  8. What are the differences between ServletContext vs ServletConfig?
  9. What are the different methods of session management in servlets?
  10. What is MIME Type?
  11. What is the use of servlet wrapper classes?
  12. What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?
  13. Why HttpServlet class is declared abstract?
  14. What is difference between GenericServlet and HttpServlet?
  15. How to notify an object in session when session is invalidated or timed-out?
  16. What is servlet attributes and their scope?
  17. How can we achieve transport layer security for our web application?
  18. What is a deployment descriptor?
  19. How to make sure a servlet is loaded at the application startup?
  20. Write a servlet to upload file on server.
  21. How do we go with database connection and log4j integration in servlet?
  22. What is the effective way to make sure all the servlets are accessible only when user has a valid session?
  23. Why do we have servlet listeners?
  24. What are Scriptlets ?
  25. What is different between web server and application server?
  26. Which HTTP method is non-idempotent?
  27. What are the advantages of Servlet over CGI?
  28. What are common tasks performed by Servlet Container?
  29. What is difference between PrintWriter and ServletOutputStream?
  30. How can we create deadlock situation in servlet?
  31. What is SingleThreadModel interface?
  32. Do we need to override service() method?
  33. Is it good idea to create servlet constructor?
  34. What is the inter-servlet communication?
  35. Are Servlets Thread Safe? How to achieve thread safety in servlets?
  36. How do we call one servlet from another servlet?
  37. why we should override only no-airs init() method.
  38. What is the difference between encodeRedirectUrl and encodeURL?
  39. Why do we have servlet filters?
  40. How to handle exceptions thrown by application with another servlet?
  41. What are different ways for servlet authentication?
  42. What is Servlet Chaining?
  43. How do you find out what client machine is making a request to your servlet?

JDBC

  1. What are the steps to connect to a database in java?
  2. What are the differences between ResultSet and RowSet?
  3. How can we execute stored procedures using CallableStatement?
  4. What are CLOB and BLOB data types in JDBC?
  5. What are the different types of lockings in JDBC?
  6. How can we store and retrieve images from the database?
  7. How can we store and retrieve the file in the Oracle database?
  8. What are the differences between stored procedure and functions?
  9. What are stored procedures? How to call stored procedure using JDBC API?
  10. What are the JDBC statements?
  11. What is batch processing and how to perform batch processing in JDBC?
  12. What are the differences between Statement and PreparedStatement interface?
  13. What is database connection pooling? What are the advantages of using a connection pool?
  14. What is JDBC Driver?
  15. Name 5 JDBC best practices your follow?
  16. What are the JDBC API components?
  17. What is the role of JDBC DriverManager class?
  18. What is JDBC Connection interface?
  19. What is the purpose of JDBC ResultSet interface?
  20. What is JDBC ResultSetMetaData interface?
  21. What is JDBC DatabaseMetaData interface?
  22. What is the return type of Class.forName() method?
  23. How can we set null value in JDBC PreparedStatement?
  24. What are the differences between execute, executeQuery, and executeUpdate?
  25. Which interface is responsible for transaction management in JDBC?
  26. How can we maintain the integrity of a database by using JDBC?
  27. What is the major difference between java.util.Date and java.sql.Date data type?
  28. How do you handle error condition while writing stored procedure or accessing stored procedure from java?
  29. How do you iterate ResultSet in the reverse order?
  30. What is the use of setAutoCommit() method?
  31. What is a “dirty read”?
  32. What are the ways to load or register driver ?
  33. How to get the Database server details in java program?
  34. What is the use of getGeneratedKeys() method in Statement?
  35. What is the use of setFetchSize() and setMaxRows() methods in Statement?
  36. What is JDBC Savepoint? How to use it?

String

  1. Define a StringJoiner and write a sample code?
  2. What is the difference between creating String as new() and literal?
  3. Why is char array better than String for storing password?
  4. Why are the objects immutable in java?
  5. How many ways can we create the string object?
  6. How can we create an immutable class in Java?
  7. Why CharArray() is preferred over String to store the password?
  8. Why strings have been made immutable in Java?
  9. What is String Constant Pool?
  10. What is String Pool?
  11. Difference between String, StringBuffer and StringBuilder?
  12. Why String is immutable or final in Java
  13. Memory leak issue in String class
  14. How many objects will be created with string initialization code?
  15. What is String in Java? How does String work in Java? String is a data type?
  16. What are different ways to create String Object?
  17. How can we make String upper case or lower case?
  18. What is String subSequence method?
  19. How to convert String to char and vice versa?
  20. How to convert String to byte array and vice versa?
  21. Can we use String in switch case?
  22. How to Split String in java?
  23. Why Char array is preferred over String for storing password?
  24. How do you check if two Strings are equal in Java?
  25. Does String is thread-safe in Java?
  26. Why String is popular HashMap key in Java?
  27. How do you check if two Strings are equal in Java?
  28. What does String intern() method do?
  29. How to convert String to int and vice versa?
  30. How to convert String to Date in java?
  31. How do you convert bytes to String?
  32. How to Optimize Java String Creation?
  33. Is String keyword in Java?
  34. String comparison with equals() and '=='?
  35. How do you convert a String(YYYYMMDD) to date in Java?
  36. Why java uses the concept of the string literal?
  37. What is the purpose of toString() method in Java?

Exception Handling

  1. What is UnsupportedOperationException?
  2. What is difference between Error and Exception?
  3. What are the types of Exceptions? Explain the hierarchy of Java Exception classes?
  4. Explain about Exception Propagation.
  5. What’s the base class of all exception classes?
  6. What are important methods of Java Exception Class?
  7. How to write custom exception in Java?
  8. What is OutOfMemoryError in Java?
  9. What are different scenarios causing “Exception in thread main”?
  10. What happens when exception is thrown by main method?
  11. Provide some Java Exception Handling Best Practices?
  12. What are the differences between Checked Exception and Unchecked Exception?
  13. What purpose does the keywords final, finally, and finalize, fulfill?
  14. What are the differences between throw and throws?
  15. What is a finally block? Is there a case when finally will not execute?
  16. What is the base class for Error and Exception?
  17. Is it necessary that each try block must be followed by a catch block?
  18. Can finally block be used without a catch?
  19. Is there any case when finally will not be executed?
  20. Can an exception be rethrown?
  21. Can subclass overriding method declare an exception if parent class method doesn't throw an exception?
  22. What will happen to the Exception object after exception handling?

Garbage Collection

  1. How can an object be unreferenced?
  2. What is the purpose of garbage collection in Java, and when is it used?
  3. The difference between Serial and Parallel Garbage Collector?
  4. A difference between WeakReference and SoftReference in Java?
  5. Explain Java Heap space and Garbage collection?
  6. How do you find memory usage from Java program? How much percent of the heap is used?
  7. What is the difference between stack and heap in Java?
  8. What does System.gc() and Runtime.gc() methods do?
  9. How do WeakHashMap works?
  10. What is -XX:+UseCompressedOops JVM option? Why use it?
  11. How do you find if JVM is 32-bit or 64-bit from Java Program?
  12. What is the maximum heap size of 32-bit and 64-bit JVM?
  13. Can you guarantee the garbage collection process?
  14. What's the difference between "a == b" and "a.equals(b)"?
  15. What is a.hashCode() used for? How is it related to a.equals(b)?
  16. What is a compile time constant in Java? What is the risk of using it?
  17. What is the size of int in 64-bit JVM?
  18. What is the size of an int variable in 32-bit and 64-bit JVM?
  19. If an object reference is set to null, will the Garbage Collector immediately free the memory held by that object?
  20. What is the difference between Serial and Throughput Garbage collector?
  21. Does Garbage collection occur in permanent generation space in JVM?
  22. When does an Object becomes eligible for Garbage collection in Java?

JavaServer Pages (JSP)

  1. What are the life-cycle methods for a jsp?
  2. How to disable caching on back button of the browser?
  3. What are the different tags provided in JSTL?
  4. How to disable session in JSP?
  5. How to delete a Cookie in a JSP?
  6. How is JSP better than Servlet technology?
  7. What are the JSP implicit objects?
  8. What are the differences between include directive and include action?
  9. Explain the jspDestroy() method.
  10. Why should we not configure JSP standard tags in web.xml?
  11. What is busy spin? Why should you use it?
  12. How do you take thread dump in Java?
  13. is Swing thread-safe?
  14. What is a thread local variable in Java?
  15. Can we create an Immutable object, which contains a mutable object?
  16. How do you convert bytes to long in Java?
  17. Can we cast an int value into byte variable? what will happen if the value of int is larger than byte?
  18. There are two classes B extends A and C extends B, Can we cast B into C e.g. C = (C) B;
  19. Which class contains clone method? Cloneable or Object?
  20. Is ++ operator is thread-safe in Java?
  21. Difference between a = a + b and a += b ?
  22. Can I store a double value in a long variable without casting?
  23. What will this return 3*0.1 == 0.3? true or false?
  24. Which one will take more memory, an int or Integer?
  25. Explain Expression Language in JSP?
  26. Which containers use a border layout as their default layout?
  27. Which containers use a FlowLayout as their default layout?
  28. What are peerless components?
  29. is there is any difference between a Scrollbar and a ScrollPane?
  30. What is a lightweight component?
  31. What is a heavyweight component?

JUnit Testing

  1. How do you test static method?
  2. How to do you test a method for an exception using JUnit?
  3. Which unit testing libraries you have used for testing Java programs?
  4. What is the difference between @Before and @BeforeClass annotation?
  5. How to check if a String contains only numeric digits?
  6. How to write LRU cache in Java using Generics?
  7. How do you check if two given String are anagrams?

Miscellaneous

  1. What is rt.jar
  2. How bootstrap class loader works
  3. Why string is immutable in java
  4. Explain string pool
  5. Explain how Garbage collector algorithm works
  6. Explain JoinPoint and Pointcut in spring
  7. Interceptors in spring
  8. Why do we need to Wrapper classes.
  9. How does hibernate loads values from Table to Entity.
  10. How Website caching works
  11. What are the various ways you will secure a website.
  12. How to create marker interface
  13. Explain how hashMap works
  14. Write a code to implement hashMap, arrayList
  15. Difference between arrayList and linkedList
  16. How do you configure Hibernate with Spring for a webapp?
  17. What are jsp implicit objects?
  18. Difference between sendRedirect and forward
  19. Use of UML diagram (sequence,activity,usecase) and what are the tools used to draw the same.
  20. Tell me what happens when a servlet is invoked, when is init invoked and when is sevice invoked.
  21. servlet, ejb, jsp lifecycle
  22. What are the major additions for jdk from 1.7 to 1.8 and so on.
  23. Show how serialization in java works
  24. Better way to manage transactions.
  25. say we have metadata information for a table, that is common to so many pages in jsp then tell me the better way to implement the same.
  26. What are the various ways to load a class.
  27. private keys and public keys + sha1 and similar algorithm implementation.
  28. How to do authentication with LDAP server.
  29. Implement link list
  30. design patterns related question(Singleton, Adaptor, Factory, Strategy)
  31. Implement bucketing using map. There is one interface named customer and other class implement this interface. Now in a map the objects of similar class should go in one bucket.
  32. Spring bean scope.
  33. What is AOP. what does spring AOP provide.what is point cut, join point.
  34. What is servlet context. parameter, argument.
  35. equals() and hashcode() contract between them.
  36. How set implement unique values.
  37. comparable and comparator difference.
  38. About spring transaction.
  39. DAO factory pattern.
  40. How to stop thread.
  41. insert a uppercase value into map without using toUpperCase() of string class.
  42. How do you implement immutable to a class.
  43. While overriding a method can you throw another exception or broader exception.
  44. How binding of Database table happens with the POJO in Hibernate.
  45. if you have hbm.xml for an entity and also you have annotated the entity then which will be overridden.
  46. Difference between entryset and keyset.
  47. Is SessionFactory thread safe.
  48. A java prog in windows, how will u run it on linux machine
  49. What is checked, unchecked exception and errors.
  50. What are the different ways to load the Spring container.
  51. How to insert in a Map key as value and value as key
  52. Write a program to read the data from stack and pass the same to the queue
  53. What are the measures that should be taken to scale the application
  54. What is the use of noSql db
  55. How to implement custom annotation which does logging in spring
  56. How to integrate MQ with ESB like camel
  57. How to implement transaction management in spring
  58. How to implement multiple datasources with spring data jpa
  59. How to implement webservices with spring using custom annotation
  60. How to integrate SMS with JMS
  61. How spring spring interceptors work
  62. Difference between @Service and @Component tags
  63. Connecting oracle, mysql, and nosql db like mongo db together
  64. Implement your own String class
  65. Jdk1.8 features like lamda expressions
  66. Implement your own HashMap, like LinkedHashMap
  67. How does xquery work implement the same
  68. There are 2 threads one thread reads a file and other writes the same to a file how to implement the same
  69. How do you identify deadlock has happened in prod environment
  70. How is grid computing implemented in oracle
  71. How do you find third highest salary
  72. difference between procedures and triggers
  73. How to call the same from hibernate
  74. Advantage of spring cloud eureka
  75. Why is string class immutable?
  76. Array and arrayList what is the difference in datastructure
  77. Different ways to create singleton in spite of cloning or serialization
  78. bootstrap, class.forname, permgen what way are these done
  79. How microservices communicate with each other
  80. How does class loader work
  81. Array or ArrayList which one is faster?
  82. Provide design principle and design for User login.
  83. How to prevent from database attacks
  84. What are the idp server that you use for SSO implementation.
  85. Various ways that you implement JAAS.
  86. Various ways that you secure your website.
  87. Assume you have a singly linked list, now you need to find reverse of it without using new operator.
  88. Name design patterns used in collection framework.
  89. Object oriented feature like: Association, Composition, Aggregation
  90. Difference between DI and IOC in spring.
  91. Optimistic vs pessimistic locking in table level and row level.
  92. Main advantage of restful implementation over SOAP
  93. How do you provide security features in REST and SOAP requests?
  94. How do you implement secondary level cache? Clustering?
  95. What is SQL injection attack?
  96. Difference between symmetric , public and private keys, plz tell the procedure to implement the same using spring security.
  97. What code coverage tools are you using for your project? (we use cobetura, you can use it with ant , maven, gradle)
  98. Implement thread-safe code without using the synchronized keyword?
  99. Design parking lot with 100 parking space.
  100. Use of Drools
  101. Scenario of browser’s browsing history, where you need to store the browsing history, what data structure will you use.?
  102. Scenario where in we have to download a big file by clicking on a link, how will you make sure that connections is reliable throughout.
  103. If you store Employee object as key say: Employee emp = new Employee(“name1”,20); store it in a HashMap as key, now if we add a new parameter emp.setMarriedStatus(true) and try to override it what will happen?
  104. JDK 1.8 features.
  105. Given a string "abc" or any other string print all possible combinations of it.
  106. When is string pool garbage collected.
  107. What is the complexity of qadtree algorithm
  108. When is string stored in string pool and what are other possibilities.
  109. Spring MVC flow (what design patterns do it use).
  110. Given a requirement where in we have a html file and textbox: -> user can enter number( find sum of digits) -> user can enter string (print the string) -> user can enter JSON object (print the attributes) -> user can enter function name: add(2,3) (invoke the respective function.) Based on user input perform the indicated task in parenthesis.
  111. Given table Employee and Department write a sql statement to find count of employees department
  112. Design patterns used in Javascript.
  113. 2 way data binding in angular.
  114. We are using a string object from string constant pool, how does it behave during concurrent programming.
  115. Difference between classnotfound and noclassdeffound
  116. What do we mean by weak reference
  117. Difference bw hashset and linkedhashset
  118. Difference bw delete and truncate
  119. oauth1.0 vs oauth 2.0
  120. java Implementation Rules : https://rules.sonarsource.com/java/RSPEC-2066
  121. What do you mean Run time Polymorphism?
  122. How will you create thread?
  123. Why implementing Runnable is better than extending thread?
  124. Please list out the features of OOPS?
  125. What is the Use of Synchronized?
  126. What is the difference between HashTable and HashMap?
  127. What will happen if I insert duplicate key-pair value inserted in to HashTable?
  128. Differentiate ArrayList from Vector?
  129. How do you sort out items in ArrayList in forward and reverse directions?
  130. What is Thread ? Why we go for multi-threading?
  131. Tell me about join() and wait() methods?
  132. Could you tell in what scenario you go for Abstract Class & Interface?
  133. If Parent Class have a method add() throws XXXException, and child class overrides same method without Exception, will that compile and run? Is it overridden or overloaded?
  134. Is substring() method creates new object in String pool?
  135. What are two uses of the equals() method?
  136. If I don't have Explicit constructor in parent class and having in child class, while calling the child's constructor jvm automatically calls Implicit Constructor of parent class? Yes OR No ?
  137. What are the different types of JDBC Driver?
  138. What is abstraction in JAVA?
  139. What is inheritance in JAVA?
  140. How Encapsulation concept implemented in JAVA?
  141. What do you mean checked and unchecked Exceptions? List some example for both?
  142. Why we go for Collections Framework?
  143. I want to have ordered collection, which allows duplicates? Which collection is used for this?
  144. I want to have class, which have the behavior of Hash-map? How this can be done?
  145. What hashCode() and equals() does in HashMap?
  146. Do you know Generics? What is it? Why we need that? How did you used in your coding?
  147. Why we prefer implements Runnable to create THREAD?
  148. Difference between String and StringBuilder and StringBuffer ?
  149. What is the use of default Constructor?
  150. What is the use of static block?
  151. How can we create a object of a class without using new operator
  152. what are the purposes of native, transiant key words?
  153. what are upcasting and downcasting?

Java Programs

  1. A maximal subarray
  2. Sort a linked list
  3. Iterative Quick sort
  4. Bucket sort
  5. Counting sort
  6. Find missing number in an array
  7. Generate random numbers
  8. How to reverse Singly Linked List?
  9. Create a Java program to find middle node of linked list in Java in one pass?
  10. How to find if a linked list contains cycle or not in Java?
  11. How to find nth element from end of linked list
  12. How to check if linked list is palindrome in java
  13. Add two numbers represented by linked list in java
  14. How to print all permutation of a String in Java?
  15. How to find duplicate characters in a string in java?
  16. Reverse the string with preserving the position of spaces
  17. How do you find longest substring without repeating characters in a string?
  18. Find all substrings of String in java
  19. Check if two string rotation of each other
  20. Write a java program to swap two string variables without using third or temp variable?
  21. Can you write a regular expression to check if String is a number?
  22. Write a method that will remove given character from the String?
  23. Write a function to find out longest palindrome in a given string?
  24. How to reverse each word of a string in java?
  25. Write a program to find top two maximum numbers in a array.
  26. Array to ArrayList and ArrayList To Array Conversion program.
  27. How to separate zeros from non-zeros in an array?
  28. Find pair whose sum is closest to zero in array in java
  29. How to find all the leaders in an integer array in java?
  30. Java Program to find gcd and lcm of two numbers
  31. Write a program to find the sum of the first 1000 prime numbers.
  32. Write a multi-threading program, print odd number using one thread and even number using other.
  33. Write a java program to find number of characters, number of words and number of lines in a text file?
  34. Find all pairs of elements whose sum is equal to given number
  35. Square root of number
  36. Program to convert lower to upper case without using toUppercase()
  37. Write a program to create deadlock between two threads.
  38. How to find the word with the highest frequency from a file in Java?
  39. Write a program to convert a given Collection to Synchronized Collection ?
  40. How to sort a text file in java?
  41. Find out middle index where sum of both ends are equal.
  42. How to sort a Stack using a temporary Stack?
  43. Implement Binary Search Tree (BST)
  44. Find min and max value from Binary Search Tree (BST)
  45. Find height of a Binary Search Tree (BST)
  46. Implement Binary Search Tree (BST) Level order traversal (breadth first).
  47. Implement Binary Search Tree (BST) pre-order traversal (depth first).
  48. Implement Binary Search Tree (BST) in-order traversal (depth first).
  49. Implement Binary Search Tree (BST) post-order traversal (depth first).
  50. How to check the given Binary Tree is Binary Search Tree (BST) or not?
  51. How to delete a node from Binary Search Tree (BST)?
  52. Binary tree level order traversal
  53. Binary tree spiral order traversal
  54. Binary tree reverse level order traversal
  55. Binary tree boundary traversal
  56. Print leaf nodes of binary tree
  57. Count leaf nodes in binary tree
  58. Get maximum element in binary tree
  59. Print all paths from root to leaf in binary tree
  60. Print vertical sum of binary tree in java
  61. Get level of node in binary tree in java
  62. Lowest common ancestor(LCA) in binary tree in java
  63. Search element in row wise and column wise sorted matrix
  64. Stock buy and sell to maximize profit.
  65. How to implement merge sort in java
  66. How to implement bubble sort in java
  67. How to implement insertion sort in java
  68. Write a program to implement hashcode and equals.
  69. Write wait-notify code for producer-consumer problem?
  70. Write a program to implement ArrayList.
  71. Printing patterns
  72. Leap year
  73. Design a Vending Machine
  74. Transpose a matrix
  75. Adding two matrices in Java
  76. Matrix multiplication
  77. Write a java program to print Floyd’s Triangle?
  78. Spiral Matrix Program.
  79. What do the expression 1.0 / 0.0 will return? will it throw Exception? any compile time error? [ Output: Infinity, No Exception ]
  80. How do you check the equality of two arrays in java? [ Arrays.equals() ]
  81. Anagram program in java
  82. How to perform matrix operations in java?
  83. How to remove duplicate elements from ArrayList in java?
  84. How to find intersection of two arrays in java?
  85. How to find trigonometric values of an angle in java?
  86. Decimal To Binary, Decimal To Octal And Decimal To HexaDecimal In Java
  87. Reverse and add until you get a palindrome
  88. Selection sort in java
  89. Launch external applications using java
  90. Write a java program to append text to a file?
  91. Write a singleton class.
  92. Write a program to sort a map by value.
  93. Write a program to print fibonacci series.
  94. Write a program to get a line with max word count from the given file.
  95. Write a program to find two lines with max characters in descending order.
  96. FizzBuzz problem
  97. Write a Comparator in Java to compare two employees based upon there name, departments and age?
  98. How to calculate complexity of algorithm
  99. How to you calculate the difference between two dates in Java? (program)
  100. Implement Producer Consumer design Pattern in Java using wait, notify and notifyAll method in Java?
  101. Find Minimum numbers of platforms required for railway station in java
  102. How to check whether given number is binary or not?
  103. Armstrong number program in java
  104. How to find sum of all digits of a number in java?
  105. How to find largest number less than a given number and without a given digit?
  106. Roman equivalent of a decimal number
  107. How to check whether user input is number or not in java?
  108. Write a program to reverse a number.
  109. Write a program to convert decimal number to binary format.
  110. Write a program to find perfect number or not.
  111. Write a program to find sum of each digit in the given number using recursion.
  112. Write a program to check the given number is a prime number or not?
  113. Write a program to convert binary to decimal number.
  114. Write a program to check the given number is binary number or not?
  115. Find prime factors of number in java
  116. Write code to avoid deadlock in Java where N threads are accessing N shared resources?

Java Programs [ Arrays ]

  1. How to find the missing number in integer array of 1 to 100?
    One trick to solve this problem is to calculate sum of all numbers in the array and compare with expected sum, the difference would be the missing number.

  2. How to find duplicate number on Integer array in Java?
    An array contains n numbers ranging from 0 to n-2. There is exactly one number is repeated in the array. You need to write a program to find that duplicate number. For example, if an array with length 6 contains numbers {0, 3, 1, 2, 3}, then duplicated number is 3. Actually, this problem is very similar to previous one and you can apply the same trick of comparing actual sum of an array to expected sum of series to find out that duplicate. This is generally asked as follow-up question of previous problem.

  3. How to check if array contains a number in Java?
    Another interesting array problem, because array doesn't provide any built-in method to check if any number exists or not. This problem is essentially how to search an element in the array. There are two options sequential search or binary search. You should ask the interviewer about whether an array is sorted or not, if the array is sorted then you can use binary search to check if given number is present in an array or not. The complexity of binary search is O(logN). BTW, if interviewer says that array is not sorted then you can still sort and perform binary search otherwise you can use sequential search. Time complexity of sequential search in array is O(n).

  4. How to find largest and smallest number in unsorted array?
    This is a rather simple array interview question. You have given an unsorted integer array and you need to find the largest and smallest element in the array. Of course, you can sort the array and then pick the top and bottom element but that would cost you O(NLogN) because of sorting, getting element in array with index is O(1) operation.

  5. How to find all pairs on integer array whose sum is equal to given number?
    This is an intermediate level of array coding question, it's neither too easy nor too difficult. You have given an integer array and a number, you need to write a program to find all elements in the array whose sum is equal to the given number. Remember, the array may contain both positive and negative numbers, so your solution should consider that. Don't forget to write unit test though, even if the interviewer is not asked for it, that would separate you from a lot of developers. Unit testing is always expected from a professional developer.

  6. How to find repeated numbers in an array if it contains multiple duplicates?
    This is actually the follow-up question of problem 2, how to find a duplicate number on integer array. In that case, an array contains only one duplicate but what if it contains multiple duplicates? Suppose, an array contains n numbers ranging from 0 to n-1 and there are 5 duplicates on it, how do you find it? You can use the approach, we have learned in similar String based problem of finding repeated characters in given String.

  7. Write a program to remove duplicates from array in Java?
    This is another follow-up question from problem 2 and 6. You have given an array which contains duplicates, could be one or more. You need to write a program to remove all duplicates from array in Java. For example if given array is {1, 2, 1, 2, 3, 4, 5} then your program should return an array which contains just {1, 2, 3, 4, 5}. This array question is also comes at intermediate category because there is no way to delete an element from an array. If substituting with another value is not an option then you need to create another array to mimic deletion.

  8. How to sort an array in place using QuickSort algorithm?
    You will often see sorting problems on array related questions because sorting mostly happen on array data structure. You need to write a program to implement in place quick sort algorithm in Java. You can implement either recursive or iterative quicksort, it's your choice but you cannot use additional buffer, array or list, you must sort array in place.

  9. Write a program to find intersection of two sorted arrays in Java?
    Another interesting array interview question, where you need to treat the array as Set. Your task is to write a function in your favorite language e.g. Java, Python, C or C++ to return the intersection of two sorted arrays. For example, if the two sorted arrays as input are {21, 34, 41, 22, 35} and {61, 34, 45, 21, 11}, it should return an intersection array with numbers {34, 21}, For the sake of this problem you can assume that numbers in each integer array are unique.

  10. There is an array with every element repeated twice except one. Find that element?
    This is an interesting array coding problem, just opposite of question related to finding duplicates in array. Here you need to find the unique number which is not repeated twice. For example if given array is {1, 1, 2, 2, 3, 4, 4, 5, 5} then your program should return 3. Also, don't forget to write couple of unit test for your solution.

  11. How to find kth smallest element in unsorted array?
    You are given an unsorted array of numbers and k, you need to find the kth smallest number in the array. For example if given array is {1, 2, 3, 9, 4} and k=2 then you need to find the 2nd smallest number in the array, which is 2. One way to solve this problem is to sort the array in ascending order then pick the k-1th element, that would be your kth smallest number in array because array index starts at zero, but can you do better? Once you are able to solve this array coding question, you can solve many similar questions easily e.g. our next question.

  12. How to find kth largest element in unsorted array?
    This problem is exactly same as previous question with only difference being finding kth largest element instead of kth smallest number. For example if given array is {10, 20, 30, 50, 40} and k = 3 then your program should return 30 because 30 is the 3rd largest number in array. You can also solve this problem by sorting the array in decreasing order and picking k-1th element. I often seen this array question on Java interviews with 2 to 3 years experienced guys.

  13. How to find common elements in three sorted array?
    Now we are coming on territory of tough array questions. Given three arrays sorted in non-decreasing order, print all common elements in these arrays.

Examples:

input1 = {1, 5, 10, 20, 40, 80}
input2 = {6, 7, 20, 80, 100}
input3 = {3, 4, 15, 20, 30, 70, 80, 120}
Output: 20, 80
  1. How find the first repeating element in an array of integers?
    Given an array of integers, find the first repeating element in it. We need to find the element that occurs more than once and whose index of the first occurrence is smallest.

Examples:

Input:  input [] = {10, 5, 3, 4, 3, 5, 6}
Output: 5 [5 is the first element that repeats]
  1. How to find first non-repeating element in array of integers?
    This array interview question is exactly opposite of previous problem, In that you need to find first repeating element while in this you need to find first non-repeating element. I am sure you can use similar approach to solve this problem, just need to consider non repeating element though.

  2. How to find top two numbers from an integer array?
    This is another one of the easy array questions you will find on telephonic round of Interviews, but its also little bit tricky. You are asked to find top two numbers not just the top or highest numbers? Can you think of how you would do it without sorting? before looking at solution.

  3. How to find the smallest positive integer value that cannot be represented as sum of any subset of a given array?
    This is another tough array question you will see on Amazon, Microsoft or Google. You have given a sorted array (sorted in non-decreasing order) of positive numbers, find the smallest positive integer value that cannot be represented as sum of elements of any subset of given set. What makes it more challenging is expected time complexity of O(n).

Examples:

Input: {1, 3, 6, 10, 11, 15};
Output: 2
  1. How to rearrange array in alternating positive and negative number?
    Given an array of positive and negative numbers, arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa maintaining the order of appearance. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array. This is also a difficult array problem to solve and you need lot of practice to solve this kind of problems in real interviews, especially when you see it first time. If you have time constraint then always attempt these kind of questions once you are done with easier ones.

Example:

Input: {1, 2, 3, -4, -1, 4}
Output: {-4, 1, -1, 2, 3, 4}

Input: {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}
output: {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0} 
  1. How to find if there is a sub array with sum equal to zero?
    There is whole set of array related questions which are based upon sub-array or only selective elements of array e.g. from some range, this is one of such problem. Here you are given an array of positive and negative numbers, find if there is a sub-array with 0 sum.

Examples:

Input: {4, 2, -3, 1, 6}
Output: true 
There is a sub-array with zero sum from index 1 to 3.
  1. How to remove duplicates from array in place?
    Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2]. 
  1. How to remove a given element from array in Java?
    This is another array coding questions similar to previous one. Here you don't have to find and remove duplicates but a given number. In this problem you are given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length.

  2. How to merge sorted array?
    Given two sorted integer arrays A and B, merge B into A as one sorted array. You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. This is another intermediate array coding question, its not as simple as previous one but neither very difficult.

  3. How to find sub array with maximum sum in an array of positive and negative number?
    Another array coding question based upon sub-array. Here you have to find the contiguous sub-array within an array (containing at least one number) which has the largest sum.

For example:

given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6. 
  1. How to find sub array with largest product in array of both positive and negative number?
    In this problem, your task is to write a program in Java or C++ to find the contiguous sub-array within an array (containing at least one number) which has the largest product.

For example:

given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6. 
  1. Write a program to find length of longest consecutive sequence in array of integers?
    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example:

Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
  1. How to find minimum value in a rotated sorted array?
    This is another advanced level array coding question and you should only attempt this one, once you have solved the easier ones. Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array. One follow-up question of this question is What if duplicates are allowed? Would this affect the run-time complexity? How and why?

  1. Given an array of of size n and a number k, find all elements that appear more than n/k times?
    Another tough array based coding questions from Interviews. You are given an array of size n, find all elements in array that appear more than n/k times. For example, if the input arrays is {3, 1, 2, 2, 1, 2, 3, 3} and k is 4, then the output should be [2, 3]. Note that size of array is 8 (or n = 8), so we need to find all elements that appear more than 2 (or 8/4) times. There are two elements that appear more than two times, 2 and 3.

  2. Returns the largest sum of contiguous integers in the array
    Example: if the input is (-10, 2, 3, -2, 0, 5, -15), the largest sum is 8

  3. Return the sum two largest integers in an array

  4. Given an array of integers write a program that will determine if any two numbers add up to a specified number N. Do this without using hash tables

  5. How to reverse array in place in Java?
    Now let's see one of the most frequently asked array interview question. You need to write a program which accepts an integer array and your program needs to reverse that array in place, which means you cannot use additional buffer or array, but one or two variables will be fine. Of course you cannot use any open source library or Java API method to directly solve this problem, you need to create your own logic. Here is one such logic to solve this problem : Array Coding Interview Questions and Answers

  6. Difference between array and linked list data structure?
    This is a theoretical questions from phone interviews. There are several differences between array and linked list e.g. array stores element in contiguous memory location while linked list stores at random places, this means linked list better utilizes the places. Consequently, its possible to have large linked list in limited memory environment compare to array of same size. Advantage of using array is random access it provides if you know the index, while in linked list you need to search an element by traversing which is O(n) operation.

  7. How to check if array contains a duplicate number?
    This may look a repeated question because we have already done similar question, but in this question, most from Java interviews, you need to write a contains() like method from Collections, which returns true or false if you pass an element and it is repeated or not.

  8. Can you change size of array once created?
    No, you cannot change the size of array once created. If you need dynamic array, consider using ArrayList class, which can resize itself.

  9. Can you store String in an array of Integer in Java? compile time error or runtime exception?
    This is a tricky question. Answer is both yes and no. You cannot store an String in an array of primitive int, it will result in compile time error as shown below, but if you create an array of Object and assign String[] to it and then try to store Integer object on it. Compiler won't be able to detect that and it will throw ArrayStoreExcpetion at runtime.

int[] primes = new int[10];
primes[0] = "a";  //compile time error
        
Object[] names = new String[3];
names[0] = new Integer(0); // ArrayStoreException at runtime
  1. What is difference between ArrayIndexOutfOBounds and ArrayStoreException?
    ArrayIndexOutOfBoundsException comes when your code tries to access an invalid index for a given array e.g. negative index or higher index than length - 1. While, ArrayStoreException comes when you have stored an element of type other than type of array, as shown in above example.

  2. Can you use Generics with array?
    No, you cannot use Generic with array, that's why sometime List is better choice over array in Java.

  3. Is it legal to initialize an array int i[] = {1, 2, 3, 4, 5};
    Yes, its perfectly legal. You can create and initialize array in same line in Java.

  4. Difference between a[] and []a in Java?
    You can declare an array in Java by either prefixing or suffixing[] with variable. There is not much difference between them if you are not creating more than one variable in one line, but if you do then it creates different types of variables, as shown in following example :

int a[], b; // first is int array, second is just int variable
int[] c, d; // both c and d are integer array
  1. How to search an array to check if an element exists there? You can search an element inside array by using either linear search or binary search. Later is faster but you need to sort the array before performing binary search on it. Arrays class from java.util package provides binarySearch() method to search an element in array. Alternatively, you can also convert array to ArrayList and use its contains() method to find out if an element exists or not.

  2. How to sort an array in Java?
    You can sort an array in Java by using Arrays.sort() method. Arrays is a utility class which contains lots of static utility method to operate on arrays. This method is overloaded and you can optionally provide a Comparator implementation to sort array in custom order.

  3. How to copy array in Java?
    You can either manually copy elements of array by iterating over them, or you can use System.arrayCopy() method to copy elements form one array to other. This is a powerful method which provides fast copy and also allows you to copy entire or part of the array.

  4. What is difference between an array and a linked list?
    Some key difference between array and linked list data structure is, Array requires contiguous memory for its element but linked list elements can be scattered in memory. Array is good for searching elements if you know the index, but adding and removing elements in array is expensive as compared to linked list.

  5. Can you make array volatile in Java?
    This is another tricky question in Java. Yes, you can make an array volatile in Java, but you only make the variable which is pointing to array volatile. If array is changed by replacing individual elements than happens before guarantee provided by volatile variables will not held.

  6. Where does array stored in memory?
    Array is created in heap space of JVM memory. Since array is object in Java, even if you create array locally inside a method or block, object is always allocated memory from heap.

  7. How to find missing number in array of 1 to 100 in Java?
    You have given an array of integer which contains numbers from 1 to 100, but exactly one number is missing, how do you find that number? You can use additional data structure.

  8. How do you find all pair whose sum is equal to given number from integer array in Java?
    You have given an array of int primitives and a number, you need to find all pairs in array whose sum is equal to given number e.g. if array is {1, 2, 3, 4, 5} and given sum is 6 then your program should return {2, 4} and {1, 5}

  9. How do you remove duplicates from array in Java?
    You have given an array, which could be array of numbers or Strings or any objects. Some objects are added multiple times in array, you need to remove those elements from array. You don't know how many duplicates are there. You can use additional data structure and memory to solve this problem.

  10. How do you reverse an array in Java?
    Given an array of String or integer, how do you reverse array, so that first element becomes last and last element becomes first e.g. if given array is {1, 2, 3, 4} then your program should reverse it as {4, 3, 2, 1}. You can use additional memory but reversing array in place will get bonus point.

  11. How to find duplicates numbers in array of integers in Java?
    You have given an array {1, 1, 2, 3, 3, 4}, write a program to return duplicate elements e.g. 1 and 3 because they have appeared more than once in array.

  12. How to find top two numbers from an integer array in Java?

  13. What is ArrayStoreException in java? When you will get this exception?
    ArrayStoreException is a run time exception which occurs when you try to store non-compatible element in an array object. The type of the elements must be compatible with the type of array object. For example, you can store only string elements in an array of strings. if you try to insert integer element in an array of strings, you will get ArrayStoreException at run time.

public class MainClass
{
    public static void main(String[] args) 
    {
        Object[] stringArray = new String[5];   //No compile time error : String[] is auto-upcasted to Object[]
        
        stringArray[1] = "JAVA";     
        
        stringArray[2] = 100;     //No compile time error, but this statement will throw java.lang.ArrayStoreException at run time
        
        //because we are inserting integer element into an array of strings
    }
}
  1. Can you pass the negative number as an array size?

No. You can’t pass the negative integer as an array size. If you pass, there will be no compile time error but you will get NegativeArraySizeException at run time.

public class MainClass
{
    public static void main(String[] args) 
    {
        int[] array = new int[-5];     //No compile time error
        
        //but you will get java.lang.NegativeArraySizeException at run time
    }
}
  1. Can you change the size of the array once you define it? OR Can you insert or delete the elements after creating an array?

No. You can’t change the size of the array once you define it. You can not insert or delete the elements after creating an array. Only you can do is change the value of the elements.

  1. What is an anonymous array? Give example?

Anonymous array is an array without reference. For example,

public class MainClass
{
    public static void main(String[] args)
    {
        //Creating anonymous arrays
 
        System.out.println(new int[]{1, 2, 3, 4, 5}.length);    //Output : 5
 
        System.out.println(new int[]{21, 14, 65, 24, 21}[1]);   //Output : 14
    }
}
  1. What is the difference between int[] a and int a[] ?

  2. There are two array objects of int type. one is containing 100 elements and another one is containing 10 elements. Can you assign array of 100 elements to an array of 10 elements?

Yes, you can assign array of 100 elements to an array of 10 elements provided they should be of same type. While assigning, compiler checks only type of the array not the size.

public class MainClass
{
    public static void main(String[] args)
    {
        int[] a = new int[10];
        
        int[] b = new int[100];
        
        a = b;      //Compiler checks only type, not the size
    }
}
  1. “int a[] = new int[3]{1, 2, 3}” – is it a legal way of defining the arrays in java?

No. You should not mention the size of the array when you are providing the array contents.

  1. What are the differences between Array and ArrayList in java?

Array ArrayList Arrays are of fixed length. ArrayList is of variable length. You can’t change the size of the array once you create it. Size of the ArrayList grows and shrinks as you add or remove the elements. Array does not support generics. ArrayList supports generics. You can use arrays to store both primitive types as well as reference types. You can store only reference types in an ArrayList.

  1. What are the different ways of copying an array into another array?

There are four methods available in java to copy an array.

  1. Using for loop

  2. Using Arrays.copyOf() method

  3. Using System.arraycopy() method

  4. Using clone() method

  1. What are jagged arrays in java? Give example?

Jagged arrays in java are the arrays containing arrays of different length. Jagged arrays are also multidimensional arrays. They are also called as ragged arrays.

  1. How do you check the equality of two arrays in java? OR How do you compare the two arrays in java?

You can use Arrays.equals() method to compare one dimensional arrays and to compare multidimensional arrays, use Arrays.deepEquals() method.

  1. What is ArrayIndexOutOfBoundsException in java? When it occurs?

ArrayIndexOutOfBoundsException is a run time exception which occurs when your program tries to access invalid index of an array i.e negative index or index higher than the size of the array.

  1. How do you sort the array elements?

You can sort the array elements using Arrays.sort() method. This method internally uses quick sort algorithm to sort the array elements.

import java.util.Arrays;
public class MainClass
{
    public static void main(String[] args)
    {
        int[] a = new int[]{45, 12, 78, 34, 89, 21};
        
        Arrays.sort(a);
        
        System.out.println(Arrays.toString(a));
        
        //Output : [12, 21, 34, 45, 78, 89]
    }
}
  1. How do you find the intersection of two arrays in java?

  2. While creating the multidimensional arrays, can you specify an array dimension after an empty dimension?

No. You can not specify an array dimension after an empty dimension while creating multidimensional arrays. It gives compile time error.

int[][][] a = new int[][5][];    //Compile time error
        
int[][][] b = new int[5][][5];   //Compile time error
        
int[][][] c = new int[][5][5];   //Compile time error

About

Java Basics ( Java-8 )

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Java 100.0%