What kind of quote marks should I choose for a single character when I concatenate it with a string?
String s1="string";
Should I use
String s2=s1+'c';
Or
String s2=s1+"c";
?
You can use both! Give it a try!
"Why?" you ask. The magic here is the + operator.
When + is used with strings, it automatically turns the other operand into a string! That's why it can be used with 'c', a character literal. It can also be used with "c" because of course, "c" is a string literal.
Not only that, you can even add integers to a string:
String s2=s1+1;
U can use it in two diferent ways : String s2=s1+'c'; and
char x = 'c';
String s2 = s1 + x;
Both approaches are ok but if you are going into the details then perhaps
String s2=s1+'c';
will take a little less memory than the second way because char is just two bytes while String requires 8+ bytes. But I don't think that such nuances are important in most cases and also I'm not even sure that this difference will exist at all because JVM may optimize it
Java automatically does the conversion for you, so it doesn't really matter, but I'd personally just use a string (double quotes) just because I personally prefer to minimize the 'automatic stuff' that happens if I can prevent it.
Also, if you ever decide that 'c' should be 'csomething', then you'll have to change it into a boudle quote anyway.
But I suppose I'm just nitpicking...
Those are 2 different types of casting: implicit casting and explicit casting.
String s2=s1+'c';
This is a implicit casting, which means that the magic is done by the compiler (no overhead).
String s2=s1+"c";
This is a explicit casting, because "c" is converted to an object like:
Object o = "c";
String s2 = (String) o;
This means that the conversion must be checked for null-pointers, which will create an overhead.
Therefore, while both ways works, I prefer casting from character ('c') because that will create less overhead!
source: http://www.javaworld.com/article/2076555/build-ci-sdlc/java-performance-programming--part-2--the-cost-of-casting.html
Related
So this is for my Java 1 class. And I'm reading the chapter on Inheritance and Interfaces. This is section "Implementing Subclasses". And there is a piece of code with a feature I don't understand. Basically the part I'm reading is describing how to implement methods. Honestly I don't even know how to say this but can someone explain the point to the empty double quotes on the second line?
// Converts choices.size() to string
String choiceString = "" + choices.size();
setAnser (choiceString);
It's a trick to convert choices.size() (an int) to a String, using the String concatenation operator, +. To quote the spec on the String concatenation operator, +:
If only one operand expression is of type String, then string
conversion (§5.1.11) is performed on the other operand to produce a
string at run time.
So, in your example, this is a trick to force the integer returned by choices.size() to be converted to a string. Then an empty string is prepended, with the final result of a string.
Another, more readable way to do this would be String.valueOf(choices.size()).
I'm making a calculator, and some computations require 3 pieces of information (eg, 3*4), whereas other only require 2 (eg, 5!).
I have managed to split the input into 3 parts using the following code:
String[] parts = myInput.split(" ");
String num1 = parts[0];
String operation = parts[1];
String num2 = parts[2];
But this means that when I only type 2 things, it doesn't work.
How can I allow for either 3 or 2 things as an input?
You should not assume that the input will always in the 3 parameter form. Rather, take a generic input, parse on it based on use cases.
In your case, it boils down to two specific use cases AFTER you accept the input:
Operators that operate on single operand - unary operator
Operators that operate on double operand - binary operator
For each case, you can define a list of operators allowed. E.g. '!' will be in case 1 list, while '*' will be in case '2'
scan through the string, look for the operator position. [^0-9] (represents a pattern which other than numbers). Or simply you can do a trivial check for the operator (by creating your own custom method)
Once you have figured out this, validate your string (optional) - e.g. makes no sense to have two operands for a unary operator.
Having done this, it is fairly easy to parse now the required operands by splitting out the string based on the operator. Computation is fairly trivial then.
Hope this helps.
Without knowing more I can't help you find a better design to accommodate for the commonalities and variances. But to answer the stated questions....
You can use parts.length to know many variables you were given and use that to branch your code (i.e. if else statement).
Why is it that Java requires the char variable to enclose anything inside of it with single quotes rather than double? An example of this:
char s = 's'; //This will not break
vs:
char s = "s"; //This will break
I understand that double quotes are primarily for strings but is there a specific reason as to why chars were built to only use single quotes and to break when a double quote is entered?
I have tried to do some research but the only thing that was relevant was another SO Question, which refers to the difference between single and double quotes, not the reasoning behind the syntactical development of the char.
Because char and String are two different types, and how else is Java supposed to know whether you want a character or string of length 1?
For example, given the methods:
public void foo(String s) { }
public void foo(char c) { }
And the call
foo("a");
If characters could be made with double quotes, how would Java know which method to call?
This is a question written by a person used to the modern easy scripting languages whose goal is to make programming easy to learn and fast to type.
Java is a language for people who know what the CPU does underneath. In the world of low level languages (assembley, C, Java etc.) a character is an integer (UTF may require more than one int) whereas a string is an array of integers. By allowing a programmer to define the exact variable type, Java allows you to write more efficient code.
But it also allows you to write String s = "s"; if you don't care about efficiency.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am learning Java this year as part of the AP Computer Science curriculum, and while I was reading about "Char" and "String" I could not understand why one would bother to use "Char" and only be able to store one character rather than just use "String" and be able to store much more than that. In short what's the point of "char" if it can only store a single character?
People are mentioning memory concerns, which are valid, but I don't think that's a very important reason 99% of the time. An important reason is that the Java compiler will tell you if you make a mistake so you don't have to figure it out on your own.
For example, if you only want 1 character for a variable, you can use a char to store the value and now nobody can put anything else in there without it being an error. If you used a String instead, there could be two characters in the String even though you intended that to never be possible. In fact, there could be 0 characters in the String which would be just as bad. Also, all your code that uses the String will have to say "get the first character of the String" where it could simply say, "give me the character".
An analogy (which may not make sense to you yet, unfortunately) would be, "Why would I say a Person has a Name when I could say a Person has a List of Names?" The same reasons apply. If you only want a Person to have one Name, then giving him a list of Names adds a lot maintenance overhead.
You could consider this analogy:
You need one apple. Would you prefer to have one apple in your hand, or a big box that could contain more apples, but only needs to contain the one?
The char primitive datatype is easier to work with than the String class in situations where you only need one character. It's also a lot less overhead, because the String class has a lot of extra methods and information that it needs to store to be efficient at handling string with multiple characters. Using the String class when you only need one character is basically overkill. If you want to read from a variable of both types to get the character, this is the code that would do that:
// initialization of the variables
char character = 'a';
String string = "a";
// writing a method that returns the character
char getChar()
{
return character; // simple!
}
char getCharFromString()
{
return string.charAt(0); // complicated, could fail if there is no character
}
If this code looks complicated, you can ignore it. The conclusion is that using String when you only need one character is overcomplicating things.
Basically, the String class is used when you need more than one character. You could also just create an array of chars, but then you would not have the useful methods of the String class, such as the .equals() and .length() methods.
Strings are objects. Objects always go on the dynamic storage. Storing one-character string would require at least a dozen of bytes.
chars (not Chars) are primitives. They take fixed amount of space (2 bytes). In situations when you need to process a single character, creating one-character string is a waste of resources. Moreover, when you expect to see a single character, using strings would require validation that the data passed in has exactly one character. This would be unacceptable in situations when you must be extremely fast, such as character-based input and output.
To summarize, you need a char because of
Memory footprint - a char is smaller than a String of one character
Speed of processing - creating objects carries an overhead
Program's maintainability - Knowing the type makes it easier for you and for the readers of your code to know what kind of data is expected to be stored in a char variable.
char take up less memory for times when you really only need one character. There are also multiple other applications for using a single character.
char is a primitive datatype while string is an object which comes at greater overhead.
A string is also made up of char, so there's that too.
Because the char takes up less memory!
Also the char is stored in memory and NOT as a reference value so theoretically its faster to access the char (You'll understand that more later)
***Note: I once had this same thought when I first started programming about why use an int when you can use a long and not have to worry about large numbers. This tells me you're on your way to be a great programmer! :)
char is a primitive type while String is a true Object. In some cases where performance is a concern it's conceivable that you would only want to use primitives.
Another case in which you would want to use char is when you're writing Java 1.0 and you're tasked with creating the String class!
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
Everything in java can be reduced to primitive types. You can write any program with primitive types. So you need some kind of minimalist way of storing text. A char is also really just a byte, that is interpreted as a character.
Also if you want to loop though all characters in a string you would do:
char[] chArr = str.toCharArray();
for(int i = 0 ; i < chArr.length ; i++)
{
//do something with chArr[i];
}
This would be much more awkward trying to substring out an exact character from the String.
Lot of answers here already. While the memory concerns are valid, you have to realize there are times when you want to directly manipulate characters. The word ladder game
where you try to turn one word into another by changing one character at a time is an example I had to do in a programming class. Having a char type lets you manipulate a singe character at a time. It also lets you assign an int to a char that maps to your local character set.
You can do thing like char c = 97; and that will print out as a. You can do things like increment a character from 97 to 122 to print out all lowercase characters. Sometimes this actually is useful.
Suppose we have the following method (it is in c code):
const char *bitap_search(const char *text, const char *pattern)
My question is how can I compare text and pattern if they are char? This method is like a substring problem but I am confused a bit can I write in term of char such code?
if (text[i]==pattern[i])?
look i am interesting at this algorithm in java
http://en.wikipedia.org/wiki/Bitap_algorithm
how implement this in java?
R = malloc((k+1) * sizeof *R);
and please help me to translate this code in java
so we have two string text?
like "i like computer it is very important"
and patter string " computer it is very"?
can anybody explain me what we have instead of char?
I'm not sure what exactly you are asking, but if you mean to find pattern in text, then strstr(text, pattern). Or if you mean to just compare text and pattern, then strcmp(text, pattern) (note that it returns 0 when text and pattern are equal).
Edit based on discussion in comments: If you mean to ask how to implement the indexing of individual characters in Java, then substitute (in Java) text.charAt(i) for the C text[i]. In C the chars in strings can be indexed directly like an array, in Java one needs to call the correct method in String.
Edit 2: The C code const char * can be replaced in Java with String.
In C malloc is used to allocate memory; in this case it allocates room in the array R for m+1 elements. So, the BIT *R can be removed and R = malloc((m+1) * sizeof *R); replaced with boolean[] R = new boolean[m + 1];. When assigning values into the array R substitute true for 1 and false for 0.
I think you are confused about the difference between char and char *. In C there is no built-in string type. Strings are represented as null-terminated character arrays, meaning that the last character of the string must be \0 So char is a single character, while char * is a pointer to an array of characters, i. e. a string. And that means that it is perfectly fine to say if (text[i] == pattern[i]).
You might try these:
Google-diff-match-patch says that it
has a
java implementation of Bitap.
Also, it appears that crosswire
has an implementation.
Finally, there
seems to be a package called String
Search, whose title is
High-performance pattern matching
algorithms in Java.
You probably need strcmp() or strpos().
You should use strncmp(). The syntax is something like:
int strncmp( const char *str1, const char *str2, size_t count );
It is the best and more secure way of comparing strings, but of course you will need to know their length, or at least the minimum length between them.