Adam Daniels

Adam Daniels

1558104818

Introduction to Java String Interview Questions and Answers

1. Introduction

The String class is one of the most widely used classes in Java, which prompted language designers to treat it specially. This special behavior makes it one of the hottest topics in Java interviews.

In this tutorial, we’ll go through some of the most common interview questions about String.

2. String Fundamentals

This section consists of questions that concern the String internal structure and memory.

Q1. What is a String in Java?

In Java, a String is represented internally by an array of byte values (or char values before JDK 9).

In versions up to and including Java 8, a String was composed of an immutable array of Unicode characters. However, most characters require only 8 bits (1 byte) to represent them instead of 16 bits (char size).

To improve memory consumption and performance, Java 9 introduced compact Strings. This means that if a String contains only 1-byte characters, it will be represented using Latin-1 encoding. If a String contains at least 1 multi-byte character, it will be represented as 2 bytes per character using UTF-16 encoding.

In C and C++, String is also an array of characters, but in Java, it’s a separate object with its own API.

Q2. How can we create a String object in Java?

java.lang.String defines 13 different ways to create a String. Generally, though, there are two:

  • Through a String literal:
String s = "abc";

  • Through the new keyword:
String s = new String("abc");

All String literals in Java are instances of the String class.

Q3. Is String a Primitive or a Derived Type?

A String is a derived type since it has state and behavior. For example, it has methods like substring(), indexOf(), and _equals(), _which primitives cannot have.

But, since we all use it so often, it has some special characteristics that make it feel like a primitive:

  • While strings are not stored on the call stack like primitives are, they are** stored in a special memory region called the string pool**
  • Like primitives, we can use the _+ _operator on strings
  • And again, like primitives, we can create an instance of a _String _without the _new _keyword

Q4. What are the benefits of strings being immutable?

According to an interview by James Gosling, strings are immutable to improve performance and security.

And actually, we see several benefits to having immutable strings:

  • The string pool is only possible if the strings, once created, are never changed, as they are supposed to be reused
  • The code can safely pass a string to another method, knowing that it can’t be altered by that method
  • Immutably automatically makes this class thread-safe
  • Since this class is thread-safe, there is no need to synchronize common data, which in turn improves performance
  • Since they are guaranteed to not change, their hashcode can be easily cached

Q5. How is a String stored in memory?

According to the JVM Specification, String literals are stored in a runtime constant pool, which is allocated from the JVM’s method area.

Although the method area is logically part of the heap memory, the specification does not dictate the location, memory size, or garbage collection policies. It can be implementation-specific.

This runtime constant pool for a class or interface is constructed when the class or interface is created by the JVM.

Q6. Are interned strings eligible for garbage collection in Java?

Yes, all _String_s in the string pool are eligible for garbage collection if there are no references from the program.

Q7. What is the String constant pool?

The string pool, also known as the String constant pool or the String intern pool, is a special memory region where the JVM stores String instances.

It optimizes application performance by reducing how often and how many strings are allocated:

  • The JVM stores only one copy of a particular String in the pool
  • When creating a new String, the JVM searches in the pool for a String having the same value
  • If found, the JVM returns the reference to that String without allocating any additional memory
  • If not found, then the JVM adds it to the pool (interns it) and returns its reference

Q8. Is String thread-safe? How?

Strings are indeed completely thread-safe because they are immutable. Any class which is immutable automatically qualifies for thread-safety because its immutability guarantees that its instances won’t be changed across multiple threads.

For example, if a thread changes a string’s value, a new String gets created instead of modifying the existing one.

Q9. For which _String _operations is it important to supply a Locale?

The Locale class allows us to differentiate between cultural locales as well as to format our content appropriately.

When it comes to the _String _class, we need it when rendering strings in format or when lower- or upper-casing strings.

In fact, if we forget to do this, we can run into problems with portability, security, and usability.

Q10. What is the underlying character encoding for strings?

According to _String’_s Javadocs for versions up to and including Java 8, Strings are stored in the UTF-16 format internally.

The char data type and java.lang.Character objects are also based on the original Unicode specification, which defined characters as fixed-width 16-bit entities.

Starting with JDK 9, Strings that contain only 1-byte characters use Latin-1 encoding, while Strings with at least 1 multi-byte character use UTF-16 encoding.

3. The String API

In this section, we’ll discuss some questions related to the String API.

Q11. How can we compare two Strings in Java? What’s the difference between str1 == str2 and str1.equals(str2)?

We can compare strings in two different ways: by using equal to operator ( == ) and by using the equals() method.

