SlideShare a Scribd company logo
1
1. To implement key Object in HashMap which two methods are used?
In HashMap, to use any object as Key it must implement equals and HashCode method in
Java.
2. What is an immutable object? Mention an immutable object?
Objects that cannot be modified once created are immutable objects in JAVA. A new object
can be resulted due to any modification in an immutable object. For example, in JAVA, String
is immutable. In order to prevent sub class from overriding methods in Java which can
compromise Immutability, immutable object are mostly final in JAVA. This same functionality
can be achieved by making member as non final but private and not modifying them except in
constructor.
3. State the difference between creating String as new() and literal?
When string is created with new() Operator, it’s created in a heap and not added into
string pool whereas using literal String are created in String pool itself which exists
in PermGen area of heap, Example: String s = new String("Test");
It does not put the object in String pool , but needs to be called String.intern() method which
is used to put them into String pool explicitly. It’s only then that’s it create String object as
String literal. For e.g. String s = "Test" Java automatically put that into String pool.
4. What is difference between StringBuffer and StringBuilder in Java?
Classic Java questions can seem to be tricky and very easy. In Java 5, StringBuilder is
introduced and the only difference between both of them is that StringBuffer methods
are synchronized while StringBuilder is non- synchronized.
5. Overriding HashCode() method has any difference in performance implication?
Yes .A poor HashCode function will result in frequent collision in HashMap which eventually
increase time for adding an object into Hash Map.
6. While writing stored procedure or accessing stored procedure from java how is the
error condition handled?
This is one of the tough questions normally asked in Java interview. The stored procedure
should return error code if some operation fails but if stored procedure itself fails than
catching SQLException is the only choice left.
7. At the compile time are the imports checked for validity? That is, will the code
containing an import such as java.lang.ABCD compile up?
Yes. The imports are checked for the semantic validity at the compile time. The above line of
import will not compile if it has the code, an error is shown saying, cannot resolve symbol.
Symbol: class ABCD
Java Interview Questions & Answers by BestOnlineTrainers
http://www.bestonlinetrainers.com
2
Location: package io
Import java.io.ABCD;
8. State difference between Executor.submit() and Executer.execute() method?
When looking at exception handling, there is a difference. If the tasks throws an
exception and if it was submitted with the execute then this exception will go to
the uncaught exception handler (that is when one explicitly is not provided, the default one
will just print the stack trace to System.err). If the task is submitted with any thrown
exception or a checked exception or not, is then part of the task's return status. And for a
task that was submitted with submit and that terminates with an exception, the future.get
will re-throw this exception wrapped in an ExecutionException.
9. What is the difference between factory and abstract factory pattern?
One more level of abstraction is provided by Abstract Factory .Different factories from each
Abstract Factory responsible for the creation of different hierarchies of objects based on type
of factory are considered. For example; Abstract Factory extended by AutomobileFactory,
UserFactory, RoleFactoryetc.For every object created in that genre, each individual factory
would be responsible.
10. Define Singleton? Which is better: to make whole method synchronized or only critical
section synchronized?
Singleton in JAVA is a class with just one instance in the whole Java application. One such
example is java.lang.Runtime is a Singleton class .With the introduction Enum by Java 5,
creating a Singleton is easy rather than being tricky as earlier.
11. Differentiate between a constructor and a method?
A member function of a class that is used to create objects of that class is called a
Constructor is. Its name is same as the class itself, has no return type. It is invoked using the
new operator.
An ordinary member function of a class is called Method. It has its own name and a return
type (which may be void).It is invoked using the dot operator.
12. State the purpose of garbage collection in Java, and also when is it used?
Identifying and discarding objects that are no longer needed by a program so that their
resources can be reclaimed and reused is the purpose of garbage collection.
When a Java object is subjected becomes unreachable to the program in which it is used; it is
subjected to garbage collection.
Java Interview Questions & Answers by BestOnlineTrainers
http://www.bestonlinetrainers.com
3
13. When is HashCode and equals() overridded ?
To do equality check or use object as a key in HashMap, HashCode and equals() are
overridden.
14. What is the issue if HashCode() method are not overridded ?
If the HashCode() is not overridded , the object will not be recovered from the HashMap if
used as key.
15. State which is better: to synchronize critical section of getInstance() method or whole
getInstance() method ?
Here the answer is a bit critical as if we lock the whole method than every time then this
method will be called and would have to wait even though any object is not being created.
16. When String gets created using literal or new() operator , what difference is seen?
When a string is created with new() its created in heap and not added into string pool while
using literal , String can be created in String pool itself which exists in Perm area of heap.
17. Does overriding HashCode() method have any performance implication or not ?
Poor HashCode function results in frequent collision in HashMap which eventually increases
the time for adding an object into Hash Map.
18. In multithreaded environment what’s wrong in using HashMap? When does get()
method go to infinite loop ?
This happens during concurrent access and re-sizing.
19. What is thread-safety? Why is it required? And how to achieve thread-safety in Java
Applications?
The legal interaction of threads with the memory in a real computer system defines
Java Memory Model. It also describes what behaviors are legal in a multi-threaded code. It
can also determine when a Thread can reliably see writes to variables made by other
threads. It also defines semantics for volatile, final and synchronize, that makes
guarantee of visibility of memory operations across the Threads.
In a Memory Barrier which there are two type of memory barrier instructions in JMM - read
barriers and write barrier.
To make the changes made by other threads visible to the current Thread, the read barrier
invalidates the local memory (cache, registers, etc) and then reads the contents from the
main memory .To make the changes made by current Thread visible to other Thread, a Write
barrier flushes out the contents of the processor’s local memory to the main memory.
Java Interview Questions & Answers by BestOnlineTrainers
http://www.bestonlinetrainers.com
4
20. What happens if you call return statement or System.exit on try or catch block? Will
it finally block execute?
This is a very popular tricky Java question because many programmers think that finally the
block always gets executed. This question challenges the concept by putting return statement
in try or catch block or calling System.exit from try or catch block. In Java, this finally block
will execute even if you put return statement in the try block or catch block finally block
won't run even if you call System.exit form to try or catch.
21. How are strings compared Using “==” or equals ()?
“==” tests if references are equal and equals () tests if values are equal. To check if two
strings are the same object, equals() is always used.
22.Char[] is preferred over String for security sensitive information. Why?
Strings are immutable, that is once they are created, and they stay unchanged until Garbage
Collector kicks in. Its elements can be explicitly changed with an array. Hence, security
sensitive information like password will not be present anywhere in the system.
23. Can string be used to switch statement?
String can be used to switch statement to version 7. From JDK 7, string can be used as switch
condition. Before version 6, string cannot be used as switch condition.
24. Can string be converted to int?
Yes .It can be .But its frequently used and ignored at times.
Java Interview Questions & Answers by BestOnlineTrainers
http://www.bestonlinetrainers.com
view source
print?
1.int n = Integer.parseInt("10");
view source
print?
01.// java 7 only!
02.switch (str.toLowerCase())
03.case "a":
04.value = 1;
05.break;
06.case "b":
07.value = 2;
08.break;
09.}
5
25. How can a string be split with white space characters?
String can be slit using regular expression. White space characters are represented as “s”.
26. What does substring() method do ?
The existing String is represented by the substring() method which gives a window to an array
of chars as in JDK 6.A new one is not created. An empty string needs to be added to create a
new one.
This creates a new char array representing a new string. This method can help to code faster
because the Garbage Collector collects the unused large string and the keeps the substring.
27. What is String vs StringBuilder vs StringBuffer
In String vs StringBuilder, StringBuilder is mutable, that is it means it can be modified after its
creation.
In StringBuilder vs StringBuffer, StringBuffer is synchronized, that is it means it is thread-safe
but would be slower than StringBuilder.
28. How is a string repeated ?
In Python, to repeat a string just multiple a number. In Java, the repeat() method of
StringUtils from Apache Commons Lang package can be used.
29. In Java, what is the default value of byte datatype?
0 is the default value of byte datatype.
Java Interview Questions & Answers by BestOnlineTrainers
http://www.bestonlinetrainers.com
print
?
1.str.substring(m,n)+ ""
view source
print?
1.String [] strArray = aString.split("s+");
6
30. In a string how to count # of occurrences of a character?
StringUtils from apache commons lang can be used.
WANT TO LEARN JAVA OR ANY OTHER
PROGRAMMING COURSE?
Ask for FREE DEMO Today
Register NOW
http://www.bestonl
inetrainers.com/
demo/index.htmlUSA: +(1) 6783896789 | UK: +(44)- 2032393637 | India: +(91) 9246449191
info@bestonlinetrainers.com | www.bestonlinetrainers.
com
Java Interview Questions & Answers by BestOnlineTrainers
http://www.bestonlinetrainers.com
view source
print?
1.int n = StringUtils.countMatches("11112222", "1");
2.System.out.println(n);
6
30. In a string how to count # of occurrences of a character?
StringUtils from apache commons lang can be used.
WANT TO LEARN JAVA OR ANY OTHER
PROGRAMMING COURSE?
Ask for FREE DEMO Today
Register NOW
http://www.bestonl
inetrainers.com/
demo/index.htmlUSA: +(1) 6783896789 | UK: +(44)- 2032393637 | India: +(91) 9246449191
info@bestonlinetrainers.com | www.bestonlinetrainers.
com
Java Interview Questions & Answers by BestOnlineTrainers
http://www.bestonlinetrainers.com
view source
print?
1.int n = StringUtils.countMatches("11112222", "1");
2.System.out.println(n);

