How can I concatanate a string from an int and a char? - java

For example I want to concatanate char a ='A' and int b = 5 into string = "A5".
String string = a + b; doesn't work.

You may want to use StringBuilder, where you can append any type of primitives :
char a ='A';
int b = 5;
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
String result = sb.toString();

The easiest way for me is to precede the String with an empty String.
String str = "" + 'a' + 10;
The conversion goes from left to right so you start out with a String.
If you do it this way,
String str = 'a' + 10 + "";
you will get a String value of "107" since the numeric addition is done before the conversion to a String.

One way to convert most primitive values to String is to utilize the overloaded method in the String class valueOf():
public static void main(String[] args)
{
char a = 'A';
int b = 5;
String str = String.valueOf(a) + b; //Can do either of these two lines, will work the same
String str2 = a + String.valueOf(b);
System.out.println(str);
System.out.println(str2);
}
You only need to convert one of the values into String, because appending them afterward will automatically convert the other into a String.
This method will work on both char, and int in this scenario, but will also work on long, double, float and boolean as well. This is identical to calling Integer.toString(int i) or Character.toString(i) etc... but it is convenient to be able to use the same overloaded method for each case instead of requiring to call methods from different classes.

To all the answers already given I provide one that explain why "it doesn´t work" as you expect. A string is nothing but an immutable collection of char. A char itself is nothing but a (signed) integer and thus can implicitely converted to such. Thus when you write char+ int an integer-operation occurs, in your case A + 5 which results in 70, because ASCII-code for A is 65.
Last but not least String s = 70 surely does not compile, because a number can´t be converted to a string.
So you have to tell the compiler that you do not want an integer-operation, but a string-concatenation, which is by turning one of the operands into a string already:
String s = 'A'.toString() + 5
or
String s = 'A' + 5.toString()

Related

How can a string accept an integer?

Can a variable String accept integer value as well. Or can we concat integer with a string ?
Example:
public class TestString1 {
public static void main(String[] args) {
String str = "420";
str += 42;
System.out.print(str);
}
}
I was expecting compilation error over here because String was getting concatenated with an integer.
JLS documentation on String concatination operator(+)-
15.18.1 String Concatenation Operator +
If only one operand expression is of type String, then string
conversion is performed on the other operand to produce a string at
run time. The result is a reference to a String object (newly created,
unless the expression is a compile-time constant expression
(§15.28))that is the concatenation of the two operand strings. The
characters of the left-hand operand precede the characters of the
right-hand operand in the newly created string. If an operand of type
String is null, then the string "null" is used instead of that operand
That is why String + int does not produce any error. And it prints 42042
None of the other answers have explained what's actually being executed here.
Your code will be converted to something like:
String str = "420";
// str += 42;
StringBuilder sb = new StringBuilder(str);
sb.append(42); // which internally does something similar to String.valueOf()
str = sb.toString();
System.out.print(str);
Anything that is given in double quotes is String and + is for concatenating string with an any value(int value).
So the integer value will be appended to the string.
Here
String str = "420";
str += 42; // 42 will be appended to 420 and result will be 42042
Adding an int to a String appends the int to the string, thus converting the int into a string.
x=20 y=10
I am showing the Order of precedence below from Higher to Low:
B - Bracket
O - Power
DM - Division and Multiplication
AS - Addition and Substraction
This works from Left to Right if the Operators are of Same precedence
Now
System.out.println("printing: " + x + y);
"printing: " : Is a String"
"+" : Is the only overloaded operator in Java which will concatenate Number to String. As we have 2 "+" operator here, and x+y falls after the "printing:" + as already taken place, Its considering x and y as Strings too.
So the output is 2010.
System.out.println("printing: " + x * y);
Here the
"*": Has higher precedence than +
So its x*y first then printing: +
So the output is 200
Do it like this if you want 200 as output in first case:
System.out.println("printing: "+ (x+y));
The Order of precedence of Bracket is higher to Addition.

Converting strings to integers and adding them in Java

I have 4 strings:
str1 = 10110011;(length of all string is:32)
str2 = 00110000;
str3 = 01011000;
str4 = 11110000;
In my project I have to add these string and the result should be:
result[1] = str1[1]+str2[1]+str3[1]+str4[1];
result should be obtained as addition of integer numbers.
For the example above, result = 22341011
I know integer to string conversion in Java is very easy but I found string to integer conversion a little harder.
To parse Integers -2^31 < n < 2^31-1 use:
Integer value = Integer.valueOf("10110011");
For numbers that are larger, use the BigInteger class:
BigInteger value1 = new BigInteger("101100111011001110110011101100111011001110110011");
BigInteger value2 = // etc
BigInteger result = value1.add(value2).add(value3); //etc.
The simplest way to do this is with Integer.parseInt(str1). Returns an int containing the value represented by the string.
valueOf() returns an Integer object, rather than an int primitive.
Because your numbers are so big they will not fit in an int. Use the BigInteger class.
I am not known about your project and what actually your problem is. But I came to guess from your partial information that, you have multiple set of strings in bit representation as you explained.
str1 = "1000110.....11";
str1 = "1110110.....01"; etc
adding those decimal values,gives an ambiguous result as an integer can be the sum of multiple integer values. Just see an example below where there are total 5 possibilities[with positive decimal values] to yield 6.
1+5 = 6;
2+4 = 6;
3+3 = 6;
4+2 = 6;
5+1 = 6;
If you proceed in that way you just do an error,nothing else in your case.
One better solution can be,
compute the decimal values of individual strings. Instead of adding(+) them, just concat(join) them to form a single string.
I am suggesting this approach because, This gives always a unique value and later you may need to know individual strings decimal values.
String strVal1 = String.format(computeDecimal(str1));
String strVal2 = String.format(computeDecimal(str2));
String strVal3 = String.format(computeDecimal(str3));
.
.
.
String strValn = String.format(computeDecimal(strn));
String myVal = String.concate(strVal1,strVal1,strVal1,....strValn);
Now you can treat your string as your wish.
//This will give you a non conflicting result.
Better to implement above approach than BigIntegers.
Hope this helps you greatly.