Both are quite different from each other:

  • **The operator (str1 == str2) **checks for referential equality
  • **The method (str1.equals(str2)) **checks for lexical equality

Though, it’s true that if two strings are lexically equal, then _str1.intern() == str2.intern() _is also true.

Typically, for comparing two Strings for their content, we should always use String.equals.

Q12. How can we split a String in Java?

The String class itself provides us with the _String#__split _method, which accepts a regular expression delimiter. It returns us a String[] array:

String[] parts = "john,peter,mary".split(",");
assertEquals(new String[] { "john", "peter", "mary" }, parts);

One tricky thing about split is that when splitting an empty string, we may get a non-empty array:

assertEquals(new String[] { "" }, "".split(","));

Of course, _split _is just one of many ways to split a Java String.

Q13. What is StringJoiner?

_StringJoiner _is a class introduced in Java 8 for joining separate strings into one, like taking a list of colors and returning them as a comma-delimited string. We can supply a delimiter as well as a prefix and suffix:

StringJoiner joiner = new StringJoiner(",", "[", "]");
joiner.add("Red")
  .add("Green")
  .add("Blue");

assertEquals("[Red,Green,Blue]", joiner.toString());

Q14. Difference between String, StringBuffer and StringBuilder?

Strings are immutable. This means that if we try to change or alter its values, then Java creates an absolutely new _String. _

For example, if we add to a string _str1 _after it has been created:

String str1 = "abc";
str1 = str1 + "def";

Then the JVM, instead of modifying str1, creates an entirely new String.

However, for most of the simple cases, the compiler internally uses StringBuilder and optimizes the above code.

But, for more complex code like loops, it will create an entirely new String, deteriorating performance. This is where StringBuilder and StringBuffer are useful.

Both StringBuilder and StringBuffer in Java create objects that hold a mutable sequence of characters.** StringBuffer is synchronized and therefore thread-safe whereas StringBuilder is not.**

Since the extra synchronization in _StringBuffer _is typically unnecessary, we can often get a performance boost by selecting StringBuilder.

Q15. Why is it safer to store passwords in a char[] array rather than a String?

Since strings are immutable, they don’t allow modification. This behavior keeps us from overwriting, modifying, or zeroing out its contents, making Strings unsuitable for storing sensitive information.

We have to rely on the garbage collector to remove a string’s contents. Moreover, in Java versions 6 and below, strings were stored in PermGen, meaning that once a String was created, it was never garbage collected.

By using a char[] array, we have complete control over that information. We can modify it or wipe it completely without even relying on the garbage collector.

Using char[] over String doesn’t completely secure the information; it’s just an extra measure that reduces an opportunity for the malicious user to gain access to sensitive information.

Q16. What does _String’_s intern() method do?

The method intern() creates an exact copy of a String object in the heap and stores it in the _String _constant pool, which the JVM maintains.

Java automatically interns all strings created using string literals, but if we create a String using the new operator, for example, String str = new String(“abc”), then Java adds it to the heap, just like any other object.

We can call the intern() method to tell the JVM to add it to the string pool if it doesn’t already exist there, and return a reference of that interned string:

String s1 = "Baeldung";
String s2 = new String("Baeldung");
String s3 = new String("Baeldung").intern();

assertThat(s1 == s2).isFalse();
assertThat(s1 == s3).isTrue();

Q17. How can we convert String to Integer and Integer to String in Java?

The most straightforward approach to convert a String to an Integer is by using Integer#parseInt:

int num = Integer.parseInt("22");

To do the reverse, we can use Integer#toString:

String s = Integer.toString(num);

Q18. What is String.format() and how can we use it?

String#format returns a formatted string using the specified format string and arguments.

String title = "Baeldung"; 
String formatted = String.format("Title is %s", title);
assertEquals("Title is Baeldung", formatted);

We also need to remember to specify the user’s _Locale, _unless we are okay with simply accepting the operating system default:

Locale usersLocale = Locale.ITALY;
assertEquals("1.024",
  String.format(usersLocale, "There are %,d shirts to choose from. Good luck.", 1024))

Q19. How can we convert a String to Uppercase and Lowercase?

String implicitly provides String#toUpperCase to change the casing to uppercase.

Though, the Javadocs remind us that we need to specify the user’s L__ocale to ensure correctness:

String s = "Welcome to Baeldung!";
assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase(Locale.US));

Similarly, to convert to lowercase, we have String#toLowerCase:

String s = "Welcome to Baeldung!";
assertEquals("welcome to baeldung!", s.toLowerCase(Locale.UK));

Q20. How can we get a character array from String?

