Put your text ad here
WestNIC provides reliable web hosting services
Web hosting directory, find affordable web hosting
Fastwebhost offers cheap web hosting & reseller hosting services
This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQ answers.
== matter?
double up to an int?
LinkedList dictionary?
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.
A: Sounds like you're looking for a user interface where you can enter Java statements and execute them. The BlueJ interactive Java environment is designed for people who are new to Java programming and lets you execute arbitrary Java statements to see how they work.
You also need to download and install a recent Java Software Development Kit first, version 6 is recommended, but all code is handled through BlueJ.
Start BlueJ, go to the View menu and the set the Code Pad visible. Type statements in the Code Pad area and they will be executed when you press the Enter key. If you include System.out.println() statements they will automatically open a Terminal Window to display the output, as follows.
… full answer hidden
Premium members click below for full answer
Is there a tool to type Java code and see what happens?
A: The Java Runtime Environment (JRE) is the plug-in software that runs Java applets in Web browsers. Normally Java applets are executed in a so-called “sandbox” environment inside the Web browser that prevents direct access to the host computer's file system and blocks potentially hazardous operations.
The JRE software from Sun, Oracle and other reputable suppliers is safe to install, but some versions of the software have been found to be vulnerable to viruses and worms. A standard virus checker with up to date virus “signature” files should detect and prevent such problems.
This Virus found in the Java cache directory article explains some typical cases and how to remove the problem. To minimise the risk of infections, keep your JRE software up to date with the latest Java Downloads.
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 =newLabel("Example label"); label.setFont(newFont("Serif", Font.BOLD, 14)); label.setForeground(newColor(0, 55, 153));
JavaFX supports a style sheet scheme that uses a similar syntax to CSS, attached to the Scene class.
A: Thinking In Java by Bruce Eckel is a good beginner's book on Java, which is available as a free download too.
A: The JDK, also called the Java Software Development Kit (SDK), is the full suite of tools required to develop, package and publish Java applications. The Sun Java SDK includes the full Java class library, with a compiler, decompiler, profiler, JAR signer, key signing tool and many other tools.
… full answer hidden
Premium members click below for full answer
What is the difference between the JVM, JRE and JDK?
A: The Java Virtual Machine (JVM) is a program that runs on a computer operating system and executes Java program code. The JVM takes the Java code and compiles it to a format that can be run directly on the computer's processor. The JVM controls the interface between the Java code and the computer like audio software enables us to play the same CD on a Windows, Mac or GNU Linux computer.
In early versions of the JVM, all the Java code for a program had to be loaded and compiled before the program could be run. More recent versions are optimised so that the Java code is compiled "Just In Time"; just before it is due to be executed on the processor. This approach accelerates program start-up, and overall performance of the Java program, but requires an extra level of coordination within the virtual machine.
A: There is no practical difference in the meaning of "invoke" versus "call" in Java programming, both mean that one class executes a method or constructor on itself or another class. In general terms the word invoke means to call upon an agent for help or guidance, or appeal for confirmation or corroboration, or summon an entity. Java programs can also be thought of as a sequence or network of messages that are sent between classes to trigger behaviour and get a response. The metaphor is basically the same in both cases.
== matter?
A: With this sort of question it is often easiest to try it yourself and see. You will find that single boolean comparisons are equivalent whichever way round you have the values.
From a reader's point of view most people would put the "unknown" variable first because it is the subject of the comparison, but syntactically it does not matter.
if (a == 10) { }
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.
… full answer hidden
Premium members click below for full answer
How do I add two numbers in Java?
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);
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.
… full answer hidden
Premium members click below for full answer
How should I round a double up to an int?
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.
… full answer hidden
Premium members click below for full answer
How can I calculate minimum, maximum and average using Java?
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.
… full answer hidden
Premium members click below for full answer
What are bitwise and bit shift operators?
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.
… full answer hidden
Premium members click below for full answer
Why does this for loop instantiation fail to compile?
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(); } }
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.
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; } }
… full answer hidden
Premium members click below for full answer
How do I access a variable declared in another class?
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.
… full answer hidden
Premium members click below for full answer
What is a recursive method?
A: A singleton class is one in which instantiation is restricted to ensure that only one instance is created for the current Java Virtual Machine. Singletons usually have a private default constructor, to prevent direct instantiation, and a static method to obtain a "new" reference to the single instance. On its first call, the static instance method creates the object using a private constructor and stores a static reference to it for all subsequent calls.
… full answer hidden
Premium members click below for full answer
What is a singleton?
A: There is only one instance of a true singleton in a single virtual machine. If two virtual machines are running, two separate and independent instances of a singleton exist. If the singleton in question is governing access to the same system resource, there may be conflicts between the two systems, which is why the singleton design pattern is not ideal in this scenario.
A: Whenever you need to represent quantities that have specific formatting and equivalence requirements, it is best to use the Quantity design pattern. For a Money type, you can associate a Currency with the amount and can deal with all rounding issues in one class. Your money and currency types can then use generic rendering methods to show the amount however you choose.
… full answer hidden
Premium members click below for full answer
How do I format my price correctly?
A: A factory method is typically used to obtain a new instance of a class, which may be one of several alternate implementations. The return type of a factory method is an interface or superclass type, which gives it the freedom to govern the actual class that is returned through polymorphism. This design pattern enables the factory to control and encapsulate the logic used to decide which instance to return.
… full answer hidden
Premium members click below for full answer
What is a factory method?
A: An immutable class is one whose field values cannot be altered after instantiation, so all variable values must be assigned in the constructor and may therefore be declared final. By definition an immutable class should not have any modifier methods, but you must also be careful that the constructor and accessor methods do not expose mutable field references.
… full answer hidden
Premium members click below for full answer
How should I create an immutable class?
A: An adapter in Java is a design pattern in which you create a class "wrapper" around an object of one type so that it can be used as, and behave like, an object of another type. The adaptation of classes to the target interface is often done by composition rather than inheritance so that the adapter fully encapsulates the adapted class to maintain the integrity of both.
To enable a plain Java Person class to be used in a Swing application, you might create a SwingPerson adapter. The example below encapsulates a private Person instance in a JPanel with labelled text fields to represent the person's first and last name, with basic getters and setters for each. The extension of the JPanel class means that the adapter inherits all standard Swing Component functionality. The encapsulation of the Person class "adaptee" means that any special behaviour the Person class has does not have to be rewritten.
… full answer hidden
Premium members click below for full answer
What are adapters in Java?
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.
… full answer hidden
Premium members click below for full answer
How can I sort 3 numbers using Java?
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.
… full answer hidden
Premium members click below for full answer
How can I make spelling checker with a LinkedList dictionary?
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.
… full answer hidden
Premium members click below for full answer
How can I use SAX to parse a Web page via JTidy?
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.
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 .
A: The design and development of a Java search engine could be suitable for a BSc final year project. The level of knowledge required about Web technology in general, the specifics of the HTTP protocol, how to spider Web pages, multi-threading techniques, indexing content, the query system and results delivery would certainly give you plenty to work with, possibly too much. Talk to your tutor about the scope of the work and perhaps consider working on a particular aspect of a Java search engine system.
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.
| Front-end FAQs | Back-end FAQs | Learn Java |
|---|---|---|
About us: site help, text ads and premium content FAQs.