Using equals() to compare strings

It was told in a previous post that when comparing two strings to use the equals()
So rather than doing something like this
package relationships;
public class Starter {
     public static void main(String[] args){
          String foo = "foo";
          String bar = "bar";
          if(foo == bar){
               System.out.println("Strings are logically equal");
          } else if(foo != bar){
               System.out.println("Strings are not logically equal");
}Where the console would output "Strings are not logically equal" How would I do this using the equals() (other then using else)
package relationships;
public class Starter {
     public static void main(String[] args){
          String foo = "foo";
          String bar = "bar";
          if(foo.equals(bar)){
               System.out.println("Strings are logically equal");
          } else if( /* WHAT GOES HERE? */ ){
               System.out.println("Strings are not logically equal");
}I know to test if they are equal just to go like this foo.equals(bar) but what would I put in the else if?
else if( /* WHAT GOES HERE? */ )

Where the console would output "Strings are not
logically equal" How would I do this using the
equals() (other then using else)You don;t need anything else. If it is not true it is false there isn't a third boolean value of maybe or perhaps.

Similar Messages

  • [svn:bz-trunk] 21292: Fix BLZ-639 - avoid the use of "==" when comparing strings.

    Revision: 21292
    Revision: 21292
    Author:   [email protected]
    Date:     2011-05-25 12:09:39 -0700 (Wed, 25 May 2011)
    Log Message:
    Fix BLZ-639 - avoid the use of "==" when comparing strings.  Just check for null explicitly.
    Ticket Links:
        http://bugs.adobe.com/jira/browse/BLZ-639
    Modified Paths:
        blazeds/trunk/modules/common/src/flex/messaging/config/ClientConfiguration.java

    Adobe has donated BlazeDS to the Apache Flex community, and the source code is hosted on the Apache Flex website in a GIT repository.
    http://flex.apache.org/dev-sourcecode.html

  • Use hashCode() to compare strings instead of equalsIgnoreCase()

    The HashCode method has a contract which says
    " If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. "
    Hence does it not make sense to use hashcode() method to compare two strings instead of using equals() method ? For example instead of using
    String s = "One";
    System.out.println("Strings equal = "+s.equals("Two"));
    we can write
    String s = "One";
    System.out.println("Strings equal = "+(s.hashCode()=="Two".hashCode()));

    Here is just a short list of strings with 3 characters that has the same hashcodes:
    2NX and 2O9 has same hashCode 50556
    3NX and 3O9 has same hashCode 51517
    4NX and 4O9 has same hashCode 52478
    5NX and 5O9 has same hashCode 53439
    6NX and 6O9 has same hashCode 54400
    7NX and 7O9 has same hashCode 55361
    8NX and 8O9 has same hashCode 56322
    9NX and 9O9 has same hashCode 57283
    :NX and :O9 has same hashCode 58244
    ;NX and ;O9 has same hashCode 59205
    <NX and <O9 has same hashCode 60166
    =NX and =O9 has same hashCode 61127
    NX and >O9 has same hashCode 62088?NX and ?O9 has same hashCode 63049
    @NX and @O9 has same hashCode 64010
    ANX and AO9 has same hashCode 64971
    BNX and BO9 has same hashCode 65932
    CNX and CO9 has same hashCode 66893
    DNX and DO9 has same hashCode 67854
    ENX and EO9 has same hashCode 68815
    FNX and FO9 has same hashCode 69776
    GNX and GO9 has same hashCode 70737
    HNX and HO9 has same hashCode 71698
    INX and IO9 has same hashCode 72659
    JNX and JO9 has same hashCode 73620
    KNX and KO9 has same hashCode 74581
    LNX and LO9 has same hashCode 75542
    MNX and MO9 has same hashCode 76503
    NNX and NO9 has same hashCode 77464
    ONX and OO9 has same hashCode 78425
    PNX and PO9 has same hashCode 79386
    QNX and QO9 has same hashCode 80347
    RNX and RO9 has same hashCode 81308
    SNX and SO9 has same hashCode 82269
    TNX and TO9 has same hashCode 83230Kaj

  • Error in using .equals in JSP

    i'm using .equals to compare string value but every time i refresh the page it returns an error.
    <%@include file = "connection/dbconnect.js"%>
    <select name="List_Type" style="width:150px;height:23px" class="styleFieldEntry">
    <%if(request.getParameter("Found")==null || request.getParameter("Type1")==""){%>
    <option value="" selected>All</option>
    <%}else{%>
    <option value="" selected>All</option>
    <%}%>
    <%rs = statement.executeQuery("SELECT Type1 From somain group by Type1 order by Type1 ");
    rs.next();
    while (rs.next())
    { if(request.getParameter("List_Type").equals(rs.getString("Type1"))){%>
    <option value="<%=rs.getString("Type1")%>" selected><%=rs.getString("Type1")%></option>
    <%}else{%>
    <option value="<%=rs.getString("Type1")%>"><%=rs.getString("Type1")%></option>
    <%}}%>
    </select>      Error:
    exception
    org.apache.jasper.JasperException
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:373)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    java.lang.NullPointerException
         org.apache.jsp.inventory.soFind_jsp._jspService(org.apache.jsp.inventory.soFind_jsp:143)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

    This is very hard to read
    insert standard rant about mixing ugly scriptlet code into a JSP like this.
    Recommend the use of JSTL to reduce scriptlet code.
    Also comment on how SQL should never be in a JSP, but rather be in a bean somewhere.
    Particularly if it is a static list, that doesn't depend on any parameters.
    And why call rs.getString("Type1") four seperate times? Call it once and reuse the variable.
    I can't see the reason for that first if statement, as it does the same thing on either branch of the if.
    Also, you have an extra rs.next() that you might not need.
    [ end rants]
    Oh - your null pointer exception.
    It could be coming from several places:
    Most likely is request.getParameter("List_Type").equals...
    If the parameter List_Type is not present, then it will fail.
    Also you have request.getParameter("Type1")=="")
    that should be
    if (request.getParameter("Type1")==null || request.getParameter("Type1".equals("")

  • Comparing equality between 2 strings using '=='

    Sorry if this seems a pretty trivial question, but it has me rather puzzled.
    when comparing reference types (objects) for equality using '==' , it normally only returns true if the two operands are one and the same object.
    Now say I were to test this out with the following code:
    public class EqualsTest {
      public static void main(String[] args)  {
         String a = "hello";
         String b = "hello";
         System.out.println(a==a);
         System.out.println(a==b);
         System.out.println(a.equals(a));
         System.out.println(a.equals(b));
    }a==b actually returns true. This seems counter to what I expected; aren't Strings a and b separate objects despite being the same value (i.e. the literal value of "hello")?
    However if I were to change the two string initializations to:
         String a = new String("hello");
         String b = new String("hello");...then it works as expected.
    What's the difference here? I'm puzzled...

    Grant, thanks for your answer - I am unclear as to
    the concept of this constants pool - maybe I'll do a
    search on that...As both a space and time saving, when you put something in "" in your code, it gets put into the 'constant pool' section of your class file, and everywhere in your code you use the exact same string ends up referencing the same entity.
    You can accomplish this with runtime Strings by using the String.intern() method - it adds the String to the CP, and lets you use == for compares. Can be useful in code where performance is more important than clarity.
    Consider this sample:public class StrCheck {
    public static boolean pool() {
      String a = "one";
      String b = "one";
      return (a==b);
    public static boolean ctor() {
      String c = new String("two");
      String d = new String("two");
      return c==d;
    }which decompiles to:ggainey@dhcp59-157 t]$ javap -c -s -verbose StrCheck
    Compiled from "StrCheck.java"
    public class StrCheck extends java.lang.Object
      SourceFile: "StrCheck.java"
      minor version: 0
      major version: 49
      Constant pool:
    const #1 = Method       #7.#17; //  java/lang/Object."<init>":()V
    const #2 = String       #18;    //  one
    const #3 = class        #19;    //  java/lang/String
    const #4 = String       #20;    //  two
    const #5 = Method       #3.#21; //  java/lang/String."<init>":(Ljava/lang/String;)V
    const #6 = class        #22;    //  StrCheck
    const #7 = class        #23;    //  java/lang/Object
    const #8 = Asciz        <init>;
    const #9 = Asciz        ()V;
    const #10 = Asciz       Code;
    const #11 = Asciz       LineNumberTable;
    const #12 = Asciz       pool;
    const #13 = Asciz       ()Z;
    const #14 = Asciz       ctor;
    const #15 = Asciz       SourceFile;
    const #16 = Asciz       StrCheck.java;
    const #17 = NameAndType #8:#9;//  "<init>":()V
    const #18 = Asciz       one;
    const #19 = Asciz       java/lang/String;
    const #20 = Asciz       two;
    const #21 = NameAndType #8:#24;//  "<init>":(Ljava/lang/String;)V
    const #22 = Asciz       StrCheck;
    const #23 = Asciz       java/lang/Object;
    const #24 = Asciz       (Ljava/lang/String;)V;
    public StrCheck();
      Signature: ()V
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    public static boolean pool();
      Signature: ()Z
      Code:
       Stack=2, Locals=2, Args_size=0
       0:   ldc     #2; //String one
       2:   astore_0
       3:   ldc     #2; //String one
       5:   astore_1
       6:   aload_0
       7:   aload_1
       8:   if_acmpne       15
       11:  iconst_1
       12:  goto    16
       15:  iconst_0
       16:  ireturn
      LineNumberTable:
       line 3: 0
       line 4: 3
       line 5: 6
    public static boolean ctor();
      Signature: ()Z
      Code:
       Stack=3, Locals=2, Args_size=0
       0:   new     #3; //class java/lang/String
       3:   dup
       4:   ldc     #4; //String two
       6:   invokespecial   #5; //Method java/lang/String."<init>":(Ljava/lang/String;)V
       9:   astore_0
       10:  new     #3; //class java/lang/String
       13:  dup
       14:  ldc     #4; //String two
       16:  invokespecial   #5; //Method java/lang/String."<init>":(Ljava/lang/String;)V
       19:  astore_1
       20:  aload_0
       21:  aload_1
       22:  if_acmpne       29
       25:  iconst_1
       26:  goto    30
       29:  iconst_0
       30:  ireturn
      LineNumberTable:
       line 9: 0
       line 10: 10
       line 11: 20
    }You can see the constant pool (and lots of other neat stuff) in the disassembled output. Note that "ldc" is LoaDing a Constant from the pool - in pool(), you can see it loading constant #2 twice, and then comparing the results. ctor() uses #4 twice, but loads the results of invokespecial() and compaes that.
    Grant

  • Compare Strings using JSTL

    How can I compare strings with JSTL? One string is a stored date and the other is a generated date. My goal is to set the correct date in a dropdown menu with date values (yyyy-MM-dd) by comparing the current date with the stored.
    Code
    <%
    Calendar cal = Calendar.getInstance(timezone, locale);
    Format fm = new SimpleDateFormat("yyyy-MM-dd");
    String date2 = (String) fm.format(cal.getTime()); %>
    <c:set var="date1" value="${mb.date}" />   // from database lookup (MySQL Date)
    <p><c:out value="${date1}"/>=<%=date2%>:<c:out value="${date1 == '<%=date2%>' }" /></p>The result is:
    2004-08-03 = 2004-08-03 : false

    well, about this:
    <%
    Calendar cal = Calendar.getInstance(timezone, locale);
    Format fm = new SimpleDateFormat("yyyy-MM-dd");
    String date2 = (String) fm.format(cal.getTime());
    pageContext.setAttribute("date2",date2);
    %>
    <c:set var="date1" value="${mb.date}" />   // from database lookup (MySQL Date)
    <p><c:out value="${date1}"/> .equals <%=date2%>:<c:out value="${date1eq date2}" /></p>I try to use the EL 'eq' like you would use '.equals()' in regular java, and EL '==' like regular java '==' And since we are comparing Strings here, which are objects, we would use .equals rather than ==, since == compares refernce and .equals compares value...

  • How come the JRE uses == to compare Strings?

    I was looking through the source of javax.swing.plaf.basic.BasicComboBoxUI and came across this:        public void propertyChange(PropertyChangeEvent e) {
                String propertyName = e.getPropertyName();
             JComboBox comboBox = (JComboBox)e.getSource();
                if ( propertyName == "model" ) {
                else if ( propertyName == "editor" && comboBox.isEditable() ) {
                else if ( propertyName == "editable" ) {
                else if ( propertyName == "enabled" ) {
                else if ( propertyName == "focusable" ) {
                else if ( propertyName == "maximumRowCount" ) {
                else if ( propertyName == "font" ) {
                else if ( propertyName == JComponent.TOOL_TIP_TEXT_KEY ) {
                else if ( propertyName == BasicComboBoxUI.IS_TABLE_CELL_EDITOR ) {
             else if (propertyName == "prototypeDisplayValue") {
             else if (propertyName == "renderer") {
            }So
    1) Is there a valid reason for the developer to have used == instead of .equals(...) to compare Strings?
    2) How does the code work consistently with this anomaly?
    Similar use of == and not .equals(...) is seen in many other swing classes.
    Doesn't affect me, but I would be interested to know if anyone can throw some light on this.
    Thanks, Darryl

    Darryl.Burke wrote:
    DeltaGeek, thank you for your response.
    Paul, I think I understand what you are saying, but the String reference propertyNamein this case comes from e.getPropertyName() from the PropertyChangeEvent class, not from within the BasicComboBoxUI class.
    I gather that all loaded classes share the same String pool, and that's how this works correctly. But in that case any comparison of a String variable to a literal String using == should also work.
    Then why the brouhaha about never using == to compare Strings?The key thing here is that the String returned by getPropertyName() must have come from a String literal. For example, in javax.swing.JComboBox:
    firePropertyChange( "maximumRowCount", oldCount, maximumRowCount );This string literal will be the same instance as the string literal in the code you posted.
    If they had instead done something like
    String s = "RowCount";
    boolean isMaximum = true;
    firePropertyChange((isMaximum ? "maximum" : "minimum") + s, oldCount, maximumRowCount );In this case, the String literal "maximumRowCount" is not used, but rather created from a concatenation at runtime, so it's likely that the comparison would fail.
    Note that the following would be the same String literal because this concatenation would be done at compile-time, not runtime:
    "maximum" + "RowCount"As for why, I agree with DeltaGeek: performance.

  • Comparing TreePaths using equals()

    hello,
      I am trying to use the equals() method on two TreePaths...
    one path is obtained like....
    TreePath test_path = new TreePath(tree.getSelectionPath());
    the other path is got from a vector of all the paths on my Jtree.
    this vector is built by the code below
    public void getPaths(JTree tree, TreePath parent, Vector list) {
            list.add(parent);
            // Create paths for all children
            TreeNode node = (TreeNode)parent.getLastPathComponent();
            if (node.getChildCount() >= 0) {
                for (Enumeration e1=node.children(); e1.hasMoreElements(); ) {
                    TreeNode nt = (TreeNode)e1.nextElement();
                    TreePath path = parent.pathByAddingChild(nt);
                    getPaths(tree, path, list);
    problem is when i try this....
    for(i=0; i<list.size(); i++){
                   TreePath pop_path = (TreePath)list.elementAt(i);
                   if(test_path.equals(pop_path)){
                        System.out.println(test_path.toString() + " equals " + pop_path.toString() );
                   else{
                        System.out.println(test_path.toString() + " no equals " + pop_path.toString() );
    I get this output.....
    [[Files and Dirs to Backup, /home/mohadib/test_dir1]]jd path
    [[Files and Dirs to Backup, /home/mohadib/test_dir1]] no equals [Files and Dirs to Backup]
    [[Files and Dirs to Backup, /home/mohadib/test_dir1]] no equals [Files and Dirs to Backup, /home/mohadib/test_dir1]
    [[Files and Dirs to Backup, /home/mohadib/test_dir1]] no equals [Files and Dirs to Backup, /home/mohadib/test_dir1, /home/mohadib/test_dir1/z]
    [[Files and Dirs to Backup, /home/mohadib/test_dir1]] no equals [Files and Dirs to Backup, /home/mohadib/test_dir1, /home/mohadib/test_dir1/jason]
    [[Files and Dirs to Backup, /home/mohadib/test_dir1]] no equals [Files and Dirs to Backup, /home/mohadib/test_dir1, /home/mohadib/test_dir1/jason, /home/mohadib/test_dir1/jason/test.class]
    i dont know where the extra [] are coming from around the first path...i regexed
    them out and still did not get a match. Could some one tell me what im
    missing?
    thanks,
    jd

    Thank you that was helpful. So, if i regex out the extra [] then
    why is this...
    [Files and Dirs to Backup, /home/mohadib/test_dir1] no equals [Files and Dirs to Backup, /home/mohadib/test_dir1]
    here is the code i used...
    String path_reg = new String(tree.getSelectionPath().toString());
              System.out.println(path_reg + "before");
              String clean_reg_string2 = new String(path_reg.replaceAll("^\\[", ""));
              String clean_reg_string1 = new String(clean_reg_string2.replaceAll("\\]$", ""));
              TreePath test_path = new TreePath(clean_reg_string1);
              System.out.println(test_path.toString() + "jd path");
              TreeNode root = (TreeNode)tree.getModel().getRoot();
              Vector list = new Vector(0);
              getPaths(tree, new TreePath(root), list);
              int i;
              for(i=0; i<list.size(); i++){
                   TreePath pop_path = (TreePath)list.elementAt(i);
                   if(test_path.equals(pop_path)){
                        System.out.println(test_path.toString() + " equals " + pop_path.toString() );
                   else{
                        System.out.println(test_path.toString() + " no equals " + pop_path.toString() );
              }thanks,
    jd

  • How to compare string in a case-insensitive manner using JavaScript?

    Hello everyone,
    Now I have a javascript to compare checkbox's value with user's input, but now seems it only can compare case-sensitively, does some one know if there is a function in javascript that it can compare string case-insensitively ?
    Here is my script :
    function findOffice(field)
    var name;
    name=prompt("What is the office name?");
    var l = field.length;
    for(var i = 0; i < l; i++)
    if(field.value==name)
    field[i].checked=true;
    field[i].focus();
    field[i].select();
    break;
    <input type="button" name="Find" value="Find And Select" onClick="findOffice(form1) >
    Thanks in advance !
    Rachel

    Thank you so much, I already solved the problem with your advice.
    You really have a beautiful mind, :-).
    I appreciate your help !
    Rachel

  • How do you make an object, whose name is equal to a String?

    Ok, heres my situation, I have a vector full of strings which i've enumerated.. and i need to create a bunch of JCheckBox's whose names are equal to the strings in the Enumeration..
    I tried going:
              Enumeration Type = TypeList.elements();
              while(Type.hasMoreElements()){
                   String T = (String)Type.nextElement();
                   list.add(new JCheckBox(""+T));
    which makes them appear in the GUI, but i dont know how i would then be able to add an actionListener onto that checkbox, or indeed how i would go about accessing any of them when they dont have actual names.
    ANy Help would be appreciated.
    Thanks

    Yeh.. i dont get this.. I've got them to appear in the JPanel with:
              Enumeration Type = TypeList.elements();
         boxMap = new HashMap();
              while (Type.hasMoreElements()) {
                   String T = (String) Type.nextElement();
                   JCheckBox b = new JCheckBox(T);
                   boxMap.put(T,b);
                   list.add(b);
                   b.addActionListener(ch);
    Thats all well and good, but when i try and see which one has been clicked using a similar fashion:
                   if(ae.getSource() instanceof JCheckBox) {          //checkbox
                   Enumeration sourceCheck = TypeList.elements();
                   System.out.println((JCheckBox)ae.getSource().getAccessibleContext());
              Map SourceMap = new HashMap();
                   JCheckBox compare = (JCheckBox) ae.getSource();
              while (sourceCheck.hasMoreElements()) {
                   String T = (String) sourceCheck.nextElement();
                   System.out.println(T);
                   JCheckBox b = new JCheckBox(T);
                   SourceMap.put(T,b);
                   if(compare == b)
                        System.out.println("Oh My : "+T);
                   System.out.println("ZoomJ I have been clicked");
    in my action performed method it doesnt seem to be able to compare them.. its definately registering that its been clicked because it prints out the 'ive been clicked ' message, and it prints out all the correct names from the Vector, but it doesn't seem to compare them..

  • Using JSplitPane for Comparing two Files/Contents

    Hi Java Gurus,
    I want to develope a Comparison tool which compares 2 jar files and report the difference in a user friendly manner. Everything is fine and i selected the JSplitPane to display the difference report. I face some problems in doing it exactly simillar way of presenting like a Comparison tools which is there in VSS.
    I created 2 panels and added in a splitpane.
    one panel contains the content of first jar file and another panel contains the content of second jar file.
    The content are added in a textarea and the textarea is added to a scrollpane, which is added to the panel.
    If i fix some size to Textarea, when i expand the Splitpane, the size is not getting expanded accordingly.
    if i remove the size for textarea, the content is not displayed.
    Can anyon give some suggestion.
    Have anybody developed a GUI using JSplitPane simmilar to any Difference Tool simillar to VSS.
    expecting your replies.
    Raffi

    Hi,
    Eventhough the left and right pane are not synchronized, It is showing the Differences.
    I have changed the JTextArea to JTextPane to have control on each of the String i am inserting.
    It is fine. but when i am doing the comparison for the second time, i am removing the content of the Document (of the JTextPane) and adding the new Content to the Document (of the JTextPane).
    While i am printing the length and text after removing the Old Content (in console), i am getting 0, "". But in the GUI old content are not removed and new content keeps on appending, eventhough i do updateUI() and validate().
    Is that a BUG of JTextPane?????????????
    Can any One Figure it out.
    My Code is Here:
    import java.io.*;
    import java.util.zip.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    * put your documentation comment here
    public class CheckZipFile extends JFrame {
    private JLabel firstZip = null;
    private JLabel secondZip = null;
    private JTextField firstZipName = null;
    private JTextField secondZipName = null;
    private JButton compare = null;
    private JPanel mainPanel = null;
    private JFileChooser fileChooser = null;
    private JButton chooseButton1 = null;
    private JButton chooseButton2 = null;
    private StringBuffer buffer = null;
    private StringBuffer buffer1 = null;
    private StringBuffer buffer2 = null;
    private ApolloFileFilter zipFilter;
    private JTextPane first = null;
    private JTextPane second = null;
    private Document doc1 = null;
    private Document doc = null;
    * put your documentation comment here
    public CheckZipFile () {
    initialize();
    buildGUI();
    addWindowListener();
    setLookAndFeel();
    this.pack();
    * put your documentation comment here
    private void initialize () {
    buffer = new StringBuffer();
    buffer1 = new StringBuffer();
    buffer2 = new StringBuffer();
    zipFilter = new ApolloFileFilter(new String[] {
    "zip", "jar"
    }, "ZIP and JAR Files");
    fileChooser = new JFileChooser(new File("c:\\"));
    //fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.addChoosableFileFilter(zipFilter);
    * put your documentation comment here
    private void setLookAndFeel () {
    try {
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    SwingUtilities.updateComponentTreeUI(this);
    if (fileChooser != null) {
    SwingUtilities.updateComponentTreeUI(fileChooser);
    } catch (UnsupportedLookAndFeelException exc) {
    System.out.println("Unsupported Look And Feel:" +
    exc);
    } catch (IllegalAccessException exc) {
    System.out.println("IllegalAccessException Error:"
    + exc);
    } catch (ClassNotFoundException exc) {
    System.out.println("ClassNotFoundException Error:"
    + exc);
    } catch (InstantiationException exc) {
    System.out.println("InstantiateException Error:"
    + exc);
    * put your documentation comment here
    private void buildGUI () {
    mainPanel = createPanel();
    this.getContentPane().setLayout(new BorderLayout());
    this.getContentPane().add(mainPanel, BorderLayout.CENTER);
    this.getContentPane().add(createDifferencePanel(), BorderLayout.SOUTH);
    this.setSize(700, 450);
    SwingUtilities.updateComponentTreeUI(this);
    * put your documentation comment here
    * @return
    private JPanel createPanel () {
    JPanel main = new JPanel() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(300, 90);
    main.setLayout(new GridLayout(3, 3));
    firstZip = new JLabel("First Jar/Zip File:") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(firstZip);
    firstZipName = new JTextField() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(firstZipName);
    chooseButton1 = new JButton("Choose File 1") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(chooseButton1);
    chooseButton1.addActionListener(new ButtonListener());
    secondZip = new JLabel("Second Jar/Zip File:") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(secondZip);
    secondZipName = new JTextField() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(secondZipName);
    chooseButton2 = new JButton("Choose File 2") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(chooseButton2);
    chooseButton2.addActionListener(new ButtonListener());
    JLabel temp1 = new JLabel("") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(temp1);
    compare = new JButton("Compare") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    compare.addActionListener(new ButtonListener());
    main.add(compare);
    JLabel temp2 = new JLabel("") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(temp2);
    return main;
    * put your documentation comment here
    * @param fileContent1
    * @param fileContent2
    private void updateGUI (String fileContent1, String fileContent2) {
    System.out.println("Came here UpdateGUI");
    updateDifferencePanel(fileContent1, fileContent2);
    System.out.println("Came here UpdateGUI after call");
    SwingUtilities.updateComponentTreeUI(this);
    * put your documentation comment here
    * @return
    private JSplitPane createDifferencePanel () {
    JPanel firstPanel = new JPanel() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(350, 360);
    first = new JTextPane();
    initStylesForTextPane(first);
    doc1 = first.getDocument();
    JScrollPane scroll1 = new JScrollPane(first);
    scroll1.setPreferredSize(new Dimension(325, 360));
    scroll1.setMinimumSize(new Dimension(100, 100));
    firstPanel.add(scroll1);
    first.updateUI();
    first.validate();
    JPanel secondPanel = new JPanel() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(350, 360);
    second = new JTextPane();
    initStylesForTextPane(second);
    doc = second.getDocument();
    JScrollPane scroll2 = new JScrollPane(second);
    scroll2.setPreferredSize(new Dimension(325, 360));
    scroll2.setMinimumSize(new Dimension(100, 100));
    secondPanel.add(scroll2);
    second.updateUI();
    second.validate();
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
    firstPanel, secondPanel);
    splitPane.setDividerLocation(0.5);
    splitPane.updateUI();
    splitPane.validate();
    splitPane.setPreferredSize(new Dimension(700, 360));
    return splitPane;
    * put your documentation comment here
    * @param fileContent1
    * @param fileContent2
    private void updateDifferencePanel (String fileContent1,
    String fileContent2) {
    System.out.println("Came here");
    try {
    doc1 = first.getDocument();
    System.out.println("Text bef: " + first.getText());
    System.out.println("Length bef: " + doc1.getLength());
    doc1.remove(0, doc1.getLength());
    System.out.println("Length aft: " + doc1.getLength());
    System.out.println("Text aft: " + first.getText());
    doc1.insertString(doc1.getLength(), "test", first.getStyle("regular"));
    first.updateUI();
    first.validate();
    } catch (BadLocationException ble1) {
    ble1.printStackTrace();
    StringTokenizer tokens1 = new StringTokenizer(fileContent1,
    String token1 = "";
    String text1 = "";
    String differs1 = "false";
    int indexOfColon1 = -1;
    int count1 = 0;
    while (tokens1.hasMoreTokens()) {
    token1 = (String)tokens1.nextToken();
    count1++;
    indexOfColon1 = token1.lastIndexOf(":");
    text1 = token1.substring(0, indexOfColon1);
    differs1 = token1.substring(indexOfColon1 + 1);
    try {
    if (count1 == 1)
    System.out.println("Start: " + doc1.getLength());
    if (differs1.equals("true"))
    doc1.insertString(doc1.getLength(), text1
    + ":", first.getStyle("bold"));
    else
    doc1.insertString(doc1.getLength(), text1
    + ":", first.getStyle("regular"));
    if ((count1%3) == 0)
    doc1.insertString(doc1.getLength(), "\n",
    first.getStyle("regular"));
    } catch (BadLocationException ble1) {
    ble1.printStackTrace();
    first.updateUI();
    first.validate();
    try {
    System.out.println("Length bef: " + doc.getLength());
    doc.remove(0, doc.getLength());
    System.out.println("Length aft: " + doc.getLength());
    second.updateUI();
    second.validate();
    } catch (BadLocationException ble1) {
    ble1.printStackTrace();
    StringTokenizer tokens = new StringTokenizer(fileContent2,
    String token = "";
    String text = "";
    String differs = "false";
    int indexOfColon = -1;
    int count = 0;
    while (tokens.hasMoreTokens()) {
    token = (String)tokens.nextToken();
    count++;
    indexOfColon = token.lastIndexOf(":");
    text = token.substring(0, indexOfColon);
    differs = token.substring(indexOfColon + 1);
    try {
    if (differs.equals("true"))
    doc.insertString(doc.getLength(), text +
    ":", second.getStyle("bold"));
    else
    doc.insertString(doc.getLength(), text +
    ":", second.getStyle("regular"));
    if ((count%3) == 0)
    doc.insertString(doc.getLength(), "\n",
    second.getStyle("regular"));
    } catch (BadLocationException ble) {
    ble.printStackTrace();
    second.updateUI();
    second.validate();
    * put your documentation comment here
    * @param textPane
    protected void initStylesForTextPane (JTextPane textPane) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = textPane.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = textPane.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = textPane.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = textPane.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = textPane.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);
    s = textPane.addStyle("icon", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    StyleConstants.setIcon(s, new ImageIcon("images/Pig.gif"));
    s = textPane.addStyle("button", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    JButton button = new JButton(new ImageIcon("images/sound.gif"));
    button.setMargin(new Insets(0, 0, 0, 0));
    button.addActionListener(new ActionListener() {
    * put your documentation comment here
    * @param e
    public void actionPerformed (ActionEvent e) {
    Toolkit.getDefaultToolkit().beep();
    StyleConstants.setComponent(s, button);
    * put your documentation comment here
    private void addWindowListener () {
    this.addWindowListener(new WindowAdapter() {
    * put your documentation comment here
    * @param we
    public void windowClosed (WindowEvent we) {
    CheckZipFile.this.dispose();
    System.exit(1);
    * put your documentation comment here
    * @param we
    public void windowClosing (WindowEvent we) {
    CheckZipFile.this.dispose();
    System.exit(1);
    * put your documentation comment here
    * @param argv[]
    * @exception Exception
    public static void main (String argv[]) throws Exception {
    CheckZipFile compareZip = new CheckZipFile();
    compareZip.pack();
    compareZip.setVisible(true);
    * put your documentation comment here
    public class ButtonListener
    implements ActionListener {
    * put your documentation comment here
    * @param ae
    public void actionPerformed (ActionEvent ae) {
    if (ae.getSource() == chooseButton1) {
    int retval = fileChooser.showDialog(CheckZipFile.this,
    "Select");
    if (retval == JFileChooser.APPROVE_OPTION) {
    File theFile = fileChooser.getSelectedFile();
    if (theFile != null) {
    File[] files = fileChooser.getSelectedFiles();
    if (fileChooser.isMultiSelectionEnabled()
    && files != null && files.length > 1) {
    String filenames = "";
    for (int i = 0; i < files.length; i++) {
    filenames = filenames + "\n"
    + files.getPath();
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose these files: \n"
    + filenames + "\n Multiple Selection Should not be done here");
    else if (theFile.isDirectory()) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose this directory: "
    + fileChooser.getSelectedFile().getPath()
    + "\n Please select a Zip File or jar File");
    else {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose this file: " +
    fileChooser.getSelectedFile().getPath());
    firstZipName.setText(fileChooser.getSelectedFile().getPath());
    return;
    else if (retval == JFileChooser.CANCEL_OPTION) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "User cancelled operation. No file was chosen.");
    else if (retval == JFileChooser.ERROR_OPTION) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "An error occured. No file was chosen.");
    else {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Unknown operation occured.");
    if (ae.getSource() == chooseButton2) {
    int retval = fileChooser.showDialog(CheckZipFile.this,
    "Select");
    if (retval == JFileChooser.APPROVE_OPTION) {
    File theFile = fileChooser.getSelectedFile();
    if (theFile != null) {
    File[] files = fileChooser.getSelectedFiles();
    if (fileChooser.isMultiSelectionEnabled()
    && files != null && files.length > 1) {
    String filenames = "";
    for (int i = 0; i < files.length; i++) {
    filenames = filenames + "\n"
    + files[i].getPath();
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose these files: \n"
    + filenames + "\n Multiple Selection Should not be done here");
    else if (theFile.isDirectory()) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose this directory: "
    + fileChooser.getSelectedFile().getPath()
    + "\n Please select a Zip File or jar File");
    else {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose this file: " +
    fileChooser.getSelectedFile().getPath());
    secondZipName.setText(fileChooser.getSelectedFile().getPath());
    return;
    else if (retval == JFileChooser.CANCEL_OPTION) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "User cancelled operation. No file was chosen.");
    else if (retval == JFileChooser.ERROR_OPTION) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "An error occured. No file was chosen.");
    else {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Unknown operation occured.");
    if (ae.getSource() == compare) {
    String file1 = firstZipName.getText();
    String file2 = secondZipName.getText();
    if (file1 == null || file2 == null) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Enter / Select the Files to be compared");
    return;
    if (file1.equals("") || file2.equals("")) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Enter / Select the Files to be compared");
    return;
    try {
    ZipFile zip1 = new ZipFile(file1);
    ZipFile zip2 = new ZipFile(file2);
    int size1 = zip1.size();
    int size2 = zip2.size();
    if (size1 != size2) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Size of both the jars are not same");
    return;
    Enumeration entries1 = zip1.entries();
    Enumeration entries2 = zip2.entries();
    ZipEntry entry1 = null;
    ZipEntry entry2 = null;
    String name1 = "";
    String name2 = "";
    long filesize1 = 0;
    long filesize2 = 0;
    long time1;
    long time2;
    //StringBuffer detail = new StringBuffer();
    boolean nameDiffers = false;
    boolean sizeDiffers = false;
    boolean timeDiffers = false;
    buffer.append(file1 + "\t\t\t" + file2 +
    "\n______________________________________________________________________\n");
    //buffer1.append("\t\t" + file1 + "\n");
    //buffer2.append("\t\t" + file2 + "\n");
    int length = buffer.length();
    for (int x = 0; x < size1; x++) {
    nameDiffers = false;
    sizeDiffers = false;
    timeDiffers = false;
    entry1 = (ZipEntry)entries1.nextElement();
    entry2 = (ZipEntry)entries2.nextElement();
    name1 = entry1.getName();
    name2 = entry2.getName();
    filesize1 = entry1.getSize();
    filesize2 = entry2.getSize();
    time1 = entry1.getTime();
    time2 = entry2.getTime();
    if (!name1.equals(name2)) {
    //System.out.println("Name of the Entries in both the Jars are not same:\n"+ entry1.getName() + " : " + entry2.getName() );
    nameDiffers = true;
    //return;
    //else
    //     System.out.println("Name: " +entry1.getName());
    if (filesize1 != filesize2) {
    //System.out.println("Size of the Entries in both the Jars are not same:\n"+ entry1.getSize() + " : " + entry2.getSize() );
    sizeDiffers = true;
    //return;
    if (time1 != time2) {
    //System.out.println("Time of the Entries in both the Jars are not same:\n"+ entry1.getTime() + " : " + entry2.getTime() );
    timeDiffers = true;
    //return;
    if (nameDiffers || sizeDiffers || timeDiffers) {
    if (filesize1 != 0 && filesize2 !=
    0) {
    buffer.append(name1 + ":" +
    filesize1 + ":" + new java.util.Date(time1)
    + "\t" + name2 + ":"
    + filesize2 + ":" +
    new java.util.Date(time2)
    + "\n");
    buffer1.append(name1 + ":" +
    nameDiffers + ";" +
    filesize1 + ":" + sizeDiffers
    + ";" + new java.util.Date(time1).toString()
    + ":" + timeDiffers +
    buffer2.append(name2 + ":" +
    nameDiffers + ";" +
    filesize2 + ":" + sizeDiffers
    + ";" + new java.util.Date(time2).toString()
    + ":" + timeDiffers +
    if (length == buffer.length())
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Both the Zip / Jar Files are Identical");
    else {
    getToolkit().beep();
    //System.out.println(buffer.toString());
    updateGUI(buffer1.toString(), buffer2.toString());
    getToolkit().beep();
    } catch (Exception ex) {
    ex.printStackTrace();

  • Simple question - compare Strings with SSIS expression language

    SSIS variables - strOne = YES, strTwo = YES. I want to compare strings using ssis expression language (ie inside a variable's expression box, constraint of task flow arrow etc).
    Will @strOne == @strTwo be true ? I hope its not like programming languages where you need to do
    @strOne.Equals(@strTwo) instead of ==. Also is @strOne == "YES" true ?

    ([User::strOne] == [User::Strtwo] ? True : False)
    The third variable created should be of type boolean if you're using above expression. if its of type int return 0 and 1 instead of False and true
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Compare string in JSTL

    Hi all,
    I have   <c:set var="status" value="${found.studentStatus}"/> inside loopI want to call it outside the loop and compare string
    <c:if test="${status.equals("A")}">
    do something
    </c:if>
    But I get bug equals symbol expect, what is wrong?

    EL is not java. The same rules don't apply. You actually do want to use the equals operator here. It ends up invoking the java .equals method in the end.
    To make it explicit:
    <c:if test="${status == 'A'}">
    //or
    <c:if test="${status eq 'A'}">Cheers,
    evnafets

  • Compareto versus equals performance for strings equality

    Hi
    Just wanted to know whether compareto and equals method performance for checking whether the two strings are equal or not .
    Which one is good with respect to bytecode , speed performance.
    Im not asking for the difference, only asking which one is good to use most number of times for comparing two strings for equilaty.
    Thanks.

    Hi
    Ya they are both for different purposes. No doubt.
    t which one is faster among the two for string
    equality?
    compareto or equals.
    thanksHis point is that it doesn't matter. You shouldn't worry about optimization for small details like this. Unless you are profiling your code and find a large slowdown with that code, then don't worry about their performance. Use the one that best suits your purpose. If you want to know if they're equal, use equals(), if you want to know their order, use compareTo().

  • How to use a custom comparator in a TableSorter?

    Hi,
    I want to use a custom comparator for sorting a table by a specific column.
    As you possibly know, the constructor for the TableSorter class looks like this:
    TableSorter(IWDTable table, IWDAction sortAction, Map comparators);
    As Map is an Interface I chose Hashmap as comparator container. So, I use the put(Key, Value) method to insert my own comparator into the Hashmap in order to deliver this Object to the TableSorter constructor.
    But there is an essential problem:
    I assume, that the column which is to be associated with my comparator is determined by the key of the Map object from the TableSorter constructor.
    Presuming this, <u>what should the map key be/look like?</u>
    An Integer counted from the columns? The column header as String? Whatever? Or am I on the wrong way?
    PS:
    Hours of search did not lead me to some kind of documentation or javadoc of the TableSorter class! This can't be, does someone have a link please?
    Thanks a lot for any help.

    (sorry Mrutyun, this did not help.)
    Ok, I solved it; let me share it with you:
    public class ExampleView
            public static void wdDoModifyView(IPrivateExampleView wdThis, IPrivateExampleView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)
                     * A custom Comparator class is used for sorting by Severity.
                     * An Object of it is delivered to an object of a Map class to be delivered to the TableSorter constructor.
                     * The Map class consists of key-value pairs, and the TableSorter must accept the Key of it
                     * because he uses it to assign the mapped Comparator to the column of the table to be sorted!
                     * And this is done with the ID of the Element, which shall be sorted with the Comparator, used as Map Key.
                     * All other columns of the assigned tables will be sorted by default Comparators.
                    IWDTable table = (IWDTable) view.getElement("[TableName]");
                    HashMap tableComps = new HashMap();
                    tableComps.put(view.getElement("[ColumnName]").getId(), new MyComp(wdContext.currentExampleElement())); //The map key value I looked for is the ID of the Element of the Column!
                    wdContext.current/*yourContextNode*/Element().setTableSort(
                            new TableSorter(table, wdThis.wdGetSortTableRowAction(),
                                    tableComps)); //Insert HashMap with the new Comparator
            public void onActionSortTableRow(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
            //@@begin onActionSortTableRow(ServerEvent)
                            wdContext.currentConfigurationElement().getTableSort().sort(wdEvent, wdContext.nodeOpenIncident());
            //@@end
    As you see, the Column which is to be sorted by the custom Comparator "MyComp", is clearly assigned to it. Thus, is will only be used when sorting by this column is done.
    The "inActionSort" method is as usual.
    My Comparator sorts a column which contains variables of a "SimpleType" with an enumeration. (If you need help with this, feel free to write me.) To achieve this, the Comparator needs to know what this SimpleType consists of. That's why I deliver this Element per Constructor to it.
    public class MyComp implements Comparator
         MappedNodeElement element;
         public SeverityComp(I/*one*/Element element)
              this.element = element;
         public SeverityComp(I/*another*/Element element)
              this.element = element;
         public int compare(Object severity1, Object severity2)
    Because MappedNodeElement is such abstract, it can be used by several different Tables, provided they use the same SimpleType.
    Concerning my quest for this resolution, I hope this is helpful.
    null

Maybe you are looking for