String provides toCharArray, which returns a copy of its internal char array pre-JDK9 (and converts the String to a new char array in JDK9+):

char[] hello = "hello".toCharArray();
assertArrayEquals(new String[] { 'h', 'e', 'l', 'l', 'o' }, hello);

Q21. How would we convert a Java String into a byte array?

By default, the method String#getBytes() encodes a String into a byte array using the platform’s default charset.

And while the API doesn’t require that we specify a charset, we should in order to ensure security and portability:

byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII);
byte[] byteArray3 = "ijkl".getBytes("UTF-8");

4. String-Based Algorithms

In this section, we’ll discuss some programming questions related to _String_s.

Q22. How can we check if two Strings are anagrams in Java?

An anagram is a word formed by rearranging the letters of another given word, for example, “car” and “arc”.

To begin, we first check whether both the Strings are of equal length or not.

Then we convert them to char[] array, sort them, and then check for equality.

Q23. How can we count the number of occurrences of a given character in a String?

Java 8 really simplifies aggregation tasks like these:

long count = "hello".chars().filter(ch -> (char)ch == 'l').count();
assertEquals(2, count);

And, there are several other great ways to count the l’s, too, including loops, recursion, regular expressions, and external libraries.

Q24. How can we reverse a String in Java?

There can be many ways to do this, the most straightforward approach being to use the reverse method from StringBuilder (or StringBuffer):

String reversed = new StringBuilder("baeldung").reverse().toString();
assertEquals("gnudleab", reversed);

Q25. How can we check if a String is a palindrome or not?

A palindrome is any sequence of characters that reads the same backward as forward, such as “madam”, “radar” or “level”.

To check if a string is a palindrome, we can start iterating the given string forward and backward in a single loop, one character at a time. The loop exits at the first mismatch.

5. Conclusion

In this article, we went through some of the most prevalent String interview questions.

All the code samples used here are available on GitHub.

#java #string #interview #interview-questions

What is GEEK

Buddha Community

Introduction to Java String Interview Questions and Answers

Top 130 Android Interview Questions - Crack Technical Interview Now!

Android Interview Questions and Answers from Beginner to Advanced level

DataFlair is committed to provide you all the resources to make you an android professional. We started with android tutorials along with practicals, then we published Real-time android projects along with source code. Now, we come up with frequently asked android interview questions, which will help you in showing expertise in your next interview.

android interview questions

Android Interview Questions – Get ready for your next interview

Android – one of the hottest technologies, which is having a bright future. Get ready to crack your next interview with the following android interview questions. These interview questions start with basic and cover deep concepts along with advanced topics.

Android Interview Questions for Freshers

1. What is Android?

Android is an open-source mobile operating system that is based on the modified versions of Linux kernel. Though it was mainly designed for smartphones, now it is being used for Tablets, Televisions, Smartwatches, and other Android wearables.

2. Who is the inventor of Android Technology?

The inventors of Android Technology are- Andry Rubin, Nick Sears, and Rich Miner.

3. What is the latest version of Android?

The latest version of Android is Android 10.0, known as Android Q. The upcoming major Android release is Android 11, which is the 18th version of Android. [Note: Keep checking the versions, it is as of June 2020.]

4. How many Android versions can you recall right now?

Till now, there are 17 versions of Android, which have their names in alphabetical order. The 18th version of Android is also going to come later this year. The versions of Android are here:

  • Android 1.0 – Its release is 23 September 2008.
  • Android 1.1 – Its release date is 9 February 2009.
  • Android 1.5 – Its name is Cupcake, Released on 27 April 2009.
  • Android 1.6 – Its name is Donut, Released on 15 September 2009.
  • Android 2.0 – Its name is Eclair, Released on 26 October 2009
  • Android 2.2 – Its name is Froyo, Released on 20 May 2010.
  • Android 2.3 – Its name is Gingerbread, Released on 06 December 2010.
  • Android 3.0 – Its name is Honeycomb, Released on 22 February 2011.
  • Android 4.0 – Its name is Ice Cream Sandwich, Released on 18 October 2011.
  • Android 4.1 – Its name is Jelly Bean, Released on 9 July 2012.
  • Android 4.4 – Its name is KitKat, Released on 31 October 2013.
  • Android 5.0 – Its name is Lollipop, Released on 12 November 2014.
  • Android 6.0 – Its name is Marshmallow, Released on 5 October 2015.
  • Android 7.0 – Its name is Nougat, Released on 22 August 2016.
  • Android 8.0 – Its name is Oreo, Released on 21 August 2017.
  • Android 9.0 – Its name is Pie, Released on 6 August 2018.
  • Android 10.0 – Its name is Android Q, Released on 3 September 2019.
  • Android 11.0 – As of now, it is Android 11.

