Put your text ad here
WestNIC provides reliable web hosting services
Free software downloads and drivers download resources
Top Canadian Hotels no booking fees from Victoria BC to Nova Scotia
This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQ answers.
double up to an int?
NumberFormatException back to the main() method?
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.
A: It is possible to control the position and spacing between Java applets and other HTML document elements using CSS, but the CSS associated with the Web page cannot affect the visual appearance of the applet embedded in it.
applet, object {
margin: 0.5em;
padding: 0;
}
The appearance of Java applets is controlled by the Abstract Windowing Toolkit (AWT) or Swing interface properties defined in the applet class. It is possible to set the logical font type, colour and background colour for applet components, as well as the internal layout.
Label label = new Label("Example label");
label.setFont(new Font("Serif", Font.BOLD, 14));
label.setForeground(new Color(0, 55, 153));
JavaFX supports a style sheet scheme that uses a similar syntax to CSS, attached to the Scene class.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 omitted
Access all premium content for $50: sign-up now.
What is a recursive method?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
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 omitted
Access all premium content for $50: sign-up now.
How do I add two numbers in Java?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
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 omitted
Access all premium content for $50: sign-up now.
How should I round a double up to an int?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: Assuming you have data values in a Java storage structure, the key part of the process is to iterate through the values, check and store the minimum and maximum values, the running total and number of data points. Lets take the simple case of an iterator over a set of DataPoint objects that have an int getValue() method.
This example has int variables for max, min, count, sum and a temporary dataValue. The initial value for max is set to Integer.MIN_VALUE so that any given value should exceed it, and min is set to Integer.MAX_VALUE. A float type is specified for the mean variable since integer division is likely to result in a fraction and the decimal part should be preserved.
… premium content omitted
Access all premium content for $50: sign-up now.
How can I calculate minimum, maximum and average using Java?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: Java bitwise operators act on the binary representation of primitive numbers int and long. Bitwise shift operators perform low level mathematical actions as if they physically shift binary digits left and right. The bitwise logical operators compare numbers bit by bit and transform them according to boolean logic. The examples below show how the 32 bit binary values are transformed by each operator and highlight some significant exceptions in the the use of shift operators in mathematics.
… premium content omitted
Access all premium content for $50: sign-up now.
What are bitwise and bit shift operators?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: 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.
A: If two Java source files are located in the same directory and neither explicitly declare a package name, they are implicitly in the same default package and no explicit import statements are required between them. Both classes can refer to each other, instantiate and call methods on each other directly provided there are no visibility modifiers that would prevent this.
When you create a package structure for your classes these relationships get a little more complicated. In the simplest case you can declare that both classes belong to the same package by adding the same package statement to the head of both source files, before the class definition. In this case both classes can refer and call on each other as with the default package above, no import statements are required.
package org.example.packagename;
The convention for package names is to be the reverse of the Internet domain associated with the project with dot separators. The package names are appended with a dot separator all in lower case.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: The examples below uses three classes, VariableHost, VariableCaller and VariableSubclass, all in the same default package for simplicity. The VariableHost class has a static class variable and an instance variable and the cases show how they are accessed from the host class itself and the other classes.
public class VariableHost { static int staticInt = 2; int instanceInt = 4; public static void main(String[] args) { // Static reference int staticAccess = staticInt; // Object reference necessary for instance variable VariableHost hostInstance = new VariableHost(); int instanceAccess = hostInstance.instanceInt; } }
… premium content omitted
Access all premium content for $50: sign-up now.
How do I access a variable declared in another class?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 omitted
Access all premium content for $50: sign-up now.
Can you give an example of catching an exception?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 omitted
Access all premium content for $50: sign-up now.
How can I throw a NumberFormatException back to the main() method?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
for loop instantiation fail to compile?
A: If you declare a variable in a for loop without braces the Sun compiler will fail with the message "not a statement", but the message is misleading. A more appropriate error message would be "o is already defined". In this case there is no contained scope for the variable o, so every pass through the loop would have the effect of declaring the variable again and again.
// Does not compile for ( ; ; ) Out o = new Out();
Without braces its as if you had written a continuous list of variable declarations:
// Does not compile Out o = new Out(); Out o = new Out(); ...
In the example below the for loop statement is enclosed in curly braces, which gives the variable declaration more precise scope. In this case, each pass through the loop creates a "throw-away" variable which is local to the statement block.
for ( ; ; ) { // Compiles Out o = new Out(); }
This question is not particularly to do with the for loop and it makes no difference whether the loop runs once or an infinite number of times. The significant point is not to do with assignment, it is about the declaration of the variable and the scope the variable has. The annotated example below continues the case of the for loop, but the key is to compare the different syntax that follows the for conditions.
… premium content omitted
Access all premium content for $50: sign-up now.
Why does this for loop instantiation fail to compile?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: Small data sets can be sorted using a simple bubble sort algorithm that steps through the sequence, compares adjacent values and swaps them if necessary. The example below uses a recursive sort(int[]) method to re-process the integer array if the sequence changes. In the final pass there is no change and the sorted array is returned.
… premium content omitted
Access all premium content for $50: sign-up now.
How can I sort 3 numbers using Java?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 class'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 omitted
Access all premium content for $50: sign-up now.
How can I make spelling checker with a LinkedList dictionary?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 omitted
Access all premium content for $50: sign-up now.
How can I use SAX to parse a Web page via JTidy?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: The source of the MKSearch search engine is available from the MKSearch Subversion repository, use the trunk path. The MKSearch Web site has a research section that includes detailed notes on several open source spider applications that can be used to acquire Web content for indexing.
Another popular open source Java search engine application is Apache Lucene .
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
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.
A: Getting information from Windows system applications relies on the programs having command line interfaces that a Java program can read from. Windows Task Manager program does not seem to support command line arguments to interrogate running processes, nor standard output, so you may need to interface with a different program to get the information you seek.
The example below uses the Java ProcessBuilder class to create a Process that opens the Task Manager graphical user interface application. The same approach can be used to run other system tools or installed applications, provided you know the path to the executable program and can supply any appropriate arguments.
… premium content omitted
Access all premium content for $50: sign-up now.
How can I copy process information from Windows task manager?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
| Front-end FAQs | Back-end FAQs | Learning Java |
|---|---|---|
About us: site help, text ads and premium content FAQs.