Working with strings under Java is far easier than with other languages. Most languages represent a string as a data type, or as an array of characters. Java however treats strings as an actual object, and provides methods that make string manipulation far easier.
Strings under Java are represented by the java.lang.String class. Since the java.lang package is imported by every Java application or applet, we can refer to it just as String. To determine the length of a String, simply call the String.length() method, which returns an int value.
String aString = "this is a string. what is my length?";
int length = aString.length();
System.out.println (aString);
System.out.println (length);
TIP - Remember that the String class is zero-indexed. Even though the String is of length n, you can only access characters in the range 0..n-1
www.referjava.com
Tuesday, February 13, 2007
How do I minimize and restore frames and JFrames?
This question stumped me when I first took a look at it. There is no minimize or restore method in JFrame, or java.awt.Frame for that matter. However, I knew there had to be a way - as JFrames frequently need to be restored programmatically. I suspected that the problem was a difference in terminology, and after a little searching, found the answer.
JFrame inherits the setState method from java.awt.Frame. This method allows you to change the state of a window from "iconified", back to "normal". This is, in actual fact, minimize and restore - but the documentation uses different terms. To minimize or restore a window, we simply call the setState method, and pass it a state parameter to indicate whether we want to minimize or restore the window..
For example, to minimize a Frame (or subclass, such as JFrame), we pass the 'iconified' parameter
myFrame.setState ( Frame.ICONIFIED );
To restore the frame to its normal state, we call the setState method with the 'normal' parameter
myFrame.setState ( Frame.NORMAL );
To demonstrate this effect, I've written a small demonstration, which you can compile and run. In the following example, a new frame is created, and then minimized. After a short delay, it is restored again.
import java.awt.*;
public class FrameTest
{
public static void main (String args[]) throws Exception
{
// Create a test frame
Frame frame = new Frame("Hello");
frame.add ( new Label("Minimize demo") );
frame.pack();
// Show the frame
frame.setVisible (true);
// Sleep for 5 seconds, then minimize
Thread.sleep (5000);
frame.setState ( Frame.ICONIFIED );
// Sleep for 5 seconds, then restore
Thread.sleep (5000);
frame.setState ( Frame.NORMAL );
// Sleep for 5 seconds, then kill window
Thread.sleep (5000);
frame.setVisible (false);
frame.dispose();
// Terminate test
System.exit(0);
}
}
www.referjava.com
JFrame inherits the setState method from java.awt.Frame. This method allows you to change the state of a window from "iconified", back to "normal". This is, in actual fact, minimize and restore - but the documentation uses different terms. To minimize or restore a window, we simply call the setState method, and pass it a state parameter to indicate whether we want to minimize or restore the window..
For example, to minimize a Frame (or subclass, such as JFrame), we pass the 'iconified' parameter
myFrame.setState ( Frame.ICONIFIED );
To restore the frame to its normal state, we call the setState method with the 'normal' parameter
myFrame.setState ( Frame.NORMAL );
To demonstrate this effect, I've written a small demonstration, which you can compile and run. In the following example, a new frame is created, and then minimized. After a short delay, it is restored again.
import java.awt.*;
public class FrameTest
{
public static void main (String args[]) throws Exception
{
// Create a test frame
Frame frame = new Frame("Hello");
frame.add ( new Label("Minimize demo") );
frame.pack();
// Show the frame
frame.setVisible (true);
// Sleep for 5 seconds, then minimize
Thread.sleep (5000);
frame.setState ( Frame.ICONIFIED );
// Sleep for 5 seconds, then restore
Thread.sleep (5000);
frame.setState ( Frame.NORMAL );
// Sleep for 5 seconds, then kill window
Thread.sleep (5000);
frame.setVisible (false);
frame.dispose();
// Terminate test
System.exit(0);
}
}
www.referjava.com
Is Java Y2K compliant? Where can I find more information?
I'd like to give a big unconditional yes, but its not quite that simple. Java is more than a language - its a platform. There are many different virtual machines, by many different vendors, running on many different hardware and software architectures. Does that present a Y2K threat? Yes.
However, work is being done to prevent problems. Sun takes its commitments very seriously - for a comprehensive list of products and their Y2K status visit
http://www.sun.com/y2000/cpl.html
The problem is - will all Java Virtual Machines be ready in time. Remember that some are third party ports, or completely re-engineered versions. So there is still the potential for problems if you use non-Sun virtual machines. If you use third party class libraries, or code, you're also running some risk. Of course, a quick test to reassure you, might be to turn your computer's clock forward till after Jan 1 2000.
www.referjava.com
However, work is being done to prevent problems. Sun takes its commitments very seriously - for a comprehensive list of products and their Y2K status visit
http://www.sun.com/y2000/cpl.html
The problem is - will all Java Virtual Machines be ready in time. Remember that some are third party ports, or completely re-engineered versions. So there is still the potential for problems if you use non-Sun virtual machines. If you use third party class libraries, or code, you're also running some risk. Of course, a quick test to reassure you, might be to turn your computer's clock forward till after Jan 1 2000.
www.referjava.com
What are exceptions, and when should I use them?
Exception handling is an important feature of C++ and Java. Exceptions indicate unusual error conditions that occur during the execution of an application or applet. When you call an object method, and an "exceptional" event occurs (such as being unable to access a file or network resource), the method can stop execution, and "throw" an exception. This means that it passes an object (the exception), back to the calling code. That code can then handle the event, and deal with unusual conditions.
That's the theory of exception handling. Let's look at a practical example. Suppose my application had to read some data from a file. Most times, it will be able to read the data, and continue on without any problems - but what would happen if the file didn't exist? Our program might crash, without reporting any meaningful error message. Let's see how exception handling can help.
The following code snippet shows our code for reading a line of text from a data file. Note the use the try / catch keywords. This indicates that code within this block can throw an exception, and how we will deal it.
String line;
try
{
// This line throws an IOException if file not present
FileInputStream fin = new FileInputStream ("config.ini");
// Create a data input stream for reading a line of text
DataInputStream din = new DataInputStream( fin );
// Read line of text
line = din.readLine();
}
catch (IOException ioe)
{
// Exit gracefully with an error message
System.err.println
("An error occurred while reading config file");
System.exit(0);
}
Exception handling also has other benefits. In the past, programmers would check the return value for a null object, or a special numerical code that indicated failure. But, programmers being human, this value wouldn't always be checked. This lead to strange errors at run-time, and no meaningful error messages. When an exception is specified in the throws clause of an object method, it must be caught, or the compiler will generate an error message. This forces programmers to always provide some form of catch statement (though many choose to leave their catch statement blank).
Finally, exception handling can also make code more legible. Its easy to see where error conditions are being handled, and which error conditions are explicitly being looked at. This also separates programming code for "normal" situations from that of handler code for unusual events. In small applications, the advantages of this are not noticeable, but when debugging large and complex systems, it helps to reduce complexity and track down problems.
www.referjava.com
That's the theory of exception handling. Let's look at a practical example. Suppose my application had to read some data from a file. Most times, it will be able to read the data, and continue on without any problems - but what would happen if the file didn't exist? Our program might crash, without reporting any meaningful error message. Let's see how exception handling can help.
The following code snippet shows our code for reading a line of text from a data file. Note the use the try / catch keywords. This indicates that code within this block can throw an exception, and how we will deal it.
String line;
try
{
// This line throws an IOException if file not present
FileInputStream fin = new FileInputStream ("config.ini");
// Create a data input stream for reading a line of text
DataInputStream din = new DataInputStream( fin );
// Read line of text
line = din.readLine();
}
catch (IOException ioe)
{
// Exit gracefully with an error message
System.err.println
("An error occurred while reading config file");
System.exit(0);
}
Exception handling also has other benefits. In the past, programmers would check the return value for a null object, or a special numerical code that indicated failure. But, programmers being human, this value wouldn't always be checked. This lead to strange errors at run-time, and no meaningful error messages. When an exception is specified in the throws clause of an object method, it must be caught, or the compiler will generate an error message. This forces programmers to always provide some form of catch statement (though many choose to leave their catch statement blank).
Finally, exception handling can also make code more legible. Its easy to see where error conditions are being handled, and which error conditions are explicitly being looked at. This also separates programming code for "normal" situations from that of handler code for unusual events. In small applications, the advantages of this are not noticeable, but when debugging large and complex systems, it helps to reduce complexity and track down problems.
www.referjava.com
How can I change the gray background of an applet?
Applets use a default background of gray, which isn't very visually appealing, and very infrequently matches the background of the web page on which it is loaded. So unless you repaint the background yourself in the paint() method of your applet, you'll want to change its background as soon as the applet loads.
The best place to do it will be in your init() method. This means the applet will change color once it has finished loading. To change background color, you need to invoke the setBackground(Color) method. It accepts as a parameter any valid Color.
public void init()
{
setBackground ( Color.black );
}
www.referjava.com
The best place to do it will be in your init() method. This means the applet will change color once it has finished loading. To change background color, you need to invoke the setBackground(Color) method. It accepts as a parameter any valid Color.
public void init()
{
setBackground ( Color.black );
}
www.referjava.com
What does certification involve?
Passing the Sun Certified Java Programmer exam involves answering a series of multiple choice questions. Sound easy enough? There's a little more to it though - you must select ALL the right answers, without missing any or adding extra ones. Often the difference between one answer and another is subtle, and it requires a good understanding of the language and the base Java APIs. There's no reference material allowed, and to make it even tougher, a score of 70% or over is required to pass.
The second level of certification involves an additional programming task. You'll be given specifications, and have to implement the system (involving actual coding). This involves a more extensive coverage of the Java APIs, but there's often more than one way to solve a problem.
www.referjava.com
The second level of certification involves an additional programming task. You'll be given specifications, and have to implement the system (involving actual coding). This involves a more extensive coverage of the Java APIs, but there's often more than one way to solve a problem.
www.referjava.com
What are the Java Certification exams?
Industry certification helps to distinguish skilled software developers from the pack, and to give employers an idea of the skill level of candidates. There's a certain amount of prestige associated with certification (ask anyone who has studied for, and passed a certification exam), and its usually a good measure of skills. Like other vendors (such as Microsoft), Sun Microsystems offers certification for for its flagship - the Java language. This certification is suited to commercial Java programmers and developers.
There are two levels of Java certification available currently, and there are plans to expand into three levels in the future (in conjunction with Netscape and other vendors). Currently, Sun offers the following :-
Sun Certified Java Programmer for JDK1.05, JDK1.5 & Java 5
Sun Certified Java Developer for JDK1.04, JDK1.4 & Java 4
www.referjava.com
There are two levels of Java certification available currently, and there are plans to expand into three levels in the future (in conjunction with Netscape and other vendors). Currently, Sun offers the following :-
Sun Certified Java Programmer for JDK1.05, JDK1.5 & Java 5
Sun Certified Java Developer for JDK1.04, JDK1.4 & Java 4
www.referjava.com
Subscribe to:
Posts (Atom)