5. Explain the Android Architecture with its components.

This is a popular android developer interview question

Android Architecture consists of 5 components that are-

a. Linux Kernel: It is the foundation of the Android Architecture that resides at the lowest level. It provides the level of abstraction for hardware devices and upper layer components. Linux Kernel also provides various important hardware drivers that act as software interfaces for hardwares like camera, bluetooth, etc.

b. Native Libraries: These are the libraries for Android that are written in C/C++. These libraries are useful to build many core services like ART and HAL. It provides support for core features.

c. Android Runtime: It is an Android Runtime Environment. Android Operating System uses it during the execution of the app. It performs the translation of the application bytecode into the native instructions. The runtime environment of the device then executes these native instructions.

d. Application Framework: Application Framework provides many java classes and interfaces for app development. And it also provides various high-level services. This complete Application framework makes use of Java.

e. Applications: This is the topmost layer of Android Architecture. It provides applications for the end-user, so they can use the android device and compute the tasks.

6. What are the services that the Application framework provides?

The Android application framework has the following key services-

a. Activity Manager: It uses testing and debugging methods.

b. Content provider: It provides the data from application to other layers.

c. Resource Manager: This provides users access to resources.

d. Notification Manager: This gives notification to the users regarding actions taking place in the background.

e. View System: It is the base class for widgets, and it is also responsible for event handling.

7. What are the important features of Linux Kernel?

The important features of the Linux Kernel are as follows:

a. Power Management: Linux Kernel does power management to enhance and improve the battery life of the device.

b. Memory Management: It is useful for the maximum utilization of the available memory of the device.

c. Device Management: It includes managing all the hardware device drivers. It maximizes the utilization of the available resources.

d. Security: It ensures that no application has any such permission that it affects any other application in order to maintain security.

e. Multi-tasking: Multi-tasking provides the users the ease of doing multiple tasks at the same time.

8. What are the building blocks of an Android Application?

This is a popular android interview question for freshers.

The main components of any Android application are- Activity, Services, Content Provider, and Broadcast Receiver. You can understand them as follows:

a. Activity- It is a class that acts as the entry point representing a single screen to the user. It is like a window to show the user interface.

b. Services- Services are the longest-running component that runs in the background.

c. Content Provider- The content provider is an essential component that allows apps to share data between themselves.

d. Broadcast receivers- Broadcast receiver is another most crucial application component. It helps the apps to receive and respond to broadcast messages from the system or some other application.

9. What are the important components of Android Application?

The Components of Android application are listed below:

  1. Widgets
  2. Intents
  3. Views
  4. Notification
  5. Fragments
  6. Layout XML files
  7. Resources

10. What are the widgets?

Widgets are the variations of Broadcast receivers. They are an important part of home screen customization. They often display some data and also allow users to perform actions on them. Mostly they display the app icon on the screen.

11. Can you name some types of widgets?

Mentioned below are the types of widgets-

a. Informative Widgets: These widgets show some important information. Like, the clock widget or a weather widget.

b. Collective Widgets: They are the collection of some types of elements. For example, a music widget that lets us change, skip, or forward the song.

c. Control Widgets: These widgets help us control the actions within the application through it. Like an email widget that helps check the recent mails.

d. Hybrid Widgets: Hybrid widgets are those that consist of at least two or more types of widgets.

12. What are Intents?

Intents are an important part of Android Applications. They enable communication between components of the same application as well as separate applications. The Intent signals the Android system about a certain event that has occurred.

13. Explain the types of intents briefly?

Intent is of three types that are-

a. Implicit Intents: Implicit intents are those in which there is no description of the component name but only the action.

b. Explicit Intents: In explicit intents, the target component is present by declaring the name of the component.

c. Pending Intents: These are those intents that act as a shield over the Intent objects. It covers the intent objects and grants permission to the external app components to access them.

14. What is a View?

A view is an important building block that helps in designing the user interface of the application. It can be a rectangular box or a circular shape, for example, Text View, Edit Text, Buttons, etc. Views occupy a certain area of the screen, and it is also responsible for event handling. A view is the superclass of all the graphical user interface components.

15. What do you understand by View Group?

It is the subclass of the ViewClass. It gives an invisible container to hold layouts or views. You can understand view groups as special views that are capable of holding other views, that are Child View.

16. What do you understand about Shared Preferences?

It is a simple mechanism for data storage in Android. In this, there is no need to create files, and using APIs, it stores the data in XML files. It stores the data in the pair of key-values. SharedPreferences class lets the user save the values and retrieve them when required. Using SharedPreferences we can save primitive data like- boolean, float, integer, string and long.

