Unclosed Character Literal error - java

Got the error "Unclosed Character Literal" , using BlueJ, when writing:
class abc
{
public static void main(String args[])
{
String y;
y = 'hello';
System.out.println(y);
}
}
But I can't figure out what is wrong.
Any idea?
Thanks.

In Java, single quotes can only take one character, with escape if necessary. You need to use full quotation marks as follows for strings:
y = "hello";
You also used
System.out.println(g);
which I assume should be
System.out.println(y);
Note: When making char values (you'll likely use them later) you need single quotes. For example:
char foo='m';

Java uses double quotes for "String" and single quotes for 'C'haracters.

I'd like to give a small addition to the existing answers.
You get the same "Unclosed Character Literal error", if you give value to a char with incorrect unicode form.
Like when you write:
char HI = '\3072';
You have to use the correct form which is:
char HI = '\u3072';

'' encloses single char, while "" encloses a String.
Change
y = 'hello';
-->
y = "hello";

String y = "hello";
would work (note the double quotes).
char y = 'h';
this will work for chars (note the single quotes)
but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.

There are 8 primitive datatypes in Java.
char is one of them. When compiler sees a char datatype is defined. It allocates 1 Bytes of memory from JVM heap and expects a value after = symbol with two conditions.
value enclosed inside ' (single quotes).
value to be single character long. It can be either a single character or valid code corresponding single character, which you can't type using English Keyboard.
In the same way, a datatype of String type should be enclosed with "(double quotes) and can have any length characters sequence.
In the given example you have mixed concepts of both char and String datatype. the compiler clearly saying:
Unclosed Character Literal
Means, you started with ' single quote, so compiler just expects a single character after opening ' and then a closing '. Hence, the character literal is considered unclosed and you see the error.
So, either you use char data type and ' single quotes to enclose single character.
Or use String datatype and " double quotes to enclose any length of character sequence.
So, correct way is:
String y = "hello";
System.out.println(y);

Use double quotes symbol as I mention below
Your y data type is String, and it should double quotes symbol
class abc
{
public static void main(String args[])
{
String y;
y = "hello";
System.out.println(y);
}
}

Character only takes one value dude! like:
char y = 'h';
and maybe you typed like char y = 'hello'; or smthg. good luck. for the question asked above the answer is pretty simple u have to use DOUBLE QUOTES to give a string value. easy enough;)

Related

Is there any method like char At in Dart?

String name = "Jack";
char letter = name.charAt(0);
System.out.println(letter);
You know this is a java method charAt that it gives you a character of a String just by telling the index of the String. I'm asking for a method like this in Dart, does Dart have a method like that?
You can use String.operator[].
String name = "Jack";
String letter = name[0];
print(letter);
Note that this operates on UTF-16 code units, not on Unicode code points nor on grapheme clusters. Also note that Dart does not have a char type, so you'll end up with another String.
If you need to operate on arbitrary Unicode strings, then you should use package:characters and do:
String name = "Jack";
Characters letter = name.characters.characterAt(0);
print(letter);
Dart has two operations that match the Java behavior, because Java prints integers of the type char specially.
Dart has String.codeUnitAt, which does the same as Java's charAt: Returns an integer representing the UTF-16 code unit at that position in the string.
If you print that in Dart, or add it to a StringBuffer, it's just an integer, so print("Jack".codeUnitAt(0)) prints 74.
The other operations is String.operator[], which returns a single-code-unit String. So print("Jack"[0]) prints J.
Both should be used very judiciously, since many Unicode characters are not just a single code unit. You can use String.runes to get code points or String.characters from package characters to get grapheme clusters (which is usually what you should be using, unless you happen to know text is ASCII only.)
You can use
String.substring(int startIndex, [ int endIndex ])
Example --
void main(){
String s = "hello";
print(s.substring(1, 2));
}
Output
e
Note that , endIndex is one greater than startIndex, and the char which is returned is present at startIndex.

Question about java String "hello" and 'hello'

Why this is invalid in java?
List<String> items=new ArrayList<String>();
items.add("hello"); // valid
items.add('hello'); // invalid (error: invalid character constants)
Because '' single quotes are used for char variables.
Meaning 'a', 'b', and so on. So only one character per variable.
The double quotes on the other side "" are used to initialize String variables, which are several characters gathered together into one variable e.g "i am a string"
char c = 'c' // I use single quotes because I am single :)
String str = "This is a string" // I use double quotes because I got a lot in me

Explain why the Wrong Output Happened?

