Well, as title says it is a weird question. I want to create an int called int and of course if i write;
int int;
java(eclipse) gives error. So I've been wondering if it is possible to create such a thing? if you are asking me why i insist on this, I've created str for strength, agi for agility, but int for intelligence can not be created. So should I just describe it in another way or is there a simple way to do it?
The identifier int is a reserved keyword in Java and cannot be used as a variable name.
I would suggest not abbreviating your attributes, but instead use full words:
int strength;
int agility;
int intelligence;
Even if there were a way to create a variable named int, the resulting code would be confusing to read later.
You can't. int isn't a valid identifier in Java, because it's a keyword.
From JLS 3.8:
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.
Compare this with str, which isn't a keyword. (And neither is String, in fact.)
As Greg says, it's clearer to use full names (strength, intelligence etc) anyway.
No, you can't, because it is keyword, i.e. reserved word in Java. Call it smth like _int or int_
It is a reserved word. You can not use it as an identifier.
You can't do that. It's a reserved word.
I'm fairly new to Java and I'm trying to use the + character as part of an enum type, but the compiler is complaining about the syntax because I believe it sees it as an operator.
I'd like to do the following:
enum mediaType{
FACEBOOK,GOOGLE+,TWITTER;
}
Any ideas?
Thanks!
Yes, the compiler will treat + as an operator. You can however choose a different name there:
enum mediaType{
FACEBOOK,
GOOGLE_PLUS,
TWITTER;
}
And if you want to use the value GOOGLE+ only, then have a field of type String, storing the value, and also a parameterized constructor.
P.S: As per proper naming convention, the enum name should be MediaType.
You can't use arithmetic symbols in identifiers. You need to find something you can use like GOOGLE_PLUS
Maybe reading the official Java tutorial's section on Naming Conventions will help you: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
You could at least define a private String myName = "Google+"; inside the enum, and define a method that a UI can use to get the value you want rather than just displaying the enum's variable itself.
public String myName() {
return myName;
}
Many people believe that you are limited to ASCII in Java just like C and C++.
Actually you have the full Unicode character set.
This is perfectly good Java:
enum Plus {
Google,
GooglePlus,
Googleᚋ,
Googleᐩ;
};
Not quite a + (which you cannot have in an enum because it will be confused with the + operator) but it will still carry the impression of a plus.
It seems you can use the Ogham character called muin which looks a bit like a plus character. Alternatively it seems the Canadian syllabics final plus is also acceptable alhough a number of the other possibilities seem not to be acceptable.
I've been wondering about this question for a long time :
Can we use a type name as a variable name ?
For example someone on a REST api called one of its variable "protected", is there a way to get it ? I'm developing an Android app, and the api return Json object. To accelerate the process i use the Gson library.
Its mentioned in the Docs already that
You cannot use any of the following as identifiers in your programs.
And wiki says
programmers cannot use keywords as names for variables, methods, classes, or as any other identifier.2
If still you want to use them add underscores or some extra letters to that name.
No. Please, read this list of reserved words for Java http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
But, if I remember right, in Gson you can mark variable by annotation with name of element in Gson - it can helps you.
In Java Language Specification:
3.8. Identifiers
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 in Java Virtual Machine Specification:
4.2.2. Unqualified Names
Names of methods, fields, and local variables are stored as unqualified names. An unqualified name must not contain any of the ASCII characters . ; [ / (that is, period or semicolon or left square bracket or forward slash).
So
You can't use a type name as a variable name in the Java Language
You can use a type name as a variable name in class file.
I was wondering how someone would name the member field that began with initials as opposed to words.
public class MyClass {
// I know this is how it is for a member field with words.
private String myString;
// What about this String? It is representing the term "RV Scale" which is
// short for "Reclose Volts Scale."
private String RVScale;
}
I know that I could just use private String recloseVoltsScale, but I'd rather keep it RVScale. If anyone knows if its supposed to be rVScale or RVScale or something else I'd appreciate the info.
EDIT :
Also, what about a member field like this...
private int RV;
as per java naming convention member field should start with mixedcase so it should be rvScale and member field like RV should be like private int rv;
Using the right letter case is the key to following a naming convention:
Lowercase is where all the letters in a word are written without any capitalization (e.g., while, if, mypackage).
Uppercase is where all the letters in a word are written in capitals. When there are more than two words in the name use underscores to separate them (e.g., MAX_HOURS, FIRST_DAY_OF_WEEK).
CamelCase (also known as Upper CamelCase) is where each new word begins with a capital letter (e.g., CamelCase, CustomerAccount, PlayingCard).
Mixed case (also known as Lower CamelCase) is the same as CamelCase except the first letter of the name is in lowercase (e.g., hasChildren, customerFirstName, customerLastName).
You should spell it out.
That being said, I would keep it rvScale.
Keep in mind that the only one that should NOT be used is rVScale since this can cause some confusion with introspection.
This case would generate getter and setter named getRVScale and setRVScale, but using bean introspection to find the property associated with these, would search for a property named RVScale, which doesn't exist. This is due to the fact that when searching for the corresponding property, the first letter after the get/set is lower cased, unless there are two adjacent letters in upper case (RV), in that case, the name is left as is, producing RVScale.
Like explained here:
Javabean convention - method naming for property gId
Do not use shortcuts unless you need to. Even if they are private (or maybe because they are), name variables clear enough. If potential code reader does not understand rv as shortcut of something like Reclose Volts, do not use shortcut. If you need provide hint it is shortcut actually, you are hinting he should lookup it somewhere what does that mean. Where will he find it? If it is in comment, you have wrong name of member, as you have to explain what does the name mean. Unless you application is all about Reclose Volts. I suggest to follow java conventions as they did have reason to appear.
Sometime ago, I remember being told not to use numbers in Java method names. Recently, I had a colleague ask me why and, for the life of me, I could not remember.
According to Sun (and now Oracle) the general naming convention for method names is:
Methods should be verbs, in mixed case
with the first letter lowercase, with
the first letter of each internal word
capitalized.
Code Conventions of Java
This doesn't specifically say that numbers can't be used, although by omission you can see that it's not advised.
Consider the situatiuon (that my colleague has) where you want to perform some logic based on a specific year, for instance, a new policy that takes affect in 2011, and so your application must act on the information and process it based on it's year. Common sense could tell you that you could call the method:
boolean isSessionPost2011(int id) {}
Is it acceptable to use numbers in method names (despite the wording of the standard)? If not, why?
Edit: "This doesn't specifically say that numbers can't be used, although by omission you can see that it's not advised." Perhaps I worded this incorrectly. The standard says 'Methods should be verbs'. I read this to say that considering a number is not a verb, then method names should not use numbers.
The standard Java class library is full of classes and methods with numbers in it, like Graphics2D.
The method seems ... overly specific.
Couldn't you instead use:
boolean isSessionAfter(int id, Date date)
?
That way the next time you have a policy applied to anything after a particular date, you don't need to copy-paste the old method and change the number - you just call it with a different date.
Sure, it's acceptable to use numbers in method names. But as per your example, that's why it's generally frowned upon. Let's say that there is now a new policy in place for the year 2012. Now, there's a new policy in place for 2014. And maybe 2020! So, you have four methods that are roughly equivalent.
What you want isn't a boolean but rather a strategy to do something, or do nothing, based on whether or not a policy was found. Hence, a method void processPolicy(Structure yourStructure); would be a better approach - now you can shield that you're doing a lookup based on the year, and don't have to have separate methods per year, or even limit it to just one policy per year (maybe a policy takes place in two different years, for example, or just three months).
The Java Language Specification seems fairly specific on this topic:
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.
...
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 preexisting names on legacy systems.
The "Java digits" include the ASCII digits 0-9 (\u0030-\u0039).
This doesn't specifically say that numbers can't be used, although by omission you can see that it's not advised.
I certainly wouldn't read the Java Style Guide that way. And judging from numerous examples in the Java class libraries, neither do they.
I guess the only caveat is that the JSG recommends use of meaningful names. And the corollary is that you should only use numbers in identifiers when they are semantically meaningful. Good examples are
"3D",
"i18n" ( == internationalization ),
"2020" (the year),
"X509" (a standard), and so on.
Even "int2Real" is meaningful in a folksy way.
UPDATE
#biziclomp has raised the case of LayoutManager2, and claims that the 2 conveys no meaning.
Here's what the javadoc says about the purpose of this interface:
This minimal extension to LayoutManager is intended for tool providers who wish to the creation of constraint-based layouts. It does not yet provide full, general support for custom constraint-based layout managers.
From this, I would say that the 2 in the name is meaningful. Basically, it is saying that you can view this as a successor to LayoutManager. I guess that could have been said in words, but see the examples above on how numbers where numbers are used as short-hand.
# BlueRaja writes:
The 2 does not explain anything - how is LayoutManager2 any different from LayoutManager?
The advice of the Style Guide is NOT that names should explain things. Rather, it advises that they should be meaningful. (For the explanation, refer to the javadoc.) Obviously meaningfulness is relative, but there is a practical limit on the amount of information you can put into an identifier before it becomes hard to read and hard to type.
My take is that the identifier should remind the reader what the meaning of the thing (class, field, method, etc) that is named.
It is a trade-off.
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
This phrasing alone already shows that they use a more general meaning of verb than the usual, where only is would be the verb, neither session nor post are verbs. The sentence means something like Method names should be verbs or verbal phrases, ..., and numbers can very well be parts of verbal phrases.
The idea is that a complete method call can be read as a complete sentence, with the subject being the object before the dot, the verb being the method name, and additional objects being the arguments to the method:
if (buffer.isEmpty())
buffer.append(word);
(Most such sentences would be either questioning or imperative ones.)
Your method name has (from a naming convention viewpoint) the only problem that the subject of the sentence (the session) is not the this object of your method, but an parameter, but this can't be avoided with Java, I think (please someone prove me wrong).
For multiple-parameter methods the smalltalk approach would work better:
"Hello" replace: "e" with: "x"
(where replace:with: is one method of the string class.)
Yes, in some circumstances. For example, maybe you want to handle X.509 certificates. I think it would be perfectly acceptable to write a method called handleX509Certificate.
The only problem I see with using numbers in method names is that it may be an indication that something in your design could be improved upon. (I hesitate to say "is wrong.") For instance, in your example, you stated that you have a specific policy which comes into effect after 2011. However, having a method specifically to check for that year seems overly specific and magic-number-y. I'd instead suggest creating a generalized function to check if an event occurred after a specified date as Anon suggested.
(Anon's answer popped up while I was halfway through mine, so my apologies if it seems like I'm just duplicating what he said. I felt that mine expanded on what he was saying a bit, so I thought I'd post it anyway.)
I would consider calling your method something else. Nothing against numbers exactly, but what happens if the project slips it release date? You'll have a method called post2011 - when it should be called post2012 now. Consider calling it postProjNameImplentation instead maybe?
The use of number it is not bad itself, but usually they are not very common.
in the specific case, I don't think isSessionPost2011(int id) {} is a good name. but it is better isSessionPostYear(int id, int year) {} more extensible for future uses.
The fact it is a coding convention and the use of the verb "should" suggest you that digits are permitted but advised against in methods names. However in your example, why not generalizing the same code as?
session.isPostYear(int year);
We use 'em all the time, like the example you showed. Also for interface versions, like IConnection2 and IConnection3.
Eclipse doesn't complain that it's a nontraditional name, either. :)
But acceptable? That's kind-of up to you.
Don't ever forget - rules are made to be broken. The only absolute should be that there are no absolutes.
I don't believe there's a per se reason to avoid numbers in identifiers, although in the case you describe, I don't know that I'd use it. Rather, I'd name the method something like boolean isPolicyXyzApplicable(int id).
If this is a policy that's expected to change more over time, consider splitting policies out into different classes so you don't end up growing a long vine of if(isPolicyX) ... else if(isPolicyY) ... else if(isPolicyZ) ... in your methods. Once this is factored out, use an abstract or interface method Policy.isApplicableTo(transaction) and a collection of Policy objects to determine what to do.
As long as you have a reason for using numbers, then imho I think it's fine.
For your example, there might be 2 isSessionPost method, so how would you name them? isSessionPost and isSessionPost2? Not very clear to be honest.
Just remember that all names must be meaningful and you won't go wrong.
I think in your case it's OK to use it as a one-off marker, specifically if you expect that the method will only live for a short period of time and eventually be deprecated.
If I understand your use case, you need to bring in some legacy data into the new version of your application. If this is the case, then definitely add this method, mark it #deprecated and retire it when all your clients are updated.
On the other hand Ralph here has a valid point. Don't let this project to slip into 2012 :)
nothing is wrong
String int2string(int i)
User findUser4Id(long id)
void startHibern8();
wow! this website doesn't like these method names! I got captchaed!