Print multiple lines output in java without using a new line character - java

this is one of the interview question. I am supposed to print multiple lines of output on command line, without using the newline(\n) character in java. I tried googling for this, didn't find appropriate answers. If i am printing 5 numbers, then it should print in the following fashion. But I am not supposed to use the newline character nor loops either. I have to print this using a single println() statement. Can you give me some ideas ? Thanks !
1
2
3
4
5

You can do it recursively:
public void foo(int currNum) {
if (currNum > 5)
return;
println(currNum);
foo(currNum + 1);
}
Then you are only using a single println and you aren't using a for or while loop.

If you're just not allowed of using \n and println() then you can get the systems line.separator, e.g.
String h = "Hello" + System.getProperty("line.separator") + "World!"
Hope this helped, have Fun!

Ok, now I think I understand your question. What about this?
println(String.format("%d%n%d%n%d%n%d%n%d%n", 1, 2, 3, 4, 5));

One way is this: Platform Independent
final String EOL = System.getProperty("line.separator");
System.out.println('1' + EOL + '2' + EOL + '3' + EOL + '4' + EOL + '5');
This is Platform Dependent
char eol = (char) 13;
System.out.println("" + '1' + eol + '2' + eol + '3' + eol + '4');

There are many ways to achieve this...
One alternative to using '\n' is to output the byte value for the character. So, an example to print out your list of the numbers 1-5 in your example...
char line = (char)10;
System.out.println("1" + line+ "2" + line+ "3" + line + "4" + line+ "5");
You could also build a byte[] array or char[] array and output that...
char line = (char)10;
char[] output = new char[9]{'1',line,'2',line,'3',line,'4',line,'5'};
System.out.println(new String(output));

Probably cheating based on the requirements, but technically only 1 println statement and no loops.
public int recursivePrint(int number)
{
if (number >=5 )
return number;
else
System.out.println(recursivePrint(number++));
}

No loops, 1 println call, +flexibility:
public static void main (String[] args) {
print(5);
}
final String newLine = System.getProperty("line.separator");
public void print(int fin) {
System.out.println(printRec("",1,fin));
}
private String printRec(String s, int start, int fin) {
if(start > fin)
return s;
s += start + newLine;
return printRec(s, start+1, fin);
}

The ASCII value of new Line is 10.
So use this
char line = 10;
System.out.print("1" + line + "2" + line ......);

ANSI terminal escape codes can do the trick.
Aside: Since System.out is a PrintStream, it may not be able to support the escape codes.
However, you can define your own println(msg) function, and make one call to that. Might be cheating, but unless they explicitly say System.out.println, you're golden (hell, even if they do, you can define your own object named System in the local scope using a class defined outside your function, give it a field out with a function println(msg) and you're still scot-free).

Related

Replace characters and keep only one of these characters

Can someone help me here? I dont understand where's the problem...
I need check if a String have more than 1 char like 'a', if so i need replace all 'a' for a empty space, but i still want only one 'a'.
String text = "aaaasomethingsomethingaaaa";
for (char c: text.toCharArray()) {
if (c == 'a') {
count_A++;//8
if (count_A > 1) {//yes
//app crash at this point
do {
text.replace("a", "");
} while (count_A != 1);
}
}
}
the application stops working when it enters the while loop. Any suggestion? Thank you very much!
If you want to replace every a in the string except for the last one then you may try the following regex option:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", " ");
somethingsomething a
Demo
Edit:
If you really want to remove every a except for the last one, then use this:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", "");
You can also do it like
String str = new String ("asomethingsomethingaaaa");
int firstIndex = str.indexOf("a");
firstIndex++;
String firstPart = str.substring(0, firstIndex);
String secondPart = str.substring(firstIndex);
System.out.println(firstPart + secondPart.replace("a", ""));
Maybe I'm wrong here but I have a feeling your talking about runs of any single character within a string. If this is the case then you can just use a little method like this:
public String removeCharacterRuns(String inputString) {
return inputString.replaceAll("([a-zA-Z])\\1{2,}", "$1");
}
To use this method:
String text = "aaaasomethingsomethingaaaa";
System.out.println(removeCharacterRuns(text));
The console output is:
asomethingsomethinga
Or perhaps even:
String text = "FFFFFFFourrrrrrrrrrrty TTTTTwwwwwwooo --> is the answer to: "
+ "The Meeeeeaniiiing of liiiiife, The UUUniveeeerse and "
+ "Evvvvverything.";
System.out.println(removeCharacterRuns(text));
The console output is........
Fourty Two --> is the answer to: The Meaning of life, The Universe and Everything.
The Regular Expression used within the provided removeCharacterRuns() method was actually borrowed from the answers provided within this SO Post.
Regular Expression Explanation:

