HTML
Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

Top 35 Java String Interview Questions with Answers for 2 to 5 Years Experienced Programmers

Hello Java Programmers, if you are preparing for a Java developer interview and want to refresh your knowledge about  String class in Java then you have come to the right place. In the past, I have shared 130+ Core Java Interview Questions and 21 String Coding Problems for Interviews and in this article, I am going to share 35 Java String Questions for Interviews. The  String class and concept is a very important class in Java. There is not a single Java program out there which is not use String objects and that's why it's very important from the interview point of view as well. In this article, I am going to share 35 String-based questions from different Java interviews.

How to calculate perimeter and area of square in Java? Example Tutorial

If you are looking for a solution of problem how to calculate perimeter and area of a given Square in Java then you have come at the right place. In this article, I have given step by step solution of this common coding problem. This was actually a homework exercise when I was learning Java program and since I was good at Maths, I know how to calculate Perimeter and Area of Circle and Square but big challenge for me was to convert that knowledge into code. Another big challenge for me was how to take input from user actually that was the mistake I made when I first solved this problem. 

Top 20 Java Access Modifier Interview Questions Answers for 1 to 2 Years Experienced

Access modifiers is one of the essential concept in Java and every programmer should be familiar with, and because of its importance, its also a popular topic in Java interviews. Access modifier can be applied to class, method, fields, and variables and as the name suggests they control the access. Like who can access that particular class, method or variable. For example, public modifier provides universal access which means any public class, method or variable is accessible by everyone and everywhere. In other words, you can access a public class both within the package and outside the package. 

How Long It Take To Become a DBA (Database Administrator) in 2023? 7 days, 1 month or 1 year?

Hello guys, if you want to become a Database Administrator in 2023 and wondering how long does it take to learn SQL and Database and become a professional Database Administrator or Junior DBA then you are at right place. In the past, I have shared free SQL and Database courses as well roadmap to become a Web Developer and in this article, I am going to share how long it will take you to become a DBA in 2023. Along the way, I will share best way to learn SQL and Database and what is the best way to become a DBA quickly. So continue reading and find out what it takes to become a DBA and get a job in real world. I will also share all the skills you need to become a DBA in 2023.

Top 10 Courses to Learn System Design and Software Architecture in 2023 - Best of Lot

Software design or System design is one of the tricky concepts to master. You can quickly learn a programming language like Java or Python, but creating software using that programming language is a totally different thing. That's where software design and coding skills come to the rescue. It's actually an art to structure your program, design your modules, specify boundaries and interactions with other parts of the system so that they are easier to read, maintain, and flexible to change. It's one of the most essential skills for a software developer but often gets ignored. If you look for an online course to learn Software design and architecture, you won't find many, forget about good ones.

How to convert float, double, String, Map, List to Set, Integer, Date in Java - Example Tutorial

Hello guys, converting one data type to another, for example String to Integer or String too boolean is a common task in Java and every Java programmer should be familiar with how to convert common data types like String, Integer, Long, Float, Double, Date, List, Map, Set, to each other. In the past, I have shared several tutorial where I have shown you how to carry out such conversion in Java and this article is nothing but a collection of such tutorial so that you can learn all of that knowledge in one place. You can also bookmark this page as I will be adding new data type conversion tutorials into this list as and when I write them, and you can also suggest if you struggle to convert a particular type to another and I will try to cover them here. 

10 points on TCP/IP Protocol, Java Programmers should Know

TCP/IP is one of the most important protocol as its backbone of HTTP, internet and most of the communication happens today. It's also important from technical interview perspective, you might have already seen difference between TCP and UDP multiple time during interviews ( I have seen). I believe every programmer, not just Java developer should know what is TCP/IP protocol? How it works and the below points I am going to mention. These are basic points and most of you already know but during Interview I have found many developers who doesn't really know what TCP/IP offers and how it works and what are the pros and cons of TCP/IP protocol. That's where, I think this article will help you. Anyway, let's jump into technical details now. 

How to solve word break problem in Java using dynamic programming? Example

Problem Statement:
You are given a dictionary of words and the input string. Determine input string can be segmented into a space-separated sequence of given dictionary words.

Note: This question is based on dynamic programming and asked multiple times in top product-based companies.

Inputs:

         Dict = {i, like, am, boy, e, o, dog, cat, g};

        word = "iIikedog"  --------can be segmented into space-separated words--------> i, like, dog




Ask yourself that 'I', 'like', and 'dog' are presented in the dictionary?

Yes, so we can say that the given string can be segmented.

Now let's take another example.

         word = "ilikecatsanddog" --------- can be segmented as-----> i, like, cats, and, dog

                                                                                                              i, like, cat, s, and, dog

We can see that the words 'cats', 'and', 's' are not present in the dictionary so such a string can't be segmented into space-separated words.



Let's try to solve it.....

Like another dynamic programming problem, we will create a matrix and will use previously calculated results to calculate the current result.


Consider the given string as an array like this.

i

l

i

k

e

d

o

g

 

The columns and rows represent the same given string in the matrix.



Now let's try to understand what each cell represents in the matrix.

The cells can have two kinds of values either '0' or '1'. Suppose the cells (3,6) and (3,7) have the value '1' this means the substrings from 3 to 6 and 3 to 7 are present in the given input dictionary.


