Java global variables - What is the convention to declare? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I think the question speaks for itself but if it doesnt here is the short explanation for what I meant:
Coding a java programm, what convention should I take to declare a global variable? I Mean, which one below should I use?
public class Variables {
private variable;
private Variable;
private VARIABLE;
private largerVariable;
private Larger_Variable;
private larger_variable;
private LARGER_VARIABLE;
}

There are several rules:
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 here
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
If I read these rules right, valid names(by naming convention) will be:
private Object largerVariable;
private Object LARGER_VARIABLE;

Another thought is to declare constants such that they can't be changed:
private static final boolean POWER_ON = true;
Additionally, if I need to define boolean constants, I try to define it so they are affirmative (true) rather than negative (false) so its easier to grasp without thinking about it too much. Example:
I use this:
private static final boolean POWER_ON = true;
rather than this:
private static final boolean POWER_OFF = false;
Another consideration:
For boolean variables, I might consider preceeding the word with 'is' or 'has' to indicate its boolean if its not obvious from the word. Example: IS_RADIOACTIVE.
Lastly, I only need to define POWER_ON rather the POWER_OFF since !POWER_ON means the same thing in a java statement.

Java has no such thing as 'global' variables.
However, if you want to use constants which can be accessed by any other class, most people will declare a public static final variable and initialize with the corresponding value right away.
public class HttpCodes {
public static final String NOT_FOUND = "404";
}
Can be accessed by any other class: HttpCodes.NOT_FOUND
If you're trying to make it an instance variable, go with camelCase private final String notFound = "404" for example.

I am assumming global means class level...
as a practice class level variables should be written in capital letters
In most cases they are marked as static so that can be access by all the class methods.
Also, if you believe they would be initialized only once then consider making them final.
correct declaration could be:
private static VARIABLE;
private static LARGER_VARIABLE;

Related

Naming variables using dataype to describe the action

I was just wondering if I am breaking some sort of naming convention while naming my variables.
Let's say I have an int named numerator1. Is it wrong to name the double type conversion variable as doubleNumerator1?
Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
This is the Naming convention for variables from Oracle.
So technically no. But variable name numerator1 is not useful for most cases since no one reading would know what that name signifies. Rule of thumb for naming variable for me is if it's being used immediately and its use is clear I can name it something short. But if I have to use the variable for more than once or it gets used after more than 20 lines, I would name it something more meaningful.

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;

Char vs String in Java? [closed]

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.

Java Code Conventions: must match pattern '^[a-z][a-zA-Z0-9]*$'

i would like to use the following constant:
final String ADD = "Add text";
But my CheckStyle tool tells me that 'ADD' does not match the pattern '^[a-z][a-zA-Z0-9]*$'.
Could anyone please tell me what is wrong with 'ADD'?
Means '^[a-z][a-zA-Z0-9]*$' that every name has to start with a low character?
Is there no other possibility?
Thanks for answers.
^[a-z][a-zA-Z0-9]*$
This regex describes something which starts with lowercase and the remainder is composed of uppercase, lowercase, and numbers. (Examples: aVariable, variable, aNewVariable, variable7, aNewVariable7.)
If you want your field to be constant and static, use:
static final String ADD = "Add text";
Otherwise, use:
final String add = "Add text";
If it is a constant you want, it should also be static
static final String ADD = "Add text";
Constants normally use uppercase letters, but since your variable was not static, it was not interpreted as a constant.
This Regex indicate the need for camelCase with the first letter being small and then every next word having the first letter in it as capital letter.
I just ran into the same problem, turns out it was because it is expected for the Java codebase I was working on to use camel case for all variables as the naming convention. So be sure to check if your variables are named according to the regex pattern ^[a-z]([a-z0-9][a-zA-Z0-9]*)?$. In my case, I got stuck in the Python mode and had my variable named version_regex instead of versionRegex. Once I have made the needed correction the error is no longer thrown.

Categories