Multiply Two Strings in Java8 May 2025 | 7 min read Multiplying two strings in Java involves converting the strings representing numbers into integer values, performing the multiplication, and converting the result back into a string. This approach is particularly useful when dealing with very large numbers that exceed the range of primitive data types like int or long. Input: String 1 = "123", String 2 = "45" Output: "5535" Explanation The output "5535" is obtained by multiplying "123" and "45" as integers. Digit-by-digit multiplication, similar to manual calculation, produces intermediate sums, which are combined to form the final product. The result is then converted back into a string, accurately representing the multiplication of the two input strings as numbers. Approach 1: Digit-by-Digit Multiplication with Result ArrayAlgorithmStep 1: Handle Edge Cases: Check if either of the strings is "0". If yes, return "0" immediately because multiplying any number with zero results in zero. Step 1.1: Check for Zero Inputs: If either of the input strings (num1 or num2) is equal to "0", the product will always be "0". This is because multiplying any number by zero results in zero. In this case, immediately return "0" without performing further calculations. This step ensures efficiency and avoids unnecessary processing. Step 2: Initialize Variables: Calculate the lengths of both input strings, num1 and num2. Create an integer array result of size n1 + n2 to store the intermediate and final results of the multiplication. This size ensures it can accommodate the largest possible product of the two numbers. Step 2.1: Calculate Lengths of Input Strings: Start by calculating the lengths of the two input strings, num1 and num2. This is essential for determining the size of the result array. The result array should be large enough to accommodate the largest possible product, which can have a length of n1 + n2. Step 3: Simulate Manual Multiplication: Loop through the digits of num1 from right to left (like in manual multiplication). For each digit in num1, loop through the digits of num2 from right to left. Multiply the current digits of num1 and num2. It gives a partial product. Step 4: Add Partial Product to Result Array: Compute the position in the result array where the partial product contributes. It depends on the indices of the digits in num1 and num2. Add the partial product to the current value in the array, accounting for carry-over to the next position. Step 5: Handle Carry-Over: After adding the partial product, determine the carry (sum divided by 10) and the remainder (sum modulo 10). Store the remainder in the current position of the result array and add the carry to the next higher position. Step 6: Build the Result String: Traverse the result array from left to right and construct the final result string. Skip leading zeros during this process. If the result string is empty after skipping leading zeros, return "0". Step 6.1: Traverse the Result Array: After all partial products and carry-overs are added to the result array, start from the leftmost position and traverse through the array. Convert each digit in the array to form the final result string. Skip any leading zeros to ensure the string represents the correct product. Step 7: Return the Result: Once the result array is processed and leading zeros are removed, convert the remaining digits into a string. This string represents the final product of the two input strings. If the result string is empty after removing zeros, return "0" to handle the case of a zero product. Let’s implement the above approach in a Java program. File Name: StringMultiplication.java Output: 5535 Complexity AnalysisTime ComplexityThe time complexity of this algorithm is O(n1 * n2), where n1 and n2 are the lengths of the two strings. It is because every digit in the first string is multiplied with every digit in the second string, resulting in a nested loop structure. Space ComplexityThe space complexity of this algorithm is O(n1 + n2), where n1 and n2 are the lengths of the two strings. It comes from the integer array used to store intermediate results, which has a maximum size of n1 + n2 to accommodate the largest possible product. Approach 2: Using Divide and Conquer MethodStep 1: Base Case (Small Numbers): If the numbers are small (e.g., single digits), you simply multiply them directly. This is the easiest case and doesn't need the full algorithm. Step 1.1: Base Case Check: When the numbers involved are very small, typically one-digit numbers, we skip the recursive multiplication process and directly multiply them. For example, multiplying "3" and "5" would directly give "15". This avoids unnecessary complexity and speeds up the process for small inputs. Step 2: Splitting the Numbers: For larger numbers, you split each number into two parts. For example, if you are multiplying "1234" and "5678": Split "1234" into two parts: high1 = "12" and low1 = "34". Split "5678" into two parts: high2 = "56" and low2 = "78". Step 3: Recursive Multiplication: Now, we need to calculate three smaller multiplications: Multiply the high parts: high1 * high2 (i.e., 12 * 56). Multiply the low parts: low1 * low2 (i.e., 34 * 78). Multiply the sum of the high and low parts of each number: (high1 + low1) * (high2 + low2) (i.e. ., (12 + 34) * (56 + 78)). Step 4: Combining the Results: After calculating the three products, you combine them to get the final result: The first product (high1 * high2) is shifted to the left by two places (like multiplying by 100). The second product ((high1 + low1) * (high2 + low2)) is adjusted by subtracting the first and third products and shifted by one place (like multiplying by 10). Finally, add the third product (low1 * low2) directly. The results in a more efficient way of multiplying compared to traditional methods. Step 4.1: Shift and Combine Products: After calculating the three products, we need to combine them into the final result. The first product (high1 * high2) is shifted left by two places, effectively multiplying it by 100. The second product, which represents the cross-multiplication of the high and low parts, is adjusted by subtracting the first and third products, then shifted left by one place. This ensures the proper placement of each product in the final result. Step 5: Final Result: After combining the results, you get the final product. If there are any leading zeros, we remove them to get the correct answer. Step 6: Build the Result String: Once all the partial products have been calculated and combined, the next step is to construct the final result string. You begin by traversing the result array, starting from the leftmost digit. As you form the string, make sure to skip any leading zeros. If, after skipping zeros, the string is empty, return "0" to handle cases where the result is zero. Let’s implement the above approach in a Java program. File Name: KaratsubaMultiplication.java Output: 5453149 Complexity AnalysisTime ComplexityThe Karatsuba algorithm improves multiplication by breaking the problem into smaller parts. Instead of performing O(n2) operations like traditional multiplication, it reduces the complexity to O(1.585 ). This means Karatsuba can multiply large numbers faster, as it requires fewer steps for the same size of input. Space ComplexityThe space complexity of the program is O(n), where n is the number of digits in the input numbers. This is because the algorithm only needs space for storing intermediate results and recursive calls, which grow linearly with the size of the input numbers. Next TopicPractical Number in Java |
Structured Concurrency in Java
Concurrency is a fundamental concept in modern software development, allowing programs to execute multiple tasks simultaneously. Java, one of the most popular programming languages, provides robust support for concurrent programming. In recent years, structured concurrency has emerged as a powerful paradigm for writing concurrent code in...
6 min read
Agile Principles Patterns and Practices in Java
Agile software development has gained immense popularity in recent years due to its flexibility, customer-centric approach, and iterative development practices. Java, being one of the most widely used programming languages, aligns seamlessly with Agile methodologies. In this section, we will explore Agile principles, patterns, and practices...
4 min read
Why Java is Object-Oriented Programming
? object shows real-world things and contains data such as variables and its behavior such as methods. The objects make the code more organized, easy to reuse and good for managing large projects. Java also uses important features such as inheritance (it shares their features), encapsulation...
8 min read
Instance Variable in Java
In any programming language, the program needs identifiers for storing different values that can be used throughout the program. These identifiers are variables. Variable in Java A variable is a name assigned to a value that is stored inside the system memory. The value can be updated during...
4 min read
Java class keyword
A is the most common keyword which is used to declare a new Java class. A class is a container that contains the block of code that includes field, method, constructor, etc. A class is a template or blueprint from which objects are created. It...
2 min read
Java Testing Tools
In Java, the code can be smaller or larger that depends on the functionality. If a user requires small functionality, the code will be smaller in length and easy to do testing. But if a user requires more functionality in the application, the code will be...
6 min read
Nested ArrayList in Java
In Java programming, there are numerous records systems which might be crucial for storing and manipulating data correctly. One such facts shape is the ArrayList, that is a dynamic array that can develop or lessen as desired. In a few times, we can stumble upon conditions...
4 min read
Business Consumer Problem in Java
In the rapidly evolving landscape of business, Java has emerged as one of the most widely used programming languages. Its versatility, platform independence, and extensive libraries make it a top choice for developing robust and scalable enterprise applications. However, like any technology, Java is not without...
4 min read
MultiValueMap in Java
Java is a flexible programming language that offers a number of data structures for organising data sets. Maps, such as HashMap and TreeMap, are essential in situations where mapping keys to values is required. There are circumstances, nevertheless, in which you must link a key to more...
4 min read
Java Parallel Stream Example
The parallel stream was introduced in Java 8 or later versions. It is a part of functional programming. Using the feature of parallel stream, we can use multiple cores of the processor. Any stream in Java can be easily transformed from sequential to parallel stream. In...
4 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India