Sect. 18) How do I manipulate bits in Java?
Java Programmer's FAQ - Part DUse bytes, shorts, chars, ints or longs if you need to manipulate no more than 64 bits at once. Use ~ for NOT, & for AND, | for OR, and ^ for XOR. Beware that the precedence for & | and ^ is not intuitive; they have lower precedence than == and !=, so you must write: if ((a & 1) == 1) rather than: if (a & 1 == 1) You can also shift bits with the <<, >> and >>> operators; >> is a signed shift and >>> is an unsigned shift.
Related QuestionsSect. 18) How can I get a globally unique ID in Java?
Java Programmer's FAQ - Part DThe only way in pure Java to create globally unique ids is to set up a server, accessible by all interested parties, which supplies the ids. There are classes in Java which may supply 'probably' unique ids, with varying levels of reliability --- but a dual processor machine with two JVMs running could easily generate duplicate ids. Note that a global server issuing a token (and periodic "are you still using it" messages) is a pretty good way to do cooperative file locking too.
Related QuestionsHow do I manipulate arrays of bits?
perlfaq4For example, this sets $vec to have bit N set if $ints[N] was set: $vec = ''; foreach(@ints) { vec($vec,$_,1) = 1 } Here's how, given a vector in $vec, you can get those bits into your @ints array: sub bitvec_to_list { my $vec = shift; my @ints; # Find null-byte density then select best algorithm if ($vec =~ tr/\0// / length $vec > 0.
Related QuestionsHow can I manipulate individual bits?
MiscellaneousBit manipulation is straightforward in C, and commonly done.
Related QuestionsSect. 18) What are the naming conventions?
Java Programmer's FAQ - Part DPackage names are guaranteed uniqueness by using the Internet domain name in reverse order: com.javasoft.jag - the "com" or "edu" (etc.) part used to be in upper case, but now lower case is the recommendation. Class and interface names are descriptive nouns, with the first letter of each word capitalized: PolarCoords. Interfaces are often called "something-able", e.g. "Observable", "Runnable", "Sortable".
Related QuestionsSect. 18) How can I set a system property?
Java Programmer's FAQ - Part DJDK 1.2 has System.setProperty( "property", "new value" ); Until then, you can get all the properties, and set just the one you want with code like this: System.getProperties().put("property", "new value" );
Related QuestionsSect. 20) What is the Java IFAQ?
Java Programmer's FAQ - Part DIt is the Java list of Infrequently Answered Questions, a FAQ maintained by Peter Norvig, author of the book "Artificial Intelligence - A Modern Approach". Take a look at the Java IFAQ at http://www.norvig.com/java-iaq.html There's a lot of good information in that document.
Related QuestionsSect. 18) How do I convert a String to an int?
Java Programmer's FAQ - Part DThere are several ways. The most straightforward is: String myString = numString.trim(); int i = Integer.parseInt(myString); long l = Long.parseLong(myString) or String myString = numString.trim(); i = Integer.parseInt(myString,myIntRadix); Note 1: There is a gotcha with parseInt - it will throw a NumberFormatException for String values in the range "80000000" to "ffffffff". You might expect it to interpret them as negative, but it does not. The values have to be "-80000000" .
Related QuestionsSect. 18) How do I convert an int to a string?
Java Programmer's FAQ - Part DTry any of these: String s = String.valueOf(i); or String s = Integer.toString(i); or String s = Integer.toString(i, radix); or // briefer but may result in extra object allocation. String s = "" + i; Note: There are similar classes for Double, Float, Long, etc.
Related QuestionsSect. 18) How do I execute a command in my program?
Java Programmer's FAQ - Part DUse Runtime.getRuntime().exec( myCommandString ) where myCommandString is something like "/full/pathname/command". An applet will need to be signed in order to allow this. If the pathname contains spaces, e.g. "c:\program files\windows\notepad", then enclose it in quotes within the quoted string. Or pre-tokenize them into elements of an array and call exec(String[] cmd) instead of exec(String cmd). From JDK1.3 there are two new overloaded Runtime.exec() methods.
Related QuestionsSect. 18) How can I clone using serialization?
Java Programmer's FAQ - Part DLook at the code below, submitted by expert programmer John Dumas. It uses serialization to write an object into a byte array, and reads it back to reconstitute a fresh copy. This is a clever hack! import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectOutputStream; import java.io.
Related QuestionsSect. 20) Are there any Java graphing tools?
Java Programmer's FAQ - Part DTake a look at GraphMaker -- a complete full-featured Java application for creating and searching graphs. It is available under GPL with source, and uses the latest Swing JFC features. Find it with a websearch.
Related QuestionsSect. 20) Where can I get icons for use with Java?
Java Programmer's FAQ - Part DPublic spirited programmer and Java supporter Dean S. Jones has created a collection of over 100 icons for use in Java technology freeware. They are available on the Java Lobby site at http://www.javalobby.org.
Related QuestionsSect. 20) Where can I find the Macintosh Java FAQ?
Java Programmer's FAQ - Part DA jolly little song that explains how to solve commonly-encountered problems in Java. The FAQ Melody by Antranig Basman. On the First Day of Christmas, my true-love said to me: Read the F-A-Q. On the Second Day of Christmas, my true-love said to me: My Image isn't drawing; Read the F-A-Q. On the Third Day of Christmas, my true-love said to me: My Pixels are not grabbing, My Image isn't drawing, Read the F-A-Q.
Related QuestionsSect. 18) Why can't I get String mutator methods to work?
Java Programmer's FAQ - Part DCode like this seems to show that the calls don't work! String s = " hello "; s.trim(); s.toUpperCase(); Note again that Strings are immutable. This means that once a String has been initialized, its contents won't change. In the code above, the method calls return a different String with the desired alterations. But this new String is not assigned to anything, so the results are discarded. To see the changes, assign the results of the method call to the original String or to another String.
Related QuestionsSect. 18) How do I print the hex value of an int?
Java Programmer's FAQ - Part DYou can print the hex equivalent of an int with: int i = 0xf1; System.out.println("i is hex " + Integer.toHexString(i) );
Related QuestionsSect. 18) How can you send a function pointer as an argument?
Java Programmer's FAQ - Part DSimple answer: use a "callback". Make the parameter an interface and pass an argument instance that implements that interface. public interface CallShow { public void Show( ); } public class ShowOff implements CallShow { public void Show( ) { .... } public class ShowOff2 implements CallShow { public void Show( ) { .... } public class UseShow { CallShow savecallthis; UseShow( CallShow withthis ) { savecallthis = withthis; } void ReadyToShow( ) { savecallthis.
Related QuestionsSect. 18) How do I do I/O redirection using exec()?
Java Programmer's FAQ - Part DThis solution works on Unix platforms using either JDK 1.0.2, or JDK 1.1. The trick is to use an array of Strings for the command line: String[] command = {"/bin/sh", "-c", "/bin/ls > out.dat"}; If you don't do this, and simply use a single string, the shell will see the -c and /bin/ls and ignore everything else after that. It only expects a single argument after the -c. import java.io.*; import java.util.
Related QuestionsSect. 18) So why can't I exec common DOS commands this way (as in 18.8)?
Java Programmer's FAQ - Part DThe reason is that many of the DOS commands are not individual programs, but merely "functions" of command.com. There is no DIR.EXE or COPY.EXE for example. Instead, one executes the command processor (shell) explicitly with a request to perform the built-in command, like so: Runtime.getRuntime().exec("command.com /c dir") for example. On NT, the command interpreter is "cmd.exe", so the statement would be Runtime.getRuntime().
Related QuestionsSect. 18) OK, how do I read the output of a command?
Java Programmer's FAQ - Part Dabove (18.8, 18.9), adjusted like this: BufferedReader pOut= new BufferedReader( new InputStreamReader(p.getInputStream())); try { String s = pOut.readLine(); while (s != null) { System.out.println(s); s = pOut.readLine(); } } catch (IOException e) { } Another possibility is to read chunks of whatever length as they come in: ... p = r.exec(cmd); InputStream is = p.getInputStream(); int len; byte buf[] = new byte[1000]; try { while( (len = is.
Related QuestionsSect. 18) What is the point of creating the temporary reference to this.layoutMgr?
Java Programmer's FAQ - Part DThis code is from the 1.0 AWT, and the programmer was probably pretty skilled. public synchronized void layout() { LayoutManager layoutMgr = this.layoutMgr; if (layoutMgr != null) { layoutMgr.layoutContainer(this); } } The code makes a local copy of a global variable for one or both of two reasons. The first reason is that accessing local variables can be faster than accessing (non final) member variables. It's good for loops or where there are many references in the source.
Related QuestionsSect. 18) What is the difference between "a & b" and "a && b" ?
Java Programmer's FAQ - Part Da & b" takes two boolean operands, or two integer operands. It always evaluates both operands. For booleans, it ANDs both operands together producing a boolean result. For integer types, it bitwise ANDs both operands together, producing a result that is the promoted type of the operands (i.e. long, or int). "|" is the corresponding bitwise OR operation. "^" is the corresponding bitwise XOR operation. a && b" is a "conditional AND" which only takes boolean operands.
Related QuestionsSect. 15) How can I write CGI programs in the Java programing language?
Java Programmer's FAQ - Part DCGI (the Common Gateway Interface for web servers) is an API for writing programs that use the web as its user interface. By far, the most popular language for this task is Perl, because of its powerful text handling capabilities, and excellent resources available for making the jobs of CGI programmers easier. CGI programs can be written in any language, including Java. Unfortunately, the interface between the web server and the CGI program uses environment variables extensively.
Related QuestionsSect. 16) What is the story with Java and viruses? What is the blackwidow virus?
Java Programmer's FAQ - Part DThe technology was designed with security in mind. The security features make it very difficult, probably impossible, to attach a virus (self-copying code) to a Java applet. There has never been a Java virus carried from system to system by applets. There has been mention of a "Java virus" called "BlackWidow" in the media (it was mentioned in Unigram in late 1996, and obliquely on the RISKS newsletter in February 1997).
Related QuestionsSect. 17) Does Java have the equivalent of "const" arguments in C and C++?
Java Programmer's FAQ - Part DJava 1.1 adds the ability to use the "final" keyword to make arguments constant. When used to qualify a reference type, however, this keyword indicates that the reference is constant, not that the object or array referred to is constant. For example, the following Java code: void foo(final MyClass c, final int a[]) { c.
Related QuestionsSect. 20) Will Java ever be fast enough for games like Quake?
Java Programmer's FAQ - Part DPlease see the site http://hem.passagen.se/carebear/fraggame.htm which has the Frag Island game (a quake-style game) written in 100% Java. You play it as an applet, by browsing the above site. If you do it at work, watch out -- it's noisy!
Related QuestionsSect. 20) Are there any commercial/shareware/free Java libraries?
Java Programmer's FAQ - Part DTake a look at the Java Collection Framework, a group of classes that are part of Java 1.2. These classes implement general-purpose data structures, and they will become widely used. Standard interfaces representing data structures of various kinds for you to implement. Since these are interfaces, you can use them in your code before you have implemented them. The standard interfaces are Collection, Set, List and Map, plus the more specialised SortedSet and SortedMap.
Related QuestionsSect. 20) Are there any URLs for regular expression handlers in Java?
Java Programmer's FAQ - Part DThere is one from ORO Inc. They dissolved as a corporation, but one of the founders maintains the software at http://www.quateams.com/oro. And don't forget to check out Lava -- a set of Java classes designed to support programmers who develop console-mode applications and/or C programmers who are converting to Java. The first release of Lava has printf and other text formatting, encryption, parsing and miscellaneous I/O. Lava can be downloaded from http://www.newbie.
Related QuestionsSect. 20) Where can I get Java programming language for my Palm Pilot PDA?
Java Programmer's FAQ - Part DIn the June 1999 JavaOne conference, Palm Pilot V's were available with a small JVM known as KJava installed on them. KJava was an early access release, and is expected to become generally available later in 1999. This is an astonishing piece of work as the Pilot has such a small memory footprint. There is a Java-PalmPilot Project called "jSyncManager" which allows PalmPilot synchronization and jConduit development in pure Java. See http://yaztromo.idirect.com/java-pilot.html.
Related QuestionsSect. 20) Are there any Java technology tools for PDF?
Java Programmer's FAQ - Part DPDF (Portable Document Format) is the text publishing format defined by Adobe. Acrobat is the technology to display and print PDF files. Adobe supplies the client (document reading) software for free. There is a PDF toolkit written in the Java programming language at http://www.etymon.com. Even better it is GPL'd. It is more a toolkit for programmers embedding PDF in their products, than an end-user technology though. It doesn't have a GUI for displaying PDF for example.
Related Questions