World class Hard Drive Recovery and renowned raid recovery services

WestNIC provides reliable web hosting services

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQs and more.

Subscribe to this FAQ: RSS news feed

Programming techniques

Q: How do I call another class in the same folder?

Assuming the Java classes are in the same package, one class should instantiate the other to call an instance method, or use a class name reference to call a static method, as below.

public class Example {

  public static void main(String[] args) {

    Other otherInstance = new Other();

    otherInstance.instanceMethod();

    Other.staticMethod();
  }
}
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How do I add two numbers in Java?

A: To add two numbers in Java, use the simple mathematical plus operator, which may be applied to any numeric variable type, as below:

int variable1 = 26;
int variable2 = 4;

int result = variable1 + variable2;
      

The result of the addition does not have to be assigned to a variable, it can also be used anonymously in control statements, as below.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How do I add two numbers in Java?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I add two numbers using a method?

A: For simple mathematical functions a method would usually declare the input variables as method arguments and a return type that matches the required numeric type for the result. In the simplest case an add(int, int) method would return an int value, as below:

public final int add(final int firstInt,
                     final int secondInt) {

  return firstInt + secondInt;
}
      

To add two numbers you would call the method and assign the return value to a variable so it can be used later.

int sum = add(5, 2);
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How should I round a double up to an int?

A: To round a double value up and convert it to an int value takes two operations. The static Math.ceil(double) method returns a double value that is equal to the "next highest" integer. You must then give an explicit down cast to an int, as below.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How should I round a double up to an int?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How do I get the name of the operating system?

A: To get the operating system name in Java use the static System.getProperty("os.name") method, which returns a string. Other operating system property keys are "os.arch" for the hardware architecture and "os.version" for the version number.

You can also get the current user name using the method System.getProperty("user.name").

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What is a recursive method?

A: A recursive method is one whose method body includes a call to itself, so that it is called repeatedly until an expected condition is met or it cannot continue the recursion any longer. These methods often take an object or numeric argument that is subject to progressive interrogation or mathematical processing at each pass. Recursive methods must be designed carefully to ensure that they do not result in a very deep or endless recursion, which is likely to cause an OutOfMemoryError.

A simple example of a recursive method is the getNodeByName(String) method below, which iterates through all child nodes in an object structure until it finds one that matches, or returns null.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
What is a recursive method?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What is a good beginner's book about Java?

A: Thinking In Java by Bruce Eckel is a good beginner's book on Java, which is available as a free download too.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Handling exceptions

Q: Can you give an example of catching an exception?

A: One common example of catching an exception is when you try to read from a file that may not exist. You may enter a file name as the first argument on the command line, for example:

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
Can you give an example of catching an exception?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I throw a NumberFormatException back to the main() method?

A: NumberFormatException is an un-checked exception. That means that the compiler will not enforce that your application catches the exception and handle the case. For example, users may enter an invalid number at runtime and the application would throw an exception and crash.

For runtime exceptions it is important that your application handles the exception in the method in which they may occur. The callers of such methods cannot be expected to know that they would throw a runtime exception and so catch the exception. Your methods should include validation and handling for specific, anticipated runtime exceptions.

If you want to signal a problem that cannot be handled locally by your method, you should catch the runtime exception and throw a checked exception, as below. This is a typical case for creating your own checked exception type, though rather heavyweight for this simple example.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I throw a NumberFormatException back to the main() method?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Java applications

Q: How do Java front- and back-end skill sets differ?

A: This is a somewhat arbitrary distinction to make about Java development, since applications often have front- and back-end components and it is important to understand how both aspects are integrated. In general terms, back-end development is concerned with database storage and retrieval, servlets, Web application frameworks and Enterprise Java Beans. This requires a good understanding of SQL and database applications, JDBC, network principles, servlet containers, the HTTP protocol and an appreciation of concurrent programming issues.

Front-end development for servlets is concerned with the delivery of HTML content to Web browsers, especially forms, and touches on most aspects of markup design, Cascading Style Sheets and Javascript. Usually, front-end developers will work to visual designs provided by others, and will implement the work using a combination of formats including JSP, JSP tag libraries and other template frameworks, such as Spring.

Front-end developers may also be involved in creating pure Java user interfaces for stand-alone Swing applications or (less commonly these days) the Abstract Windowing Toolkit (AWT) for applets. In this case, it is important to have a good knowledge of the Swing API components, their intended use, and the data structures they operate on.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I make spelling checker with a LinkedList dictionary?

A: A basic spelling checker that processes an input stream of some kind might use a StreamTokenizer to identify the words from the input and use the LinkedList's contains(Object) method to check whether the given word is recognised. How you deal with un-matched words is up to the application interface, this example just lists the line number and word on the console output.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I make spelling checker with a LinkedList dictionary?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I use SAX to parse a Web page via JTidy?

