Q: What is difference between: String My = "Test"; and String My = new String ("My"); ? Answer: Because the compiler automatically creates a new String object for every literal string it encounters, you can use a literal string to initialize a String. String s = "Test"; The above construct is equivalent to, but more efficient than, this one, which ends up creating two Strings instead of one: String s = new String("Test"); The compiler creates the first string when it encounters the literal string "Test", and the second one when it encounters new String. source: http://java.sun.com/docs/books/tutorial/java/data/stringsAndJavac.html Advice: If you are C/C++ programmer be careful with shortcut assignment operator "+=" in Java when you work with Strings! Why: The shortcut assignment operator += when used with Strings may confuse C and C++ programmers at first. Recall that a += b is equivalent to a = a + b. Let's look at two code file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (1 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part samples written in C++ and the Java programming language: //C++ code string* s1 = new string("hello"); string* s2 = s1; (*s1) += " world"; cout<<*s1<<endl<<*s2<<endl; return 0; //s1 = s2 = "hello world" //Java programming language code String s1 = "hello"; String s2 = s1; s1 += " world"; System.out.println(s1 + "\n" + s2); //s1 = "hello world" and s2 = "hello" In the C++ example, the strings s1 and s2 print the same result because they both point to the same address. In the Java programming language, Strings can't be modified, so the + operator must create a new String when "world" is appended to s1. source: http://java.sun.com/docs/books/tutorial/java/data/stringsAndJavac.html Q: Why the String does not have a capacity method? Answer: The String class doesn't have a capacity method, because a string cannot be changed. Q: When do I use String and when StringBuffer? Answer: The Java platform provides two classes: String and StringBuffer that store and manipulate strings-character data consisting of more than one character. The String class provides for strings whose value will not change. For example, if you write a method that requires string data and the method is not going to modify the string in any way, pass a String object into the method. The StringBuffer class provides for strings that will be modified; you use string buffers when you know that the value of the character data will change. You typically use string buffers for constructing character data dynamically: for example, when reading text data from a file. Because strings are constants, they are more efficient to use than are string buffers and can be shared. So it's important to use strings when you can. source: http://java.sun.com/docs/books/tutorial/java/data/whytwo.html Q: Why do I get different results here: System.out.println(2 + 2 + "=result"); System.out.println("result=" + 2 + 2); file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (2 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part In the first case I get: 4=result and in the second one: result=22 Answer: Because Java uses "left to right" principle. In the first case Java sums up two integers: 2+2=4 and then converts it to a string: 4=result In the second case Java takes string "result" then converts 2 to a string, concatenates them together. Then this process repeats with next number... Finally we get: result=22 Q: I need to detect whether a user enters a capitalized letter. I'm using the following code so far: // The keyboard BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = null; do{ try { input = br.readLine(); } catch (IOException ioe) { System.out.println("IO error"); System.exit(1); } //check input for uppercase characters (ignore the //fact that it might be numbers, assume valid input) ... I have searched the API, in particular, the string function for a way to do this but no luck. Answer: Try this: if(input.equals(input.toLowerCase)) { // no upper case letters // (untested code) } Additionally, if you need to test individual characters, char comparisons are perfectly fine. char blah = 'a'; if(blah >= 'A' && blah <= 'Z'){} // if the char is uppercase then... -- Jeff P.S If you want that code works for all languages, not only English use please do it like this: if (Character.isUpperCase(blah)) { ... } file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (3 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part -- Dr. Harald M. Muller Senior Consultant - OO, Java, SW-Architecture Cortex Brainware, WWW: http://www.cortex-brainware.de Q: An idea for validating the phone number field on a form.., Does anyone have an idea for validating the phone number field on a form. I am looking for something that will basically check this input mask *111*111*1111* Where the 1's are number's and the *'s are either - . spaces, or any other character like (). Please advise. Answer 1: You could use a regular expression package. For example, Jakarta ORO: http://jakarta.apache.org/oro/ Answer 2: i'm thinking regular expressions. See: http://www.cacas.org/java/gnu/regexp/ http://www.crocodile.org/~sts/Rex/ Q: Could someone show me a basic File I/O example? I just can't figure out streams. I'm willing to accept basic mockery in exchange... Could someone show me a basic File I/O example? I just can't figure out streams. I'm willing to accept basic mockery in exchange... Answer: import java.io.*; public class FileIO { public static void main(String[] args) throws Exception { if(args.length!=1){ System.out.println("Invalid parameters!!!"); System.exit(0); } File fl = new File(args[0]); FileReader fileReader = new FileReader(fl); BufferedReader bufferedReader = new BufferedReader(fileReader); String currentLine; while( (currentLine = bufferedReader.readLine()) != null ){ System.out.println(currentLine); } } } file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (4 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part Q: Does anybody know a convenient way to pause the dos program execution until user hits enter? In C I used getc. Does Java have an equivalent of "cin>>"? Answer: try { System.in.read() } catch (Exception e) { } Have fun! -- Bary Q: I've got a (simple) menu on a new application and am trying to put in the works behind the cut, copy & paste menu options - does anyone know how I can do this - what's the code or can you point me in the right direction? Answer: Look at java.awt.datatransfer package. It contains much of the tools necessary to implement cut. copy, paste. Can anyone please explain clearly how BufferedReader works and how to use it to get input from a keyboard? Q: How do I encode the value of a variable of type long (or int) into bytes? And how do I restore the original value of the long (or int) variable back How do I encode the value of a variable of type long (or int) into bytes such that the number of bytes used will always be the same, say 4 bytes? Answer: int in; ... byte b1 = (byte)(in & 0xff); byte b2 = (byte)((in >> 8) & 0xff); byte b3 = (byte)((in >> 16) & 0xff); byte b4 = (byte)(in >>> 24); : How do I restore the original value of the long (or int) variable back : from the bytes that i have just created then? Answer: int in = (b1 & 0xff) | ((b2 << 8) & 0xff00) | ((b3 << 24) >>> 8) | (b4 << 24); by Tim Tyler Q: I would like to know if there was a method that replace a substring (in a string) by an file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (5 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part other one. For ex: in the string: "toto=yes, tata=no", I want to replace "yes" by "no", and "no" by "N/A", Answer: There isn't a method to do it, since Strings are immutable, so you can't directly replace elements. (If you're doing a lot of string manipulation, shift the string to a StringBuffer.) However, it's not hard to create a new string that performs the replacement, along the lines of: int p = source.indexOf (target); String result = source.substring (0, p) + replacement + source.substring (p + target.length ()) In your example, beware of the order of replacement, since the second no will replace the first one. Matt Humphrey Q: I have a String containing multiple logical lines separated with "\r\n". I want to tokenize that string to individual lines. However, StringTokenizer doesn't work the way I would like it to work with "empty" lines. Example: String str = "first line\r\n" + "\r\n" + "third line\r\n"); I would like StringTokenizer to tokenize the string to the following three strings: "first line" "" "third line". I have set "\r\n" to delim, but StringTokenizer.nextToken doesn't seem to return the second, empty line. I also tried setting the returnDelims in StringTokenizer constructor to false, but then nextToken returns the "\r" and "\n" as seperate strings. It should return "", in order to make rest of my code to work OK. How should I solve this problem? Answer: There are several ways to get around this problem with utilities that I have written. The easiest way is to use a split function. String[] stuff = StringHelper.split("first\r\n\r\nthird", "\r\n"); stuff will be a string array with 3 elements, including the empty line in the middle. You can get StringHelper from: http://ostermiller.org/utils/StringHelper.html The second way is to use a StringTokenizer that returns empty tokens. file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (6 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part I have written a StringTokenizer that does such at: http://ostermiller.org/utils/StringTokenizer.html The only problem that you would run into is that StringTokenizer is a character tokenizer. So you would get extra empty tokens in between the \r and the \n. -- Stephen Q: I'm looking for a solution for parsing a String object. I need to parse a math expression and calculate it. At first, I thought of StringTokenizer, but when I looked through the API document, multiple delimiters might not be allowed. What is the best way to do this operation? Answer: multiple delimiters _are_ allowed. StringTokenizer st = new StringTokenizer(your_string, "+-/* ") and so on. Q: Are there any public domain matrix/linear algebra java packages out there? I'm mainly interested in solving systems of equations and finding matrix inverses. Answer: http://math.nist.gov/javanumerics/ The JavaNumerics page provides a focal point for information on numerical computing in Java. Q: I am using the sinusoidal wave calculated by feeding a in function sin(a) values from zero to pi (3.142).I am wondering how is the Math.sin implemented in respect to effective calculating in practice: Should I prepare a table with pre-calculated sine-values, or does java already have that table prepared for me? If I 'pre-calculate' that table once, it'll make about 1024 sin-calculations plus all the lookups from the table (r, g, b + a values (4 * 255 values *4 transitions)). Otherwise it’s just the Math.sin-function call for the aforementioned RGB-values. Answer: Most likely the JVM utilizes the floating point unit (FPU) of your microprocessor. The FPU is hard to beat these days in software. You could try a Taylor sequence, and Chebyshev approximations, but I doubt that you will be faster. On Intel, it is a hardware instruction. It is implemented internally as a polynomial approximation. You are best to treat it as a black box. Profile it. If speed is a problem, pre-calculating a table is an option. It's the old trade-off memory vs. performance. -- Thomas Weidenfeller Q: Does anyone know how to write multi-line string in Java? file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (7 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part Answer: Something like this: String a = "This is a multiline string."; It is really pain to print HTML or XML from the Java program. Perl offer something like this: print <<END_HTML; <html> <body> <h1>this is html.</h1> </body> </html> END_HTML; Answer: Try this: String a = "This is a\nmultiline string" A "\n" stands for a line feed. Take a look at the Java language specification (downloadable on Sun's site), it has a section about strings. Answer2: You mean like this? String a = "<html>" + " <body>" + " <h1>this is html.</h1>" + " </body>" + "</html>"; I cannot find the method to convert a binary number to an int. I used Integer.toBinaryString to get a decimal to binary but I don't know how to to convert it back. Answer: Try using Integer.parseInt(String s, int radix) with radix = 2 that should do your job. Q: How do I launch a native Document by its Associated MIME Type? For example, I would like to ask the 'operating system' what application is associated with .DOC and then launch it. Answer: On WinNt, String docName = "c:\\someyourdir\\nameofdoc.doc"; Runtime.getRuntime().exec("cmd.exe /c "+docName); Q: How do I indicate Unicode characters that cannot be represented in ASCII, such as ö? Answer: from "Java Tutorial file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (8 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part (http://java.sun.com/docs/books/tutorial/i18n/text/convertintro.html) "To indicate Unicode characters that cannot be represented in ASCII, such as o, we used the \uXXXX escape sequence. Each X in the escape sequence is a hexadecimal digit. The following example shows how to indicate the o character with an escape sequence: String str = "\u00F6"; char c = '\u00F6'; Character letter = new Character ('\u00F6'); " Q: When I tried to read one string representing boolean value and convert it into boolean it didn't work. Finally I found that Java API has a bug! I wrote the program that uses redaing ini file settings for initialization. All settings in a file are strings. I am converting them to appropriate type during reading. When I tried to read one string representing boolean value and convert it into boolean it didn't work. Finally I found that Java API has a bag: boolean x = true; getBoolean(x); will show false!!!! Why Java has method that doesn't work? Is it bug in Java or I am stupid? Answer: neither statement is true! It is not a bug and you are Ok! Just please read more carefully JavaDoc next time. It is written there for getBoolean (): "Returns is true if and only if the system property named by the argument exists and is equal to the string "true". (Beginning with Java 1.0.2, the test of this string is case insensitive.) A system property is accessible through getProperty, a method defined by the System class." So you didn't use this method properly... Use instead: public static Boolean valueOf(String s) This method returns the boolean value represented by the specified String. A new Boolean object is constructed. This Boolean contains the value true if the string argument is not null and is equal, ignoring case, to the string "true". example: boolean x= true; (Boolean.valueOf(x)).booleanValue() gives you proper boolean (not Boolean!) value Q: Is there any Java API allowing creating easily PDF files (Adobe Acrobat type) including images? file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (9 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part Answer: No, just text Etymon™ PJ is a developer toolkit for parsing, modifying, and creating PDF documents. http://www.etymon.com/pj/index.html Q: I'm working on a java project and looking for a better API that can generate PDF, work with Excel, Word documents... Where can I find it? Answer: iTest This library contains classes that generate documents in the Portable Document Format(PDF) and/or HTML XML->PDF FOP is the world's first print formatter driven by XSL formatting objects. It is a Java application that reads a formatting object tree and then turns it into a PDF document. The formatting object tree, can be in the form of an XML document (output by an XSLT engine like XT or Xalan) or can be passed in memory as a DOM Document or (in the case of XT) SAX events. JPageLayout from Sitraka JClass PageLayout provides sophisticated and easy-to-use APIs for adding text, images, and tables to any document. Output directly to the Java AWT Printer, Acrobat PDF, HTML, PostScript Level 2, or PCL 5. Customize almost every aspect of your report styles and print output for professional results. Q: How can I extract text from PDF file? Answer: I have used the Acrobat Viewer Bean (http://www.adobe.com/products/acrviewer/main.html) to extract text from PDFs. This bean is quite buggy but it was OK for this task. One drawback is that it depends on AWT even if you don't do anything GUIish with it, so if you want to use it on a Server with no X-Windows running you'll have to install the Pure Java AWT to get things running. -- Patrick Q: I'm looking for a rich text editor that I can embed within a web page, and allow users to enter rich text that I can in turn store as HTML. I've seen similar applets through web based e-mail clients. I'd appreciate it if someone could point me in the right direction! Answer: Try Swing, by Robinson, Manning Publication. You could probably adjust the code to fit into the applet style. It is here http://javafaq.nu/java/free-swing-book/free-swing-book-chapter20.shtml file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (10 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O I part John Q: I want to have a while loop execute for a maximum of n seconds or until it receives something in an input stream. How would I do this? Answer: I think you could do it this way: ******************************************** InputStream Input=null; int n=10; /*Number of seconds to wait*/ /*initialize you input stream*/ ... /*Now start you while loop*/ long lStart = (new Date()).getTime(); long lCurrent = (new Date()).getTime(); while((lCurrent-lStart < n*1000) && (Input.available()==0)){ Thread.currentThread.sleep(100); /* This will give JVM time to other threads */ lCurrent = (new Date()).getTime(); } ******************************************** You could simply count number of steps inside the loop keeping in mind that each step takes 100ms but I think using dates would be a bit more precise method. Alex Shlega (c)1999, 2000, 2001, 2002, 2003 JavaFAQ.nu. All rights reserved worldwide. This document can not be changed, either in whole or in part without the express written permission of the publisher. All questions please file:///C|/330_new/330_new/stings_text__date_numbers_io-I.htm (11 of 11) [2003-07-22 22:08:07] String, text, numbers, I/O II part Receive our newsletter with new tips! More than 13,500 subscribers (by July 2003) can not be wrong! They read our tips every week! To subscribe to "The Java FAQ Daily Tips" weekly edition newsletter send email with "subscribe" word in the header and the body (write just subscribe without ""!!!) to: javafaqtips-request@javafaq.nu or on the web: http://www.javafaq.nu/plm2html/my_subscription.shtml String, text, numbers, I/O II part Q: How do I parse it to date and make a date difference?? How many days in between the String from and to? I am always confusing with date and time. I have 2 String, from and to String from = "01.01.2001" //dd.MM.yyyy String to = "01.03.2001" //dd.MM.yyyy How do I parse it to date and make a date difference?? How many days in between the String from and to? Answer: import java.text.SimpleDateFormat; import java.util.Date; public class Tmp { public static void main( String argv[] ) throws Exception { long DAY = 24L * 60L * 60L * 1000L; SimpleDateFormat df = new SimpleDateFormat( "MM.dd.yyyy" ); Date d1 = df.parse( "01.01.2001" ); Date d2 = df.parse( "01.03.2001" ); System.out.println( "The number days between:" ); System.out.println( d1 ); System.out.println( "and:" ); System.out.println( d2 ); file:///C|/330_new/330_new/stings_text__date_numbers_io-II.htm (1 of 10) [2003-07-22 22:08:09] String, text, numbers, I/O II part System.out.println( "is: " + (( d2.getTime() - d1.getTime() ) / DAY )); } } But the calculation of the difference in times may not be suitable due to timezone issues and such. I believe there must be a better way? Michael B. Allen Q: I am looking for some code to compare current date and a date entered by user. I want to return years between dates. I can't find a method to do this with. Answer: try GregorianCalendar class which is found in java.util.* Calendar fdate= new GregorianCalendar(1999,1,25); Calendar ldate= new GregorianCalendar(2000,1,25); then use get methods and compare fyear= fdate.get(Calendar.YEAR); lyear= ldate.get(Calendar.YEAR); Q: If I have a string with a hex value (e.g. "7FFFFF"), is there a way to obtain an int value from this (e.g. 8388607)? Answer: See Integer.parseInt (String s, int radix). The radix for a hexadecimal number is 16. Q: How do I convert this double to the following String: double d = 19.969332079021637; String s = "19.97"; Answer: double d = 19.969332079021637; DecimalFormat df = new DecimalFormat("##,###.##"); String s = df.format(d); or Use NumberFormat in the java.text package ... double d = 19.969332079021637 NumberFormat format = NumberFormat.getInstance(); format.setMaximumFractionDigits(2); format.setMinimumFractionDigits(2); String s = format.format(d); // s="19.97" Q: How do I convert a String to an integer. For example: String strSEQ = "SEQ7"; file:///C|/330_new/330_new/stings_text__date_numbers_io-II.htm (2 of 10) [2003-07-22 22:08:09] String, text, numbers, I/O II part How do I pull "7" from the string and convert it to an integer? Answer: I'd do something like this: StringBuffer digits = new StringBuffer(); char c; for (int i=0; i<strSEQ.length(); i++) { c = strSEQ.charAt(i); if (Character.isDigit(c)) digits.append(c); } int intValue = Integer.parseInt(digits.toString()); -- Michiel Q: How can I display other languages such as chinese, french, japanses etc. inside applet or frame? Answer: You have to install the approriate font, and add it to a font.properties file. Further information can be found here: http://forum.java.sun.com/read/16805306/q_CUP8NP-1rgAAYsA#LR http://java.sun.com/products/jdk/1.1/docs/guide/intl/index.html http://developer.java.sun.com/developer/qow/archive/65/index.html Q: I need to determine the current year, at runtime, in the form of a four digit number, preferably in "int" form. How can I do this? Answer: Hey, what makes you think that the year is a four digit number? It won't always be, you know. That's the kind of sloppy thinking that got us into that whole y2k mess, and we all know what a huge issue THAT turned out to be! If you write your program assuming that the year is 4 digits, it will cease to function properly in less that 8000 years! Try not to have such a "short term" viewpoint. Here's the deprecated solution: int year = new java.util.Date().getYear() + 1900; This was deprecated because it is too convenient! We programmers often get paid per line of code, you know. Actually it was deprecated because it didn't have an implicit way to deal with time zones and it contains that silly Y2K problem. The SUPERIOR way to do is as follows: file:///C|/330_new/330_new/stings_text__date_numbers_io-II.htm (3 of 10) [2003-07-22 22:08:09] String, text, numbers, I/O II part java.util.Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); -- Marshall Q: I have a string like 23,N/A,,N/A,87, then I used the StringTokenizer t = new StringTokenizer( s, ","); to get the token. I seems I only got 4 tokens back, not 5. How doesStringTokenizer treat the ,, in this case? I had tried String.equals("") or String.equals(null) to pick the EMPTY string between ,, , it did not work. Anyone can give a clue? Answer: There is another constructor, with a third parameter. Using that one, you can get the`boundary markers, such as the comma, returned to you as well. That would allow you to handle your empty strings. -- Michele. Q: How to know in Java if a given font has or not a fixed width ? For example to list all the "fixed width" fonts that are available on the user's platform. Answer: I'm not sure whether there's an easier solution... if there is none, you might try to get the FontMetrics objects from a specific Font. Then iterate over every character and call charWidth(char ch) on each. It should return the same value for each character if it's monospaced, different values for each one otherwise. This might be a little "hacky", but if you really need an idea... Karsten Q: I want to create a Date object by just specifying the Year, Month and Day. e.g. the user can enter 1998 as Year, 11 as Month of Nov, 15 as the day. With these three information, how can i create a Date object (or similar object that stores the data)? Answer: The correct way to do this is something like this: Calendar cal = Calendar.getInstance(); cal.set(1998, Calendar.December, 15); Date date = cal.getTime(); Q: I want to send Image through network. I made OutputStream to send Image... file:///C|/330_new/330_new/stings_text__date_numbers_io-II.htm (4 of 10) [2003-07-22 22:08:09] String, text, numbers, I/O II part OutputStream out = socket.getOutputStream(); but I can't send Image directly. How can I send Image? Answer: Unfortunately, the java.awt.Image class is abstract and is not serializable, otherwise this would be easy. From the Java docs: "The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner." Consider using the Image.getSource method, getting the producer, getting the bytes, then send [width][height][bytes...]. -- Mark Watson, Java consulting, Open Source and Content: www.markwatson.com Commercial software products: www.knowledgebooks.com Q: I want to get the code behind an HTML page. Answer: URL url = new URL("http://www.sun.com"); BufferedReader reader; reader = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = reader.readLine())!=null){ // process str } Q: I am wondering if JDK supports to open a file in the exclusive mode? Answer: No, file locking is not supported in current VMs. You can implement lockfiles, however, using the File.createNewFile() method. Since JDK 1.3: "Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the ' existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file. This method, in combination with the deleteOnExit() method, can therefore serve as the basis for a simple but reliable cooperative file-locking protocol." Q: Does anyone know how I can get around the fact that a Message obj (from the JavaMail API) is not serializable? I would like to save a message obj to the hd, then read the file (is 'file' the wrong word here?) back to my e-mail client and read it as a Message obj. Answer: The obvious answer is: implement serializable yourself in a subclass! But! That won't work. The serialization mechanism will throw an exception at runtime. Even if it didn't, the class may be nonserializable for a good reason, for example it might contain a file:///C|/330_new/330_new/stings_text__date_numbers_io-II.htm (5 of 10) [2003-07-22 22:08:09] String, text, numbers, I/O II part socket, which can't be reinitialized from a stream. What you need is a subclass that implements the Externalizable interface, and then your own code that saves as serializable objects those attributes of the object that you need to reconstitute it later. I'm not familiar with this particular object, but I imagine it has several get() methods that return serializable objects like Strings or ints. What you have to do is recover those objects and put them into the output stream yourself, and reverse the process on unserialization. The fields that are not serializable you ignore. You have to provide a no-argument constructor that reconstructs anything you aren't going to serialize (for example, opening a new socket). Read about the Externalizable interface for more details. -- Frank LaRosa Q: I wrote a little Java Tool that imports a 10 MB Text file. My Problem is that this text file has no line breaks, that means the whole file contains one record, which are all records put to one together. With the readLine () method it takes more than an hour to complete my instruction. How can I accelerate this process, I only need to insert a break line after each "record" (after x characters -> "\n"). Answer: If you will tell us what you are trying to accomplish, we may be able to offer a suggestion. If you are trying to reformat the file to have line breaks, you will have to read the entire file once and write out a new file with the line breaks. It seems obvious that the original file was meant to be random-accessed and has fixed-length records, in which case it is just fine as it is -- if it is read appropriately. -- Paul Lutus www.arachnoid.com Q: How can you tell if an integer is odd or even? I know an even number is divisible by 2 but I'm thinking then how can I detect if a resulting number after dividing 2 ints has a remainder? Answer: Basically the method is simple, if a variable contains an odd number I want to return the value 'zero', and on the other hand if the variable contains an even number I want to return the value 'one'. Check out the % (modulus) operator, it computes the remainder. public int modMethod(int div){ if(div%2==0){ return 1; } else{ file:///C|/330_new/330_new/stings_text__date_numbers_io-II.htm (6 of 10) [2003-07-22 22:08:09] String, text, numbers, I/O II part return 0; } } Q: I'm looking for an algorithm that would compress a large integer down to a not-that-long string. Actually, it's not an integer, but a series of integers that could have hundreds of digits in total. Answer: Use classes ZipInputStream and ZipOutputStream. They are meant for exactly this purpose. And they meet the requirement of portability between languages (because ZIP compression is ubiquitous). -- Paul Q: How can I round a number to specified precision? I have a double field that I would like to round to 2 places of precision, however, it seems like the documentation on the round function only rounds to closest integers. So that I would not be able say .3658585859 = .37 as I would like. Answer: can you scale the number up and then down again when you are finished? e.g. 0.3658585859 * 100 = 36.58585859 round(36.58585859) = 37 37 / 100 = 0.37 Q: I understand that bitwise operations change the 0/1 bits of a number. Question is why? I suppose it's interesting that you can manipulate numbers this way, but I can't think of a practical use for doing that. Can anyone help me understand when are bitwise operations used and why you would use them? Answer: Bitwise manipulation is often used where memory consumption is critical, and a piece of information may be encoded in less that one byte, for instance. In communication software and protocols, information may be interpreted as a stream of bits where the information is encoded at the bit-level, and you use bitwise manipulation to extract the pieces of information encoded in the bytes. There are other situations where bitwise manipulation is used, as well. by Greger Ohlson Q: Why cannot I cast from double to java.lang.Object? I'm trying to build a vector, however, one of the objects that I'm passing to the vector is of type double. How do I cast the double as an object so that I may insert the value into a vector? Does this make sense? Here is the following snippet of code I was trying to use: file:///C|/330_new/330_new/stings_text__date_numbers_io-II.htm (7 of 10) [2003-07-22 22:08:09] String, text, numbers, I/O II part myVector.add (1, (Object)myDouble); Of course when I try to compile I get the following message: Invalid cast from double to java.lang.Object Could someone please explain why? I realize that Object is the mother of all objects and therefore ANY reference data type "is an" Object. So therefore I shouldn't have to cast the double, right? Help, I'm a beginner! Answer: A double is not a reference type, but a primitive one. Hence, it doesn't inherit from Object (or anything else, for that matter). To put primitives (byte, short, int, long, float, double, boolean, char) into something that requires an Object, use Java's wrapper classes. The wrapper classes are Double, Integer, Long, Boolean, etc., and are basically an object "wrapped" around a primitive type. You make a Double object by: Double d = new Double (myDouble); and to get the actual value back, double z = d.doubleValue(); It works the same way for all the rest of the primitive/wrapper pairs. by Trevor Hill Q: is there a mod (x, y) function that returns the remainder when x is divided by y? Something equivalent to fmod(x,y) in C? Answer: a = x%y; Q: I'm having trouble figuring out how to convert characters to their ASCII value in java. Is there a class like NumberFormat that will do it? Answer: I can't see any problem here: char ch = 'A'; // character 'A' int i = (int)ch; // ASCII value for 'A' (=>65) Yes. And just be aware that ASCII only runs from 0 through 127. Anything higher needs to be addressed differently, since Java is using Unicode values. Q: How to do "Press any key to continue"? I want to do it at Console. Answer: // ReadConsole.java import java.io.*; public class ReadConsole { file:///C|/330_new/330_new/stings_text__date_numbers_io-II.htm (8 of 10) [2003-07-22 22:08:09] String, text, numbers, I/O II part public static void main(String args[]) throws IOException { System.out.print("Press Enter to continue: "); System.in.read(); } } You cannot have "press any key" from the console, for various system-dependent reasons. You need to press Enter. -- Paul Lutus www.arachnoid.com Q: Just wondering how people generally convert BufferedOutputStream into a BufferedInputStream to be read from.... This seems really stupid, but I can't find a way to do it in the API.... Answer: if you want to just take what's coming in and send it out then do something like this BufferedInputStream in = new BufferedInputStream(some inputstream); BufferedOutputStream out = new BufferedOutputStream(some outputstream); int i = 0; while((i = in.read()) != -1){ out.write(i); } of course you will have to handle exceptions, but that should be the general way to do it. -- michael Q: I have heard that String concatenation operator + affects performance of program if it used much. Is it true? Answer: Yes, it affects your program performance if you do a lot of "+" operations with strings: A new StringBuffer must be created, then two arguments are added to it with append(), and the final result must be converted back with a toString(). Your time and space is wasted... In case if you are appending more than one String, try to use a StringBuffer directly.