Core java interview Questions You'll Most Likely Be Asked (Second Edition)
Suppose you are reading 10000 String values from the
Download 1.52 Mb. Pdf ko'rish
|
Core JAVA Interview Questions Youll M...
Suppose you are reading 10000 String values from the
database. You need to create a concatenated String with these values. Which is the most efficient way to achieve this? Answer: There are several ways in which you can concatenate String values. The mostly commonly used method is to use the concatenation operator (+). However, this is not at all efficient in terms of performance and should be avoided when you have a large number of Strings. This is because the String class is immutable. So, using the + operator results in the creation of a large number of Strings. Java provides the StringBuffer class. This has a method called append that can be used to create concatenated Strings. This has better performance since it is a mutable class. There is also another class called StringBuilder which is very similar to StringBuffer. The only difference is that StringBuffer is synchronized while StringBuilder is not. So StringBuilder has a slightly better performance compared to 287. 288. StringBuffer. So, if synchronization is not an issue, you can use StringBuilder, otherwise you can use StringBuffer. Suppose you are developing an application that performs a lot of mathematical calculations involving very large decimal numbers. Which data type will you use for your variables given that precision is important? Answer: Normally, programmers use float or double data types while dealing with decimal numbers. However, these data types have a downside. While dealing with very large or very small numbers, a loss of precision can occur with these data types leading to inaccurate results. So, using these data types in situations where precision is important is not a good idea. Java provides a class called java.lang.BigDecimal. This class overcomes the limitations of the float and double data types. It does not lose precision while dealing with large or small numbers and therefore provides exact results. It has methods corresponding to all the arithmetic operations like addition, subtraction, multiplication and division. In addition, it supports a lot of other operations as well. So, it can be used to perform all mathematical operations and provides precise results. The only downside of BigDecimal is performance. However, if precision is a priority over performance, then BigDecimal should be used. Download 1.52 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling