Answers to Common Questions
These are answers to “muddy” point questions students have asked. A muddy point is when there is still confusion about the topic even after learning about it. My intention to continuously add points to this web page. The errors section is open by default. Click on the arrows to open or close a section.
What do these error messages mean?
It is important to realize that not all error messages are helpful. Many times the message is completely off. Good developers look beyond the error message because you are being pointed to the general location of the error. It is always a good idea to examine the line of code directly above and below the line the error message is pointing to. Also, ask yourself, why am I getting this error? When it comes to deciphering error messages, you need to put your thinking cap on! Below are some common error messages.
Error message: Cannot find symbol
This is one of the most common errors beginners have. It means you are trying to use a resource
(variable, method, etc.)that has not been declared. Check the following:
- Is the resource declared?
- Is the resource declared where it should be? (Think scope)
- Is the resource name spelled correctly?
Error message: Class, interface, or enum expected
When you get this error and there are LOTS of red underlines in your code, it usually means your file is
not set up correctly and you should check your curly braces.
Remember, your code goes into a method and each method should be between the beginning and ending curly braces of the class.
Review “Why do we need curly braces?”, Code organization - packages, classes, and methods, oh my!"
and "What classes do I need and what goes in them?" All these topics are listed in the web page.
Error message: Unexpected type. Required: variable. Found: value
Whenever you get an “unexpected type” error, look at what is listed after required and found.
In this case, you needed (required) a variable, but instead you used (found) a value.
In this instance, your assignment statement is set up incorrectly. Remember, the variable you want to assign
a value is always on the left side of the equals sign.
Sometimes the words after “required” and “found” are different, but with a bit of practice, you will recognize where you went wrong.
Error message: Incompatible types: double cannot be converted to a String
This error occurs with you try to assign a variable but your value is of the wrong data type.
Remember, variable = value; however, “value” can be another variable. Sometimes the error
details say something like: "possible lossy conversion from double to int". In this case, you are trying to
assign a double value into an int variable.
Error message: Input Mismatch Exception
You encounter this error when you try to save a value into your variable and they are of non-compatible data types.
Typically, in this course, you tried to save a String value into a number variable.
Error message: Reached End of File While Parsing
Typically, you encounter this error when your curly braces do not match-up or you have one missing. You may see a similar error if you put a semi-colon in the wrong place.
What are library methods?
Library methods are methods that are built into the Java programming language. They are tried and true methods
that you do not need to write, you just need to know how to use them. For instance, the .toUpperCase()
method gets applied to a String variable. Used correctly, the .toUpperCase() method
gives you back a String variable that is all uppercase letters. The Java language has many library methods.
Getting to know them makes programming easier.
How do I export my project into a Zip file?
Use NetBeans. Click on your project name and then click File | Export Project | To ZIP... The default location is somewhere crazy, so I usually copy only the filename part, traverse to where I want the file to be, and then past the name into the dialog window.
Using NetBeans to export your file creates a project that I can import into my development environment. If you do not use NetBeans, I have several steps to accomplish before I can grade your assignment. Thank you for doing this correctly.
Why do we need curly braces?
We use curly braces to designate that the code between the braces is performed as a unit. Code between curly braces is also known as a code block. Curly braces are found to the right of the letter “P” on a standard US keyboard. We always add curly braces as a pair, first you open { then you close }. Between the braces is were we write code. Curly braces are used to designate classes, methods, decision structures, and repetition structures. Use the comment syntax // to label the ending curly braces of a class, method, decision structure, and repetition structure, especially if the code block is long. This technique helps you to stay organized and write your code in the proper place. For methods and classes, label the ending curly brace with the name of the class or method. With the other structures, you may need a description.
If you get the error message “Reached End of File While Parsing” then you need to check your curly braces. You are probably missing one. Click on the right side of either an opening or closing curly brace, NetBeans will highlight what it believes in the corresponding brace.
Why do we need a semicolon?
Whereas curly braces say perform this code as a unit; the semi-colon says I am at the end of this statement, so terminate it. Typically, statements are inside of curly braces. Be careful! In general, a semi-colon does NOT belong immediately after a beginning or ending curly brace. If you get an “empty statement” warning, check to insure your semi-colons are properly positioned.
Code organization - packages, classes, and methods, oh my!
Packages are the first step in code organization and they are an industry standard. I will use a filing cabinet analogy to describe packages, classes, and methods. Your Java project is the filing cabinet. Inside of the cabinet are drawers. A package is like a drawer in a filing cabinet. A class is like a folder in the drawer. Each package has one or more classes. Our folders are not empty, though. Think of methods as paper within a folder. Therefore, inside each class is one or more methods.
In Program Logic, we only have one package, however, in my Java courses there are several. Best practice is to use the reverse domain naming convention when naming packages. We typically have two classes in that package, one named Controller and the other named Main. Our Main class contains one method whereas our Controller class may contain several.
What classes do I need and what goes in them?
In Java, all our code goes inside of a class. In Program Logic, we create two class files, Controller and Main. A class is designated by a signature followed by opening and closing curly braces. The class signature does NOT contain parentheses. In this course, we do NOT nest classes, we create two distinct class files and place our code within the appropriate class. We use Pascal case when naming our classes. The signature of a class should be as seen below. Remember, in Program Logic, your ClassName is either Controller or Main.
public class ClassName{
}
Controller Class
Best practice is to separate code into similar functional groups. I have you use the name Controller for two reasons. One by using the same name for each assignment, you have one less thing to think about and two, because we follow one flavor of the Model, View, Controller design pattern. Although the main() method in the Main class kicks off our program, it is the Controller class that controls the flow of your application. The kick off is done by instantiating the Controller class, which in turns runs the code within the constructor of the Controller class. There is more information on instantiation and constructor below.
public class Controller {
public Controller() {
//below is the call to the method that will start the "work" of your program
myJavaStatements();
System.exit(0); //this exits the program and can be other places in the code, or not at all
} //end constructor
private void myJavaStatements () {
//Code goes here
} //end method
} //end Controller() class
Main Class
Many code examples you see on the Internet, put all code inside the Main class. This is for simplicity, but does not prepare you for writing more complex code. Separating code into logical units, makes your code easier to maintain, especially when (in Beginning Java) we have more packages and more classes. Our Main class has one and only one job and that is to be the container for the main() method. When your Main class contains a main() method, the file name in your NetBeans project has a green play button on it.
What is the main() method? Where does it go and what goes in it?
The main() method goes inside of the Main class and it is the only method in that class. Furthermore, the main() method has a specific signature that we do not alter. If you allow NetBeans to generate the main() method for you, then the signature form main() will be correct. The purpose of the main() method is to instantiate our Controller class.
Instantiate means to provide an instance of something, but if you are like me, you really dislike a definition that just use another form of the word to define it. So, what instantiate means in programming terms is that you bring a class to life. In other words, you call a class so that you can start using it. In Java, when a class is instantiated, it is referred to as an object. The statement to instantiate our Controller class is always: Controller control = new Controller(); Furthermore, the statement always goes inside of the main() method. In fact, it is the ONLY statement we put inside of our main() method.
PLEASE NOTE, If you right clicked on your package and selected New | Java Main Class, then the main method is automatically built for you. You SHOULD have a play button icon on this class name in NetBeans.
Your Main class should be set up similar to this:
public class Main {
public static void main(String [ ] args) {
//below is how you "instantiate" the Controller class
Controller control = new Controller();
} //end of method main
} //end Main() class
What is a constructor? Where does it go and what goes in it?
The constructor is a special method that tells the class how it should be built. Even built-in Java classes such as Scanner and StringBuilder have at least one constructor. When you instantiate a class using the keyword new, you are asking it to build itself. We always include a constructor method in our Controller class. A constructor must have the same name as its containing class, therefore our constructor is always named as such:
public Controller(){
}
Notice the name of our constructor is the same as our class, Controller. Also notice that the constructor signature contains parentheses whereas the class signature does not. And, as I am sure you noticed, the constructor signature does NOT contain the keyword class. Remember, the constructor is a special method. Other methods we create have a return type, even if that type is
void. However, the constructor never includes a return type.
The constructor is automatically called when we instantiate our Controller class. In this course, we always call at least one method from within the constructor. By doing so we are controlling the flow of our application.
Why do we organize code into methods?
Methods organize our code into functional tasks. Methods are designated by a signature, with parentheses, followed by opening and closing curly braces. This is known as the method signature and body, albeit at this point the body is empty. Methods are always placed between the curly braces of its containing class. Let's get this straight, a class has one or more methods nested inside of it.
Use the comment syntax // to label the ending curly braces with the method name. This technique helps you to stay organized and write your code in the proper place. Knowing that there should be only two ending curly braces at the bottom of your code also helps. The last ending curly brace is for the class, the other is for the last method in your code. Yes, you can and will have more than one method in your code. However, we do NOT nest methods. If you have lots of red lines in your code, check your curly braces. There is a good chance either you nested a method or you are missing a curly brace.
Minimizing your white space between the last line of code and the ending curly brace of the method also helps. If you manually create a method or other structure, open and close the curly braces right away so they are properly paired. If you have already made a method call, but have not yet created the method, then NetBeans can create the method signature and empty body for you.
What is the difference between a string literal and a String variable?
String literals must be surrounded by quotes. Remember, a string literal means write my words exactly as written. This is known as "hard-coding" values. If a value is going to change, you do not want it hard-coded. Many times, part of a message to the end-user is constructed of hard-coded words joined with variables. A variable of the data type String does not have quotes around it, for example, String firstName; In this example, firsName is the variable and it is not initialized.
We use variables because the value assigned is obtained from another source, such as the end-user, or the value is likely to change while the code is executing. Whenever you display a variable, the contents of the variable is displayed to the end-user. Take this example: String firstName = "Nancy"; If you display firstName and "Nancy" (without quotes) is printed, then you built your display statement correctly, however, if firsName is displayed, then you erroneously put quotes around the variable name in your display statement, making Java think it is a literal.
What is the difference between an argument and a parameter?
A parameter is the variable between the parentheses in a method or class signature. Methods and classes can have zero or more parameters. If you provide a parameter, you must include its data type.
An argument is used when you call a method or class. Methods and classes can have zero or more arguments. If you provide an argument, you do not include the data type.
What is a code snippet?
A code snippet is a piece of source code. The snippet is syntactically correct, but does not run unless put within a program.
How do I format numbers to only two decimal places?
System.out.printf
If the assignment has NO requirement to use a StringBuilder object, then the easiest way to format a number is to two decimal places is to use printf. Here is the syntax: System.out.printf("%.2f", salesTax); Please note, you may experience rounding, which for this course is okay. Printf prints inline with content.
String.format
If the assignment has a StringBuilder requirement, then you need to use a different method. This example works with StringBulder: sb.append(String.format("%.2f", salesTax)); In this example, sb represent the StringBuilder object and .append is the method being applied to the object.
Remember, there are many ways to brew the Java. If you were creating an application that relied upon precision for currency, neither of the above would suffice.
How do I use StringBuilder?
Instantiate
To instantiate, a non-static class (Scanner, Controller, StringBuilder, etc.) you need to include the keyword new. Please note, there is a way of using a class to get at its static methods. In that instance, you do not instantiate, you just use. I just wanted to make that clear because we use both techniques in Beginning Java.
- Here is how you instantiate the Scanner: Scanner input =
newScanner(System.in); - Here is how you instantiate StringBuilder: StringBuilder sb =
newStringBuilder();
Notice the similarities: ClassName variableName = new ClassName();
In the case of the Scanner, we are passing something into it;
however, with StringBuilder, we are not, but you use instantiated class methods the same:
There are other ways to "construct" a StringBuilder. For instance:
StringBuilder sb = new StringBuilder(100);
This example gives your StringBuilder object and initial capacity of 100 elements. The default is 16 elements.
The capacity of the StringBuilder object automatically grows as needed, however, efficiency may be gained
if you set a realistic capacity.
.append()
Remember, the StringBulder .append() method does not return anything; it just concatenates your values together. As with other library functions, you use StringBuilder functions using the following format: variableName.method();
- sb.append("literal");
- sb.append(variable);
Please note, you should NOT include a concatenation operator ( + ) inside of the
parentheses of the append method. You can string two append methods together:
sb.append("literal").append(variable);
Also note, append does not format, it just concatenates. I quite often create a named constant called SPACE with the value of one space ( " " ). If you put the append method inside of the loop, then you will have a sentence.
Printing
In order to print the "sentence" to the console you can use either of the following:
- System.out.println(sb.toString());
- System.out.println(sb);
The method .toString() is implied in the second example.
Clearing the content
Sometimes you want a global StringBuilder object, or just want to reuse it locally. Remember, the method .append() does just that. It will continuously add more content to your StringBuilder. There are two ways to clear the content from a StringBuilder so you can use the same object to print different stuff.
- sb.delete(0, sb.length());
- sb.setLength(0);
The delete method takes two integer arguments: which position to start deleting and which position to end deleting. Zero means start at the beginning. Since the StringBuilder has a built-in length property, you can use that for the ending position. Please note, length is NOT capacity. Length says I am using this many elements of my given capacity.
The method setLength() does not affect the capacity of your StringBuilder object, but it does remove all the characters you already but into the object.
In either example, you will want to print the contents of your StringBuilder before removing it.
How do I Create a New/Blank Line?
As I am sure you have noticed, there tends to be more than one way to brew the Java. Remember, when we create messages in Java, our System print options do not format, neither does the StringBuilder object. When we want to split the text onto separate lines or put a blank line between lines of text, we must manually insert new line characters.
System.out.println()
When you do not put anything between the parentheses of System.out.println(), you have just created a blank line.
Line Separator
Java is a platform independent language, meaning the your Java programs should run on any operating system. Limitations are introduced, depending on the way you write your code. For that reason, it is a good idea to use System.lineSeparator() when a new line is needed. Furthermore, it is okay to create a global named constant that is assigned this code: private final String NEW_LINE = System.lineSeparator();
Where do I put Global Variables and Named Constants?
Best practice is to use global resources sparingly as they are available throughout the Java class. In the case of variables, they can be changed anywhere within the class. However, I occasionally tell you it is okay to use a global resource. Mark your global resources as final and put them after the class declaration, but before the constructor declaration. Include the access modifier private when naming your resources. The below code shows you were to put your global resources.
public class Controller {
//this is the global resource area
private final String NEW_LINE = System.lineSeparator();
public Controller(){
//at least one method call goes here
}//end of constructor
//methods go here
}//end of class
How do I make comments in my code?
There are actually three different comment types in Java. In NetBeans, there is an icon for single line comments and another icon for uncommenting. You can also press the control key and the forward slash, which toggles comments on and off.
//Use two forward slashes for a single line comment
/* Slash asterisk and ending with
asterisk slash denotes a multiple line comment */
/** A slash with two asterisks, represents Java documentation (javadoc).
These comments can be made into official documentation for a project **/