17. What is a Notification?

A notification is just like a message that shows up outside the Application UI to provide reminders to the users. They remind the user about a message received, or some other timely information from the app.

18. Give names of Notification types.

There are three types of notifications namely-

a. Toast Notification- This notification is the one that fades away sometime after it pops up.

b. Status Notification- This notification stays till the user takes some action on it.

c. Dialog Notification- This notification is the result of an Active Activity.

19. What are fragments?

A fragment is a part of the complete user interface. These are present in Activity, and an activity can have one or more fragments at the same time. We can reuse a fragment in multiple activities as well.

20. What are the types of fragments?

There are three types of fragments that are: Single Fragment, List Fragment, Fragment Transactions.

  1. Single Transactions can only show a single view for the user.
  2. List Fragments have a special list view feature that provides a list from which the user can select one.
  3. Fragment Transactions are helpful for the transition between one fragment to the other.

Frequently asked Android Interview Questions and Answers

21. What are Layout XML files?

Layout XML files contain the structure for the user interface of the application. The XML file also contains various different layouts and views, and they also specify various GUI components that are there in Activity or fragments.

22. What are Resources in Android Application?

The resources in Android Apps defines images, texts, strings, colors, etc. Everything in resources directory is referenced in the source code of the app so that we can use them.

23. Can you develop Android Apps with languages other than Java? If so, name some.

Yes, there are many languages that we can work with, for the development of Android Applications. To name some, I would say Java, Python, C, C++, Kotlin, C#, Corona/LUA.

24. What are the states of the Activity Lifecycle?

Activity lifecycle has the following four stages-

a. Running State: As soon as the activity starts, it is the first state.

b. Paused State: When some other activity starts without closing the previous one, the running activity turns into the Paused state.

c. Resume State: When the activity opens again after being in pause state, it comes into the Resume State.

d. Stopped State: When the user closes the application or stops using it, the activity goes to the Stopped state.

25. What are some methods of Activity?

The methods of Activity are as follows:

  • onCreate()
  • onStart()
  • onPause()
  • onRestart()
  • onResume()
  • onStop()
  • onDestroy()

26. How can you launch an activity in Android?

We launch an activity using Intents. For this we need to use intent as follows:

  1. ntent intent_name= new Intent(this, Activity_name.class);
  2. startActivity(intent_name);

27. What is the service lifecycle?

There are two states of a service that are-

a. Started State: This is when the service starts its execution. A Services come in start state only through the startService() method.

b. Bounded State: A service is in the bounded state when it calls the method bindService().

28. What are some methods of Services?

The methods of service are as follows-

  • onStartCommand()
  • onBind()
  • onCreate()
  • onUnbind()
  • onDestroy()
  • onRebind()

29. What are the types of Broadcast?

Broadcasts are of two types that are-

a. Ordered Broadcast: Ordered broadcasts are Synchronous and work in a proper order. It decides the order by using the priority assigned to the broadcasts.

b. Normal Broadcast: These are asynchronous and unordered. They are more efficient as they run unorderly and all at once. But, they lack full utilization of the results.

30. What are useful impotent folders in Android?

The impotent folders in an Android application are-

  1. build.xml- It is responsible for the build of Android applications.
  2. bin/ – The bin folder works as a staging area to wrap the files packages into the APK.
  3. src/ – The src is a folder where all the source files of the project are present.
  4. res/ – The res is the resource folder that stores values of the resources that are used in the application. These resources can be colors, styles, strings, dimensions, etc.
  5. assets/ – It provides a facility to include files like text, XML, fonts, music, and video in the Android application.

31. What are the important files for Android Application when working on Android Studio?

This is an important android studio interview question

There are following three files that we need to work on for an application to work-

a. The AndroidManifest.xml file: It has all the information about the application.

b. The MainActivity.java file: It is the app file that actually gets converted to the dalvik executable and runs the application. It is written in java.

c. The Activity_main.xml file: It is the layout file that is available in the res/layout directory. It is another mostly used file while developing the application.

32. Which database do you use for Android Application development?

The database that we use for Android Applications is SQLite. It is because SQLite is lightweight and specially developed for Android Apps. SQLite works the same way as SQL using the same commands.

33. Tell us some features of Android OS.

The best features of Android include-

  1. Multi-tasking
  2. Support for a great range of languages
  3. Support for split-screen
  4. High connectivity with 5G support
  5. Motion Control

34. Why did you learn Android development?