More Related Content

What's hot (15)

PDF
Extreme Interview Questions
Ehtisham Ali
 
PDF
9 crucial Java Design Principles you cannot miss
Mark Papis
 
PDF
Java Interview Questions
Kuntal Bhowmick
 
DOCX
Java questions with answers
Kuntal Bhowmick
 
PDF
Java j2ee interview_questions
ppratik86
 
PDF
Hibernate Interview Questions
Syed Shahul
 
PPTX
Dev labs alliance top 20 basic java interview question for sdet
devlabsalliance
 
PDF
Java interview question
varatharajanrajeswar
 
PPT
Design pattern
Mallikarjuna G D
 
PDF
Top 100 Java Interview Questions with Detailed Answers
Whizlabs
 
PPT
8 most expected java interview questions
Poonam Kherde
 
PDF
Hibernate Advance Interview Questions
Rudra Garnaik, PMI-ACP®
 
PDF
Java questions for interview
Kuntal Bhowmick
 
PPSX
Spring - Part 3 - AOP
Hitesh-Java
 
PPT
Hibernate introduction
Sagar Verma
 
Extreme Interview Questions
Ehtisham Ali
 
9 crucial Java Design Principles you cannot miss
Mark Papis
 
Java Interview Questions
Kuntal Bhowmick
 