If you notice the cell (5,3) and the corresponding substring in the given word the direction is reverse and there is no point in considering the reverse computation of the given string. So we will mark all such cells as '0'.

We filled half of the matrix with value '0' so we no need to perform the reverse computations for these cells. This way we can save both memory and time.

Now start filling rest of the cells manually by comparing the row-column pair value against the given dictionary.

So the cell (0, 0) i.e. 'i' is present in the dictionary so matrix[0][0] = 1.

Similarly cell (4, 4) i.e. 'e' is also present in the dictionary so matrix[4][4] = 1.

Now let's take one substring 'ilike' and see the logic to solve this problem.

i

l

i

k

e

d

o

g

0

1

2

3

4

5

6

7


          

          i      l     i     k      e

          0     1    2    3      4


We will try to separate this string into 2 parts in all the possible ways.

Let say we have first 2 parts: 

(0, 0)--------> 'i' and (1, 1)----------> 'l' 

matrix[0][0] && matrix[1][1]

                  1 && 0

So 'il' is not present in the dictionary.

Consider another combination.

(4, 3)--------> 'k' and (4, 4)----------> 'e' 

matrix[4][3] && matrix[4][4]

                  0 && 1



This is false means 'ke' is not present in the dictionary.

So I will keep on taking the substrings from the given word to be space separated and divide them into 2 parts in different ways and will check against the matrix that if both the parts are true i.e. '1' means the substring is present in the dictionary.


So finally we will consider the entire given word and divide it into 2 parts in all the possible ways and we will use the values of the previously computed cells to calculate the value of the marked cell and if the the value is '1' means the given word can be separated into the space separated segments.

Start Implementing it...

Consider below code snippet.

i

l

i

k

e

d

o

g

0

1

2

3

4

5

6

7



       For i = 0 and N = 7


      for(int k = 0; k < N+1; k++){



              if(matrix[i][i+k]) && matrix[k+1][N])

              {

                    return true;

              }

     }


The if condition shows the logic to divide the given word into 2 parts in all possible ways.


Complete Code:

public class Main {

   

    public String wordBreakProblem(String word, Set<String> dict){

            int matrix[][] = new int[word.length()][word.length()];

            

// fill all the cells with '-1'.

            for(int i=0; i < matrix.length; i++){

                for(int j=0; j < matrix[i].length ; j++){

                    matrix[i][j] = -1; 

                }

            }

            

            

//If the substring is present in the dictionary then fill the corresponding cell with non-negative value.

            for(int l = 1; l <= word.length(); l++){

                for(int i=0; i < word.length() -l + 1 ; i++){

                    int j = i + l-1;

                    String str = word.substring(i,j+1);

                    

                    if(dict.contains(str)){

                        matrix[i][j] = i;

                        continue;

                    }

                    

// Filling the value of the corresponding cell for the taken substring using value of the previously calculated cell.

                    for(int k=i+1; k <= j; k++){

                        if(matrix[i][k-1] != -1 && matrix[k][j] != -1){

                            matrix[i][j] = k;

                            break;

                        }

                    }

                }

            }

            if(matrix[0][word.length()-1] == -1){

                return null;

            }

            

            

//Finally segregate the given word into the words available in the dictionary.

            StringBuffer buffer = new StringBuffer();

            int i = 0; int j = word.length() -1;

            while(i < j){

                int k = matrix[i][j];

                if(i == k){

                    buffer.append(word.substring(i, j+1));

                    break;

                }

                buffer.append(word.substring(i,k) + " ");

                i = k;

            }

            

            return buffer.toString();

        }

        public static void main(String args[]){

            Set<String> dictionary = new HashSet<String>();

            dictionary.add("I");

            dictionary.add("like");

            dictionary.add("had");

            dictionary.add("play");

            dictionary.add("to");

            String str = "Ihadliketoplay";

            Main bmw = new Main();

            String result1 = bmw.wordBreakProblem(str, dictionary);

            

            System.out.print(result1);

        }

    }


Output:

I had like to play

Test your understanding...



Q. 1) Given dict = {'li, 'sop', 'tree', 'ding', 'g'} and word = 'sopptreeg'. Is it possible to segment the given string into space separated segments of the given dict. words ?

Ans. 'sop' , 'p', 'tree', 'g'

'so', 'pp', 'tree', 'g'

It looks like the given word can't be separated.

Before you leave...

Knowledge of data structure and algorithms is must to simulate the real world problem in code.

If you want to learn more about this article, drop a comment below and reach out to us to let us know your interest.

If you enjoyed learning the fundamentals of DSA share your knowledge to your fellow programmers and social circle. May be someone out really needs this resource, and you might be helping them out by sharing it.

eeeeellldldkonoioid


How ThreadLocal variables works in Java?

Hello guys, ThreadLocal variable is an interesting concept and class from Java API. Not many developer knows about it and very few know how to use it correctly. A couple of years ago it was also a popular Java interview questions for experienced developer but over the years, it lost the popularity as more and more people are now asking about Phaser, CompletableFuture, ForkJoinPool, and other newly added concurrency utilities. ThreadLocal variables, as name suggests is local to thread, which means every thread has there own copy. This means they don't need to look at the main memory when they want to use that variable and best thing is that the variable is not even shared between threads so no locking or synchronization is needed.