NullPointerException on String methods

All,
I am trying to get date values on the fly and add them to my sql statement. I have a DateWorker class that provides month, day of month and year.
When I use the class in another class, I get NullPointerException. These are just plain ol' String methods, why are they giving me problems. When I run the code on its won, it works fine.
Code:
package mybeans;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Calendar;
public class DateWorker {
public DateWorker dateWorker;
     public DateWorker(){
          dateWorker = new DateWorker()
     public static void main(String[] args){
          String m = dateWorker.getMonth();
          String dm = dateWorker.getDayOfMonth();
          String dw = dateWorker.getDayOfWeek();
          String y = dateWorker.getYear();
          System.out.println("day of week " + dw + "<BR>");
          System.out.println("day of month" + dm + "<BR>");
          System.out.println("month " + m + "<BR>");
          System.out.println("year " + y + "<BR>");
     //get a Calendar instance.
     private Calendar cal = Calendar.getInstance();
     //gets the current month
     public String getMonth(){
     int x = cal.get(Calendar.MONTH) + 1;
     String s = String.valueOf(x);
     return s;
     //gets the current day of month
     public String getDayOfMonth(){
          int x = cal.get(Calendar.DAY_OF_MONTH);
          String s = String.valueOf(x);
          return s;
     //gets the current day of week
     public String getDayOfWeek(){
          int x = cal.get(Calendar.DAY_OF_WEEK) -1;
          String s = String.valueOf(x);
          return s;
     //gets the current year
     public String getYear(){
          int x = cal.get(Calendar.YEAR);
          String s = String.valueOf(x);
          return s;
Edited by: ink86 on Oct 8, 2007 12:57 PM

package mybeans;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Calendar;
public class DateWorker {
     public static void main(String[] args){
          DateWorker dateWorker = new DateWorker();
          String m = dateWorker.getMonth();
          String dm = dateWorker.getDayOfMonth();
          String dw = dateWorker.getDayOfWeek();
          String y = dateWorker.getYear();
          System.out.println("day of week " + dw + "<BR>");
          System.out.println("day of month" + dm + "<BR>");
          System.out.println("month " + m + "<BR>");
          System.out.println("year " + y + "<BR>");
     //get a Calendar instance.
     Calendar cal = Calendar.getInstance();
     //gets the current month
     public String getMonth(){
     int x = cal.get(Calendar.MONTH) + 1;
     String s = String.valueOf(x);
     return s;
     //gets the current day of month
     public String getDayOfMonth(){
          int x = cal.get(Calendar.DAY_OF_MONTH);
          String s = String.valueOf(x);
          return s;
     //gets the current day of week
     public String getDayOfWeek(){
          int x = cal.get(Calendar.DAY_OF_WEEK) -1;
          String s = String.valueOf(x);
          return s;
     //gets the current year
     public String getYear(){
          int x = cal.get(Calendar.YEAR);
          String s = String.valueOf(x);
          return s;
     }

Similar Messages

  • "Import string" method not supported in LabVIEW 7.1

    We have made an application that support multi-language (English, French, etc.). In LabVIEW 6.1, we used the "import string" VI method to support this option. The method was executed just before to open front panel. The code was based on this example found in NI Developer Zone:
    Translation/Localization Tools in LabVIEW
    (http://sine.ni.com/apps/we/niepd_web_display.disp​lay_epd4?...
    But surprise in version 7.1, this method can't be loaded without the diagram block. So the built application doesn't support it! It works only in the development interface. Why this change?
    If someone has an idea to solve this, let me know.

    If you build that example into an EXE under LabVIEW 7.1, it should work fine as long as you add the non top-level VIs as Dynamic VIs and add the language files as Support Files when you create the executable, making sure to specify in "Custom Destinations" that you want the string files to end up in the same directory as the EXE.
    Your point about the method requiring the block diagram is correct, according to the help for the method. However, I think the diagrams will be available to the run-time engine as long as you haven't purposefully removed them prior to creating the EXE in the manner described above. Maybe someone else can chime in on this point, because I know the App Builder changes a lot with every new major LabVIEW version (and sometimes, with minor versions too!).
    In any case, I just did a test where I downloaded the example you referenced, created a .BLD file as I indicated above, and got a successful executable that was able to use the Import VI Strings method to load the desired language at run-time.
    Regards,
    John

  • Import & Export Strings method

    Hi,
    I have a multilanguage application. I have used export & import
    strings methods. I have one .txt file for each language but when I
    modify something in my vi I must export all again and then modify the
    tags again for each language file... Is there a way that I can modify
    my vi and I don't have to export all again?
    Thanks,
    ToNi.

    As far as i know you need to export strings again only if you have made any changes on front panel.
    exported file is nothing but a xml file so that you can manually edit it instead of exporting everything again (helpfule if you have done very small changes on front panel)
    Tushar Jambhekar
    [email protected]
    Jambhekar Automation Solutions
    LabVIEW Consultancy, LabVIEW Training
    Rent a LabVIEW Developer, My Blog

  • Urgent!!!   Problem on the String method and File method

    I would like to ask two questions:
    (1) From the String method, it can use .equals() method to compare two strings whether two string exactly equal or not. But what method can i use to compare two strings see whether any words exists in the string?
    (2) From the following code,
    Java.io.File outFile = new java.io.File("TestProg.java");If i would like to use a variable (e.g. let the variable be name) instead of the filename "TestProg.java", do you know how to revise the above code??
    If i write as following, is it correct???
    Java.io.File outFile = new java.io.File(""+name+"");Please help!!!

    1- To check whether a word (sunstring) exists in a longer string, you can use the following String method:
    indexOf(substring) on the string that you are searching. If the word does not exist, -1 is returned.
    2- yes you can provide a variable (of type string) in the constrcutor of File.

  • Regex or String methods

    Hi
    Im wondering how more experienced Java developers would approach this.
    I have a parser which receives Strings according to the irc-protocol.
    servername PRIVMSG #channel :Hello worldAlmost every message is defined by the second word in the String. So its easy to just do String.split(" ") ... check the messagetype and start working with the other elements. Of course things gets a bit out of hand with compareTo(), IndexOf(), Substring() ... and all the other String methods.
    How would u use regex for this if u had to? I see this as exercise ... slower code, more work ... doesnt matter and its a plus learning more about regex.
    Example ... the line above, how would u use regex to check the messagetype "privmsg" ... channel "#channel" and the messagepart after the ':' etc ...
    many thanks in advance

    I wouldn't use regex, but split indeed, since I'd
    have very easy access to each part of the message.
    Anyway, since you want to learn regex: why don't you
    grab the Pattern API and read and try a little
    yourself? Nothing teaches you better than finding out
    yourself.Well yes regexes are nice easy and clean. And a wevy usefull if you learn them cos it gives you unlimited power of string manipulation.
    But at a high cost.
    It is verry important to make the right choice (regex or string methods) becouse it will decide how good your code looks and work.
    If the pattern that need to be parsed is simple and cam be done using string methods (including string tokenizer) regex is not the way to go.
    Normally when handling simple text patterns like above the string methods will perform about 5 times faster than regexes.
    So my recomendation is.
    If you are doing this for learning do it both ways and practice both regexes and string methods. Becouse in the industry you have know the both well.
    If you are doing this for some sort of a project and performance is a significant quality factor you need to use string methods in this perticuler situation.
    Above pattern can easilly broaken down using a combination of substring, index of and string tokenizer.

  • Why is String method called not Object method

    In the below program ::
    class Test
         public void callMethod(Object o)
              System.out.println("Object Method Called");
         public void callMethod(String s)
              System.out.println("String Method Called");
         public static void main(String[] args)
              Test t = new Test();
              t.callMethod(null);
    }

    In the below program ::
    class Test
         public void callMethod(Object o)
              System.out.println("Object Method Called");
         public void callMethod(String s)
              System.out.println("String Method Called");
         public static void main(String[] args)
              Test t = new Test();
              t.callMethod(null);
    }If more than one method could be called the most specific one is called. Since a String is an Object then the String one gets called.

  • Can I use to.String() method with NamedCache

    Hi,
    I have a distributed cache. Can I use to.String() method to print the contents of cache on the console. In my case it is not working..Do I neet to import anything?
    NamedCache cache = CacheFactory.getCache("Test");
    cache.put("hello", "world");
    System.out.println(cache.toString());
    Thanks,
    Chaya

    Hi Chaya,
    Assuming that I understand your question correctly, each JVM has the same view of the cache if you're using a distributed (or optimistic, replicated, ...) cache. So when you add records from one JVM, they are visible to all the JVMs immediately (if you start up a new JVM, it will join the cluster and share the data as well).
    So if you populate a named cache from JVM1, you can simply execute the display code (from my previously reply) in any JVM connected through Coherence, and it will display the entire contents of the logical named cache.
    Jon Purdy
    Tangosol, Inc.

  • String method indexOf

    I have to show the number of occurances of a character in a string.
    I chose the letter 'a' - here is my code, my problem is i only get one occurance, how do i show all indexes of 'a'?
    thanks,
    barb
    // Java extension packages
    import javax.swing.*;
    public class IndexOf {
    public static void main( String args[] )
    String text ="This class is really hard \n" +
         "I'm glad I did well on the midterm \n" +
         "It took a long time.";
         String output1 =      "'This class is really hard.\n" +
                   "I'm glad I did well on the midterm.\n" +
                   "It took a long time.'"+ "\n\n";
         int pos;
    int count = 0;
    pos = text.indexOf ('a');
    while ( pos != -1)
              count++;
              pos = text.indexOf ('a', pos+1);
    // test indexOf to locate a character in a string
    String output2 = "'a' is located at index " + text.indexOf ('a') +
    text.indexOf('a');
    JOptionPane.showMessageDialog( null, output1 + output2,
              "String method indexOf",
    JOptionPane.INFORMATION_MESSAGE );
    System.exit( 0 );
    } // end class String IndexOf

    // Try this.
    String text ="This class is really hard \n" +
    "I'm glad I did well on the midterm \n" +
    "It took a long time.";
    String result="";
    for (int i=0; i<text.length(); i++)
    { if  (text.charAt(i)=='a')result += "Index: " + i + System.getProperty( "line.separator" ); }
    System.out.print(result);

  • Return from String method

    Hi
    Can anyone help me:
    I have a class with a String method.
    The returned value for the method is calculated in a thread. Since I have to share the same literal for the String and run methods, the returned value for the String method is not the value that the run method is supposed to calculate for me. It just wouldn't wait until it's ready.
    What should I do? Can I block the String method to return the string until the run method is ready?

    Look up Thread.waitFor()

  • Which String method would be used to...

    Which string method (maybe it's not even a string method) would be used to change user input for example from:
    User input: Brandon Bell
    Changed to Bell, Brandon
    Thanks.
    Brandon Bell

    Which string method (maybe it's not even a string
    method) would be used to change user input for
    example from:
    User input: Brandon Bell
    Changed to Bell, Brandon
    Your question is very vague. What are the exact requirements? Are you assuming that the inputted string is a first name and a last name, separated by a space, and you want to change it to last name comma first name?
    If so, the methods indexOf and substring will be enough for a first, naive implementation. With that in place you might want to ask yourself:
    Will you allow the first name to have one or more spaces? Will you allow the last name to have one or more spaces? Etc, etc.

  • String method compareTo

    I am trying to write a program that compares two strings and comes back with the result of wether the first string is "less then", "equal to" or "more then" the second string. I have written the code and will post it. I am only coming across one error, it is saying it cannot resolve the variable "value" in....
    displayField.setText("The first string is "+ value +" the secone one!");
    here is the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CompareWindow extends JFrame{
         private JLabel string1Label,string2Label;
         private JTextField string1Field,string2Field,displayField;
         private JButton exitButton;
    public CompareWindow()
    super("String method compareTo");
    ActionEventHandler handler=new ActionEventHandler();
    Container container = getContentPane();
    container.setLayout(new FlowLayout() );
    string1Label=new JLabel("Enter first string");
    string1Field=new JTextField(20);
    string1Field.addActionListener(handler);
    container.add(string1Label);
    container.add(string1Field);
    string2Label=new JLabel("Enter second string");
    string2Field=new JTextField(20);
    string2Field.addActionListener(handler);
    container.add(string2Label);
    container.add(string2Field);
    displayField=new JTextField(30);
    displayField.setEditable(false);
    container.add(displayField);
    exitButton=new JButton("Exit");
    exitButton.addActionListener(handler);
    container.add(exitButton);
    public void displayCompare()
    displayField.setText("The first string is "+ value +" the secone one!");
    public static void main(String args[])
    CompareWindow window = new CompareWindow();
    window.setSize(400,140);
    window.setVisible(true);
    private class ActionEventHandler implements ActionListener{
    String first=string1Field.getText();
    String second=string2Field.getText();
    int compare1=0;
    String value;
    public void actionPerformed(ActionEvent event)
    String first=string1Field.getText();
    String second=string2Field.getText();
    int compare1=0;
    String value;
    if (event.getSource()==exitButton)
    System.exit(0);
    else if (event.getSource()==string1Field) {
    compare1=first.compareTo(second);
    else if (event.getSource()==string2Field) {
    compare1=first.compareTo(second);
    if (compare1<0){
    value="less then";
    else if (compare1==0){
    value="equals";
    else if (compare1>0){
    value="greater then";
    displayCompare();
    }Any help will be appreciated.

    The variable value is not accessible displayCompare method.You will need to pass it as parameter to that displayCompare method or move the declaration to the outer Class i.e. CompareWindow.

  • SAX XML NullPointerException in character() method

    I'm having issues when parsing my xml file. Everything works fine unless I am trying to push values into my parameters Vector.
    class SAXLoader extends DefaultHandler {
        private static String className, //name of the class for module in xml
                methodName,              //name of the method for the class
                path;                    //path to jar. should be in URI format
        private Vector params;      //parameters to the method
        private boolean isClassName,     //true if element begins className tag
                isMethodName,            //true if element begins methodName tag
                isParameter,             //true if element begins parameter tag
                isPath;                  //true if element begins path tag
        //=======================init()================================
        //opens XML file specified and parses it for className,
        //the methodName,and the path to the JAR
        //This should be called before doing any of the getter methods
        //=============================================================
        public void init() {
            try {
                XMLReader xmlreader = XMLReaderFactory.createXMLReader();
                SAXLoader handler = new SAXLoader();
                xmlreader.setContentHandler(handler);
                xmlreader.setErrorHandler(handler);
                try {
                    FileReader r = new FileReader("myclass.xml");
                    xmlreader.parse(new InputSource(r));
                } catch (FileNotFoundException e) {
                    System.out.println("File Not Found!");
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    System.out.println("Parse Error!");
                    e.printStackTrace();
            } catch (Exception e) {
                System.out.println("XML Reader Error!");
                e.printStackTrace();
    public void characters(char ch[], int start, int length) {
            String temp = "";
            for (int i = start; i < start + length; i++) {
                switch (ch) {
    case '\\':
    // System.out.print("\\\\");
    break;
    case '"':
    // System.out.print("\\\"");
    break;
    case '\n':
    // System.out.print("\\n");
    break;
    case '\r':
    // System.out.print("\\r");
    break;
    case '\t':
    // System.out.print("\\t");
    break;
    default:
    temp += ch[i];
    break;
    if (isClassName) {
    className = temp;
    } else if (isMethodName) {
    methodName = temp;
    } else if (isPath) {
    path = temp;
    } else if (isParameter) {
    System.out.println("zomg!: " + temp);
    params.add(temp);
    } //end of characters(...
    Right there at params.add(temp);
    I'm using this DefaultHandler based class to parse an XML file for information regarding a user's own class [its classname, its methodname, and the methods parameters].
    Any clues?
    Message was edited by:
    nick.mancuso
    Message was edited by:
    nick.mancuso

    You don't actually allocate the params Vector, at least not on the code you've posted. You want something like:
    private Vector params = new Vector();or better yet:
    private List params = new LinkedList();perhaps.
    But even better yet...I suspect that having a handful of global temp variables like that isn't going to work. In my experience, when using SAX you pretty much have to create a stack to hold the current place in the XML tree. That's how you traverse trees, with stacks. Then instead of setting isMethodName, isParameter, etc. (which I presume you do in open/close tag handlers) you define an enumeration of values like "class", "method", "parameter", and then have a stack of those values, or something.

  • NullPointerException on a method declaration?

    Hi all,
    I'm not sure whether I should be posting this here on on the app server board.
    But anyway, I have an ADF application (with ADF Faces) that works fine in JDev 10.1.3, and after some difficulty, I've managed to get it deployed, so that the first page comes up properly in a browser.
    When I click on a link in my navigation tree, however, I get an error in the method called by the CommandLink in the tree node. Here's what it is:
    javax.faces.FacesException: #{homeBean.treeNavigate}: javax.faces.el.EvaluationException
    Caused by [at the bottom]: java.lang.NullPointerException
    at mypackage.BasePage.TreeNavigate (BasePage.java:53)
    So OK, for some reason my code is firing a null pointer exception in the deployed version. Let's see what it is by checking BasePage.java, line 53:
    53) public String treeNavigate() {
    A method declaration. That shouldn't be able to throw a NullPointerException, or indeed any other runtime error, should it?
    Can anyone shed some light about what might be going on here?
    Thanks much,
    Avrom

    public void drawPictures(int size, Graphics page)
              page.drawImage (board, 0, 0, 720, 567, this);
    public void paint (Graphics page)
              drawPictures (APPLET_WIDTH, page);
    private final int APPLET_WIDTH = 720;
    board = getImage (getDocumentBase(), "board.jpg"); //inside my init() methodThanks for the quite response. I looked at my code with your suggestions and came up with this:
    If I take away my "paint" method, the buttons have no problems, but, of course, no picture comes up. Any ideas?
    I was also throw out the fact that this is my first time with GUIs. My teacher saved them to the end last year, got lazy, and then never did them. So if I am using horrible self-taught practices, it would be awesome if you can let me know, so I can improve. Thanks.
    Edited by: 7sunami on Feb 22, 2009 6:00 PM

  • Strange about invoking web service method declared “string  method(void)”;

    Dear forum readers
    I’m experimenting with OpenESB and web services. I’ve create a simple web service using NetBeans 6.1. The method consists of a single method, getTime, that is declared:
    String getTime()
    My current experiment is to invoke this method from a BPEL-process using the “Invoke” process object. The strange thing is that it seems like I have to provide a “dummy” inbound variable from the BPEL-designer even though the method doesn’t take any parameters. I include a snippet from the BPEL process below which includes the section where I set the dummy GetTimeIn-variable and then invokes the WS method getTime().
    <assign name="Assign2">
    <copy>
    <from>'DummyValue'</from>
    <to variable="GetTimeIn" part="parameters"/>
    </copy>
    </assign>
    <invoke name="Invoke1" partnerLink="PartnerLink1" operation="getTime" xmlns:tns="http://ws/" portType="tns:MyWebService" outputVariable="GetTimeOut" inputVariable="GetTimeIn"/>
    If I don’t initiate the dummy variable or remove it altogether, I can’t successfully call the method. If I include the dummy in-parameter the call works just fine and I get back the current time as a string.
    I must admit that I’m still a rookie to web services, especially when calling them from a BPEL-process, so it may be a very trivial reason for this behaviour. Anyway, any help on this matter would be greatly appreciated.
    Regards, Ola

    Thank you both for the response. Regarding Rennay’s posting I have an additional question. When I create a new web service I don't have the "Document Literal" option nor a "Concrete Configuration" tab. I've created the web service using the "Web Application" project type and then adding a web service using the "Web Service..." wizard. This wizard doesn't have the configuration properties you mention, but if I add a WSDL-file to a BPEL-project the wizard has the properties you mention.
    Is it possible to create a web service, programmed as an ordinary Java-class, from an existing WSDL-file? In that case it may solve the problem with the “Document Literal” property. Currently I don’t know any other way to create such a web-service other than the through the web service wizard in a web application project. Of course, it’s possible to craft it from scratch but that’s to much work to be practical.
    Regards, Ola

  • Java.lang.NullPointerException in checkTransaction method

    EJB2.1 / weblogic 10.3
    I get en nullpointerexception in a weblogic generated class.
    The method in the generated class is :
    private void checkTransaction()
    weblogic.transaction.Transaction tx = (weblogic.transaction.Transaction)
    TransactionHelper.getTransactionHelper().getTransaction();
    if ((tx == null) && (__WL_createTxId == null))
    return;
    else if ((tx == null) && (__WL_createTxId != null))
    if (! true) {
    Loggable l1 = EJBLogger.logaccessedCmrCollectionInDifferentTransactionLoggable("CustomOffice", "officehours");
    throw new IllegalStateException(l1.getMessage());
    else if (!tx.getXid().equals(__WL_createTxId) && ! true ) {
    Loggable l1 = EJBLogger.logaccessedCmrCollectionInDifferentTransactionLoggable("CustomOffice", "officehours");
    throw new IllegalStateException(l1.getMessage());
    I get the nullpointer at the line
    else if (!tx.getXid().equals(__WL_createTxId) && ! true ) {
    I have an EntityBean named CustomOffice, this bean has a collection of Officehours entitybeans.
    When I call ( from a SessionBean with @ejb.transaction type="Supports" )
    Iterator iter = customOfficeLocal.getOfficehours().iterator();
    I get the NullPointeException when not using an transaction, when using a transaction it works.
    But I would llike to call this witout an transaction.

    The method checkTransaction is in a weblogic generated class.
    java.lang.NullPointerException
         at dk.steria.exp.midtier.model.customs.ejb.CustomOffice_up2n56__WebLogic_CMP_RDBMS_officehours_Set.checkTransaction(CustomOffice_up2n56__WebLogic_CMP_RDBMS_officehours_Set.java:644)
         at dk.steria.exp.midtier.model.customs.ejb.CustomOffice_up2n56__WebLogic_CMP_RDBMS_officehours_Set.iterator(CustomOffice_up2n56__WebLogic_CMP_RDBMS_officehours_Set.java:186)
         at dk.steria.exp.midtier.tools.factory.DeclarationFactory.createOfficeHoursTOList(DeclarationFactory.java:1443)
         at dk.steria.exp.midtier.tools.factory.DeclarationFactory.createCustomOfficeTO(DeclarationFactory.java:1415)
    The error comes when I call
    Iterator iter = customOfficeLocal.getOfficehours().iterator();
    in my code.
    I guess it is because I am using a EJB 2.1 entitybean.... that needs a transaction ??????

Maybe you are looking for

  • Purchase order specific to copy function

    Hi All, We have new requirement for one of our client. During PO creation or change,  user has the option to copy with reference of existing PO items. However by doing that, the PO will default certain values/info that are no longer valid of which ma

  • Iphone 5 3G connection issue

    My phone 3G connection is full of bar, but the speed is very slow, so i try to switch on and off the cellular data, then the speed is faster back. is quite annoying of this problem. please help!

  • Dynamic selection screen variant

    Hi Gurus, There are two parameters in the selection screen of a report. One for Date, whose format is ww.yyyy and purchasing organization. Both the fields are mandatory fields. I have to create variants for this report in such a way that when user se

  • Changing the cast member of a sprite

    Hi, I have the following code so that when a user clicks on a shape (acting as a button), it changes the cast member of an existing sprite called "base" on the stage to an image cast member called "Italian Lira". However the code does not work, any s

  • Buttons behave differently

    I have a page process doing some DML, which is supposed to execute after submit and when button P_X is pressed. When creating a button P_X in a region position the page process is NOT triggered when creating the button P_X displayed among this region