Learning Android Studio is a good idea because of the following-

  1. It has a low application development cost.
  2. It is an open-source platform.
  3. It has multi-platform support as well as Multi-carrier support.
  4. It is open for customizations.
  5. Android is a largely used operating system throughout the world.

35. What are the different ways of storage supported in Android?

The various storage ways supported in Android are as follows:

  1. Shared Preference
  2. Internal Storage
  3. External Storage
  4. SQLite Databases
  5. Network Connection

36. What are layouts?

Layout is nothing but arrangements of elements on the device screen. These elements can be images, tests, videos, anything. They basically define the structure of the Android user interface to make it user friendly.

37. How many layout types are there?

The type of layouts used in Android Apps are as follows:

  1. Linear Layout
  2. Relative Layout
  3. Constraint Layout
  4. Table Layout
  5. Frame Layout
  6. Absolute Layout
  7. Scrollview layout

38. What is an APK?

An APK stands for Android Package that is a file format of Android Applications. Android OS uses this package for the distribution and installation of the Android Application.

39. What is an Android Manifest file?

The manifest file describes all the essential information about the project application for build tools, Android operating system, and google play. This file is a must for every Android project that we develop, and it is present in the root of the project source set.

#android tutorials #android basic interview questions #android basic questions #android developer interview questions #android interview question and answer #android interview questions #android interview questions for experienced #android interview questions for fresher

Sigrid  Farrell

Sigrid Farrell

1623718560

Top 10 Critical Spring Boot Interview Questions and Answers [For Beginners & Experienced]

offers powerful features for the rapid development of deployment-ready applications. It is the most used and best java framework for the development of scalable microservices and web applications.

If you want to become a domain expert, you have come to the right place. We have curated some the most repeatedly asked spring boot interview questions and answers to help you ace the interview.

Basic Spring Boot Interview Questions And Answers

Technical Spring Boot Interview Questions And Answers

Conclusion

#full stack development #interview question answer #spring boot interview questions answer #top spring boot interview questions #top 10 critical spring boot interview questions #answers

Tyrique  Littel

Tyrique Littel

1600135200

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK?

OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.

In this article, we will be installing OpenJDK on Centos 8.

#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment

Adam Daniels

Adam Daniels

1558104818

Introduction to Java String Interview Questions and Answers

1. Introduction

The String class is one of the most widely used classes in Java, which prompted language designers to treat it specially. This special behavior makes it one of the hottest topics in Java interviews.

In this tutorial, we’ll go through some of the most common interview questions about String.

2. String Fundamentals

This section consists of questions that concern the String internal structure and memory.

Q1. What is a String in Java?

In Java, a String is represented internally by an array of byte values (or char values before JDK 9).

In versions up to and including Java 8, a String was composed of an immutable array of Unicode characters. However, most characters require only 8 bits (1 byte) to represent them instead of 16 bits (char size).

To improve memory consumption and performance, Java 9 introduced compact Strings. This means that if a String contains only 1-byte characters, it will be represented using Latin-1 encoding. If a String contains at least 1 multi-byte character, it will be represented as 2 bytes per character using UTF-16 encoding.

In C and C++, String is also an array of characters, but in Java, it’s a separate object with its own API.

Q2. How can we create a String object in Java?

java.lang.String defines 13 different ways to create a String. Generally, though, there are two:

  • Through a String literal:
String s = "abc";

  • Through the new keyword:
String s = new String("abc");

All String literals in Java are instances of the String class.

Q3. Is String a Primitive or a Derived Type?

A String is a derived type since it has state and behavior. For example, it has methods like substring(), indexOf(), and _equals(), _which primitives cannot have.

But, since we all use it so often, it has some special characteristics that make it feel like a primitive:

  • While strings are not stored on the call stack like primitives are, they are** stored in a special memory region called the string pool**
  • Like primitives, we can use the _+ _operator on strings
  • And again, like primitives, we can create an instance of a _String _without the _new _keyword

Q4. What are the benefits of strings being immutable?

According to an interview by James Gosling, strings are immutable to improve performance and security.

And actually, we see several benefits to having immutable strings:

  • The string pool is only possible if the strings, once created, are never changed, as they are supposed to be reused
  • The code can safely pass a string to another method, knowing that it can’t be altered by that method
  • Immutably automatically makes this class thread-safe
  • Since this class is thread-safe, there is no need to synchronize common data, which in turn improves performance
  • Since they are guaranteed to not change, their hashcode can be easily cached

Q5. How is a String stored in memory?

According to the JVM Specification, String literals are stored in a runtime constant pool, which is allocated from the JVM’s method area.

