how to use specials characters in the variables declaration in java? - java

Is it possible to declare java attribute name using specials characters, exemple:
private String var/name;
private int one+one;
I ask this question because I need to retrieve data from DB, whose the name of one colomn is annoces/status, And I need to use sql query (not hql or criteria)

It's not possible to do that:
Variable names are case-sensitive. A variable's name can be any legal
identifier — an unlimited-length sequence of Unicode letters and
digits, beginning with a letter, the dollar sign "$", or the
underscore character "_". The convention, however, is to always begin
your variable names with a letter, not "$" or "_". Additionally, the
dollar sign character, by convention, is never used at all. You may
find some situations where auto-generated names will contain the
dollar sign, but your variable names should always avoid using it. A
similar convention exists for the underscore character; while it's
technically legal to begin your variable's name with "_", this
practice is discouraged. White space is not permitted.
I don't understand why you need that though.
Edit
You can use something like bbr.sendQuery("Select Status, Name, Annonces/Sta AS annoncesSta, From table ",MyObject.class); with AS you can change the name of the column that you receive in the result. So your attribute in the java class can be "annoncesSta".
Anyway is wired to have column names with "/", best practices for names are:
AnnoncesSta
announces_sta
And most mappers handle those names automatically.

There is absolutely no need to name the Java variables same as the column names in some table in some database.
If you are trying to store column values in some Map then map keys can have any special character you want.

You can't do what you are asking - as detailed by others. My suggested solution is to sort out the column names in your database so that they follow normal standards and then you can use the same names in java.
By normal standards I mean:
alphanumeric characters or the following special characters: $ _ #

Related

Can I text wrap a Java method name on multiple lines?

