How to print 2 int(s) but not add them? - java

I know this seems like a stupid question (so excuse me). Basically this is what I want to do:
int a = 5;
int b = 3;
System.out.print(a+b);
this will give me 8, but is there a way other than putting an empty string inbetween for it to print 5 and 3 (and not by converting the int to a string)?
Thank you so much.

The print method will simply convert its argument to a string and write out the result. Therefore, if you want to display the two numbers concatenated, you will need to do this yourself by converting them to a string (either explicitly, or using "" as you've already mentioned).
If you want to avoid building the string yourself, you'd probably need to use the printf() method:
System.out.printf("%d%d", a, b);

try
System.out.print(a+""+b)
or
System.out.print(a+" "+b)
if you want a space between them

Java will always execute an arithmetic operator. To avoid this behavior, you need to convert the numbers to string.
This should work for you:
System.out.println("" + a + b);
Because of the empty string at the beginning, Java is going to interpret + as a concatenation operator and joins the values of your variables with the empty string.

User explicit string conversion (not so elegant solution):
System.out.print(new Integer(a).toString()+b);
Use sequential calls to System.out.print (no new line will be added):
System.out.print(a);
System.out.print(b);
Use java.lang.StringBuilder:
import java.lang.StringBuilder;
...
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
System.out.print(sb.toString());

You need to convert the parameter inside the println method into a string
literal ,then java compiler would recognize it as a string and will not add
two integers.
System.out.println(a+""+b);
or use format method
System.out.format("%d%d",a,b);

Related

Why do println(measure + '"'); and println(measure + '\"'); add to measure, while using seperate statements prints correctly?

to test myself in Java, I wrote up a program where I needed to display the contents of double[] measurements, containing: {8.0, 7.7474, 7.4949, 7.7474, 8.0, 7.7474, 7.4949, 7.7474, 8.0}. A simple enhanced for loop and a println() seems to work fine, but
for(double measure: measurements)
{
System.out.println(measure + '"');
}
prints out 42, 41.7474, 41.4949, etc. Exactly 34 more than the value of measure. Changing the code to
for(double measure: measurements)
{
System.out.println(measure + '\"');
}
prints out 18,17.7474, 17.4949, etc. Exactly 10 more than the correct value. It only prints correctly when the println statement is split into two lines:
System.out.print(measure);
System.out.println("\"");
Why is it that the first two examples add to the value of measure? I'm fairly new to programming, but it seems to me that they would all have worked because Java uses both apostrophes and quotes to declare a string. Why does splitting it into two statements work correctly while connotating the two add to the value of measure? Thanks!
It's because you are printing the result of the expression measure + '"'. At the moment, you're performing an addition between a double and a char. If you instead use " instead of ' it will work.
Like this: System.out.println(measure + "\"");
Another option is to first convert measure to a string. That's rarely the best alternative, but the whole gist here is that you need to know the types of the operands and what the resulting type of the operation will be. Addition between a double and a char will result in a double. Addition between a double (or int or char among others) and a String will result in a String.
Apostrophes are used to declare char not String remember that. You can't have more than one char within single quotes.
Just do measure + "\""

When is the + operator faster than a StringBuilder? [duplicate]

This question already has answers here:
StringBuilder/StringBuffer vs. "+" Operator
(4 answers)
StringBuilder vs String concatenation in toString() in Java
(20 answers)
Closed 8 years ago.
In the past, I have been lead to believe that you should use StringBuilder and append(String) when building a string with variables, as opposed to string += split[i]. In what cases is this accurate? I ask because normally, if I was to write the following:
String[] split = args; // command line arguments or whatever
String myString = "";
for (int i = 0; i < split.length; i++) {
myString += split[i];
}
I am told by my IDE that it should be converted to use a StringBuilder instead. However, writing something like this:
StringBuilder build = new StringBuilder();
build.append("the ").append(build.toString()).append(" is bad").append(randomvar);
build.toString();
IntelliJ actually lists as a performance issue using a StringBuilder when I should be using a String. The fact that it's listed as a performance issue would indicate it could actually cause problems as opposed to just being a tiny bit slower.
I did notice that the first example is a loop and the second isn't - is a StringBuilder recommended for lots of concatenations but normal concatenation is better for non-looping situations (this also means in a loop the operator += would be used, whereas outside of a loop it could be "the " + build.toString() + " is bad" + randomVar - is += the problem as opposed to +?)
String concatenations are converted into calls to StringBuilder.append() behind the scenes.
String literal concatenations are (or at least can be) converted to individual String literals.
You're presumably using a String variable (not just two literals) inside the loop, so Java can't just replace that with a literal; it has to use a StringBuilder. That's why doing String concatenations in a loop should be done using a single StringBuilder, otherwise Java ends up creating another instance of StringBuilder every time the loop iterates.
On the other hand, something like this:
String animals = "cats " + "dogs " + "lizards ";
Will (or can be) replaced (by Java, not you) with a single String literal, so using a StringBuilder is actually counter-productive.
Beginning in java 1.5, the String + operator is translated into calls to StringBuilder.
In your example, the loop should be slower because the + operator creates a new StringBuilder instance each time through the loop.
The compiler will actually turn them both into the same form before compiling so neither will result in any performance difference. In this scenario you want to go with the shortest and most readable method available to you.
"An implementation may choose to perform conversion and concatenation
in one step to avoid creating and then discarding an intermediate
String object. To increase the performance of repeated string
concatenation, a Java compiler may use the StringBuffer class or a
similar technique to reduce the number of intermediate String objects
that are created by evaluation of an expression.
For primitive types, an implementation may also optimize away the
creation of a wrapper object by converting directly from a primitive
type to a string."
Source: http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.18.1.2
For little concats you can use the + operator with none issue. StringBuffer is indicated when we have large strings to be concatened, so with this class you can save memory and processor's time as well.
You can make a test trying to concat 1 million of words using + operator, and run the same teste using StringBuffer to see the different by yourself.

Convert code with pointers in C to Java code

I am having some difficulty in understanding how to write the below piece of code using String or char[] in Java.
void xyz(char *a, int startIndex, int endIndex)
{
int j;
for (j = startIndex; j <= endIndex; j++)
{
doThis((a+startIndex), (a+j));
xyz(a, startIndex+1, endIndex);
}
}
Here char *a points to the starting location of the char name[]
The above are just some random functions, but I just want the logic of how to use char* and character index char[] in Java
Based on the rephrased question from the comment thread:
You cannot change the characters of a Java String. If you need to modify a sequence of characters, use StringBuilder, which supports setCharAt(int, char), insert(int, char), and append(char). You can use new StringBuilder(myString) to convert a String to a StringBuilder, and stringBuilder.toString() to convert back.
This is perfectly legit Java code -- it's not code smelly, it's just the way you work with mutable character sequences.
A char* in C is, as you noted, pointing to the start of your character array (which is how C manages Strings).
In C the size of a char is one byte, and pointers always point to the start of a byte. Your C String is an array of characters, so adding 1 to a pointer moves the start of your string right by one character.
That means that the C code:
char *a;
// Set the String here
a = a + 1;
translates in Java to something like:
String a;
// Set the String here
a = a.substring(1);
or if you are using a char array:
char[] a;
// Set the array contents here
char[] copyTo = new char[a.length];
System.arraycopy(a, 1, copyTo, 0, a.length);
a = copyTo;
Java will be a bit more careful of protecting you that C will be though. For instance, if you have a zero length string, the C code has the potential to either segfault (crashing the application) or give you a gibberish string full of memory junk (then, eventually, crash the application), whereas the Java code will throw an exception (normally an IndexOutOfBoundsException) which you can, hopefully, handle cleanly.
Remember though, that String in Java are immutable. You cannot change them, you can only create new Strings. Fortunately, String has several built in functions which allow you to do a lot of the standard actions, like replace part of the String with another and return the result. A character array is mutable, and you can change the characters within them, but you will lose a lot of the nice benefits you get from using the proper String class.
Simple Answer:
You can't do exactly that. Java is pass by reference only. You don't have access to memory location information, so you can't do arithmetic with it.
Longer Answer:
It looks like you are passing in a string for manipulation. You have several options to simulate that.
You can convert the string to an array of characters and then pass in a char[]. If your manipulations are not any sort of standard string operation and completely custom this is probably what you need to do. Keep in mind that you can't change the size of the array passed in, nor can you have a point at a new array after the function completes. (again, only pass by value). Only the values of the existing elements of the array can be modified.
You can pass in the String and use the String methods, such as subString() (which your begin and end indexes seem to suggest, but this may not meet your needs. Note that strings are immutable however, and you can only get a result out via the return statement.
If you really need to modify the contents of the object passed in you can pass a StringBuilder, StringBuffer or CharBuffer object and modify away.
There's a hack that can also be used to circumvent pass by reference, but it's poor style except in special situations. Pass in an array of whatever you need to modify, so in this case an array of array of characters would allow you to set a new sub-array, and effectively acheive pass by reference, but try not to do this :)
If your method modifies the values you cant use String as that is immutable, you can use StringBuilder instead.
If your methods already rely on char arrays and you need the offsets you can use a CharBuffer to wrap an array. It does not support String operations but supports views for sub ranges, which seems to be what you use in the doThis() method.

I asked a question about arrays before, but this one won't compile

I asked about this array a little while ago, and I can't see what the problem is. Too tired. What have I done wrong? Basically, I am taking a string array and trying to check to see if it contains numbers or an x (ISBN number validation). I want to take the number from a given input (bookNum), check the input, and feed any valid input into a new array (book). At the line
'bookNum.charAt[j]==book[i]'
I get the 'not a statement error'. What gives?
String[] book = new String [ISBN_NUM];
bookNum.replaceAll("-","");
if (bookNum.length()!=ISBN_NUM)
throw new ISBNException ("ISBN "+ bookNum + " must be 10 characters");
for (int i=0;i<bookNum.length();i++)
{
if (Character.isDigit(bookNum.charAt(i)))
bookNum.CharAt[j]==book[i];
j++;
if (book[9].isNotDigit()||
book[9]!="x" ||
book[9]!="X")
throw new ISBNException ("ISBN " + bookNum + " must contain all digits" +
"or 'X' in the last position");
== is java is used for equivalence comparison. If you want to assign it, use a single =.
The first issue here is that charAt is a function, and thus needs parenthesis even though you are accessing with an index like an array.
The other issue is that the line is a boolean expression, which just by itself does not mean anything. A lot of people are suggestion that you mean to make an assignment to that character, but just changing to a single equals causes other problems. The left side of an equals sign needs to be a variable, and the result of a function is not a variable.
Strings are immutable, so you can not simply change one of the characters in the string. Earlier in your code, you have a call to replaceAll(), that returns a new string with the alterations. As written, this altered string is being lost.
There are few odd problems here. For starters, did you mean for book to be an array of Strings, as opposed to just one string? You're trying (assuming CharAt was written properly and the assignment was proper) to assign a character to a string.
Second, instead of copying character by character, why not check the whole string, and copy the whole thing at the end if it is a proper ISBN? Depending on what you do with Exceptions (if you continue regardless), you could add a boolean as a flag that gets set if there is an error. At the end, if there is no error, then make book = to booknumber.replace(etc...)
bookNum.CharAt[j]==book[i];
Should be
bookNum.CharAt[j]=book[i];
You are using an equality boolean operator, not an assignment one.
Looks like you're using .charAt(i) wrong! Assuming that "bookNum" is a String, you should use:
bookNum.charAt(i)==book[i];
Instead. Note that this is a boolean expression, and not "=".
The line bookNum.CharAt[j]==book[i]; isn't a statement. It's a comparison. Perhaps you want bookNum.CharAt[j]=book[i]; (single = instead of ==).
Edit: That's not going to fix things, though, since you can't assign to bookNum.CharAt[j].

append or + operator in StringBuffer?

In my project there are some code snippets which uses StringBuffer objects, and the small part of it is as follows
StringBuffer str = new StringBuffer();
str.append("new " + "String()");
so i was confused with the use of append method and the + operator.
ie the following code could be written as
str.append("new ").append("String()");
So are the two lines above same?(functionally yes but) Or is there any particular usage of them? ie performance or readability or ???
thanks.
In that case it's more efficient to use the first form - because the compiler will convert it to:
StringBuffer str = new StringBuffer();
str.append("new String()");
because it concatenates constants.
A few more general points though:
If either of those expressions wasn't a constant, you'd be better off (performance-wise) with the two calls to append, to avoid creating an intermediate string for no reason
If you're using a recent version of Java, StringBuilder is generally preferred
If you're immediately going to append a string (and you know what it is at construction time), you can pass it to the constructor
Actually the bytecode compiler will replace all string concatenation which involve non constants in a Java program with invocations of StringBuffer. That is
int userCount = 2;
System.out.println("You are the " + userCount + " user");
will be rewritten as
int userCount = 2;
System.out.println(new StringBuffer().append("You are the ").append(userCount).append(" user").toString());
That is at least what is observable when decompiling java class files compiled with JDK 5 or 6. See this post.
The second form is most efficient in terms of performance because there is only one string object that is created and is appended to the stringbuffer.
The first form creates three string objects 1) for "new" 2)for "new String" 3) for the concatenated result of 1) and 2). and this third string object is concatenated to the string buffer.
Unless you are working with concurrent systems, use StringBuilder instead of StringBuffer. Its faster but not thread-safe :)
It also shares the same API so its more or less a straight find/replace-

Categories