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.
Related
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
In C++ I can do something like this...
String s = "abc";
char c = s[i]; // works fine...
But in Java, if I try doing the same, it throws an error. Why?.
In java, to achieve the above, I have to do :
s.toCharArray();
How is the implementation of Strings in C++ different from that in Java?
In java, to achieve the above, I have to do :
s.toCharArray();
Not really. You can use charAt instead:
char c = s.charAt(i);
Basically, C++ allows user-defined operators - Java doesn't. So the String class doesn't expose any sort of "indexing" operator; that only exists for arrays, and a String isn't an array. (It's usually implemented using an array, but that's a different matter.)
EDIT: As noted in comments, the + operator is special-cased for strings - right in the language specification. The same could have been done for [], but it isn't - and as it's not in the language specification, and Java doesn't support overloaded operators, it can't be performed in library code. (For example, you can't give custom behaviour to + for any other class.)
The difference is that C++ has operator overloading, and uses it to access the string contents.
They both store the string characters in such a way as you cannot change them.
The reason that it is possible to write
string s = "abc";
char c = s[i];
in C++ is that the string class has overloaded the indexing operator (say [] operator) which allows programmers to access characters of a string object the same way that they access an element of an array, despite the fact that a string object is not an array.
Java, on the other hand, does not allow operator overloading of any kind (the only exception is the + operator that is overloaded for strings) and hence, the indexing operator is not and can not be overloaded for String objects. In Java, to access a character of a string, you need to use accessor member methods, such as charAt. You can also invoke the toCharArray method of the String class, which returns to you an array of the characters of the string object and you can use the indexing operator with this returned value:
char c = s.toCharArray()[i];
See the method String#charAt
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
public char charAt(int index)
in c++ strings are already treated as array of characters,
but in java String is a built in class.
it is different from array of characters.
In C++, a string is typically just an array of (or a pointer to) chars, terminated with a NULL (\0) character. You can process a string by indexing also as you would process any array.
But in Java , a strings are not arrays. Java strings are objects of type java.lang.String so You cannot process them by indexing .
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.
Pretty simple question and my brain is frozen today so I can't think of an elegant solution where I know one exists.
I have a formula which is passed to me in the form "A+B"
I also have a mapping of the formula variables to their "readable names".
Finally, I have a formula parser which will calculate the value of the formula, but only if its passed with the readable names for the variables.
For example, as an input I get
String formula = "A+B"
String readableA = "foovar1"
String readableB = "foovar2"
and I want my output to be "foovar1+foovar2"
The problem with a simple find and replace is that it can be easily be broken because we have no guarantees on what the 'readable' names are. Lets say I take my example again with different parameters
String formula = "A+B"
String readableA = "foovarBad1"
String readableB = "foovarAngry2"
If I do a simple find and replace in a loop, I'll end up replacing the capital A's and B's in the readable names I have already replaced.
This looks like an approximate solution but I don't have brackets around my variables
How to replace a set of tokens in a Java String?
That link you provided is an excellent source since matching using patterns is the way to go. The basic idea here is first get the tokens using a matcher. After this you will have Operators and Operands
Then, do the replacement individually on each Operand.
Finally, put them back together using the Operators.
A somewhat tedious solution would be to scan for all occurences of A and B and note their indexes in the string, and then use StringBuilder.replace(int start, int end, String str) method. (in naive form this would not be very efficient though, approaching smth like square complexity, or more precisely "number of variables" * "number of possible replacements")
If you know all of your operators, you could do split on them (like on "+") and then replace individual "A" and "B" (you'd have to do trimming whitespace chars first of course) in an array or ArrayList.
A simple way to do it is
String foumula = "A+B".replaceAll("\\bA\\b", readableA)
.replaceAll("\\bB\\b", readableB);
Your approach does not work fine that way
Formulas (mathematic Expressions) should be parsed into an expression structure (eg. expression tree).
Such that you have later Operand Nodes and Operator nodes.
Later this expression will be evaluated traversing the tree and considering the mathematical priority rules.
I recommend reading more on Expression parsing.
Matching Only
If you don't have to evaluate the expression after doing the substitution, you might be able to use a regex. Something like (\b\p{Alpha}\p{Alnum}*\b)
or the java string "(\\b\\p{Alpha}\\p{Alnum}*\\b)"
Then use find() over and over to find all the variables and store their locations.
Finally, go through the locations and build up a new string from the old one with the variable bits replaced.
Not that It will not do much checking that the supplied expression is reasonable. For example, it wouldn't mind at all if you gave it )A 2 B( and would just replace the A and B (like )XXX 2 XXX(). I don't know if that matters.
This is similar to the link you supplied in your question except you need a different regular expression than they used. You can go to http://www.regexplanet.com/advanced/java/index.html to play with regular expressions and figure out one that will work. I used it with the one I suggested and it finds what it needs in A+B and A + (C* D ) just fine.
Parsing
You parse the expression using one of the available parser generators (Antlr or Sable or ...) or find an algebraic expression parser available as open source and use it. (You would have to search the web to find those, I haven't used one but suspect they exist.)
Then you use the parser to generate a parsed form of the expression, replace the variables and reconstitute the string form with the new variables.
This one might work better but the amount of effort depends on whether you can find existing code to use.
It also depends on whether you need to validate the expression is valid according to the normal rules. This method will not accept invalid expressions, most likely.
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.