Although the method area is logically part of the heap memory, the specification does not dictate the location, memory size, or garbage collection policies. It can be implementation-specific.

This runtime constant pool for a class or interface is constructed when the class or interface is created by the JVM.

Q6. Are interned strings eligible for garbage collection in Java?

Yes, all _String_s in the string pool are eligible for garbage collection if there are no references from the program.

Q7. What is the String constant pool?

The string pool, also known as the String constant pool or the String intern pool, is a special memory region where the JVM stores String instances.

It optimizes application performance by reducing how often and how many strings are allocated:

  • The JVM stores only one copy of a particular String in the pool
  • When creating a new String, the JVM searches in the pool for a String having the same value
  • If found, the JVM returns the reference to that String without allocating any additional memory
  • If not found, then the JVM adds it to the pool (interns it) and returns its reference

Q8. Is String thread-safe? How?

Strings are indeed completely thread-safe because they are immutable. Any class which is immutable automatically qualifies for thread-safety because its immutability guarantees that its instances won’t be changed across multiple threads.

For example, if a thread changes a string’s value, a new String gets created instead of modifying the existing one.

Q9. For which _String _operations is it important to supply a Locale?

The Locale class allows us to differentiate between cultural locales as well as to format our content appropriately.

When it comes to the _String _class, we need it when rendering strings in format or when lower- or upper-casing strings.

In fact, if we forget to do this, we can run into problems with portability, security, and usability.

Q10. What is the underlying character encoding for strings?

According to _String’_s Javadocs for versions up to and including Java 8, Strings are stored in the UTF-16 format internally.

The char data type and java.lang.Character objects are also based on the original Unicode specification, which defined characters as fixed-width 16-bit entities.

Starting with JDK 9, Strings that contain only 1-byte characters use Latin-1 encoding, while Strings with at least 1 multi-byte character use UTF-16 encoding.

3. The String API

In this section, we’ll discuss some questions related to the String API.

Q11. How can we compare two Strings in Java? What’s the difference between str1 == str2 and str1.equals(str2)?

We can compare strings in two different ways: by using equal to operator ( == ) and by using the equals() method.

Both are quite different from each other:

  • **The operator (str1 == str2) **checks for referential equality
  • **The method (str1.equals(str2)) **checks for lexical equality

Though, it’s true that if two strings are lexically equal, then _str1.intern() == str2.intern() _is also true.

Typically, for comparing two Strings for their content, we should always use String.equals.

Q12. How can we split a String in Java?

The String class itself provides us with the _String#__split _method, which accepts a regular expression delimiter. It returns us a String[] array:

String[] parts = "john,peter,mary".split(",");
assertEquals(new String[] { "john", "peter", "mary" }, parts);

One tricky thing about split is that when splitting an empty string, we may get a non-empty array:

assertEquals(new String[] { "" }, "".split(","));

Of course, _split _is just one of many ways to split a Java String.

Q13. What is StringJoiner?

_StringJoiner _is a class introduced in Java 8 for joining separate strings into one, like taking a list of colors and returning them as a comma-delimited string. We can supply a delimiter as well as a prefix and suffix:

StringJoiner joiner = new StringJoiner(",", "[", "]");
joiner.add("Red")
  .add("Green")
  .add("Blue");

assertEquals("[Red,Green,Blue]", joiner.toString());

Q14. Difference between String, StringBuffer and StringBuilder?

Strings are immutable. This means that if we try to change or alter its values, then Java creates an absolutely new _String. _

For example, if we add to a string _str1 _after it has been created:

String str1 = "abc";
str1 = str1 + "def";

Then the JVM, instead of modifying str1, creates an entirely new String.

However, for most of the simple cases, the compiler internally uses StringBuilder and optimizes the above code.

But, for more complex code like loops, it will create an entirely new String, deteriorating performance. This is where StringBuilder and StringBuffer are useful.

Both StringBuilder and StringBuffer in Java create objects that hold a mutable sequence of characters.** StringBuffer is synchronized and therefore thread-safe whereas StringBuilder is not.**

Since the extra synchronization in _StringBuffer _is typically unnecessary, we can often get a performance boost by selecting StringBuilder.

Q15. Why is it safer to store passwords in a char[] array rather than a String?

Since strings are immutable, they don’t allow modification. This behavior keeps us from overwriting, modifying, or zeroing out its contents, making Strings unsuitable for storing sensitive information.

We have to rely on the garbage collector to remove a string’s contents. Moreover, in Java versions 6 and below, strings were stored in PermGen, meaning that once a String was created, it was never garbage collected.