Java questions with answers
Kuntal Bhowmick
 
Java j2ee interview_questions
ppratik86
 
Hibernate Interview Questions
Syed Shahul
 
Dev labs alliance top 20 basic java interview question for sdet
devlabsalliance
 
Java interview question
varatharajanrajeswar
 
Design pattern
Mallikarjuna G D
 
Top 100 Java Interview Questions with Detailed Answers
Whizlabs
 
8 most expected java interview questions
Poonam Kherde
 
Hibernate Advance Interview Questions
Rudra Garnaik, PMI-ACP®
 
Java questions for interview
Kuntal Bhowmick
 
Spring - Part 3 - AOP
Hitesh-Java
 
Hibernate introduction
Sagar Verma
 

Similar to Java interview-questions-and-answers (20)

PDF
20 most important java programming interview questions
Gradeup
 
PPTX
Java interview questions 2
Sherihan Anver
 
PDF
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
nofakeNews
 
DOC
Java interview questions
G C Reddy Technologies
 
PDF
Java interview questions and answers
kavinilavuG
 
PDF
1669617800196.pdf
venud11
 
DOCX
25 java tough interview questions
Arun Banotra
 
DOC
Core java interview questions1
Lahari Reddy
 
DOCX
Java mcq
avinash9821
 
PDF
Core Java Interview Questions PDF By ScholarHat
Scholarhat
 
ODT
Designing Better API
Kaniska Mandal
 
PDF
java basic .pdf
Satish More
 
PDF
C# interview-questions
nicolbiden
 
DOCX
Viva file
anupamasingh87
 
PDF
Java Faqs useful for freshers and experienced
yearninginjava
 
PDF
Top 371 java fa qs useful for freshers and experienced
Gaurav Maheshwari
 
DOCX
Java interview questions and answers
Krishnaov
 
DOC
C#
LiquidHub
 
PPTX
Android - Preventing common memory leaks
Ali Muzaffar
 
PPTX
Interview-QA.pptx
SharanabasavaSharanu1
 
20 most important java programming interview questions
Gradeup
 
Java interview questions 2
Sherihan Anver
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
nofakeNews
 
Java interview questions
G C Reddy Technologies
 
Java interview questions and answers
kavinilavuG
 
1669617800196.pdf
venud11
 
25 java tough interview questions
Arun Banotra
 
Core java interview questions1
Lahari Reddy
 
Java mcq
avinash9821
 
Core Java Interview Questions PDF By ScholarHat
Scholarhat
 
Designing Better API
Kaniska Mandal
 
java basic .pdf
Satish More
 
C# interview-questions
nicolbiden
 
Viva file
anupamasingh87
 