Split a string all alpha and all numeric

I have a List and I would like to split the first two characters (alpha characters) into a different string and then all the numbers that follow (they vary in length).
How could I do that?
String wholeString == "AB4578";
String alpha; // this has to be AB
String num; // this has to be 4578
Thank you very much in advance!
Tested and works:
String wholeString = "AB4578";
String alpha = null;
String num = null;
for (int i = 0; i < wholeString.length(); i++) {
if (wholeString.charAt(i) < 65) {
alpha = wholeString.substring(0, i);
num = wholeString.substring(i);
break;
}
}
With this approach both the A-z part and the 0-9 part can vary in size, it might not be very effective though considering it's calling charAt(...) for every char in the String.
Hope this helps.
String wholeString = "AB4578";
String alpha = wholeString.substring(0,2);
String num = wholeString.substring(2);
Must See
String.substring(int, int)
If the format is the same, then the answer is already provided. But if the format is not same than you can convert the string into char array and check each character against the ASCII values to check if it is an alphabet or a number.
char[] ch=wholestring.toCharArray();
Now you can apply a for loop for checking each character individually.
for(int l=0; l<ch.length;l++)
{
//code to check the characters
}
And you can separate both types in different strings using StringBuilder or forming two char arrays and then converting them to strings using
String.valueOf(chArray);
ASCII values - http://www.asciitable.com/
Try using the substring method for Strings.
Example:
String alpha = wholeString.substring(0,2);
String num = wholeString.substring(2);
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring%28int%29
If the format is always the same you can just do this:
String wholeString = "AB4578";
String alpha = wholeString.substring(0, 2);
String num = wholeString.substring(2);
Recommend String API. You would need to use substring operations.

have a char reference an object in an array

Is it possible to have a char point to an object in an array? im trying to have the characters : +,-,*,/ point to an index in my array.
I AM WELL AWARE MY SECTION BELOW IS NOT CORRECT SYNTAX. its just my way of describing what i wish to accomplish.
public static void main(String[] args) {
Operations plus;
Operations minus;
Operations multiply;
Operations divide;
/**********Create jumpTable*******************/
Operations[] jumpTable = new Operations[255];
/**********Add Object to jumpTable************/
jumpTable[0] = new Addition();
jumpTable[1] = new Subtraction();
jumpTable[2] = new Multiplication();
jumpTable[3] = new Division();
/**********Point to index in table************/
plus = jumpTable[0];
minus = jumpTable[1];
multiply = jumpTable[2];
divide = jumpTable[3];
//this is what im trying to do:
//***************************************
char +;
char -;
'+' = plus
'-' = minus and etc...
//****************************************
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
System.out.printf("%f %s %f = %f%n", x, op, y, op.Compute(x, y));
}
}
Is it possible to have a char point to an object in an array?
Assuming that you are asking: "is it possible to use a char as an index for an array", then the answer is "Yes it is possible".
An index expression for an array can have any type that can be promoted to int; see JLS 15.13. And the char type can be promoted to int. (You don't even need to include a typecast to make it happen. It just works.)
Could you use a Map<String, Operations> instead of the Operations[]?
Also Operations should probably be called Operation.
you can cast the char to a int or byte
char addition = '+';
operators[(byte)addition] = ...
You can use a value of type char every where a value of type int is allowed, and (apart from String concatenation and where there are two methods of both types) it works the same as the int obtained by casting.
So, operators['+'] is identical to operators[43], and similar.
If you only need *, +, -, /, you could use an array of length 6, and index into it by taking the difference to * (which is the first of them):
Operations[] jumptable = {
new Multiplication(), // * = 42 = '*' + 0
new Addition(), // + = 43 = '*' + 1
null, // , = 44
new Subtraction(), // - = 45 = '*' + 3
null, // . = 46
new Division() // / = 47 = '*' + 5
};
char operator = ...;
Operation op = jumptable[operator - '*'];
Of course you could always make the table as big as necessary and directly index.
No.
A char is a Java primitive type representing a single 16-bit unicode character.
See here:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Integer to String conversion methods

What are the alternative methods for converting and integer to a string?
Integer.toString(your_int_value);
or
your_int_value+"";
and, of course, Java Docs should be best friend in this case.
String one = Integer.toString(1);
String myString = Integer.toString(myInt);
Here are all the different versions:
a) Convert an Integer to a String
Integer one = Integer.valueOf(1);
String oneAsString = one.toString();
b) Convert an int to a String
int one = 1;
String oneAsString = String.valueOf(one);
c) Convert a String to an Integer
String oneAsString = "1";
Integer one = Integer.valueOf(oneAsString);
d) Convert a String to an int
String oneAsString = "1";
int one = Integer.parseInt(oneAsString);
There is also a page in the Sun Java tutorial called Converting between Numbers and Strings.
String.valueOf(anyInt);
There is Integer.toString() or you can use string concatenation where 1st operand is string (even empty): String snr = "" + nr;. This can be useful if you want to add more items to String variable.
You can use String.valueOf(thenumber) for conversion. But if you plan to add another word converting is not nessesary. You can have something like this:
String string = "Number: " + 1
This will make the string equal Number: 1.

Categories