A question about string.trim()

I got a fragment of code as follows:
String s = "abcd ";
boolean a = (s.trim()=="abcd");
boolean b = (s =="abcd ");
Why a is false, b is true?

The reason why the below code has true assigned to be is quite easy to explain:
String s = "abcd";
String y = "abcd";
boolean b = (s == y);
...The String class has a "Pool" of strings. When you use String literals; the compiler automatically checks if it is in the String pool already and if it exists; a reference to that String is returned; if not a new entry in the pool is added and then you get a reference to that. This is only true for Stirng literals and String created using the intern() method.
If you compile this code you will see that the strings are not equal:
public static void main(String args[])
  String s = "abcd";
  String y = args[0];
  boolean b = (s == y);
  System.out.println(b);
}This is because the "abcd" is in the String pool when your program starts; but because the value "abcd" passed in (is not created in the pool automaticlaly). Therefor they are two different String objects.
This code block shows that you can add Strings to the pool. The intern() method checks to see if the String is in the pool already and if it is it will return you a reference to it; if not it will create one and then return it.
public static void main(String args[])
  String s = "abcd ";
  String y = args[0].intern();
  boolean b = (s == y);
  System.out.println(b);
}- Chris

Similar Messages

  • Question about string manipulation

    Hello, I am practicing with Java and trying to learn it, and have a quick question. I am trying to get the count on a string of numbers for after a decimal point. the numbers are generated as the result of a math, so I can't use index, since the location of the decimal changes based on the number imputed. I want to figure this out on my own, but have hit a wall here, i've spent the past few hours trying every string command I can think of, and haven't figured it out yet, anyone mind pointing me in the right direction for which string to use? Thanks in advance for any help you can provide!

    Is this what you want?
    public class Fallen{
      public static void main(String[] args){
        String number = "123.45678";
        String frac = number.substring(number.indexOf('.') + 1);
        System.out.println(frac + " length=" + frac.length());
        frac = number.replaceFirst("^.+\\.", "");
        System.out.println(frac + " length=" + frac.length());
    }

  • Question about ssd Trim in boot camp.

    we all know that mac osx wont support trim function for ssd. Now if i installed win7 on boot camp. can i use boot camp to use trim?

    Why not post in the Boot Camp forum? That's where you are more likely to find your answer.
    http://discussions.apple.com/category.jspa?categoryID=237

  • Question about String constant pool

    Is there is any function available to find how many Sring literal in String Constant pool

    Well, there's stuff like BCEL.
    But it may not do what you want.
    Why do you want to find out what's in the constant pool?

  • Easy question about String

    Hi!
    I have a string in a variable. how can I check if the String is composed just by numbers?
    thank you very much!

    Use the following method from Integer API
    parseInt
    public static int parseInt(String s)
                        throws NumberFormatExceptionParses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002d') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.If it throws NumberFormatException its alphanumeric else its numeric. You would however have to remove any spaces or commas etc. since they are not mumeric either

  • A question about String.hashCode()

    Why the implementation of hashCode() for String class using 31 as a base?

    Why the implementation of hashCode() for String class
    using 31 as a base?I think it's a magic number. It has been found to produce a reasonably even distribution over the int range.

  • Question about string constant in Hex display format

    how to get a plus of 2 string constant which is display in Hex display like attahced, for example I have string "28" and "5D" in Labview which has been in Hex format, the plus of this 2 string should be "85" in Hex. pls help on this, thanks
    Attachments:
    1.jpg ‏21 KB

    This'll work, too.  I'm afraid of casting types...
    Jm
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice
    Attachments:
    hex.png ‏2 KB
    hex.vi ‏7 KB

  • Question about String initialization~~~

    String a = "sss";
    String b = "sss";
    the result of a==b is true .
    String a = new String("sss");
    String b = new String("sss");
    however , the result of a==b is false .
    why? the operator "==" compares WHAT of two object ??
    thanks , ;[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    == compare the reference of the object
    String s1 = new String("sss") creates a new String object at location xxxxxx, while
    String s2 = new String("sss") creates a new String object at location yyyyy.
    therefor xxxxxxx != yyyyyyyy
    by location..the memory address
    String s3 = "sss"; // java create a new String object "sss" at location zzzzzzzz and assign the reference to s3
    String s4 = "sss"; // java assign the reference (location zzzzzzzz) to s4
    so s3 == s4....
    noticed only one String object is created...s3 and s4 holds the reference to the 1st String created..though it is not clearly shown in th ecode...it actually look something like this
    String temp = new String("sss");
    String s3 = temp;
    String s4 = temp;

  • Question about string array?

    Hello,
    When passing Stting arrays to a function, is there anyto test if the array is emply?
    void testFucntion(String[] test){
    }

    Or test the array is null.
    if (test == null || test.length == 0)

  • Another question about string!

    Hi,
    I want to return a function as true if all the characters in that string are hexDigit. false otherwise.
    & also another class should return as true if all the charaters are Digit. false otherwise i was using
    public boolean isDigit(String str)
    for (int i=0; I<str.length(); i++)
    if (str.charAt(i).isDigit)
    return true
    return false
    what's wrong with this code? what shall I use instead of this? can anyone Help please?

    The way you've written it, you'll be returning true as soon as the first digit in the string is found:
    // on first loop will check first char in string.
    if(str.charAt(i)isDigit)
    // first char in string is a digit so method returns true
    return true;
    [\code]
    You could change it so that you will return false when non-numerical character is found. If none is found you will fall out the loop and return true.if(!str.charAt(i).isDigit)
    return false;
    return true;
    [\code]
    Don't know if there's a method for checking hexDigit. If not use something like:
    if (str.charAt(x).isDigit || str.charAt(x) >='A' && str.charAt(x) <='F');
    [\code]

  • A question about string

    hello,
    String s1 = "123";
    String s2 = "123";The following codes, create two String objects or one object?
    Any ideas?
    Thanks.

    The compiler creates one string, and both variables get pointed at it.
    http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#101083

  • Question about String

    hi all,
    I am new to java
    I have one problem..
    that is I have one string like : 85WS98(or also: 67S, 1G3)
    from this String I want to only the
    85W98 = 85;
    67S = 67
    1G3 = 1
    I am using below code but its not working for : 85W98 and 1G3
    StringBuffer sb = new StringBuffer();
    for(int i = 0; i < str.length(); i++){
    char comp = str.charAt(i);
    if(Character.isDigit(comp)){
    sb.append(comp);
    String result = sb.toString();
    So if anyone knows please send the solution
    thanks

    So you want all the numeric chars before the first non-numeric char?
    Change this part of the code:
    if (Character.isDigit(comp)) {
      sb.append(comp);
    } else break; // break after first non-numeric char

  • Question about string in xdoxslt

    Hi,
    When using xdoxslt i want to set a variable to store many fields which means the variable is a concat of the fields and it seems that the '||' is not allowed in xdoxslt.
    I find a function append_to() and uses it as below
    <?xdoxslt:set_variable($_XDOCTX,'PeopleCnt',xdoxslt:append_to($_XDOCTX,xdoxslt:get_variable($_XDOCTX,'PeopleCnt'),'sdfs'))?>
    and the output of PeopleCnt is still the original value.
    Is there anything wrong i have taken for this function or is there anyting else i can do?
    Thanks!

    This'll work, too.  I'm afraid of casting types...
    Jm
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice
    Attachments:
    hex.png ‏2 KB
    hex.vi ‏7 KB

  • Questions on StringTokenizer, trim(), and parsing.

    im doing an assignment that requires parsing and havent had that much practice with parsing regular text from a file, ive been doing mostly parsing from a html. my question is if im parsing a line and i need 2 different types of information from it, should i just tokenize it twice or do it all at once, assuming the text format is always the same. for example
    String input= "this is a test[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]";if parsed correctly with StringTokenizer it would be 4 Strings(this is a test) and 10 ints for the countdown of numbers. now since the Strings doesnt have a delimiter such as a comma i can use the default delimiter which is the whitespace but then would that mean i would have to parse that same String twice since the numbers has "," has a delimiter? also should i worry about the whitespace that is separating the numbers after the comma? i did a small driver to test out the trim() using this and both outputs were the same. this may be a dumb question but if i call the trim() it eliminates the white space right, therefore i can just set "," as my delimiter, question is why is my output for both Strings the same?
        String input= "this is a test[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]";
        String trimmed = test.trim();
        System.out.println(input);
        System.out.println("\n" + trimmed);SORRY if its confusing im trying not to reveal too much of the hw assignment and just get hints on parsing this efficiently. Thanks in advance

    similar example on how to parse out the numbers with
    "," as a delimiter. thanks in advanceThe following is a simple recursive descent parser to parse a comma delimited list of numbers "(1, 2, 3, 5, 6)". The grammar parser by this code is
    START -> LPAREN LIST RPAREN
    LIST -> NUMBER TAIL
    TAIL -> COMMA LIST | LambdaThe nonterminals NUMBER, LPAREN, RPAREN, and COMMA are defined by the regular expressions in the code.
    Lexical analysis is done by the function advanceToken(). It stores the next token in the variable "lookahead" for further processing. The parse tree is represented recursively through the functions start(), lparen(), rparen(), list(), number(), tail(), comma(), which match the corresponding symbols in the grammar. Finally, translation is done in the function number(). All it does is put the numbers it finds into the List intList. you can modify it to your needs.
    This code originally parsed simple arithmetic expressions, but it took only ten minutes to parse lists of integers. It's not perfect and there are several obvious improvement that will speed up performance, however the strength of the design is that it can be easily changed to suit a variety of simple parsing needs.
    import java.util.regex.*;
    import java.util.*;
    public class RDPParenList {
        private static final Pattern numberPat=
                        Pattern.compile("([1-9]\\d*)|0");
        public static final Object NUMBER = new Object();
        public static final Pattern commaPat = Pattern.compile(",");
        public static final Object COMMA = new Object();
        public static final Pattern lparenPat=
                        Pattern.compile("\\(");
        public static final Object LPAREN = new Object();
        public static final Pattern rparenPat=
                        Pattern.compile("\\)");
        public static final Object RPAREN = new Object();
        public static final Token NULLTOKEN = new Token(null, null);
        String input;
        String workingString=null;
        Token lookahead=NULLTOKEN;
        List intList = new ArrayList();
        /** Creates a new instance of RecursiveDescentParse */
        public RDPParenList(String input) {
            this.input=input;
        public void parse(){
            workingString=input;
            advanceToken();
            start();
            if(! "".equals(workingString))
                error("Characters still remaining in input '" + workingString + "'");
        private void advanceToken() {
            // calling advanceToken must give a token
            if("".equals(workingString))
                error("End of input reached unexpectedly");
            // prune the old token, and whitespace...
            if(lookahead != NULLTOKEN){
                int cutPoint = lookahead.symbol.length();
                while(cutPoint < workingString.length() &&
                        Character.isWhitespace(workingString.charAt(cutPoint))){
                    ++ cutPoint;
                workingString=workingString.substring(cutPoint);
            // Now check for the next token, starting with the null token...
            if("".equals(workingString)){
                lookahead=NULLTOKEN;
                return;
            Matcher m=numberPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), NUMBER);
                return;
            m=commaPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), COMMA);
                return;
            m=lparenPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), LPAREN);
                return;
            m=rparenPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), RPAREN);
                return;
            error("Error during lexical analysis. Working string: '" +
                           workingString + "'");
        private void start() {
            lParen(); list(); rParen();
        private void lParen(){
            if(lookahead.attrib == LPAREN){
                advanceToken();
                // OK. Do nothing...
            else error("Error at token '" + lookahead.symbol + "' expected '('");
        private void rParen(){
            if(lookahead.attrib == RPAREN){
                advanceToken();
                // OK. Do nothing...
            else error("Error at token '" + lookahead.symbol + "' expected ')'");
        private void list() {
            number(); tail();
        private void number() {
            if(lookahead.attrib == NUMBER){
                // Do something with the number!
                try{
                    intList.add(new Integer(lookahead.symbol));
                catch(NumberFormatException e){
                    // This shouldn't happen if the lexer is working...
                    e.printStackTrace();
                    error("Unknown Error");
                advanceToken();
            else error("Error at token '" + lookahead.symbol + "' expected a number");
        private void tail() {
            if(lookahead.attrib == COMMA){
                comma(); list();
            else {
                // Lambda production
        private void comma() {
            if(lookahead.attrib == COMMA){
                advanceToken();
                // OK. Do nothing...
            else error("Error at token '" + lookahead.symbol + "' expected ','");
        private void error(String message){
            System.out.println(message);
            System.exit(-1);
        public static class Token{
            public Token(String symbol, Object attrib) {
                this.symbol=symbol;
                this.attrib=attrib;
            public String symbol;
            public Object attrib;
        public static void main(String []args){
            if(args.length == 0)
                return;
            System.out.println("\nParse String: " + args[0]);
            RDPParenList p=new RDPParenList(args[0]);
            p.parse();
            System.out.println("OK!");

  • Basic questions about programing for J9 VM

    I need to create a java application to run on a Pocket PC 2003 OS and I'm limited to using IBM's Websphere J9 Virtual Machine. I'm new to using java in this capacity and therefore have lots of questions which I'm guessing are pretty basic. Despite my best efforts, I've found very little to help me online. Below are a couple questions I have that I'm hoping someone can help me with. Even better, if you know of any resources that could help me with these and other questions, I'd love to have them. Thanks in advance.
    1. I'm using standard AWT for the GUI but I'm having problems getting frames, dialogs, etc., to come up in anything less then full screen. setSize() and resize() have no effect, even if I extend the frame and override the setMinimumSize, setPreferredSize, setMaximumSize methods. What do I need to do to get a child window to appear in something less than full screen?
    2. I'd like to be able to add menu's to the buttom toolbar (with the keyboard) but have no idea how I would add something to it. Can someone point me in the right direction?
    3. When my application gets an iconified event I go ahead and call a System.exit() to exit the application. This doesn't kill the java VM though, which continues to run in the background (taking up plenty of memory). If I run my application using the J9w.exe so that it runs without the console, then not only does the VM continue to run, but I have no way to stop it (the running program list can't see it). Since each time I run my application it starts a new VM, it only takes a couple of times before I'm out of memory and have to do a soft reset of the PDA to make things right. Can I kill the VM when I kill my application?
    4. I learn best by looking at example code, but have been unable to find any code people are running on J9. I have the GolfScoreTracker installed and running on my PDA, but the jar file contains only the classes. Since it's supposed to be a demo, I had hoped that the source code would be included, is that hoping too much or is the source code available somewhere? In addition, if you know of any applications out there with available source code that are known to run well on a PocketPC J9 environment I'd appreciate the link.

    Hi there, I saw your questions, im currently developing a java pocket pc application as well and here's what i go so far:
    AWT seem to be hard to use on pocket pc, instead i recommend that you use SWT, which is a technology developed by eclipse. It's already installed on the eclipse plugins, you just need to download the jar and dll files for the pocket pc. They are available at: http://www.eclipse.org/downloads/index.php
    I assume that you already have the J9 working on your device. So you only need to copy the SWT.jar file and the swt-win32-3064.dll to the folder containing the .class files on your device.
    Now, on your java IDE(im using eclipse) Add the SWT.jar library to your project which should be on C:/eclipse/plugins/org.eclipse.swt.win32_3.0.2/ws/win32/swt.jar or something like taht depending on your eclipse root.
    Now you are ready to code some SWT, here is a sample program from Carolyn MacLeod, i modified a few things so it could run on the pocket pc but it's almost the same. Once you coded in eclipse run it, then copy the class file from your desktop to your device(There should be like 4 or 5 classes like sample.class, sample$1.class etc. copy all of them) where you put the jar and dll files(If program does not run you may try to rename the dll file for swt-win32-3050.dll instead of 3064.dll). Now after you have everything set up you need to create the lnk file in order to run the program. On your desktop create a new textfile and write the following on it:
    255#"\Archivos de Programa\J9\PPRO10\bin\j9w.exe" "-jcl:PPRO10" "-cp" "\My
    Documents\Java\swt.jar" ;\My Documents\Java" sample
    Paths depend on your install, and the place where you put your classes and jar file. path for j9w is usually "\Program Files\J9\PPRO10\bin\j9w.exe", and the last word should be the classname.
    Currently this form only displays an image on a canvas, click on the browse button and choose a pic and it will display on the canvas. Im trying to connect the form to an oracle database but no success yet on the device.
    Hope it helps, if you have any questions about the code or something, and I know the answer, please feel free to ask.
    See ya
    import org.eclipse.swt.*;
    import org.eclipse.swt.widgets.*;
    import org.eclipse.swt.layout.*;
    import org.eclipse.swt.events.*;
    import org.eclipse.swt.graphics.*;
    public class sample {
    static Shell shell;
    static Display display;
    static Text dogName;
    static Text textdb;
    static Combo dogBreed;
    static Canvas dogPhoto;
    static Image dogImage;
    static List categories;
    static Text ownerName;
    static Text ownerPhone;
    static String[] FILTER_EXTS = {"*.jpg"};
    public static void main(String[] args) {
    display = new Display();
    shell = new Shell(display, SWT.RESIZE | SWT.CLOSE);
    Menu menu = new Menu(shell, SWT.BAR);
    shell.setText("Dog ShowS Entry");
    shell.setMenuBar(menu);
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 3;
    shell.setLayout(gridLayout);
    new Label(shell, SWT.NONE).setText("Dog's NameS:");
    dogName = new Text(shell, SWT.SINGLE | SWT.BORDER);
    GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    gridData.horizontalSpan = 2;
    gridData.widthHint = 60;
    dogName.setLayoutData(gridData);
    new Label(shell, SWT.NONE).setText("Breed:");
    dogBreed = new Combo(shell, SWT.NONE);
    dogBreed.setItems(new String [] {"Collie", "Pitbull", "Poodle", "Scottie"});
    dogBreed.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    Label label = new Label(shell, SWT.NONE);
    label.setText("Categories");
    label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    new Label(shell, SWT.NONE).setText("Photo:");
    dogPhoto = new Canvas(shell, SWT.BORDER);
    gridData = new GridData(GridData.FILL_BOTH);
    gridData.widthHint = 60;
    gridData.verticalSpan = 3;
    dogPhoto.setLayoutData(gridData);
    dogPhoto.addPaintListener(new PaintListener() {
    public void paintControl(final PaintEvent event) {
    if (dogImage != null) {
    event.gc.drawImage(dogImage, 0, 0);
    categories = new List(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    categories.setItems(new String [] {
    "Best of Breed", "Prettiest Female", "Handsomest Male",
    "Best Dressed", "Fluffiest Ears", "Most Colors",
    "Best Performer", "Loudest Bark", "Best Behaved",
    "Prettiest Eyes", "Most Hair", "Longest Tail",
    "Cutest Trick"});
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
    gridData.widthHint = 60;
    gridData.verticalSpan = 4;
    int listHeight = categories.getItemHeight() * 12;
    Rectangle trim = categories.computeTrim(0, 0, 0, listHeight);
    gridData.heightHint = trim.height;
    categories.setLayoutData(gridData);
    Button browse = new Button(shell, SWT.PUSH);
    browse.setText("BrowsePic");
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    gridData.widthHint = 60;
    browse.setLayoutData(gridData);
    browse.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent event) {
              FileDialog dialog = new FileDialog(shell, SWT.OPEN);
              dialog.setFilterExtensions(new String[] {"*.*"});
              String fileName = dialog.open();
    if (fileName != null) {
    dogImage = new Image(display, fileName);
    shell.redraw();
    Button delete = new Button(shell, SWT.PUSH);
    delete.setText("No action");
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING);
    gridData.widthHint = 60;
    delete.setLayoutData(gridData);
    delete.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent event) {
    Button enter = new Button(shell, SWT.PUSH);
    enter.setText("No action");
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
    gridData.horizontalSpan = 3;
    enter.setLayoutData(gridData);
    enter.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent event) {
         shell.open();
         while (!shell.isDisposed()) {
              if (!display.readAndDispatch())
                   display.sleep();
         display.dispose();
    if (dogImage != null) {
    dogImage.dispose();
    }

Maybe you are looking for