Java Faqs useful for freshers and experienced
yearninginjava
 
Top 371 java fa qs useful for freshers and experienced
Gaurav Maheshwari
 
Java interview questions and answers
Krishnaov
 
Android - Preventing common memory leaks
Ali Muzaffar
 
Interview-QA.pptx
SharanabasavaSharanu1
 
Ad

Recently uploaded (20)

PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
Difference between write and update in odoo 18
Celine George
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Introduction presentation of the patentbutler tool
MIPLM
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Ad

Java interview-questions-and-answers

  • 1. 1 1. To implement key Object in HashMap which two methods are used? In HashMap, to use any object as Key it must implement equals and HashCode method in Java. 2. What is an immutable object? Mention an immutable object? Objects that cannot be modified once created are immutable objects in JAVA. A new object can be resulted due to any modification in an immutable object. For example, in JAVA, String is immutable. In order to prevent sub class from overriding methods in Java which can compromise Immutability, immutable object are mostly final in JAVA. This same functionality can be achieved by making member as non final but private and not modifying them except in constructor. 3. State the difference between creating String as new() and literal? When string is created with new() Operator, it’s created in a heap and not added into string pool whereas using literal String are created in String pool itself which exists in PermGen area of heap, Example: String s = new String("Test"); It does not put the object in String pool , but needs to be called String.intern() method which is used to put them into String pool explicitly. It’s only then that’s it create String object as String literal. For e.g. String s = "Test" Java automatically put that into String pool. 4. What is difference between StringBuffer and StringBuilder in Java? Classic Java questions can seem to be tricky and very easy. In Java 5, StringBuilder is introduced and the only difference between both of them is that StringBuffer methods are synchronized while StringBuilder is non- synchronized. 5. Overriding HashCode() method has any difference in performance implication? Yes .A poor HashCode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map. 6. While writing stored procedure or accessing stored procedure from java how is the error condition handled? This is one of the tough questions normally asked in Java interview. The stored procedure should return error code if some operation fails but if stored procedure itself fails than catching SQLException is the only choice left. 7. At the compile time are the imports checked for validity? That is, will the code containing an import such as java.lang.ABCD compile up? Yes. The imports are checked for the semantic validity at the compile time. The above line of import will not compile if it has the code, an error is shown saying, cannot resolve symbol. Symbol: class ABCD Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com
  • 2. 2 Location: package io Import java.io.ABCD; 8. State difference between Executor.submit() and Executer.execute() method? When looking at exception handling, there is a difference. If the tasks throws an exception and if it was submitted with the execute then this exception will go to the uncaught exception handler (that is when one explicitly is not provided, the default one will just print the stack trace to System.err). If the task is submitted with any thrown exception or a checked exception or not, is then part of the task's return status. And for a task that was submitted with submit and that terminates with an exception, the future.get will re-throw this exception wrapped in an ExecutionException. 9. What is the difference between factory and abstract factory pattern? One more level of abstraction is provided by Abstract Factory .Different factories from each Abstract Factory responsible for the creation of different hierarchies of objects based on type of factory are considered. For example; Abstract Factory extended by AutomobileFactory, UserFactory, RoleFactoryetc.For every object created in that genre, each individual factory would be responsible. 10. Define Singleton? Which is better: to make whole method synchronized or only critical section synchronized? Singleton in JAVA is a class with just one instance in the whole Java application. One such example is java.lang.Runtime is a Singleton class .With the introduction Enum by Java 5, creating a Singleton is easy rather than being tricky as earlier. 11. Differentiate between a constructor and a method? A member function of a class that is used to create objects of that class is called a Constructor is. Its name is same as the class itself, has no return type. It is invoked using the new operator. An ordinary member function of a class is called Method. It has its own name and a return type (which may be void).It is invoked using the dot operator. 12. State the purpose of garbage collection in Java, and also when is it used? Identifying and discarding objects that are no longer needed by a program so that their resources can be reclaimed and reused is the purpose of garbage collection. When a Java object is subjected becomes unreachable to the program in which it is used; it is subjected to garbage collection. Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com
  • 3. 3 13. When is HashCode and equals() overridded ? To do equality check or use object as a key in HashMap, HashCode and equals() are overridden. 14. What is the issue if HashCode() method are not overridded ? If the HashCode() is not overridded , the object will not be recovered from the HashMap if used as key. 15. State which is better: to synchronize critical section of getInstance() method or whole getInstance() method ? Here the answer is a bit critical as if we lock the whole method than every time then this method will be called and would have to wait even though any object is not being created. 16. When String gets created using literal or new() operator , what difference is seen? When a string is created with new() its created in heap and not added into string pool while using literal , String can be created in String pool itself which exists in Perm area of heap. 17. Does overriding HashCode() method have any performance implication or not ? Poor HashCode function results in frequent collision in HashMap which eventually increases the time for adding an object into Hash Map. 18. In multithreaded environment what’s wrong in using HashMap? When does get() method go to infinite loop ? This happens during concurrent access and re-sizing. 19. What is thread-safety? Why is it required? And how to achieve thread-safety in Java Applications? The legal interaction of threads with the memory in a real computer system defines Java Memory Model. It also describes what behaviors are legal in a multi-threaded code. It can also determine when a Thread can reliably see writes to variables made by other threads. It also defines semantics for volatile, final and synchronize, that makes guarantee of visibility of memory operations across the Threads. In a Memory Barrier which there are two type of memory barrier instructions in JMM - read barriers and write barrier. To make the changes made by other threads visible to the current Thread, the read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory .To make the changes made by current Thread visible to other Thread, a Write barrier flushes out the contents of the processor’s local memory to the main memory. Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com
  • 4. 4 20. What happens if you call return statement or System.exit on try or catch block? Will it finally block execute? This is a very popular tricky Java question because many programmers think that finally the block always gets executed. This question challenges the concept by putting return statement in try or catch block or calling System.exit from try or catch block. In Java, this finally block will execute even if you put return statement in the try block or catch block finally block won't run even if you call System.exit form to try or catch. 21. How are strings compared Using “==” or equals ()? “==” tests if references are equal and equals () tests if values are equal. To check if two strings are the same object, equals() is always used. 22.Char[] is preferred over String for security sensitive information. Why? Strings are immutable, that is once they are created, and they stay unchanged until Garbage Collector kicks in. Its elements can be explicitly changed with an array. Hence, security sensitive information like password will not be present anywhere in the system. 23. Can string be used to switch statement? String can be used to switch statement to version 7. From JDK 7, string can be used as switch condition. Before version 6, string cannot be used as switch condition. 24. Can string be converted to int? Yes .It can be .But its frequently used and ignored at times. Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com view source print? 1.int n = Integer.parseInt("10"); view source print? 01.// java 7 only! 02.switch (str.toLowerCase()) 03.case "a": 04.value = 1; 05.break; 06.case "b": 07.value = 2; 08.break; 09.}
  • 5. 5 25. How can a string be split with white space characters? String can be slit using regular expression. White space characters are represented as “s”. 26. What does substring() method do ? The existing String is represented by the substring() method which gives a window to an array of chars as in JDK 6.A new one is not created. An empty string needs to be added to create a new one. This creates a new char array representing a new string. This method can help to code faster because the Garbage Collector collects the unused large string and the keeps the substring. 27. What is String vs StringBuilder vs StringBuffer In String vs StringBuilder, StringBuilder is mutable, that is it means it can be modified after its creation. In StringBuilder vs StringBuffer, StringBuffer is synchronized, that is it means it is thread-safe but would be slower than StringBuilder. 28. How is a string repeated ? In Python, to repeat a string just multiple a number. In Java, the repeat() method of StringUtils from Apache Commons Lang package can be used. 29. In Java, what is the default value of byte datatype? 0 is the default value of byte datatype. Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com print ? 1.str.substring(m,n)+ "" view source print? 1.String [] strArray = aString.split("s+");
  • 6. 6 30. In a string how to count # of occurrences of a character? StringUtils from apache commons lang can be used. WANT TO LEARN JAVA OR ANY OTHER PROGRAMMING COURSE? Ask for FREE DEMO Today Register NOW http://www.bestonl inetrainers.com/ demo/index.htmlUSA: +(1) 6783896789 | UK: +(44)- 2032393637 | India: +(91) 9246449191 [email protected] | www.bestonlinetrainers. com Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com view source print? 1.int n = StringUtils.countMatches("11112222", "1"); 2.System.out.println(n);
  • 7. 6 30. In a string how to count # of occurrences of a character? StringUtils from apache commons lang can be used. WANT TO LEARN JAVA OR ANY OTHER PROGRAMMING COURSE? Ask for FREE DEMO Today Register NOW http://www.bestonl inetrainers.com/ demo/index.htmlUSA: +(1) 6783896789 | UK: +(44)- 2032393637 | India: +(91) 9246449191 [email protected] | www.bestonlinetrainers. com Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com view source print? 1.int n = StringUtils.countMatches("11112222", "1"); 2.System.out.println(n);