Match Substring that contains separators in full string

I wasn't sure how to phrase the question. Long story short, I want to pull both strings (a, b) from the line In: a (b). In almost all cases a=b, but just in case, I've separated them. The problem: both strings can contain any character which includes Unicode, white space, punctuation, and parenthesis.
1: In: ThisName (ThisName) is in this list
2: In: OtherName (With These) (OtherName (With These)) is in this list
3: In: Really Annoying (Because) Separators (Really Annoying (Because) Separators) is in this list
Line 1, easy: ^\w+:\s(?'a'.+?)\s\((?'b'.+)\) a:ThisName b:ThisName
Line 2, same as before:a:OtherName b: With These) (OtherName (With These)
Line 2, lazy: ^\w+:\s(?'a'.+?)\s\((?'b'.+?)\) a:OtherName b:With These
Line 3, head desk
Is this possible? Perhaps I need to go another route? We know one set of parenthesis is required to be there. Perhaps I have to go down a math route, calculate the number of parenthesis and find that route to determine which should actually contain b? Count every open and close somehow.
What I've been playing with: https://regex101.com/r/8YIweJ/2
By the way, if I could change the input formatting, I most definitely would.
Added Question: If that is not possible, does assuming a=b all the time make this any easier? I can't think of how it would.
My comments are embedded in the processInput method.
public static void main(String[] args)
{
String input = "1: In: ThisName (ThisName) is in this list\n" +
"2: In: OtherName (With These) (OtherName (With These)) is in this list\n" +
"3: In: Really Annoying (Because) Separators (Really Annoying (Because) Separators) is in this list\n" +
"4: In: Not the Same (NotTheSame) is in this list\n" +
"5: In: A = (B) (A = (B)) is in this list\n" +
"6: In: A != (B) (A != B) is in this list\n";
for (String line : input.split("\n"))
{
processInput(line);
}
}
public static void processInput(String line)
{
// Parse the relevant part from the input.
Matcher inputPattern = Pattern.compile("(\\d+): In: (.*) is in this list").matcher(line);
if (!inputPattern.matches())
{
System.out.println(line + " is not valid input");
return;
}
String inputNum = inputPattern.group(1);
String aAndB = inputPattern.group(2);
// Check if a = b.
Matcher aEqualsBPattern = Pattern.compile("(.*) \\(\\1\\)").matcher(aAndB);
if (aEqualsBPattern.matches())
{
System.out.println("Input " + inputNum + ":");
System.out.println("a = b = " + aEqualsBPattern.group(1));
System.out.println();
return;
}
// Check if a and b have no parentheses.
Matcher noParenthesesPattern = Pattern.compile("([^()]*) \\(([^()]*)\\)").matcher(aAndB);
if (noParenthesesPattern.matches())
{
System.out.println("Input " + inputNum + ":");
System.out.println("a = " + noParenthesesPattern.group(1));
System.out.println("b = " + noParenthesesPattern.group(2));
System.out.println();
return;
}
// a and b have one or more parentheses in them.
// All you can do now is guess what a and b are.
// There is at least one " (" in the string.
String[] split = aAndB.split(" \\(");
for (int i = 0; i < split.length - 1; i++)
{
System.out.println("Possible Input " + inputNum + ":");
System.out.println("possible a = " + mergeParts(split, 0, i));
System.out.println("possible b = " + mergeParts(split, i + 1, split.length - 1));
System.out.println();
}
}
private static String mergeParts(String[] aAndBParts, int startIndex, int endIndex)
{
StringBuilder s = new StringBuilder(getPart(aAndBParts, startIndex));
for (int j = startIndex + 1; j <= endIndex; j++)
{
s.append(" (");
s.append(getPart(aAndBParts, j));
}
return s.toString();
}
private static String getPart(String[] aAndBParts, int j)
{
if (j != aAndBParts.length - 1)
{
return aAndBParts[j];
}
return aAndBParts[j].substring(0, aAndBParts[j].length() - 1);
}
Executing the above code outputs:
Input 1:
a = b = ThisName
Input 2:
a = b = OtherName (With These)
Input 3:
a = b = Really Annoying (Because) Separators
Input 4:
a = Not the Same
b = NotTheSame
Input 5:
a = b = A = (B)
Possible Input 6:
possible a = A !=
possible b = B) (A != B
Possible Input 6:
possible a = A != (B)
possible b = A != B
What I would do is not use regular expressions for this. Follow this kind of algorithm:
Find the first index of ( that should give you your "a" string if I follow your question
From that index go through the string character by character using charAt. Count up when you hit a ( and down when you get to a ). Once you hit zero in this counter then your brackets match and you have the position of the end of your "b" string.
It also looks like there could be multiple string making up "B" (from line 3), so you can just keep iterating over the string per step 2 above, adding the strings to either a list or a string builder as appropriate.
Well, you could parse your text, but not with a regular expression, and with at least one of the following conditions being true:
The parentheses in the B expression are guaranteed to be matched properly. That is, no )) ((, :-), etc.
The A and B are exactly the same. In such a case, even if you have unmatched parentheses inside them, e.g. Hello (-: (Hello (-:), you know that the ( before the second Hello is the "right" one.
If you can't make those guarantees, then you should write an isMatchedParenthesis(String) method, that checks if all parentheses are properly matched. Have a counter, starting from zero, and scan through the string.
For each character in the string:
If current char is (, counter++.
If current char is ), counter--.
If counter is negative, return false
If at the end the counter is positive, return false. Otherwise true.
Test your string with that method. If it works, you can rely on finding the "significant" parenthesis using parenthesis matching. If it returns false, you can try the fallback method that assumes that both strings are the same.
Find the significant parenthesis when balanced
Find the index of the rightmost ) (use lastIndexOf).
counter=0.
For each character going down from that index to 4 (The character after In::
If it is a ), counter++
If it is a (, counter--.
If counter==0 stop, return current index.
Now you have the index of the significant parenthesis. Your A is the substring between 4 and this index - 1 (remember the space before the (). Your B is from that index+1 to the index of the right ) that you found first.
Fallback method
Suppose your parentheses are not balanced. Can you do anything?
Make a list of all the indexes of ( in the string.
If the length of the list is even - bad string, report to user.
If the length is odd, take the index of the middle (. Assuming that A and B are the same, they should each have the same number of (, so the one that has the same number of ( to its left and to its right is your candidate.
Extract the A and B as before. If they are not equal - bad string, report to user.

Recursion- reversing String

I believe that I have a decent understanding of recursion (factorial etc), however in the following example in reversing a string I do not understand the line. Can someone please explain what it does?
return reverseString(str.substring(1)) + str.charAt(0);
Full Code from method:
public static String reverseString(String str){
if(str.length()<2){
System.out.println("reached Base case");
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
The call substring(1) takes the first character off of the string. That is fed into the recursive call, which reverse all but the last character. Then, the first character is appended, completing the reversal.
Example:
reverseString("abc") =>
reverseString("bc") + 'a' =>
(reverseString("c") + 'b') + 'a' =>
("c" + 'b') + 'a' =>
"cb" + 'a' =>
"cba"
It takes everything after the first character and calls the recursive function. The first character is put at the end of the string. This results in a reversal.
return reverse(Everything after the first) + the first
return reverseString(str.substring(1)) + str.charAt(0);
For example, the String is HelloWorld
Then "HelloWorld".substring(1) returns "elloWorld"
and "HelloWorld".charAt(0) returns "H"
You take the first letter and add it to the end od the string. But before, you do it again with the first part. In the end, this algorithm reverses the string.
Let's take this string:
str = "Reverse";
The value of str.substring(1) is "everse".
The value of str.charAt(0) is "R".
I think you can take it from there if you understand recursion.
It inefficiently reverses the string by placing each successive sub-string on the stack until it reaches a length less then 2; it then reverses the characters by popping those results off the stack and appending the first character to the sub-string. It is inefficient because Java includes the StringBuilder class and that has a reverse method.
Try to think of reversing a string in this manner:
//reverse of a string can be expressed as the last character
//plus the reverse of everything remaining. For example, if we had
//"food", you would have "d" + reverse("foo"), which is "d" + "oof"
//which gives you "doof". So:
reverse(str) = str[str.length - 1] + reverse(str[0:str.length - 2]);
reverse(str[0]) = str[0] //reverse of a 1 character string is the character itself
So apply this to the string abcd:
You have:
reverse("abcd") = "d" + reverse("abc")
reverse("abc") = "c" + reverse("ab")
reverse("ab") = "b" + reverse("a")
reverse("a") = "a";
Now when you substitute you have:
reverse("ab") = "b" + "a" = "ba"
reverse("abc") = "c" + "ba" = "cba"
reverse("abcd") = "d" + "cba" = "dcba"
Think about how you can write code that mimics this behavior.

Regular expression to recognize string of '#'

I have a java question. I can't figure out how to write my regular expression to print something to a file when encountering one or more instances of '#'. It must not print when the string equals "", but it must print when the string equals "#". Here's my code:
int num = 1;
StringBuffer noletterbuf = new StringBuffer(nospaces);
noletterbuf.deleteCharAt(0);
String noletter = noletterbuf.toString();
//if(num == noletter.split("[^#]").length){//applies # to C# and C
if(num == noletter.split("[#*]").length){//applies # to C
double yacc = octave*-50;
p6.println("sb.append(\"/Times-Roman findfont 70 scalefont setfont 1 -1 scale newpath \"); sb.append(" + xaccplace + " + \" \" +" + yacc + " + \" moveto \"); sb.append(\"( # ) show 1 -1 scale \");");
}
Thanks in advance!
Bjorn
Why use regex and .split() at all, since you just discard the resulting array?
You can check if the string contains # using the following:
if (noletter.indexOf('#') >= 0) {
// ...
}
Your code:
noletter.split("[#*]")
This will split at each # and each *, since the asterisk is within brackets.
A simple way to check using regex is:
if (str.matches(".*#.*")) // true if there's a # in str
I don't understand the "no spaces" relevance, or why you used a StringBuffer, or why you deleted the first character.

How do I concatenate two strings in Java?

I am trying to concatenate strings in Java. Why isn't this working?
public class StackOverflowTest {
public static void main(String args[]) {
int theNumber = 42;
System.out.println("Your number is " . theNumber . "!");
}
}
You can concatenate Strings using the + operator:
System.out.println("Your number is " + theNumber + "!");
theNumber is implicitly converted to the String "42".
The concatenation operator in java is +, not .
Read this (including all subsections) before you start. Try to stop thinking the php way ;)
To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:
new StringBuilder().append("firstString").append("secondString").toString()
There are two basic answers to this question:
[simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
[less simple]: Use StringBuilder (or StringBuffer).
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");
value.toString();
I recommend against stacking operations like this:
new StringBuilder().append("I").append("like to write").append("confusing code");
Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.
Note: Spaceisavaluablecommodity,asthissentancedemonstrates.
Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below
Example 1
String Blam = one + two;
Blam += three + four;
Blam += five + six;
Example 2
String Blam = one + two + three + four + five + six;
Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:
1. The simplest way
You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and
In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).
Example with a non null object:
Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
Example with a null object:
Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is null!
Example with a primitive type:
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
2. The explicit way and potentially the most efficient one
You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.
Example:
int theNumber = 42;
StringBuilder buffer = new StringBuilder()
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)
Output:
Your number is 42!
Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.
Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.
So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:
Example optimized :
int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)
Output:
Your number is 42!
3. The most readable way
You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.
Example:
int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);
Output:
Your number is 42!
Your number is still 42 with printf!
The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.
The java 8 way:
StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);
StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);
You must be a PHP programmer.
Use a + sign.
System.out.println("Your number is " + theNumber + "!");
"+" instead of "."
Use + for string concatenation.
"Your number is " + theNumber + "!"
This should work
public class StackOverflowTest
{
public static void main(String args[])
{
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
}
}
For exact concatenation operation of two string please use:
file_names = file_names.concat(file_names1);
In your case use + instead of .
For better performance use str1.concat(str2) where str1 and str2 are string variables.
String.join( delimiter , stringA , stringB , … )
As of Java 8 and later, we can use String.join.
Caveat: You must pass all String or CharSequence objects. So your int variable 42 does not work directly. One alternative is using an object rather than primitive, and then calling toString.
Integer theNumber = 42;
String output =
String // `String` class in Java 8 and later gained the new `join` method.
.join( // Static method on the `String` class.
"" , // Delimiter.
"Your number is " , theNumber.toString() , "!" ) ; // A series of `String` or `CharSequence` objects that you want to join.
) // Returns a `String` object of all the objects joined together separated by the delimiter.
;
Dump to console.
System.out.println( output ) ;
See this code run live at IdeOne.com.
In java concatenate symbol is "+".
If you are trying to concatenate two or three strings while using jdbc then use this:
String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);
Here "" is used for space only.
In Java, the concatenation symbol is "+", not ".".
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
You can concatenate Strings using the + operator:
String a="hello ";
String b="world.";
System.out.println(a+b);
Output:
hello world.
That's it
So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.
Different ways by which Strings could be concatenated in Java
By using + operator (20 + "")
By using concat method in String class
Using StringBuffer
By using StringBuilder
Method 1:
This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.
String temp = "" + 200 + 'B';
//This is translated internally into,
new StringBuilder().append( "" ).append( 200 ).append('B').toString();
Method 2:
This is the inner concat method's implementation
public String concat(String str) {
int olen = str.length();
if (olen == 0) {
return this;
}
if (coder() == str.coder()) {
byte[] val = this.value;
byte[] oval = str.value;
int len = val.length + oval.length;
byte[] buf = Arrays.copyOf(val, len);
System.arraycopy(oval, 0, buf, val.length, oval.length);
return new String(buf, coder);
}
int len = length();
byte[] buf = StringUTF16.newBytesFor(len + olen);
getBytes(buf, 0, UTF16);
str.getBytes(buf, len, UTF16);
return new String(buf, UTF16);
}
This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.
Method 3:
This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = value.length >> coder;
int newCapacity = (oldCapacity << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
if (UNSAFE_BOUND - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > SAFE_BOUND)
? minCapacity : SAFE_BOUND;
}
Method 4
StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.
In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.
First method: You could use "+" sign for concatenating strings, but this always happens in print.
Another way: The String class includes a method for concatenating two strings: string1.concat(string2);
import com.google.common.base.Joiner;
String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));
This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.
you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).
here is an example to read and concatenate 2 string without using 3rd variable:
public class Demo {
public static void main(String args[]) throws Exception {
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
System.out.println("enter your first string");
String str1 = br.readLine();
System.out.println("enter your second string");
String str2 = br.readLine();
System.out.println("concatenated string is:" + str1 + str2);
}
}
There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);

Categories

Resources