Equals() in StringBuffer

I tried the follow code:
StringBuffer s1 = new StringBuffer("F10");
StringBuffer s2 = new StringBuffer("F10");
System.out.println(s1.equals(s2));
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
I found StringBuffer is different from String. s1 and s2 are not equal. Why I got this result? The return of hashCode() is change every time I run it.
Thanks!

The String class overrides Object.equals, while
StringBuffer inherits Object.equals. SoStringBuffer
is looking for Object equality, while the Stringclass
has its own set of rules.Ok, that explains the behaviour ... stays the question
why doesn't StringBuffer override the equals method?
The way it is seems to be not intuitive at all!
If somebody had asked my I for sure had said
StringBuffer.equal() would behave just as
String.equal() does ... and I'm sure many other
developers had thought so too!
SpielerThat's what I thought, until I looked at the APIs.
You can always use StringBuffer.toString().equals(...). A bit long and annoying, but it gets the job done.

Similar Messages

  • Using global variable

    Hello,
    i am trying to store a result of a function in an array of strings declared as a global variable, but any time the fuction is called the array content become null and stores the current result in the specified location. i.e. method A(int i){ args[i] = "awe"}
    method B(int k){args[k] = "cat"}. the string stored intially in args is now null although the new value isn't stored in the same location.
    pls help
    thanks in advance

    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.JOptionPane.*;
    import javax.swing.BorderFactory.*;
    import javax.swing.border.*;
    import javax.swing.JFileChooser.*;
    import java.lang.reflect.*;
    public class FileSystem{
         JFileChooser fc = new JFileChooser();
         FileSystem sys;
         private String[] args = new String[50];
         private int j = 0;
         public void openFile(File file, JTextArea display, String button,int i){
              String openFile = "";
              j = i;
              System.out.println(j);
              try{
              //reads in text file
              BufferedReader in = new BufferedReader(new FileReader(file));
              if(button.equals("browse1")){
                   StringBuffer temp = new StringBuffer();
                   String c1 = "";
                   String line = in.readLine();
                   while(line != null) {
                   temp.append(line + "\n");
                   c1 = temp.toString();
                   line = in.readLine();
                   args[i] = c1;
                   else if(button.equals("browse2")){
                   StringBuffer temp2 = new StringBuffer();
                   String line2 = in.readLine();
                   String c2 = "";
                   while(line2 != null) {
                   temp2.append(line2 + "\n");
                   c2 = temp2.toString();
                   line2 = in.readLine();
                   }args[i] = c2;
                   else if(button.equals("browse3")){
                   StringBuffer temp3 = new StringBuffer();
                   String line3 = in.readLine();
                   String c3 = "";
                   while(line3 != null) {
                   temp3.append(line3 + "\n");
                   c3 = temp3.toString();
                   line3 = in.readLine();
                   }args[i] = c3;}
                   else if(button.equals("browse4")){
                   StringBuffer temp4 = new StringBuffer();
                   String line4 = in.readLine();
                   String c4 = "";
                   while(line4 != null) {
                        temp4.append(line4 + "\n");
                        c4 = temp4.toString();
                        line4 = in.readLine();
                   args[i] = c4;}
                   else if(button.equals("browse5")){
                   StringBuffer temp5 = new StringBuffer();
                   String line5 = in.readLine();
                   String c5 = "";
                   while(line5 != null) {
                   temp5.append(line5 + "\n");
                   c5 = temp5.toString();
                   line5 = in.readLine();
                   }args[i] = c5;}
                   else if(button.equals("browse6")){
                   StringBuffer temp6 = new StringBuffer();
                   String line6 = in.readLine();
                   String c6= "";
                   while(line6 != null) {
                   temp6.append(line6 + "\n");
                   c6 = temp6.toString();
                   line6 = in.readLine();
                   }args[i] = c6;}
                   else if(button.equals("browse7")){
                   StringBuffer temp7 = new StringBuffer();
                   String line7 = in.readLine();
                   String c7 = "";
                   while(line7 != null) {
                   temp7.append(line7 + "\n");
                   c7 = temp7.toString();
                   line7 = in.readLine();
                   }args[i] = c7;}
                   else if(button.equals("browse8")){
                   StringBuffer temp8 = new StringBuffer();
                   String line8 = in.readLine();
                   String c8 = "";
                   while(line8 != null) {
                   temp8.append(line8 + "\n");
                   c8 = temp8.toString();
                   line8 = in.readLine();
                   }args[i] = c8;}
                   else if(button.equals("browse9")){
                   StringBuffer temp9 = new StringBuffer();
                   String line9 = in.readLine();
                   String c9 = "";
                   while(line9 != null) {
                   temp9.append(line9 + "\n");
                   c9 = temp9.toString();
                   line9 = in.readLine();
                   }args[i] = c9;}
                   else if(button.equals("browse10")){
                   StringBuffer temp10 = new StringBuffer();
                   String line10 = in.readLine();
                   String c10 = "";
                   while(line10 != null) {
                   temp10.append(line10 + "\n");
                   c10 = temp10.toString();
                   line10 = in.readLine();
                   }args[i] = c10;}
              in.close();
              }catch (FileNotFoundException e) {
    display.setText("IOERROR: File NOT Found: " + file + "\n");
    e.printStackTrace();
    } catch (IOException e) {
    display.setText("IOERROR: " + e.getMessage() + "\n");
         e.printStackTrace();}
         //preprocess function, gets the command and the arguments ready for the radiance process
         public void preProcess(String cmd,JTextArea display,String fn,int i){
              int temp = i+2;
              args[0] = cmd;
              args[temp-2] = ">";
              String[] rad = new String[50];
              args[temp-1] = fn;
              System.out.println(temp);
              sys = new FileSystem();
              //sys.radCall(args, display);
              for(int k = 1; k<temp; k++){
              System.out.println(" " + args[k] + " ");
              rad[k] = args[k];}
    //radCall method call on the radiance process
         public void radCall(String[] call, JTextArea display){
              try {
              String ls_str;
              Process ls_proc = Runtime.getRuntime().exec(call);
              // get its output (your input) stream
              DataInputStream ls_in = new DataInputStream(
    ls_proc.getInputStream());
              try {
                   while ((ls_str = ls_in.readLine()) != null) {
                        display.setText(ls_str);
              } catch (IOException e) {
                   System.exit(0);
              } catch (IOException e1) {
              System.err.println(e1);
              System.exit(1);
              System.exit(0);
    }

  • Null pointer Exception in Standard Controller Extension

    Hi All,
    I extend the controller, The controller is related to two Standard pages.
    My code is working fine for one controller, but where as for the other page it throws an error null pointer exception.
    Please help me as this is very urgent issue.
    My code is as follows:
    // This Controller is used to display Item Description and manufacturer name, which is extended from Standard Controller EgoItemDetailPageLayoutCO
    package oracle.apps.eng.changemgmt.webui;
    import com.sun.java.util.collections.ArrayList;
    import com.sun.java.util.collections.HashMap;
    import java.io.IOException;
    import java.io.Serializable;
    import java.net.URLEncoder;
    import java.util.Dictionary;
    import java.util.Vector;
    import oracle.apps.eng.changemgmt.nir.util.DisplayUtils;
    import oracle.apps.eng.changemgmt.util.*;
    import oracle.apps.eng.changemgmt.util.server.ActionServerUtil;
    import oracle.apps.eng.changemgmt.util.webui.ChangeRouteUIUtil;
    import oracle.apps.eng.changemgmt.util.webui.EngChangeUtil;
    import oracle.apps.eng.util.server.WorkflowUtil;
    import oracle.apps.fnd.common.MessageToken;
    import oracle.apps.fnd.common.VersionInfo;
    import oracle.apps.fnd.framework.*;
    import oracle.apps.fnd.framework.server.OADBTransaction;
    import oracle.apps.fnd.framework.webui.*;
    import oracle.apps.fnd.framework.webui.beans.OAImageBean;
    import oracle.apps.fnd.framework.webui.beans.OAWebBean;
    import oracle.apps.fnd.framework.webui.beans.form.OAFormValueBean;
    import oracle.apps.fnd.framework.webui.beans.form.OASubmitButtonBean;
    import oracle.apps.fnd.framework.webui.beans.layout.*;
    import oracle.apps.fnd.framework.webui.beans.message.*;
    import oracle.apps.fnd.framework.webui.beans.nav.*;
    import oracle.apps.fnd.framework.webui.beans.table.OATableBean;
    import oracle.apps.fnd.framework.webui.beans.OAFormattedTextBean;
    import oracle.cabo.ui.BaseMutableUINode;
    import oracle.cabo.ui.UIConstants;
    import oracle.cabo.ui.beans.*;
    import oracle.cabo.ui.beans.form.SubmitButtonBean;
    import oracle.cabo.ui.beans.form.TextInputBean;
    import oracle.cabo.ui.beans.layout.*;
    import oracle.cabo.ui.beans.message.MessageBoxBean;
    import oracle.cabo.ui.beans.message.MessageStyledTextBean;
    import oracle.cabo.ui.beans.nav.LinkBean;
    import oracle.jbo.*;
    import oracle.jbo.domain.Number;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import oracle.apps.ego.item.eu.util.EgoItemContext;
    import oracle.apps.ego.item.eu.util.EgoOrganizationContext;
    import oracle.apps.fnd.framework.OAApplicationModule;
                   public class XXNRChangeDetailPageEXTCO extends ChangeDetailPageCO
                        public void processRequest(OAPageContext oapagecontext, OAWebBean oawebbean)
                             super.processRequest(oapagecontext, oawebbean);
                             XXNRchangeDetailIncontext(oapagecontext,oawebbean);
                   public void XXNRchangeDetailIncontext(OAPageContext oapagecontext,OAWebBean oawebbean)
                             int x=2;
                   int y=3;
                                  EgoItemContext egoitemcontext = EgoItemContext.getItemContextObject(oapagecontext);
                                  OAApplicationModule am=oapagecontext.getApplicationModule(oawebbean);
                             EgoOrganizationContext egoorganizationcontext = EgoOrganizationContext.getOrganizationContextObject(oapagecontext);
                                  int invitemid=egoitemcontext.getItemId();
                             int organizationid=egoorganizationcontext.getOrganizationId();
                             StringBuffer stringbuffer = new StringBuffer();
                             String s = EngChangeUtil.getItemPageContextFlag(oapagecontext);
                             OAPageLayoutBean oapagelayoutbean = oapagecontext.getPageLayoutBean();
                                  String manufacturer=XXNRgetManufactuer(am,invitemid,organizationid);
                   String s1 = null;
                   String s2 = "";
                   String s3 = EngChangeUtil.getChangeNumber(oapagecontext) != null ? EngChangeUtil.getChangeNumber(oapagecontext) : "";
                             if(EngChangeUtil.getChangeName(oapagecontext) != null)
                                  EngChangeUtil.getChangeName(oapagecontext);
                             if(EngChangeUtil.getItemNumber(oapagecontext) != null)
                                  EngChangeUtil.getItemNumber(oapagecontext);
                   String s4 = EngChangeUtil.getOrgCodeContext(oapagecontext) != null ? EngChangeUtil.getOrgCodeContext(oapagecontext) : "";
                   String s5 = EngChangeUtil.getOrgNameContext(oapagecontext) != null ? EngChangeUtil.getOrgNameContext(oapagecontext) : "";
                   String s6 = EngChangeUtil.getOrgIdContext(oapagecontext) != null ? EngChangeUtil.getOrgIdContext(oapagecontext) : "";
                             if(!"Y".equals(s))
                                  if(s3 != null && !s3.trim().equals(""))
                                            s1 = "NORMAL";
                                            s2 = "<b>" + EngChangeUtil.getOriginalChangeMgmtTypeName(oapagecontext) + ": " + s3 + "</b>";
                                       } else
                                                 s1 = "CREATE";
                   String s7 = "<b>" + oapagecontext.getMessage("ENG", "ENG_ORGANIZATION_TEXT", null) + ": " + s5 + " (" + s4 + ")</b>";
                   if(!"-1".equals(s6) && !"".equals(s4) && !"Y".equals(s))
    //StringBuffer stringbuffer = new StringBuffer();
                   if(s1 != null && !s1.equals("CREATE"))
                             stringbuffer.append(s2 + "<br>");
                             if(egoitemcontext != null)
                             stringbuffer.append("<b>");
                             stringbuffer.append(oapagecontext.getMessage("EGO", "EGO_ITEM", null));
                             stringbuffer.append(": ");
                             stringbuffer.append(egoitemcontext.getItemNumber());
                             stringbuffer.append("  ");
                             stringbuffer.append(oapagecontext.getMessage("EGO", "EGO_REVISION_CODE", null));
                             stringbuffer.append(": ");
                             stringbuffer.append(egoitemcontext.getRevisionLabel());
                             stringbuffer.append("</b><br>");          
                             if(x==2)
                                            stringbuffer.append(oapagecontext.getMessage("EGO", "EGO_ITEM_DESC", null));
                                  stringbuffer.append(": ");
                                  stringbuffer.append(egoitemcontext.getItemDescription());
                                  stringbuffer.append("</b><br>");
                             if(y==3)
                             stringbuffer.append("<b>");
                             stringbuffer.append(oapagecontext.getMessage("EGO", "EGO_MANUFACTURER", null));
                             stringbuffer.append(": ");
                             stringbuffer.append(manufacturer);
                             stringbuffer.append("</b><br>");
                                  stringbuffer.append(s7+"<br>");
              OAFormattedTextBean oaformattedtextbean = (OAFormattedTextBean)createWebBean(oapagecontext, "FORMATTED_TEXT_BEAN");
              oaformattedtextbean.setCSSClass("OraTipLabel");
              oaformattedtextbean.setText(stringbuffer.toString());
              oapagelayoutbean.setInContextBranding(oaformattedtextbean);
              return;     
                        OAApplicationModule oaapplicationmodule = oapagecontext.getApplicationModule(oawebbean);
                        if(oaapplicationmodule.getOADBTransaction().getResponsibilityApplicationId() == 242 && s2 != null && !"".equals(s2))
                             OAFormattedTextBean oaformattedtextbean1 = (OAFormattedTextBean)createWebBean(oapagecontext, "FORMATTED_TEXT_BEAN");
                             oaformattedtextbean1.setStyleUsage("inContextBranding");
                             oaformattedtextbean1.setText(s2);
                             oapagelayoutbean.setInContextBranding(oaformattedtextbean1);
                   public String XXNRgetManufactuer(OAApplicationModule am,int invitemid ,int organizationid)
                        String manufacturer=null;
                             try
                                  PreparedStatement ps=am.getOADBTransaction().getJdbcConnection().prepareStatement("Select XXNRgetManufacturer(?,?) from dual");
                                  ps.setInt(1,invitemid);
                                  ps.setInt(2,organizationid);
                                  ResultSet rs=ps.executeQuery();
                                  while (rs.next())
                             manufacturer=rs.getString(1);
              catch(SQLException e)
                   e.printStackTrace();
    return manufacturer;
    My Error is as follows:
    java.lang.NullPointerException
         at oracle.apps.eng.changemgmt.webui.XXNRChangeDetailPageEXTCO.XXNRchangeDetailIncontext(XXNRChangeDetailPageEXTCO.java:65)
         at oracle.apps.eng.changemgmt.webui.XXNRChangeDetailPageEXTCO.processRequest(XXNRChangeDetailPageEXTCO.java:55)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequest(OAWebBeanHelper.java:587)
         at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processRequest(OAWebBeanContainerHelper.java:247)
         at oracle.apps.fnd.framework.webui.beans.layout.OAHeaderBean.processRequest(OAHeaderBean.java:389)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequestChildren(OAWebBeanHelper.java:959)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequestChildren(OAWebBeanHelper.java:926)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequest(OAWebBeanHelper.java:646)
         at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processRequest(OAWebBeanContainerHelper.java:247)
         at oracle.apps.fnd.framework.webui.beans.layout.OAStackLayoutBean.processRequest(OAStackLayoutBean.java:350)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequestChildren(OAWebBeanHelper.java:959)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequestChildren(OAWebBeanHelper.java:926)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequest(OAWebBeanHelper.java:646)
         at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processRequest(OAWebBeanContainerHelper.java:247)
         at oracle.apps.fnd.framework.webui.OAPageLayoutHelper.processRequest(OAPageLayoutHelper.java:1136)
         at oracle.apps.fnd.framework.webui.beans.layout.OAPageLayoutBean.processRequest(OAPageLayoutBean.java:1569)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequestChildren(OAWebBeanHelper.java:959)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequestChildren(OAWebBeanHelper.java:926)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequest(OAWebBeanHelper.java:646)
         at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processRequest(OAWebBeanContainerHelper.java:247)
         at oracle.apps.fnd.framework.webui.beans.form.OAFormBean.processRequest(OAFormBean.java:385)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequestChildren(OAWebBeanHelper.java:959)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequestChildren(OAWebBeanHelper.java:926)
         at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processRequest(OAWebBeanHelper.java:646)
         at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processRequest(OAWebBeanContainerHelper.java:247)
         at oracle.apps.fnd.framework.webui.beans.OABodyBean.processRequest(OABodyBean.java:353)
         at oracle.apps.fnd.framework.webui.OAPageBean.processRequest(OAPageBean.java:2336)
         at oracle.apps.fnd.framework.webui.OAPageBean.preparePage(OAPageBean.java:1735)
         at oracle.apps.fnd.framework.webui.OAPageBean.preparePage(OAPageBean.java:509)
         at oracle.apps.fnd.framework.webui.OAPageBean.preparePage(OAPageBean.java:430)
         at oa_html._OA._jspService(_OA.java:82)
         at oracle.jsp.runtime.HttpJsp.service(HttpJsp.java:119)
         at oracle.jsp.app.JspApplication.dispatchRequest(JspApplication.java:385)
         at oracle.jsp.JspServlet.doDispatch(JspServlet.java:259)
         at oracle.jsp.JspServlet.internalService(JspServlet.java:178)
         at oracle.jsp.JspServlet.service(JspServlet.java:148)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:588)
         at oracle.jsp.provider.Jsp20RequestDispatcher.forward(Jsp20RequestDispatcher.java:162)
         at oracle.jsp.runtime.OraclePageContext.forward(OraclePageContext.java:175)
         at oa_html._OA._jspService(_OA.java:92)
         at oracle.jsp.runtime.HttpJsp.service(HttpJsp.java:119)
         at oracle.jsp.app.JspApplication.dispatchRequest(JspApplication.java:385)
         at oracle.jsp.JspServlet.doDispatch(JspServlet.java:259)
         at oracle.jsp.JspServlet.internalService(JspServlet.java:178)
         at oracle.jsp.JspServlet.service(JspServlet.java:148)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:588)
         at org.apache.jserv.JServConnection.processRequest(JServConnection.java:456)
         at org.apache.jserv.JServConnection.run(JServConnection.java:294)
         at java.lang.Thread.run(Thread.java:595)
    Thanks and Regards
    Zaheer

    Hi,
    Can you paster your error log here, also during which execution flow are you getting the error.
    Thanks,
    Ankul

  • Geting  Error in Controller

    Hi friends
    In controller am geting below error...
    java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1937)at java.lang.String.substring(String.java:1904)at xxuss.oracle.apps.xp2p.fnd.framework.attachments.webui.XXFndAttachedDocCO.processFormRequest(XXFndAttachedDocCO.java:117)
    in controller i had written...
    super.processFormRequest(pageContext, webBean);
    String hideShowEvent = pageContext.getParameter(OAWebBeanConstants.EVENT_PARAM);
    if ((OAWebBeanConstants.SHOW_EVENT.equals(hideShowEvent)) ||(OAWebBeanConstants.HIDE_EVENT.equals(hideShowEvent)))
    String hideShowId = pageContext.getParameter(OAWebBeanConstants.SOURCE_PARAM);
    String s7 = "";
    if(hideShowId.startsWith("SearchAttachHideShow"))
    s7 = hideShowId.substring(21);//am geting error here
    if(!"".equals(s7))
    StringBuffer stringbuffer = (new StringBuffer("SearchBasicRN")).append("_").append(s7);
    String as[] = {
    stringbuffer.toString()
    OAPartialPageRenderUtils.addPartialTargets(pageContext, as);
    anybody help me out
    Thanks and Regards
    Harrrry

    Why are you using substring(21)? Are you sure that the String will not contain less than 21 characters?
    If you are searching for a particular pattern in the String then use indexOf(String str) functio, then used the substring() function.
    What do you exactly intend to do?

  • "com.mysql.jdbc.PacketTooBigException": Help needed urgently

    hi,
    I am using mm.mysql j/connector ver 3.0.6 and MYSQL server version 4.0.
    Max_allowed packet= 8MB at the server side
    I am getting PacketTooBigException when i am trying to update a particular column.
    What should i do.
    Any help will be greatly appreciated!!!

    the driver uses a 64 k max packet size by default. it is supposed to change this as neccessary upon connection but perhaps that is failing?
    below is the 3.0.7 connection code that i have slightly modified for you so that it prints out the connection properties after they have been initialized so that you can see what they are.
    try it out and i hope you find this helpful.
       Copyright (C) 2002 MySQL AB
          This program is free software; you can redistribute it and/or modify
          it under the terms of the GNU General Public License as published by
          the Free Software Foundation; either version 2 of the License, or
          (at your option) any later version.
          This program is distributed in the hope that it will be useful,
          but WITHOUT ANY WARRANTY; without even the implied warranty of
          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
          GNU General Public License for more details.
          You should have received a copy of the GNU General Public License
          along with this program; if not, write to the Free Software
          Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    /*Slight Modification by Max Stocker April 29, 2003 to trace what the connection values get initialized to. */
    package com.mysql.jdbc;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.Reader;
    import java.io.UnsupportedEncodingException;
    import java.math.BigDecimal;
    import java.net.URL;
    import java.sql.Clob;
    import java.sql.Date;
    import java.sql.ParameterMetaData;
    import java.sql.Ref;
    import java.sql.SQLException;
    import java.sql.Savepoint;
    import java.sql.Time;
    import java.sql.Timestamp;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Properties;
    import java.util.StringTokenizer;
    import java.util.TimeZone;
    * A Connection represents a session with a specific database.  Within the
    * context of a Connection, SQL statements are executed and results are
    * returned.
    * <P>A Connection's database is able to provide information describing
    * its tables, its supported SQL grammar, its stored procedures, the
    * capabilities of this connection, etc.  This information is obtained
    * with the getMetaData method.
    * @see java.sql.Connection
    * @author Mark Matthews
    * @version $Id: Connection.java,v 1.31.2.19 2003/03/28 22:42:24 mmatthew Exp $
    public class Connection implements java.sql.Connection {
        // The command used to "ping" the database.
        // Newer versions of MySQL server have a ping() command,
        // but this works for everything
        private static final String PING_COMMAND = "SELECT 1";
         * Map mysql transaction isolation level name to
         * java.sql.Connection.TRANSACTION_XXX
        private static Map mapTransIsolationName2Value = null;
         * The mapping between MySQL charset names
         * and Java charset names.
         * Initialized by loadCharacterSetMapping()
        private static Map charsetMap;
         * Table of multi-byte charsets.
         * Initialized by loadCharacterSetMapping()
        private static Map multibyteCharsetsMap;
         * Default socket factory classname
        private static final String DEFAULT_SOCKET_FACTORY = StandardSocketFactory.class
            .getName();
        static {
            loadCharacterSetMapping();
            mapTransIsolationName2Value = new HashMap(8);
            mapTransIsolationName2Value.put("READ-UNCOMMITED",
                new Integer(TRANSACTION_READ_UNCOMMITTED));
              mapTransIsolationName2Value.put("READ-UNCOMMITTED",
                   new Integer(TRANSACTION_READ_UNCOMMITTED));
            mapTransIsolationName2Value.put("READ-COMMITTED",
                new Integer(TRANSACTION_READ_COMMITTED));
            mapTransIsolationName2Value.put("REPEATABLE-READ",
                new Integer(TRANSACTION_REPEATABLE_READ));
            mapTransIsolationName2Value.put("SERIALIZABLE",
                new Integer(TRANSACTION_SERIALIZABLE));
         * Internal DBMD to use for various database-version
         * specific features
        private DatabaseMetaData dbmd = null;
         * The list of host(s) to try and connect to
        private List hostList = null;
          * A map of statements that have had setMaxRows() called on them
         private Map statementsUsingMaxRows;
         * The I/O abstraction interface (network conn to
         * MySQL server
        private MysqlIO io = null;
         * Mutex
        private final Object mutex = new Object();
         * The driver instance that created us
        private NonRegisteringDriver myDriver;
         * The map of server variables that we retrieve
         * at connection init.
        private Map serverVariables = null;
         * Properties for this connection specified by user
        private Properties props = null;
         * The database we're currently using
         * (called Catalog in JDBC terms).
        private String database = null;
         * If we're doing unicode character conversions,
         * what encoding do we use?
        private String encoding = null;
         * The hostname we're connected to
        private String host = null;
         * The JDBC URL we're using
        private String myURL = null;
         * The password we used
        private String password = null;
         * Classname for socket factory
        private String socketFactoryClassName = null;
         * The user we're connected as
        private String user = null;
         * The timezone of the server
        private TimeZone serverTimezone = null;
         * Allow LOAD LOCAL INFILE (defaults to true)
        private boolean allowLoadLocalInfile = true;
         * Are we in autoCommit mode?
        private boolean autoCommit = true;
         * Should we capitalize mysql types
        private boolean capitalizeDBMDTypes = false;
         * Should we continue processing batch commands if
         * one fails. The JDBC spec allows either way, so
         * we let the user choose
        private boolean continueBatchOnError = true;
         * Should we do unicode character conversions?
        private boolean doUnicode = false;
         * Are we failed-over to a non-master host
        private boolean failedOver = false;
        /** Does the server suuport isolation levels? */
        private boolean hasIsolationLevels = false;
         * Does this version of MySQL support quoted identifiers?
        private boolean hasQuotedIdentifiers = false;
        // This is for the high availability :) routines
        private boolean highAvailability = false;
         * Has this connection been closed?
        private boolean isClosed = true;
         * Should we tell MySQL that we're an interactive client?
        private boolean isInteractiveClient = false;
         * Is the server configured to use lower-case
         * table names only?
        private boolean lowerCaseTableNames = false;
         * Has the max-rows setting been changed from
         * the default?
        private boolean maxRowsChanged = false;
         * Do we expose sensitive information in exception
         * and error messages?
        private boolean paranoid = false;
         * Should we do 'extra' sanity checks?
        private boolean pedantic = false;
         * Are we in read-only mode?
        private boolean readOnly = false;
        /** Do we relax the autoCommit semantics? (For enhydra, for example) */
        private boolean relaxAutoCommit = false;
         * Do we need to correct endpoint rounding errors
        private boolean strictFloatingPoint = false;
         * Do we check all keys for updatable result sets?
        private boolean strictUpdates = true;
        /** Are transactions supported by the MySQL server we are connected to? */
        private boolean transactionsSupported = false;
         * Has ANSI_QUOTES been enabled on the server?
        private boolean useAnsiQuotes = false;
         * Should we use compression?
        private boolean useCompression = false;
         * Can we use the "ping" command rather than a
         * query?
        private boolean useFastPing = false;
         * Should we tack on @hostname in DBMD.getTable/ColumnPrivileges()?
        private boolean useHostsInPrivileges = true;
         * Should we use SSL?
        private boolean useSSL = false;
         * Should we use stream lengths in prepared statements?
         * (true by default == JDBC compliant)
        private boolean useStreamLengthsInPrepStmts = true;
         * Should we use timezone information?
        private boolean useTimezone = false;
        /** Should we return PreparedStatements for UltraDev's stupid bug? */
        private boolean useUltraDevWorkAround = false;
        private double initialTimeout = 2.0D;
         * How many hosts are in the host list?
        private int hostListSize = 0;
         * isolation level
        private int isolationLevel = java.sql.Connection.TRANSACTION_READ_COMMITTED;
         * The largest packet we can send (changed
         * once we know what the server supports, we
         * get this at connection init).
        private int maxAllowedPacket = 65536;
        private int maxReconnects = 3;
         * The max rows that a result set can contain.
         * Defaults to -1, which according to the JDBC
         * spec means "all".
        private int maxRows = -1;
        private int netBufferLength = 16384;
         * The port number we're connected to
         * (defaults to 3306)
        private int port = 3306;
         * How many queries should we wait before we try to re-connect
         * to the master, when we are failing over to replicated hosts
         * Defaults to 50
        private int queriesBeforeRetryMaster = 50;
         * What should we set the socket timeout to?
        private int socketTimeout = 0; // infinite
         * When did the last query finish?
        private long lastQueryFinishedTime = 0;
         * When did the master fail?
        private long masterFailTimeMillis = 0L;
         * Number of queries we've issued since the master
         * failed
        private long queriesIssuedFailedOver = 0;
         * How many seconds should we wait before retrying to connect
         * to the master if failed over? We fall back when either
         * queriesBeforeRetryMaster or secondsBeforeRetryMaster is
         * reached.
        private long secondsBeforeRetryMaster = 30L;
         * The type map for UDTs (not implemented, but used by
         * some third-party vendors, most notably IBM WebSphere)
        private Map typeMap;
         * Ignore non-transactional table warning for rollback?
        private boolean ignoreNonTxTables = false;
         * Creates a connection to a MySQL Server.
         * @param host the hostname of the database server
         * @param port the port number the server is listening on
         * @param info a Properties[] list holding the user and password
         * @param database the database to connect to
         * @param url the URL of the connection
         * @param d the Driver instantation of the connection
         * @exception java.sql.SQLException if a database access error occurs
        Connection(String host, int port, Properties info, String database,
            String url, NonRegisteringDriver d) throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = { host, new Integer(port), info, database, url, d };
                Debug.methodCall(this, "constructor", args);
            this.serverVariables = new HashMap();
            hostList = new ArrayList();
            if (host == null) {
                this.host = "localhost";
                hostList.add(this.host);
            } else if (host.indexOf(",") != -1) {
                // multiple hosts separated by commas (failover)
                StringTokenizer hostTokenizer = new StringTokenizer(host, ",", false);
                while (hostTokenizer.hasMoreTokens()) {
                    hostList.add(hostTokenizer.nextToken().trim());
            } else {
                this.host = host;
                hostList.add(this.host);
            hostListSize = hostList.size();
            this.port = port;
            if (database == null) {
                throw new SQLException("Malformed URL '" + url + "'.", "S1000");
            this.database = database;
            this.myURL = url;
            this.myDriver = d;
            this.user = info.getProperty("user");
            this.password = info.getProperty("password");
            if ((this.user == null) || this.user.equals("")) {
                this.user = "nobody";
            if (this.password == null) {
                this.password = "";
            this.props = info;
            initializeDriverProperties(info);
            if (Driver.DEBUG) {
                System.out.println("Connect: " + this.user + " to " + this.database);
            try {
                createNewIO(false);
                this.dbmd = new DatabaseMetaData(this, this.database);
            } catch (java.sql.SQLException ex) {
                cleanup();
                // don't clobber SQL exceptions
                throw ex;
            } catch (Exception ex) {
                cleanup();
                StringBuffer mesg = new StringBuffer();
                if (!useParanoidErrorMessages()) {
                    mesg.append("Cannot connect to MySQL server on ");
                    mesg.append(this.host);
                    mesg.append(":");
                    mesg.append(this.port);
                    mesg.append(".\n\n");
                    mesg.append("Make sure that there is a MySQL server ");
                    mesg.append("running on the machine/port you are trying ");
                    mesg.append(
                        "to connect to and that the machine this software is "
                        + "running on ");
                    mesg.append("is able to connect to this host/port "
                        + "(i.e. not firewalled). ");
                    mesg.append(
                        "Also make sure that the server has not been started "
                        + "with the --skip-networking ");
                    mesg.append("flag.\n\n");
                } else {
                    mesg.append("Unable to connect to database.");
                mesg.append("Underlying exception: \n\n");
                mesg.append(ex.getClass().getName());
                throw new java.sql.SQLException(mesg.toString(), "08S01");
         * If a connection is in auto-commit mode, than all its SQL
         * statements will be executed and committed as individual
         * transactions.  Otherwise, its SQL statements are grouped
         * into transactions that are terminated by either commit()
         * or rollback().  By default, new connections are in auto-
         * commit mode.  The commit occurs when the statement completes
         * or the next execute occurs, whichever comes first.  In the
         * case of statements returning a ResultSet, the statement
         * completes when the last row of the ResultSet has been retrieved
         * or the ResultSet has been closed.  In advanced cases, a single
         * statement may return multiple results as well as output parameter
         * values.  Here the commit occurs when all results and output param
         * values have been retrieved.
         * <p><b>Note:</b> MySQL does not support transactions, so this
         *                 method is a no-op.
         * @param autoCommit - true enables auto-commit; false disables it
         * @exception java.sql.SQLException if a database access error occurs
        public void setAutoCommit(boolean autoCommit) throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = { new Boolean(autoCommit) };
                Debug.methodCall(this, "setAutoCommit", args);
            checkClosed();
            if (this.transactionsSupported) {
                // this internal value must be set first as failover depends on it
                // being set to true to fail over (which is done by most
                // app servers and connection pools at the end of
                // a transaction), and the driver issues an implicit set
                // based on this value when it (re)-connects to a server
                // so the value holds across connections
                this.autoCommit = autoCommit;
                String sql = "SET autocommit=" + (autoCommit ? "1" : "0");
                execSQL(sql, -1, this.database);
            } else {
                if ((autoCommit == false) && (this.relaxAutoCommit == false)) {
                    throw new SQLException("MySQL Versions Older than 3.23.15 "
                        + "do not support transactions", "08003");
                } else {
                    this.autoCommit = autoCommit;
            return;
         * gets the current auto-commit state
         * @return Current state of the auto-commit mode
         * @exception java.sql.SQLException (why?)
         * @see setAutoCommit
        public boolean getAutoCommit() throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = new Object[0];
                Debug.methodCall(this, "getAutoCommit", args);
                Debug.returnValue(this, "getAutoCommit",
                    new Boolean(this.autoCommit));
            return this.autoCommit;
         * A sub-space of this Connection's database may be selected by
         * setting a catalog name.  If the driver does not support catalogs,
         * it will silently ignore this request
         * <p><b>Note:</b> MySQL's notion of catalogs are individual databases.
         * @param catalog the database for this connection to use
         * @throws java.sql.SQLException if a database access error occurs
        public void setCatalog(String catalog) throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = { catalog };
                Debug.methodCall(this, "setCatalog", args);
            checkClosed();
            String quotedId = this.dbmd.getIdentifierQuoteString();
            if ((quotedId == null) || quotedId.equals(" ")) {
                quotedId = "";
            StringBuffer query = new StringBuffer("USE ");
            query.append(quotedId);
            query.append(catalog);
            query.append(quotedId);
            execSQL(query.toString(), -1, catalog);
            this.database = catalog;
         * Return the connections current catalog name, or null if no
         * catalog name is set, or we dont support catalogs.
         * <p><b>Note:</b> MySQL's notion of catalogs are individual databases.
         * @return the current catalog name or null
         * @exception java.sql.SQLException if a database access error occurs
        public String getCatalog() throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = new Object[0];
                Debug.methodCall(this, "getCatalog", args);
                Debug.returnValue(this, "getCatalog", this.database);
            return this.database;
         * DOCUMENT ME!
         * @return DOCUMENT ME!
        public boolean isClosed() {
            if (Driver.TRACE) {
                Object[] args = new Object[0];
                Debug.methodCall(this, "isClosed", args);
                Debug.returnValue(this, "isClosed", new Boolean(this.isClosed));
            return this.isClosed;
         * Returns the character encoding for this Connection
         * @return the character encoding for this connection.
        public String getEncoding() {
            return this.encoding;
         * @see Connection#setHoldability(int)
        public void setHoldability(int arg0) throws SQLException {
            // do nothing
         * @see Connection#getHoldability()
        public int getHoldability() throws SQLException {
            return ResultSet.CLOSE_CURSORS_AT_COMMIT;
         * NOT JDBC-Compliant, but clients can use this method
         * to determine how long this connection has been idle.
         * This time (reported in milliseconds) is updated once
         * a query has completed.
         * @return number of ms that this connection has
         * been idle, 0 if the driver is busy retrieving results.
        public long getIdleFor() {
            if (this.lastQueryFinishedTime == 0) {
                return 0;
            } else {
                long now = System.currentTimeMillis();
                long idleTime = now - this.lastQueryFinishedTime;
                return idleTime;
         * Should we tell MySQL that we're an interactive client
         * @return true if isInteractiveClient was set to true.
        public boolean isInteractiveClient() {
            return isInteractiveClient;
         * A connection's database is able to provide information describing
         * its tables, its supported SQL grammar, its stored procedures, the
         * capabilities of this connection, etc.  This information is made
         * available through a DatabaseMetaData object.
         * @return a DatabaseMetaData object for this connection
         * @exception java.sql.SQLException if a database access error occurs
        public java.sql.DatabaseMetaData getMetaData() throws java.sql.SQLException {
            checkClosed();
            return new DatabaseMetaData(this, this.database);
         * You can put a connection in read-only mode as a hint to enable
         * database optimizations
         * <B>Note:</B> setReadOnly cannot be called while in the middle
         * of a transaction
         * @param readOnly - true enables read-only mode; false disables it
         * @exception java.sql.SQLException if a database access error occurs
        public void setReadOnly(boolean readOnly) throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = { new Boolean(readOnly) };
                Debug.methodCall(this, "setReadOnly", args);
                Debug.returnValue(this, "setReadOnly", new Boolean(readOnly));
            checkClosed();
            this.readOnly = readOnly;
         * Tests to see if the connection is in Read Only Mode.  Note that
         * we cannot really put the database in read only mode, but we pretend
         * we can by returning the value of the readOnly flag
         * @return true if the connection is read only
         * @exception java.sql.SQLException if a database access error occurs
        public boolean isReadOnly() throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = new Object[0];
                Debug.methodCall(this, "isReadOnly", args);
                Debug.returnValue(this, "isReadOnly", new Boolean(this.readOnly));
            return this.readOnly;
         * @see Connection#setSavepoint()
        public java.sql.Savepoint setSavepoint() throws SQLException {
            throw new NotImplemented();
         * @see Connection#setSavepoint(String)
        public java.sql.Savepoint setSavepoint(String arg0)
            throws SQLException {
            throw new NotImplemented();
         * DOCUMENT ME!
         * @return DOCUMENT ME!
        public TimeZone getServerTimezone() {
            return this.serverTimezone;
         * DOCUMENT ME!
         * @param level DOCUMENT ME!
         * @throws java.sql.SQLException DOCUMENT ME!
        public void setTransactionIsolation(int level) throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = { new Integer(level) };
                Debug.methodCall(this, "setTransactionIsolation", args);
            checkClosed();
            if (this.hasIsolationLevels) {
                StringBuffer sql = new StringBuffer(
                        "SET SESSION TRANSACTION ISOLATION LEVEL ");
                switch (level) {
                case java.sql.Connection.TRANSACTION_NONE:
                    throw new SQLException("Transaction isolation level "
                        + "NONE not supported by MySQL");
                case java.sql.Connection.TRANSACTION_READ_COMMITTED:
                    sql.append("READ COMMITTED");
                    break;
                case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED:
                    sql.append("READ UNCOMMITTED");
                    break;
                case java.sql.Connection.TRANSACTION_REPEATABLE_READ:
                    sql.append("REPEATABLE READ");
                    break;
                case java.sql.Connection.TRANSACTION_SERIALIZABLE:
                    sql.append("SERIALIZABLE");
                    break;
                default:
                    throw new SQLException("Unsupported transaction "
                        + "isolation level '" + level + "'", "S1C00");
                execSQL(sql.toString(), -1, this.database);
                isolationLevel = level;
            } else {
                throw new java.sql.SQLException("Transaction Isolation Levels are "
                    + "not supported on MySQL versions older than 3.23.36.", "S1C00");
         * Get this Connection's current transaction isolation mode.
         * @return the current TRANSACTION_* mode value
         * @exception java.sql.SQLException if a database access error occurs
        public int getTransactionIsolation() throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = new Object[0];
                Debug.methodCall(this, "getTransactionIsolation", args);
                Debug.returnValue(this, "getTransactionIsolation",
                    new Integer(isolationLevel));
            if (this.hasIsolationLevels) {
                 java.sql.Statement stmt = null;
                 java.sql.ResultSet rs = null;
                 try {
                      stmt = this.createStatement();
                      String query = null;
                      if (this.io.versionMeetsMinimum(4, 0, 3)) {
                           query = "SHOW VARIABLES LIKE 'tx_isolation'";
                      } else {
                           query = "SHOW VARIABLES LIKE 'transaction_isolation'";
                      rs = stmt.executeQuery(query);
                      if (rs.next()) {
                           String s = rs.getString(2);
                           if (s != null) {
                                  Integer intTI = (Integer) mapTransIsolationName2Value.get(s);
                                  if (intTI != null) {
                                       return intTI.intValue();
                           throw new SQLException("Could not map transaction isolation '" + s + " to a valid JDBC level.", "S1000");
                      } else {
                           throw new SQLException("Could not retrieve transaction isolation level from server", "S1000");
                 } finally {
                      if (rs != null) {
                           try {
                                rs.close();
                           } catch (Exception ex) {
                                // ignore
                           rs = null;
                      if (stmt != null) {
                           try {
                                stmt.close();
                           } catch (Exception ex) {
                                // ignore
                           stmt = null;
            return isolationLevel;
         * JDBC 2.0
         * Install a type-map object as the default type-map for
         * this connection
         * @param map the type mapping
         * @throws SQLException if a database error occurs.
        public void setTypeMap(java.util.Map map) throws SQLException {
            this.typeMap = map;
         * JDBC 2.0
         * Get the type-map object associated with this connection.
         * By default, the map returned is empty.
         * @return the type map
         * @throws SQLException if a database error occurs
        public synchronized java.util.Map getTypeMap() throws SQLException {
            if (this.typeMap == null) {
                this.typeMap = new HashMap();
            return this.typeMap;
         * The first warning reported by calls on this Connection is
         * returned.
         * <B>Note:</B> Sebsequent warnings will be changed to this
         * java.sql.SQLWarning
         * @return the first java.sql.SQLWarning or null
         * @exception java.sql.SQLException if a database access error occurs
        public java.sql.SQLWarning getWarnings() throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = new Object[0];
                Debug.methodCall(this, "getWarnings", args);
                Debug.returnValue(this, "getWarnings", null);
            return null;
         * Allow use of LOAD LOCAL INFILE?
         * @return true if allowLoadLocalInfile was set to true.
        public boolean allowLoadLocalInfile() {
            return this.allowLoadLocalInfile;
         * DOCUMENT ME!
         * @return DOCUMENT ME!
        public boolean capitalizeDBMDTypes() {
            return this.capitalizeDBMDTypes;
         * After this call, getWarnings returns null until a new warning
         * is reported for this connection.
         * @exception java.sql.SQLException if a database access error occurs
        public void clearWarnings() throws java.sql.SQLException {
            if (Driver.TRACE) {
                Object[] args = new Object[0];
                Debug.methodCall(this, "clearWarnings", args);
            // firstWarning = null;
         * In some cases, it is desirable to immediately release a Connection's
         * database and JDBC resources instead of waiting for them to be
         * automatically released (                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      

  • Why StringBuffer does not override equals()

    Is there any reason for StringBuffer to don't override equals()
    Wargo

    Not that I can think of. I'd expect two StringBuffer instances to be considered equivalent (equal) if they both would hand me equivalent results from their toString() methods. Instead, I guess someone at Sun decided that identity was preferable to equivalence for this class's equals() method.

  • StringBuffer and .equals()

    this is my test codes:
    public class Testing
         public static void main(String arg[])
              StringBuffer sb1 = new StringBuffer("test");
              StringBuffer sb2 = new StringBuffer("test");
              if (sb1.equals(sb2))
                   System.out.println("1");
                    System.out.println("End");
    }At runtime, the program only prints out End, without the number 1.
    My question is shouldn't the if-statement is equal to true?
    Doesnt .equals() method compare the content of one object to another object?
    thanks for any explanation
    daffy

    String is deliberately immutable (a value object). This means you can pass it around and share it as a data member in many classes without the danger that one class might change its value and therefore surprise all the other classes sharing it. IOW, you can treat it much like a basic type. StringBuffer is class for the efficient manipulation of String contents. It is mutable, and not really intended to be 'passed around' (i.e. made part of a interface, declared as an argument or return type in a non-private method) or shared by classes. In general, a String is passed to a method, manipulated via StringBuffer, then returned as a new String.

  • Arrays.equals doesnt seem to be working

    Hi
    i have an app that copys the contents of an object array into another, then reruns and compares its contents to the previous copy. they should be equal, but i get a not equal message. i have tried printing out the objects in a loop to see whats happening, i get this:
    (code)
    for(int i = 0; i < count; i++)
    System.out.println(TestPcContainer);
    System.out.println(TestPcContainerCopy[i];
    output:
    Thread[Thread-20,5,main] (orig element 0)
    Thread[Thread-15,5,main] (copy element 0)
    Thread[Thread-21,5,main] (orig element 1
    Thread[Thread-16,5,main] (copy element 1)
    Thread[Thread-22,5,main] (orig element 2)
    Thread[Thread-17,5,main] (copy element 2)
    i dont understand why i keep getting its not equal. i have copied the arrays using : System.arraycopy(TestPcContainer, 0, TestPcContainerCopy, 0, count);
    and i compare by doing: if(Arrays.equals(TestPcContainer, TestPcContainerCopy)) { System.out.println("equal");}else not ......
    thanx for any help on this
    ness

    ok,heres the code:
    ckage tmhealthproject;
    import com.xyratex.utils.EventHandler;
    import com.xyratex.utils.EventInterface;
    import com.xyratex.xyrmi.io.XYRMIMessageHandler;
    import com.xyratex.xyrmi.io.XYRMIObjectInterface;
    import com.xyratex.xyrmi.tcp.XYRMIClient;
    import java.io.*;
    import java.net.UnknownHostException;
    import jicmp.*;
    import java.util.*;
    * <p>Title: TMHealthStatusTestPc </p>
    * <p>Description: Class reads in ip addresses from IpAddress.txt, then creates 16 new
    * TMHealthStatusTestPc objects, allocating each one an ip address from the txt file. Each object represents
    * a tm, and holds 3 fields of data: ipaddress, Morb and TM. These attributes are set to 1 or a zero depending
    * on whether the tm is on or offline, its orb is running and the TestManager software is running. Once these
    * checks have been done, the data is sent to the calling application, either terminal or applet.
    * <p>Copyright: Copyright (c) 2003</p>
    * <p>Company: Xyratex</p>
    * @author Vanessa Radford
    * @version 1.0
    public class TestPc extends Thread implements XYRMIMessageHandler, EventInterface
    FileReader filereader;
    BufferedReader bufferedreader;
    String ipaddress = new String();
    int count;
    TestPc TestPcContainer[];
    TestPc TestPcContainerCopy[];
    TestPc testpc = null;
    int ipvalid = 0;
    int morbvalid = 0;
    int tmvalid = 0;
    int result = 0;
    String tmname = new String();
    String host = "127.0.0.1";
    String className = "className";
    String objectName = "broadCast";
    int port = 9765;
    String object = new String("Object:");
    XYRMIClient Orblink;
    XYRMIClient Orblink1[];
    XYRMIClient Orblink2[];
    String initalMessage1 = (objectName + " " + className + "1 ");
    String initalMessage2 = (objectName + " " + className + "2 ");
    String initialMessage3 = (objectName + " " + className + "3 ");
    EventHandler StatusRequestTimer = null;
    EventHandler StatusResponseTimer = null;
    int counter = 0;
    String viewMessage = (objectName + " StatusView " + "status " + "numberoftms:");
    *</p> This method opens the TMipaddress.txt file, reads in each line, creates a
    * TMHealthStatusTestPc object for each line that is read in, and assign it an ip address.
    * These objects are then stored into a container called TestPcContainer</p>
    public void initializeObjects()
    counter ++;
    //set a count variable to zero. this variable sets the sizes of the Container and Orblink arrays
    count = 0;
    //try to find the file TMipaddress.txt
    try
    filereader = new FileReader("TMipaddress.txt");
    bufferedreader = new BufferedReader(filereader);
    //count how many ip addresses it holds
    while ((ipaddress = bufferedreader.readLine()) != null)
    count ++;
    catch(IOException ioexception)
    System.out.println(ioexception.getMessage());
    //open the file again and read each line
    //now we have the number of tms in the txt file, call the setArraySizes method
    //and send it the count variable. This will inialize the containers and arrays to the correct size
    setArraySizes(count);
    TestPcContainer = new TestPc[count];
    try
    filereader = new FileReader("TMipaddress.txt");
    bufferedreader = new BufferedReader(filereader);
    for(int i = 0; i < count; i++)
    //for each ip address create a new testpc object
    testpc = new TestPc();
    //read in each line from the txt file
    ipaddress = bufferedreader.readLine();
    //create a tokenizer object for each line, and ignore any tabs, spaces or newlines
    StringTokenizer str = new StringTokenizer(ipaddress, " \n\t\r,");
    //send to the setTmName method the first part of the line which holds the tm name
    testpc.setTmName(str.nextToken());
    //send to toe setIp method the second part of the line whcih holds the ip address
    testpc.setIp(str.nextToken());
    //add the object to the container
    TestPcContainer[i] = testpc;
    catch(IOException e)
    //call the method that checks the ip addresses
    checkIp();
    *<p>This method creates a new ICMPPing object in a loop, and passes in a TestPc object
    * as an argument to its constructor. The ICMPPing object extracts the TestPcs host ip
    * address and conducts an ICMP ping on it. The result of this is passed back into setIPValid.
    * The loop ends when all of the TestPc objects stored in the container have been passed in.
    * There is then a 10 second sleep for the data to be collected, then the morb is done </p>
    *@param pc Takes a TMHealthStatusTestPc object as its argument
    public void checkIp()
    for(int i = 0; i < count; i++)
    //create a new ICMPPing object and pass in each object in the container
    ICMPPing checkIPAddress = new ICMPPing(TestPcContainer);
    try
    //sleep so that the data can be collected
    Thread.sleep(2000);
    catch(Exception e)
    System.out.println("message in checkip is " + e.getMessage());
    //call the morb check
    System.out.println("checking morbavail");
    checkMorbAvail();
    public int doSomething()
    if(counter != 1)
    if(Arrays.equals(TestPcContainer, TestPcContainerCopy))
    StatusRequestTimer();
    else
    sendRMI();
    StatusRequestTimer();
    if(counter ==1)
    sendRMI();
    StatusRequestTimer();
    return 1;
    public void setArraySizes(int count)
    TestPcContainer = null;
    if(TestPcContainerCopy == null)
    TestPcContainerCopy = new TestPc[count];
    if(Orblink1== null)
    Orblink1 = new XYRMIClient[count];
    if(Orblink2 == null)
    Orblink2 = new XYRMIClient[count];
    *<p>Method to send RMI message to StatusView applet. Checks to see if an OrbLink has already been created,
    * if so uses XYRMIMessageHandler to forward message. Otherwise registers with the Orb of the TM and forwards
    * message within registration</p>
    *@return int
    public int sendRMI()
    StringBuffer ipbuffer = new StringBuffer();
    for (int t = 0; t < count; t++)
    t++;
    ipbuffer.append(" Object" + t + ":");
    t--;
    ipbuffer.append("\"" + TestPcContainer[t].getTmName() + ",");
    if(TestPcContainer[t].ipvalid == 1)
    if(TestPcContainer[t].morbvalid == 1)
    if(TestPcContainer[t].tmvalid == 1)
    ipbuffer.append("OK\"");
    else
    ipbuffer.append("NoTestMan\"");
    else
    ipbuffer.append("NoOrb\"");
    else
    ipbuffer.append("TimedOut\"");
    String result = ipbuffer.toString();
    try
    if(counter != 1)
    Orblink.XYRMIMessageHandler(viewMessage + "\"" + count + "\"" + result);
    else
    Orblink = new XYRMIClient(this, host, port, viewMessage + "\"" + count + "\"" + result);
    Orblink.SetIdentity(className, objectName);
    Orblink.start();
    catch(Exception e)
    System.out.println("error in sendrmi " + e.getMessage());
    return 1;
    *<p>This method runs the applicatoin every 60 seconds, so that accurate data is recorded</p>
    public void StatusRequestTimer()
    StatusRequestTimer = new EventHandler(this, "message");
    StatusRequestTimer.initialise();
    StatusRequestTimer.startEvent(90);
    public void eventMessage(Object obj, String s)
    if(obj == StatusRequestTimer)
    System.arraycopy(TestPcContainer, 0, TestPcContainerCopy, 0, count);
    TestPcContainer = null;
    testpc = null;
    initializeObjects();
    *<p>method to set an ip address </p>
    *@param ipadd IP address
    public void setIp(String ipadd)
    ipaddress = ipadd;
    public void setTmName(String tm)
    tmname = tm;
    *<p>method to get an ip address</p>
    *@return string ip address
    public String getIp()
    return ipaddress;
    public String getTmName()
    return tmname;
    *<p>method to get whether the tm was valid, meaning it responded or not. /p>
    *@return string ip address
    public int getTmValid()
    return tmvalid;
    *<p>method to get whether the ip address was valid, meaning online or not, 1 for valid, 0 for not</p>
    *@return string ip address
    public int getIpValid()
    return ipvalid;
    *<p>method to get whether the morb on the TestPc is running or not, 1 for valid, 0 for invalid</p>
    *@return int morbValid
    public int getMorbValid()
    return morbvalid;
    *<p>method to set validity of the ip addres, recieves result from TMHealthStatusICMPcheck</p>
    *@param result passed in result of validity check on ip address, 1 for valid, 0 for invalid</p>
    public void setIPValid(int result)
    ipvalid = result;
    *<p>method to set validity of the Morb to the result</p>
    *@param result passed in result of validity check on morb, 1 for valid, 0 for invalid</p>
    public void setMorbValid(int result)
    morbvalid = result;
    *<p>method to set validity of the Morb to the result</p>
    *@param result passed in result of validity check on morb, 1 for valid, 0 for invalid</p>
    public void setTmValid(int result)
    tmvalid = result;
    *<p>method to create new XYRMIClient object, pass to it a TMHealthStatusTestPc object, extract
    * its ip address, then send an rmi message to the orb of that machine. Used to check if the TestPc's
    * Orb is runnning.
    *@param pc TMHealthStatusTestPc object
    public int checkMorbAvail()
    for(int q = 0; q < count; q++)
    if(TestPcContainer[q].getIpValid() == 1)
    host = TestPcContainer[q].getIp();
    if(counter != 1)
    Orblink1[q].XYRMIMessageHandler(initalMessage2 + host);
    }//close if
    else
    try
    Orblink1[q] = new XYRMIClient(this, host, port, initalMessage2 + host);
    Orblink1[q].SetIdentity(className + "2", objectName);
    Orblink1[q].start();
    } //close try
    catch(Exception e)
    System.out.println("error in checkmorbavail" + e.getMessage());
    }//close catch
    }//close if
    try
    Thread.sleep(30000);
    catch(Exception e)
    System.out.println("errror here");
    checkTmAvail();
    return 1;
    *<p>method to register with the Orb and send a message to its TestManager. If successful sends
    * initial message consisting of the ip address of the TestPc plus "tm" attached to the end.
    * Used to check whether the TestManager software is running on that machine</p>
    *@param pc takes a TMHealthStatusTestPc object as argument
    public int checkTmAvail()
    for(int r = 0; r < count; r++)
    if(TestPcContainer[r].getMorbValid() == 1)
    host = TestPcContainer[r].getIp();
    if(counter != 1)
    Orblink2[r].XYRMIMessageHandler(initialMessage3 + host + "tm");
    else
    try
    Orblink2[r] = new XYRMIClient(this, host, port, initialMessage3 + host + "tm");
    Orblink2[r].SetIdentity(className + "3", objectName);
    Orblink2[r].start();
    catch(Exception e)
    System.out.println("error in checktm is " + e.getMessage());
    else
    System.out.println("not valid");
    try
    Thread.sleep(1000);
    catch(Exception e)
    doSomething();
    StatusRequestTimer();
    return 1;
    *<p>method to create a new XYRMIObjectInterface to handle incoming messages. Checks to see
    *whether the incoming meesage has the method name of the ipaddress of each tm meaning that its morb
    *has been successfully registered with. Also checks to see if the method has the method name of
    *the ipaddress of the tm plus "tm" attached to the end, meaing that the tm has successfully received
    *the message and is returning with conformation. </p>
    *@return int
    *@param s Takes as a parameter a string
    public synchronized int XYRMIMessageHandler(String s)
    XYRMIObjectInterface msg = null;
    XYRMIObjectInterface msg1 = null;
    msg1 = new XYRMIObjectInterface(s);
    if(msg1.IsMethodName("RequestTestManagerStatus"))
    System.out.println("got requesttestmanstatus, sending rmi");
    sendRMI();
    else
    for (int i = 0; i < count; i ++)
    msg = new XYRMIObjectInterface(s);
    try
    if(msg.IsMethodName(TestPcContainer[i].getIp()))
    TestPcContainer[i].setMorbValid(1);
    System.out.println("setting morb valid");
    if(msg.IsMethodName(TestPcContainer[i].getIp() + "tm"))
    TestPcContainer[i].setTmValid(1);
    System.out.println("setting tmvalid");
    catch(Exception e)
    System.out.println("message in xyrmimesagehandler is " + e.getMessage());
    return 1;

  • How do you determine StringBuffer and List capacity?

    hi all,
    I'm curious and would like to post this query that how to determine the StringBuffer and List capacity after read some of the Java Platform performance book. Some of this performance books simply tells number of capacity brieftly without telling what and how does the capacity stand for.
    First, the book mentioned StringBuffer(50). Note, my question is that what is this 50 stand for? 50 Characters? or any. Can someone help me to rectify this?
    Second, List. ArrayList(0.75). And what is this 0.75(by default) stand for? A heap space? Then how many of them? How many objects that can be stored for not to "exceed 0.75"?
    Please help. :)
    regards,
    Elvis
    scjp

    I think the capacity is the CURRENT size of a container. But it is not equal to the number of elements that container currently hold. Just like, a house can have 10 people within, but problably only 3 people at some time. Also, the capacity is not equal to the maximum size, because container can grows automatically.
    For example, a container whose capacity is 50, currently has 30 elements in it. If you add 10 elements more. That is only an addition operation. But if you add 30 elements to it. Then the container first enlarge its capacity according to some arithmetic(a enlarging rate), secondly carry out the addition operation.
    Now that the capacity is the size, it should be a number standing for HOW MANY elements.... In the case of StringBuffer, it should be how many chars; in the case of ArrayList, it should be how many Objects. I do not think 0.75 can stand for a capacity. Prabaly, it was used to describe the enlarging rate when containers need to contain more elements than its current capacity. ( From JDK API, you can see the type of capacity is int ).
    For containers and alike, the questions "how many I can hold" and "how many I am holding", "Do I can enlarge"? are helpful for understanding how it works.

  • Storing data in Array or StringBuffer and then comparing it to a string

    I want to store some data in a list or an Array (but apparently an Array only holds 10 items?) and then I want to be able to check if myString is equal to any of the posts in the array/list.
    Or if I use a StringBuffer I want to check to see if myString is part of the StringBuffer?
    How do I do this?
    / Elin

    I want to store some data in a list or an Array (but
    apparently an Array only holds 10 items?)Uh, no. Arrays can (theoretically) contain Integer.MAX_VALUE elements.
    and then I want to be able to check if myString is equal to any
    of the posts in the array/list.Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same character sequence), use equals(), e.g. if (str1.equals(str2))...
    Example:String s1 = "foo";
    String s2 = new String("foo");
    System.out.println("s1 == s2: " + (s1 == s2)); // false
    System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus ==
    Or if I use a StringBuffer I want to check to see if
    myString is part of the StringBuffer?See above discussion on .equals().
    How do I do this?
    Here are some other resources to help you get started with Java.
    The Java&#153; Tutorial - A practical guide for programmers
    Essentials, Part 1, Lesson 1: Compiling & Running a Simple Program
    New to Java Center
    How To Think Like A Computer Scientist
    Introduction to Computer Science using Java
    The Java Developers Almanac 1.4
    JavaRanch: a friendly place for Java greenhorns
    jGuru
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

  • Collection.equals

    The javadocs for collection.equals states
    "The general contract for the Object.equals method states that equals must be symmetric (in other words, a.equals(b) if and only if b.equals(a)). The contracts for List.equals and Set.equals state that lists are only equal to other lists, and sets to other sets. Thus, a custom equals method for a collection class that implements neither the List nor Set interface must return false when this collection is compared to any list or set. (By the same logic, it is not possible to write a class that correctly implements both the Set and List interfaces.) "
    Why not? Couldn't a class implement both List and Set and compare either way, depending on what kind of object it is being compared with?
    FYI I grumbled about equals before in a previous post
    http://forum.java.sun.com/thread.jspa?forumID=425&threadID=619976
    I was just working on something and came across a bug in my code because I was hashing something using an arrayList as a key, and I believed incorrectly that equals would be implemented the same way it is for arrays.
    It seems weird to me that Collection, List and Set require symmetry and transitivity between all classes implementing them, but CharSequence (an interface implemented by both String and StringBuffer, ala my other post) does not.
    CharSequence states:
    "This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. It is therefore inappropriate to use arbitrary CharSequence instances as elements in a set or as keys in a map"
    Ok. So the guys working on Java have given us at least three or four different patterns to follow here: There are arrays which we know are only equal if they are the same array. There's the Object (general) implementation of equals in which we can count on objects of different classes being different. There's List and Set where all lists and sets are equal to other lists and set respectively, and there's the CharSequence pattern in which all bets are off.
    Wouldn't it be easier for people to learn and program in java if they could rely on one of these patterns without having to go through the javadocs with a fine toothed comb?

    No.
    Let's say you have a List, (L) a Set (S) and a
    List/Set (LS).
    You want both of the following to be able to be
    true:
    LS.equals(L)
    LS.equals(S)
    However, symmetry and transitivity combine to tell us
    that L.equals(S) and S.equals(L) must also return
    true.
    The contracts for List and Set require L.equals(S)
    and S.equals(L) to return false.
    Ah ok. Thanks for clearing that up for me. It seems kind of limiting to say that there could never be a collection that is both a list and a set, but I guess it wouldn't be too hard to work around.
    Object and arrays use the same equals method--only
    returns true if the references are equal.Yes, I meant Object in the general sense, not the Object class itself. So things like Integer(5) can be equal to another Integer, but never to a Float.
    There's List and Set where all lists and
    sets are equal to other lists and setrespectively,
    No. Any List can be equal to any other List,
    and any Set can be equal to any other Set. In
    both cases, it depends on what elements the
    collection contains.Right, sorry that's what I meant to say.
    It makes sense that List and Set define equals the
    way they do. Since Lists are ordered, it makes sense
    that the order should matter in determining equality.
    Since Sets are not ordered, it would not make
    sense to use order in determining equality.Naturally. But it might also make sense just to say that lists and sets are only equal to themselves.
    and there's the CharSequence pattern in which all
    bets are off.There's nothing special about CharSequence. It's just
    another interface that doesn't define a specific
    equals implementation.Yes. What I was trying to get at is that while in general objects (such as subclasses of Number) are only be equal to objects of the same class, and lists and sets must be equal to other lists and sets, respectively, that CharSequence says that some subclasses MAY be comparable using equals.
    However, ease of learning is not the one and only
    supreme driving force behind the design of the
    language and the APIs.Acknoledged. What I mean is that with equals following all these different patterns, it is easy to make a mistake that goes unnoticed until software is in the hands of the clients.
    Rather than trying to cram equals (or anything else)
    into a fixed set of pigeonholes, you'd be better
    served to try to undertand the fundamental purpose
    behind it and what kinds of factors go into deciding
    what the appropriate implementation is in a given
    situation.Ok. What is the fundamental purpose behind equals? Not trying to be hostile here, I'm just curious. I know that one of the biggest factors is with collections and such questions as hashing and contains. Another big one is String.equals(...) to compare strings. Are there any others?
    I'm just trying to figure out how it might be possible to make equals() more opaque in future languages, so that people can read the basic definition of equals given in Object and know how it is used and how to use it. If you think that it is already clear and easy to use, consider that using FindBugs (google for FindBugs if you are interested) I found a bug in the java source in ChoiceFormat that has existed since ChoiceFormat's inception in Java 1.1 in which it calls equals between a StringBuffer and a String. If the people working on designing Java can make these mistakes, what hope have the rest of us?

  • Needed help in sorting values in StringBuffer

    Hi,
    I will get a StringBuffer as an input which contains lines in different order,
    Please refer the below example
    "A,B,C,D, LINE_NO=1"
    "E,F,G,H, LINE_NO=8"
    "I,J,K,L, LINE_NO=6"
    "M,N,O,P, LINE_NO=3"
    All the above four lines will be in the StringBuffer based on the above order,
    I need to create a new StrinBuffer order by Line_No.
    Can anyone help me on this..?

    Steps
    1) Split the StringBuffer content into an array containing the lines. You can use String.split() to do this.
    2) Create a java.util.Comparator that takes two lines and returns -1 if the first should be earlier than the second, zero if the two lines are considered equal and +1 if the second should be earlier than the first.
    3) Sort the array using java.util.Arrays.sort(array, comparator);
    4) Build a new StringBuffer from the sorted array.

  • Alternative for StringBuffer

    Hi,
    In the DAO classes, we are using the StringBuffer to append various SQL statements based on the condition, hence there are so many append statements every where. Is there any other alternative we have
    public List<Customer> getReport(String custType) {
    StringBuffer strBuffer = new StringBuffer();
    strBuffer.append("Select * from Customer cust");
    if(custType.equals("HOME)){
    strBuffer.append("where ......");
    } else if(custType.equals("BUSINESS){
    strBuffer.append("where ......");
    )else if(custType.equals("NONE"){
    strBuffer.append("where ......");
    This is just a sample likewise we have many more, Is there anyway to optimize it through a design pattern?
    Thanks

    797836 wrote:
    This is just a sample likewise we have many more, Is there anyway to optimize it through a design pattern?You are building SQL based on some dynamic input. Thus by definition it is and will remain dynamic.
    So the question is what options are there to build it dynamically?
    Options
    1. Do it as you are doing it.
    2. Use full length strings that reflect all of the possibilities. Unlikely to be a real solution because it involves too many possibilities.
    3. Provide another construction idiom. This changes the specifics but not general idiom.
    4. Generate the code.
    Myself I would choose the last. You provide a source file that specifies each target case.
    You have a compiler which takes the source file and emits java code, which produces basically exactly what you already have.
    Changes then are a matter of changing the source file.
    The complexity of this depends on the complexity of what you are doing. One should be cautious of attempting all cases if it appears the complexity level of some are too great. Doing the most complex manually might be more cost effective.
    A sample source file could be a text file that looked like the following.
           Statement: Select * from Customer cust
           Field: HOME ...
           Field: BUSINESS ...Naturally the cost here is in building the compiler.

  • Initialization of a stringbuffer

    I would like to know if it is possible in the code below to initialize "feedback" to a number of '_' equal to the length of "code". Is there anything in a string api that would allow me to do this?
    public class stringTest
         StringBuffer feedback; // replace this example variable with your own
    String code="alicja";;
         * Default constructor for objects of class stringTest
         public stringTest()
         {super();
         feedback=new StringBuffer(code);
         }

    Lilith26 wrote:
    The problem is that I don't want a method Why not?
    as this is kind of quiz. So?
    I code a password and replace it with "*". Each time you guess a letter star changes into a letter. problem is that if I do a method it would reset my stringbuffer every turn to a number of *s. This is why I wanted to initiazlize it in a constructor and than write a method to replace stars with letters
    StringBuffer sb = new StringBuffer(myMethod('*', count));StringBuffer has a c'tor that takes a String, so all you have to do is write a tiny little method that takes in a character and a count and builds up a String from them.
    Or, you could create an empty SB, then pass it to a method that calls append as many times as you need. What's the difference if you initialize the SB or fill it up one statement later?
    Edited by: jverd on Dec 23, 2008 2:45 PM

  • Verify special char is in String before append into StringBuffer

    I have following code to verify A special char "X" is in the String before continue adding it to a StringBuffer:
    private boolean veriChar(String poem){
    if(peom.indexOf("X")==-1) return false;// make sure X is in the String
    return true
    However, if I only want a single X in String to return true, any method to use? for example: poem=" EXTRA TEXT" (2 Xes here) needs to be rejected to be false.

    take this code compile it and see for yourself.
    public class Test{
      public static void main(String args[]){
        Test t = new Test();
        System.out.println(""+t.veriChar("MATT"));
        System.out.println(""+t.veriChar("MAX"));
        System.out.println(""+t.veriChar("MAXX"));
      private boolean veriChar(String toCheck){
        return!((toCheck.indexOf("X")<0)||(toCheck.indexOf("X")!=toCheck.lastIndexOf("X")));
    } you will see that the first and third ones return false and the second returns true which is as you want.
    now an explanation of what is happening.
    the method looks like this
    private boolean veriChar(String toCheck){
        return!((toCheck.indexOf("X")<0)||(toCheck.indexOf("X")!=toCheck.lastIndexOf("X")));
      }first we check if the special X or whatever exists in the string at all
    toCheck.indexOf("X")<0;this returns true for the first test of MATT
    now we check if the last occurance in our string of the special X is the same position as the first occurance. if it is then we have only one special X. if not then we have more than one special X.
    toCheck.indexOf("X")!=toCheck.lastIndexOf("X")note that we check for not equals so that for MAX it returns false and for MAXX it returns true
    so now we have our answers but they are inverted from what we want so we put the ! which gives the boolean opposite. so that the MAX returns true and the other two return false.

Maybe you are looking for

  • How to print a table in OA Framework using Jdeveloper?

    I am using JDeveloper for OA Framework, in my page i want to print a table thorugh Print button. Please give me some suggestion/methods to do this...

  • Class Cast Exception when Rich Table is typecasted with Rowset

    The following line throws a Class Cast Exception if(RowCountHelper.containsNoRows((RowSet)getAddMembersTable())) The above piece of code has been working since long & it started throwing the class cast exception recently. Not sure how the line of cod

  • WDA application on virtual host (port)

    Hi, is there a way how to deploy (create) a webdynpro application on a virtual host (port)? As I generate a webdynpro application, SAP creates a service under default host (port). I need to have my application accessible only on virtual host (port) -

  • Help with the check box.

    Hi, I have a question with the Checkbox. I am using Apex 4.0. I have 5 checkboxes and using the Lovs I have given values to each check box. When I select the checkboxes and submit, the values are inserted into a single column. Example Consider CB as

  • Modem status on hold after some inactivity

    here is the problem i have nokia 5320 XM .I have edge gprs by airtel. When i remain inactive for 1 hour or so the modem status shows "on hold" and if i have a download in progress it also breaks and stops. Is there a way to use the internet connectio