A: The JTidy project help page is not all that helpful. The original HTML Tidy configuration options are a better reference to the equivalent methods in the Java implementation and the Code Style JTidy development notes article should help you get started.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I use SAX to parse a Web page via JTidy?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I create a search engine in Java?

A: This is a big question and there are many aspects to consider. You may find it helpful to take a look at the MKSearch system. This is an open source project, so you can review the code yourself. The project Web site includes Java documentation, configuration notes and how to guides to get you started.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I design my own fonts using Java?

A: It is puzzling that you would want to design fonts using Java, the language is not particularly suited for this purpose. There are several very good applications for designing and converting fonts such as Fontographer for example.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Network programming

Q: How can I download a Web page and write it to a file?

A: The standard Java input/output and network APIs make it quite easy to acquire content from the Internet and write files. Writing from a stream input to a file output is the slightly complex part. The example below uses a copy(InputStream, OutputStream) method adapted from a version in Java I/O by Elliotte Rusty Harold.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I download a Web page and write it to a file?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How do I get the domain name from a URL?

A: If you want to extract a domain name from an existing URL object, use the URL's getHost() method.

String urlString = "http://www.test.example/path/page.htm";

URL url = new URL(urlString);

String domain = url.getHost();
          

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How do I get a domain name from an IP address?

A: It is possible to do a reverse name look-up for an IP address using the java.net.InetAddress class. The example below first gets an instance of the class using the static getByName(String) method, then applies the getHostName() method to it. The method will only resolve a domain name if there is one configured for the host, otherwise the method returns the original IP address.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How do I get a domain name from an IP address?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: My Java Web client gets the wrong site!

A: Many Web sites use virtual hosting, which requires you send an HTTP Host header with your request.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
My Java Web client gets the wrong site!

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I set a code name identifier for my feed reader?

Your application should pass a User-Agent header in the HTTP request with the code name of your application as the header value. Web browser user agents often include the full version and build number for the application and the software platform it was built for. Feed readers tend to use simpler name and version number combination. See the Java example below.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I set a code name identifier for my feed reader?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Static context questions

Q: What is special about static variables?

A: A static variable is shared by all instances of a class. Every instance has a reference to the same variable and can modify it directly. Static instances are declared with the static modifier.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
What is special about static variables?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What is the difference between static and final keywords?

A: The static and final modifiers have quite distinct purposes in Java, though they can be used in combination to declare class constants. When the static modifier is applied to a variable or method it belongs to all instances of the class and can be referenced in a static context. In other words, the class does not have to be instantiated before the variable can be read or the method called. That means that static variables must be assigned at compile time and static methods cannot reference instance variables or call instance methods.

The final modifier can be applied to a class definition or method to prevent extension or overriding respectively. This helps the compiler optimise byte code for the class. When the final modifier is declared on a variable it means that its initial assignment will not change during the execution of the code. Final instance variables must be assigned at compile time or in the class' constructor, as in the example below.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
What is the difference between static and final keywords?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: I get "non-static variable this cannot be referenced from a static context"!

A: The main method must be declared public static void because it is invoked when the Java Virtual Machine first starts up, before any Java object instances exist. The main method may reference any number of static variables and call static methods. Any series of calls to other static methods only extends this original static context. To reference a non-static or instance variable from the main method, you must first instantiate the relevant object, even if it is the host of the main method itself, as below.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
I get "non-static variable this cannot be referenced from a static context"!

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I call super() from a static context?

A: The super() method can only be called in an object's constructor, it cannot be called in a static context. The only way to invoke the super() method is to place this statement in the first line of an object's constructor and instantiate the object. You can then invoke this method via the static void main(String[]) method, as below.

public class SuperConstructor extends Superclass {

  public SuperConstructor() {

    super();
  }

  public static void main(String[] args) {

    SuperConstructor object = new SuperConstructor();
  }
}
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How do I call a static method in a separate class?

A: To call a static method in a separate class you should prefix the method reference with the name of the class it belongs to, known as the host class. For example, the String class has valueOf() methods to convert primitive values to strings:

String booleanString = String.valueOf(true);
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I call a static method from an object reference?

A: Yes, it is possible to call a static method on an object reference using the same dot syntax as for a static class reference, as below.

String stringRef = "Example";

System.out.println(stringRef.valueOf(true));
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I call static class members from a different class?

A: Calling static members in a separate class is very similar to calling a static method in a separate class. Most importantly, the static member must have a public, package or protected modifier that makes it accessible to the calling class. Use the class name, a dot separator and the name of the member variable, as with the AWT Color class properties below:

Color textColor = Color.black;
Color panelColor = Color.lightGray;
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Add this page to your chosen social bookmarking service

Style warning - please read

Home · CSS · Java · Javascript · HTML · Help · Log