public class ArrayIntro
{
public static void main(String[] args)
{
int[] a;
a=new int[10];
Scanner sc =new Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
for(int e:a)
{
System.out.print(e+' ');
}
}
}
Input:1 2 3 4 5 6 7 8 9 10
Output:33343536373839404142
Its mean it added 32 to each number
Just try with below code.
As you are printing sout inside for loop, it's printing sum of number and Space( ' '). And space have ASCII value of 32, so you are able to see every element with added value of 32.
For ASCII Or Unicode you can refer this link, it will help you.
Simply you put something like this System.out.print(new Integer(' '));, it will print 32.
If you want to add space only then go with double quote.
System.out.print(e+" ");.
Single quote consider as character and charater added with Integer will summing up with their ASCII code.
public static void main(String[] args)
{
int[] a;
a=new int[10];
Scanner sc =new Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
for(int e:a)
{
System.out.print(e+" ");
}
}
To put it simply, ' ' is a character in ASCII and the value of it is 32. So, as far as I know, you might want it the just print directly so you can just replace ' ' with " ". Always remember that single quotes are for characters and double quotes are for strings.
For your answer you can just do this:System.out.print(e+" ");
Instead of this: System.out.print(e+' ');
In short, to fix your program, you need to use " " (with double quotes) instead of ' '.
The issue is that the + operator has two different meanings in Java.
If either of the operands is a String, then + means "concatenate these two operands together". If the other operand is not a String, then it will have to be converted somehow, and there are some rules around how to do this.
If neither operand is a String, then + means "add these two operands together" - that is, they are treated as numbers. They can be added as double values, float values, long values or int values, depending on the data types. But if they are short, byte or char, they will be treated as int. This is called binary numeric promotion, and is explained in detail in the Java Language Specification.
Now in Java, single quotes are used to delimit a char literal. So when you write e + ' ', you're adding an int to a char. This is addition - the char is treated as an int, and the operands are added as numbers. The number corresponding to is 32, since that's the numeric value in the character encoding that Java uses, which is something like UTF-16. Contrary to some other answers on this page, it's not ASCII.
Double quotes are used to delimit a String literal. So if you write e + " ", the operands are an int and a String. That means you're not adding any more, but concatenating. The int is converted to a String first, then concatenated to " ", which will give you the result you're expecting.

Java Regex X{n,m} X, at least n but not more than m times

I am trying to understand how to match an email address to the following pattern:
myEmail#something.any
The any should be between 2,4 characters.
Please find Java code below. I cannot understand why it returns true. Thanks!
public static void main(String[] args){
String a = "daniel#gmail.com";
String b = "[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.+-]+.[a-zA-Z]{2,4}";
String c = "MyNameis1#abcx.comfff";
Boolean b1 = c.matches(b);
System.out.println(b1);
}
OUTPUT: true
In regex, . matches any character (except newline). If you want to match . literally, you need to escape it:
[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.+-]+\\.[a-zA-Z]{2,4}
This is better, but it still matches the MyNameis1#abcx.comf portion. We can add an end of string anchor ($) to ensure there are no trailing unmatched characters:
[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.+-]+\\.[a-zA-Z]{2,4}$
Escape the . in String b = "[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.+-]+.[a-zA-Z]{2,4}";. It is a special character in regex.
Use : String b = "[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.+-]+\\.[a-zA-Z]{2,4}";
In your expression dot meant any character. escape that and make sure no character follows post your min/max char checks like below:
[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.+-]+\\.[a-zA-Z]{2,4}$

how to check if a string contain any of operator in java

i wanted to check if string contains operand
char m='\0';
char match[]={'(',')','=',';','{','}','[',']','+','-
','*','/','&','!','%','^','|','<','>'};
for(int i =0; i<code.length(); i++)
{
m=code.charAt(i);
for(int j=0;j<match.length;j++){
if(m==match[j]){
o++;
}
}
}
The above code can get the total no of operand use in string, but is there some easy way.
You can use regular expression to do the same thing with one line of code.
if(code.matches("[,/!%<>]")) sysout("There is Operator");
Place all the operators you need in between brackets.
I couldn't test above code now, but you may have to escape some operators using a back slash.
You can use a regular expression character class to find any of a list of characters, e.g.:
// (See note below about these -++--++
// || ||
// vv vv
if (stringToTest.match("[()=;{}[\\]+\\-*/&!%^|<>']")) {
// It has at least one of them
}
The [ and ] indicate a character class. Within that, you have to escape ] (because otherwise it looks like the end of the character class) with a backslash, and since backslashes are special in string literals, you need two. Similarly, you have to escape - within a character class as well (unless it's the first char, but it's easier just to remember to do it). I've highlighted those with tickmarks above.
Docs:
String#match
Pattern
java.util.regex
Try to use these functions
String.contains() - which checks if the string contains a specified sequence of char values
String.indexOf() - which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)
instead of checking each char in array.
If you store "match" as a hash table, your lookups will be more efficient:
HashSet<Character> match = new HashSet<Character>(Arrays.asList('(',')','=',';','{','}','[',']','+','-','*','/','&','!','%','^','|','<','>');
for(int i =0; i < code.length(); i++) {
if (match.contains(code.charAt(i)) {
o++;
}
}

Categories

Resources