By using a char[] array, we have complete control over that information. We can modify it or wipe it completely without even relying on the garbage collector.

Using char[] over String doesn’t completely secure the information; it’s just an extra measure that reduces an opportunity for the malicious user to gain access to sensitive information.

Q16. What does _String’_s intern() method do?

The method intern() creates an exact copy of a String object in the heap and stores it in the _String _constant pool, which the JVM maintains.

Java automatically interns all strings created using string literals, but if we create a String using the new operator, for example, String str = new String(“abc”), then Java adds it to the heap, just like any other object.

We can call the intern() method to tell the JVM to add it to the string pool if it doesn’t already exist there, and return a reference of that interned string:

String s1 = "Baeldung";
String s2 = new String("Baeldung");
String s3 = new String("Baeldung").intern();

assertThat(s1 == s2).isFalse();
assertThat(s1 == s3).isTrue();

Q17. How can we convert String to Integer and Integer to String in Java?

The most straightforward approach to convert a String to an Integer is by using Integer#parseInt:

int num = Integer.parseInt("22");

To do the reverse, we can use Integer#toString:

String s = Integer.toString(num);

Q18. What is String.format() and how can we use it?

String#format returns a formatted string using the specified format string and arguments.

String title = "Baeldung"; 
String formatted = String.format("Title is %s", title);
assertEquals("Title is Baeldung", formatted);

We also need to remember to specify the user’s _Locale, _unless we are okay with simply accepting the operating system default:

Locale usersLocale = Locale.ITALY;
assertEquals("1.024",
  String.format(usersLocale, "There are %,d shirts to choose from. Good luck.", 1024))

Q19. How can we convert a String to Uppercase and Lowercase?

String implicitly provides String#toUpperCase to change the casing to uppercase.

Though, the Javadocs remind us that we need to specify the user’s L__ocale to ensure correctness:

String s = "Welcome to Baeldung!";
assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase(Locale.US));

Similarly, to convert to lowercase, we have String#toLowerCase:

String s = "Welcome to Baeldung!";
assertEquals("welcome to baeldung!", s.toLowerCase(Locale.UK));

Q20. How can we get a character array from String?

String provides toCharArray, which returns a copy of its internal char array pre-JDK9 (and converts the String to a new char array in JDK9+):

char[] hello = "hello".toCharArray();
assertArrayEquals(new String[] { 'h', 'e', 'l', 'l', 'o' }, hello);

Q21. How would we convert a Java String into a byte array?

By default, the method String#getBytes() encodes a String into a byte array using the platform’s default charset.

And while the API doesn’t require that we specify a charset, we should in order to ensure security and portability:

byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII);
byte[] byteArray3 = "ijkl".getBytes("UTF-8");

4. String-Based Algorithms

In this section, we’ll discuss some programming questions related to _String_s.

Q22. How can we check if two Strings are anagrams in Java?

An anagram is a word formed by rearranging the letters of another given word, for example, “car” and “arc”.

To begin, we first check whether both the Strings are of equal length or not.

Then we convert them to char[] array, sort them, and then check for equality.

Q23. How can we count the number of occurrences of a given character in a String?

Java 8 really simplifies aggregation tasks like these:

long count = "hello".chars().filter(ch -> (char)ch == 'l').count();
assertEquals(2, count);

And, there are several other great ways to count the l’s, too, including loops, recursion, regular expressions, and external libraries.

Q24. How can we reverse a String in Java?

There can be many ways to do this, the most straightforward approach being to use the reverse method from StringBuilder (or StringBuffer):

String reversed = new StringBuilder("baeldung").reverse().toString();
assertEquals("gnudleab", reversed);

Q25. How can we check if a String is a palindrome or not?

A palindrome is any sequence of characters that reads the same backward as forward, such as “madam”, “radar” or “level”.

To check if a string is a palindrome, we can start iterating the given string forward and backward in a single loop, one character at a time. The loop exits at the first mismatch.

5. Conclusion

In this article, we went through some of the most prevalent String interview questions.

All the code samples used here are available on GitHub.

#java #string #interview #interview-questions

50 Python Interview Questions and Answers

Ace your next coding interview

Are you preparing for a job interview or an exam that involves knowledge about Python? Or do you want to quickly go through common topics of Python?

Here is a list of 50 interview questions with answers. The list is in no particular order.

I hope you enjoy it.

1. Name Some Differences Between a List and a Tuple

2. What Does the Range() Function Do?

3. How Does Map() Function Work?

4. What is the Difference between “is” and “==”?

#python #data-science #software-development #50 python interview questions and answers #interview questions and answers #python interview questions and answers