Merfantz Technologies Interview Questions with Answers – Part 1
This blog explains about Merfantz Technologies Fresher Interview Questions with Answers and is given below :-
Merfantz Technologies Fresher Interview Questions with Answers
1. How to remove all white spaces from a string in Java ?
Given a String with white spaces, the task is to remove all white spaces from a string using Java built-in methods.
Examples:
Input: str = ” Geeks for Geeks “
Output: GeeksforGeeks
Input: str = ” A Computer Science Portal”
Output: AComputerSciencePortal
To remove all white spaces from String, use replaceAll() method of String class with two arguments,
i.e.
replaceAll(“\\s”, “”);
where \\s is a single space in unicode.
Program:
class BlankSpace {
public static void main(String[] args)
{
String str = ” Geeks for Geeks “;
// Call the replaceAll() method
str = str.replaceAll(“\\s”, “”);
System.out.println(str);
}
}
Output:
Geeks for Geeks
2.
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Answer:
public class pattern15
{
public static void main(String[] args)
{
int n =5;
for (int i=1; i<=n; i++) {
for(int j=1; j<=(n-i); J++)
{
System.out.print(” “):
}
for(int j=1; j<=i; j++)
{
System.out.print(i+” “);
}
System.out.println();
}
}
}
3. How Can we count length of a String without using length() ?
- Using toCharArray
- Using StringIndexOutOfBoundsException Using toCharArray is simplest solution.
Using toCharArray:
- Convert string to char array using toCharArray method
- Iterate over char array and incrementing length variable.
class LenghtOfStringMain{
public static void main(String args[]){
String helloWorld=”This is hello world”;
out.println(“length of helloWorld string :”+getLengthOfStringWithCharArray(helloWorld));
}
public static int getLengthOfStringWithCharArray(String str)
{
int length=0;
char[] strCharArray=str.toCharArray();
for(char c:strCharArray)
{
length++;
}
return length;
}
you will get following output:
length of helloWorld string :19
Using StringIndexOutOfBoundsException:
You must be wondering how we can use StringIndexOutOfBoundsException to find length of String. Please refer below logic :
- Initialize i with 0 and iterate over String without specifying any condition. So it will be always true.
- Once value of i will be more than length of String, it will throw StringIndexOutOfBoundsException exception.
- We will catch the exception and return i after coming out of catch block.
Class LenghtOfStringMain{
public static void main(String args[])
{
String helloWorld=”This is hello world”;
System.out.println(“length of helloWorld string :”+getLengthOfString(helloWorld));
}
public static int getLengthOfString(String str)
{
int i=0;
try{
for(i=0;;i++)
{
str.charAt(i);
}
}
catch(Exception e)
{
}
return i;
}
you will get following output:
length of helloWorld string :19