I know your first reaction will be "why on earth would you do this, your method names are clearly ridiculous" but it's because I'm using Spring Boot JPA where you can use the method name to construct the query for you by reflection (it's amazing). But when querying based on a few different columns and the entity variables have longish names the method name ends up being quite long and hard to read, so I was wondering if there is a way of splitting it across multiple lines?
At the moment I have something like (simplified for this question):
public List<Employee> findByFirstNameAndLastNameAndAgeBetweenAndBirthdayBefore(String firstName, String lastName, Integer minAge, Integer maxAge, Date maxBirthday);
And I would like it in my code to be more like:
public List<Employee> findBy
FirstName
AndLastName
AndAgeBetween
AndBirthdayBefore
(String firstName, String lastName, Integer minAge, Integer maxAge, Date maxBirthday);
Is this at all possible?
A method name is an identifier, which is made up of IdentifierChars.
IdentifierChars are defined as starting with a Java Letter, and thereafter may be a Java Letter or Digit. Those are described in the Javadoc of Character.isJavaIdentifierPart (and isJavaIdentifierStart):
A character may be part of a Java identifier if any of the following
are true:
it is a letter it is a currency symbol (such as '$') it is a
connecting punctuation character (such as '_')
it is a digit
it is a
numeric letter (such as a Roman numeral character)
it is a combining
mark
it is a non-spacing mark
isIdentifierIgnorable(codePoint) returns
true
And isIdentifierIgnorable(int) says (emphasis mine):
The following Unicode characters are ignorable in a Java identifier or a Unicode identifier:
ISO control characters that are not whitespace
'\u0000' through '\u0008'
'\u000E' through '\u001B'
'\u007F' through '\u009F'
all characters that have the FORMAT general category value
So no, you can't have newlines in a method name.
Well, that is an invalid method declaration, Java doesn't allow you to extend method name to next line but even if it does it is still not a good practice.
I guess you trying to do this because of long method names, and even Spring Data JPA documentation suggests that if your method names are growing large you consider writing the query by using #Query annotation or use Query DSL.
No you can't include line breaks into you method name.
Because a method name should be a valid "Java Identifier" (see "Method Declarations" from Java Language Specification) and a "Java Identifier" is made of Java letters or digits but no line breaks (see "Identifiers" from Java Language Specification)
The "Java letters" include uppercase and lowercase ASCII Latin letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.
The "Java digits" include the ASCII digits 0-9 (\u0030-\u0039).

Why can't Java variable names start with a number?

In Java, variable names start with a letter, currency character ($) etc. but not with number, :, or .
Simple question: why is that?
Why doesn't the compiler allow to have variable declarations such as
int 7dfs;
Simply put, it would break facets of the language grammar.
For example, would 7f be a variable name, or a floating point literal with a value of 7?
You can conjure others too: if . was allowed then that would clash with the member selection operator: would foo.bar be an identifier in its own right, or would it be the bar field of an object instance foo?
Because the Java Language specification says so:
IdentifierChars:
JavaLetter {JavaLetterOrDigit}
So - yes, an identifier must start with a letter; it can't start with a digit.
The main reasons behind that:
it is simply what most people expect
it makes parsing source code (much) easier when you restrict the "layout" of identifiers; for example it reduces the possible ambiguities between literals and variable names.

Java pound (#) character syntax [duplicate]

What characters are valid in a Java class name? What other rules govern Java class names (for instance, Java class names cannot begin with a number)?
You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...
Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.
An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.
However, see this question for whether or not you should do that.
Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:
Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.
Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.
If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.
From the official Java Tutorial.
Further to previous answers its worth noting that:
Java allows any Unicode currency symbol in symbol names, so the following will all work:
$var1
£var2
€var3
I believe the usage of currency symbols originates in C/C++, where variables added to your code by the compiler conventionally started with '$'. An obvious example in Java is the names of '.class' files for inner classes, which by convention have the format 'Outer$Inner.class'
Many C# and C++ programmers adopt the convention of placing 'I' in front of interfaces (aka pure virtual classes in C++). This is not required, and hence not done, in Java because the implements keyword makes it very clear when something is an interface.
Compare:
class Employee : public IPayable //C++
with
class Employee : IPayable //C#
and
class Employee implements Payable //Java
Many projects use the convention of placing an underscore in front of field names, so that they can readily be distinguished from local variables and parameters e.g.
private double _salary;
A tiny minority place the underscore after the field name e.g.
private double salary_;
As already stated by Jason Cohen, the Java Language Specification defines what a legal identifier is in section 3.8:
"An identifier is an unlimited-length sequence of Java letters and Java digits, the
first of which must be a Java letter. [...] A 'Java letter' is a character for which the method Character.isJavaIdentifierStart(int) returns true. A 'Java letter-or-digit' is a character for which the method Character.isJavaIdentifierPart(int) returns true."
This hopefully answers your second question. Regarding your first question; I've been taught both by teachers and (as far as I can remember) Java compilers that a Java class name should be an identifier that begins with a capital letter A-Z, but I can't find any reliable source on this. When trying it out with OpenJDK there are no warnings when beginning class names with lower-case letters or even a $-sign. When using a $-sign, you do have to escape it if you compile from a bash shell, however.
I'd like to add to bosnic's answer that any valid currency character is legal for an identifier in Java. th€is is a legal identifier, as is €this, and € as well. However, I can't figure out how to edit his or her answer, so I am forced to post this trivial addition.
What other rules govern Java class names (for instance, Java class names cannot begin with a number)?
Java class names usually begin with a capital letter.
Java class names cannot begin with a number.
if there are multiple words in the class name like "MyClassName" each word should begin with a capital letter. eg- "MyClassName".This naming convention is based on CamelCase Type.
Class names should be nouns in UpperCamelCase, with the first letter of every word capitalised. Use whole words — avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
The naming conventions can be read over here:
http://www.oracle.com/technetwork/java/codeconventions-135099.html
Identifiers are used for class names, method names, and variable names. An identifiermay be any descriptive sequence of uppercase and lowercase letters, numbers, or theunderscore and dollar-sign characters. They must not begin with a number, lest they beconfused with a numeric literal. Again, Java is case-sensitive, so VALUE is a differentidentifier than Value.
Some examples of valid identifiers are:
AvgTemp ,count a4 ,$test ,this_is_ok
Invalid variable names include:
2count, high-temp, Not/ok

Which of these are valid variable names?

This is a question from a Java test I took at University
I. publicProtected
II. $_
III. _identi#ficador
I've. Protected
I'd say I, II, and I've are correct. What is the correct answer for this?
Source of the question in spanish: Teniendo la siguiente lista de identificadores de variables, ¿Cuál (es) es (son) válido (s)?
From the java documentation:
Variable names are case-sensitive. A variable's name can be any legal
identifier — an unlimited-length sequence of Unicode letters and
digits, beginning with a letter, the dollar sign "$", or the
underscore character "". The convention, however, is to always begin
your variable names with a letter, not "$" or "". Additionally, the
dollar sign character, by convention, is never used at all. You may
find some situations where auto-generated names will contain the
dollar sign, but your variable names should always avoid using it. A
similar convention exists for the underscore character; while it's
technically legal to begin your variable's name with "_", this
practice is discouraged. White space is not permitted. Subsequent
characters may be letters, digits, dollar signs, or underscore
characters. Conventions (and common sense) apply to this rule as well.
When choosing a name for your variables, use full words instead of
cryptic abbreviations. Doing so will make your code easier to read and
understand. In many cases it will also make your code
self-documenting; fields named cadence, speed, and gear, for example,
are much more intuitive than abbreviated versions, such as s, c, and
g. Also keep in mind that the name you choose must not be a keyword or
reserved word.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
In short: yes, you're right. You can use underscores, dollarsigns, and characters to start a variable name. After the first letter of the variable name, you can also use numbers. Note that using dollar signs is generally not good practice.
From your comment, you said that your teacher rejected "II". Under your question, II is perfectly fine (try it, it will run). However, if the question on your test asked which are "good" variable names, or which variable names follow common practice, then II would be eliminated as explained in the quotation above. One reason for this is that dollar signs do not make readable variable names; they're included because internally Java makes variables that use the dollar sign.
What is the meaning of $ in a variable name?
As pointed out in the comments, IV is not a good name either, since the lower case version "protected" is a reserved keyword. With syntax highlighting, you probably wouldn't get the two confused, but using keyword-variations as variable names is certainly one way to confuse future readers
Private protected public are reserved or keywords in java.. Use _ or to use that those words.. example
int public_x;
int protected_x;
String private_s;

Search database table with all special characters

I have a table of project in which i have a project name and that project name may contain any special character or any alpha numeric value or any combination of number word or special characters.
Now i need to apply keyword search in that and that may contain any special character in search.
So my question is: How we can search either single or multiple special characters in database?
I am using mysql 5.0 with java hibernate api.
This should be possible with some simple sanitization of you query.
e.g: a search for \#(%*#$\ becomes:
SELECT * FROM foo WHERE name LIKE "%\\#(\%*#$\\%";
when evaluated the back slashes escape so that the search ends up being anything that contains "\#(%*#$\"
In general anything that's a special character in a string can be escaped via a backslash. This only really becomes tricky if you have a name such as: "\\foo\\bar\\" which to escape properly would become "\\\\foo\\\\bar\\\\"
A side note, please proof read your posts prior to finalizing. Its really depressing and shows a lack of effort when your questions title has spelling errors in it.

Categories