Static method and variables doubts

i have a doubt
i have the following method
private static void checkActionType(String action) {
if (action.startsWith(" a")) {
++totalAddedActions;
} else if (action.startsWith(" c")) {
++totalChangedFolders;
} else if (action.startsWith(" p")) {
++totalPersonalizedActions;
} else if (action.startsWith(" r")) {
++totalRemovedActions;
} else if (action.startsWith(" v")) {
++totalViewedActions;
} else if (action.startsWith(" u")) {
++totalUpdateActions;
to use it, i need to declare my int variables static, because im calling this method from another static method that is called by main method.
but this can cause me problems ?
if i have two instances of this class running, my statics int will show the right value?
there is a better approach?

Here is my class, i want some advices to know if i am doing right, because everything is a little new for me.
My class, read a log file and based upon a regular expression, it can retrieve a general statistic or a personal statistic.
package br.com.organox.aggregator;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import org.apache.oro.text.regex.*;
public class LogFileReader {
private static Pattern regexpPattern;
private static PatternMatcher patternMatcher;
private static PatternCompiler patternCompiler;
private static PatternMatcherInput patternInput;
private static MatchResult matchResult;
private static final String patternString = "^[^\']+User\\s+\'([^\']+)\'[^\']+session\\s+\'([^\']+)\'\\s+(\\S+)";
// Integers used to store number of user, sessions and specific actions
private static int totalUsers;
private static int totalSessions;
private static int totalAddedActions;
private static int totalChangedFolders;
private static int totalPersonalizedActions;
private static int totalRemovedActions;
private static int totalUpdateActions;
private static int totalViewedActions;
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No file name was specified");
printClassUsage();
} else if (args.length == 1) {
printGeneralData(args[0]);
} else if (args.length == 2) {
System.out.println("You must set file name, data value and data type in order to " +
"this class run properly");
printClassUsage();
} else {
printSelectedData(args[0],args[1],args[2]);
public static void printGeneralData(String fileName) {
String data = "";
//Users and the Session Vector are used to avoid count repeated values.
Vector usersVector = new Vector();
Vector sessionVector = new Vector();
patternCompiler = new Perl5Compiler();
patternMatcher = new Perl5Matcher();
try {
regexpPattern = patternCompiler.compile(patternString);
} catch (MalformedPatternException mpe) {
System.out.println("Error Compiling Pattern");
System.out.println(mpe.getMessage());
try {
FileReader fileRead = new FileReader(fileName);
BufferedReader buffRead = new BufferedReader(fileRead);
while ((data = buffRead.readLine())!= null) {
patternInput = new PatternMatcherInput(data);
while(patternMatcher.contains(patternInput,regexpPattern)) {
matchResult = patternMatcher.getMatch();
// Avoid to insert repeated data in user and session Vectors
if (usersVector.lastIndexOf(matchResult.group(1)) == -1) {
usersVector.add(matchResult.group(1));
if (sessionVector.lastIndexOf(matchResult.group(2)) == -1) {
sessionVector.add(matchResult.group(2));
increaseActionType(matchResult.group(3));
for (int i=0;i<usersVector.size();i++) {
totalUsers++;
for (int i=0;i<sessionVector.size();i++) {
totalSessions++;
fileRead.close();
buffRead.close();
} catch (IOException ioe) {
System.out.println("An I/O error occurred while getting log file data");
ioe.printStackTrace();
System.out.println("Users logged : " + totalUsers);
System.out.println("Sessions opened : " + totalSessions);
System.out.println("Added contents : " + totalAddedActions);
System.out.println("Changed folders : " + totalChangedFolders);
System.out.println("Personalized contents : " + totalPersonalizedActions);
System.out.println("Removed contents : " + totalRemovedActions);
System.out.println("Viewed Contents : " + totalViewedActions);
System.out.println("Updated contents : " + totalUpdateActions);
public static void printSelectedData(String fileName,String value,String valueType) {
String data = "";
String user = "";
//Flag used to print the right result on screen
String printFlag = "";
Vector sessionVector = new Vector();
Vector userVector = new Vector();
Vector actionVector = new Vector();
patternCompiler = new Perl5Compiler();
patternMatcher = new Perl5Matcher();
try {
regexpPattern = patternCompiler.compile(patternString);
} catch (MalformedPatternException mpe) {
System.out.println("Error Compiling Pattern");
System.out.println(mpe.getMessage());
try {
FileReader fileRead = new FileReader(fileName);
BufferedReader buffRead = new BufferedReader(fileRead);
while ((data = buffRead.readLine())!= null) {
patternInput = new PatternMatcherInput(data);
while(patternMatcher.contains(patternInput,regexpPattern)) {
matchResult = patternMatcher.getMatch();
if (valueType.equalsIgnoreCase("-user")) {
printFlag = "userPrint";
if ((matchResult.group(1).equalsIgnoreCase(value))) {
userVector.add(matchResult.group(1));
// avoid insert a repeated value inside session vector.
if (sessionVector.lastIndexOf(matchResult.group(2)) == -1) {
sessionVector.add(matchResult.group(2));
increaseActionType(matchResult.group(3));
if (userVector.size() == 0) {
printFlag = "userPrintError";
} else if (valueType.equalsIgnoreCase("-session")) {
printFlag = "sessionPrint";
if ((matchResult.group(2).equalsIgnoreCase(value))) {
user = matchResult.group(1);
sessionVector.add(matchResult.group(2));
increaseActionType(matchResult.group(3));
if (sessionVector.size() == 0) {
printFlag = "sessionPrintError";
} else if (valueType.equalsIgnoreCase("-action")) {
printFlag = "actionPrint";
if ((matchResult.group(3).equalsIgnoreCase(value))) {
if (userVector.lastIndexOf(matchResult.group(1)) == -1) {
userVector.add(matchResult.group(1));
actionVector.add(matchResult.group(3));
if (actionVector.size() == 0) {
printFlag = "actionPrintError";
fileRead.close();
buffRead.close();
} catch (IOException ioe) {
System.out.println("An I/O error occurred while getting log file data");
ioe.printStackTrace();
if (printFlag.equals("userPrint")) {
for (int i=0;i<sessionVector.size();i++) {
totalSessions++;
System.out.println("Sessions opened by user " + value + " : " + totalSessions);
System.out.println("Added contents by user " + value + " : " + totalAddedActions);
System.out.println("Changed folders by user " + value + " : " + totalChangedFolders);
System.out.println("Personalized contents by user " + value + " : " + totalPersonalizedActions);
System.out.println("Removed contents by user " + value + " : " + totalRemovedActions);
System.out.println("Viewed contents by user " + value + " : " + totalViewedActions);
System.out.println("Updated contents by user " + value + " : " + totalUpdateActions);
} else if (printFlag.equals("userPrintError")) {
System.out.println("This user " + value + " was not found on log file");
} else if (printFlag.equals("sessionPrint")){
System.out.println("Session " + value + " was opened by user " + user);
System.out.println("Added contents by session " + value + " : " + totalAddedActions);
System.out.println("Changed folders by session " + value + " : " + totalChangedFolders);
System.out.println("Personalized contents by session " + value + " : " + totalPersonalizedActions);
System.out.println("Removed contents by session " + value + " : " + totalRemovedActions);
System.out.println("Viewed Contents by session " + value + " : " + totalViewedActions);
System.out.println("Updated contents by session " + value + " : " + totalUpdateActions);
} else if (printFlag.equals("sessionPrintError")){
System.out.println("This session " + value + " was not found on log file");
} else if (printFlag.equals("actionPrint")){
System.out.println("Action " + value + " was performed " + actionVector.size() +
" times for " + userVector.size() + " different user(s)");
} else if (printFlag.equals("actionPrintError")){
System.out.println("This action " + value + " was not found on log file");
} else {
System.out.println("Wrong search type!");
System.out.println("Accepted types are: ");
System.out.println("-user -> Search for a specified user");
System.out.println("-session -> Search for a specified session");
System.out.println("-action -> Search for a specified action");
private static void increaseActionType(String action) {
if (action.startsWith("a")) {
++totalAddedActions;
} else if (action.startsWith("c")) {
++totalChangedFolders;
} else if (action.startsWith("p")) {
++totalPersonalizedActions;
} else if (action.startsWith("r")) {
++totalRemovedActions;
} else if (action.startsWith("v")) {
++totalViewedActions;
} else if (action.startsWith("u")) {
++totalUpdateActions;
}

Similar Messages

  • Do the Interface contains static components like static methods and attribu

    Do the Interface contains static components like static methods and attributes ?

    >
    You have to supply a bit more detail: is that Lotus
    Notes API a Java API?Hmm, It's Java interface to Lotus Notes API
    Does it use JNI? Perhaps it is used somewhere underneath, I do not know for sure, but I think so
    Possibly the Lotus Notes
    implementation keeps a
    reference to those arrays, who knows?
    Maybe, but I'd be really suprised if it did. I derive this thread from Lotus Notes class and provide my own "worker method", overriding Lotus API abstract one, where I reference arrays. Arrays are specific to my program and since they are private fields in thread's class Lotus Notes layer does not have any way of referencing them, nor any reason for this matter
    For starters: if you zero out (set to null) your
    references to those arrays
    in your threads when the threads finish, there might
    surface a useful
    indication that you can blame Lotus Notes for this
    Well, I've become deeply suspect of whether these Notes' threads do really finish :-) My method finishes for sure, but it is just a part of run() method of Lotus Notes thread. Anyway, you can always safely blame Lotus Notes for almost anything :-)

  • Static method and threads?

    I have a question regarding "static". for example, I have the following code
    class Test{
    public int i=0;
    public static calculateInt(){
    ....some operations on i;
    if two processes attempt to call Test.calculateInt() at the same time. What will the effects be? shall these two calls be implemented totally independent? each call holds it own "i" for calculation. OR there will be operation conflicit on i.
    what if I change "public i" to :private i", the same effects?

    You can't operate on i in a static method, since i is an instance variable.
    If you make i static, then you can operate on it in a static method. In that case, all threads will share a single i--there's only one i for the whole class, and threads don't change that. Making it private won't change that.
    If you make the method into an instance (non-static) method, then any threads operating on the same instance will share the same i, regardless of whether it's public or private. Different threads operating on different instances will each have their own i.
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Also check out http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html

  • Why global var can be initialized with a static method and not by other static global var declared after its usage

    Take this:
    class test
    static int i=j;
    static int j=10;
    this will give illegal forward reference ....
    but this will compile successfully ..
    class test
    static int i=test1();
    static test1()
    return 20;
    plz assume we have main method in both cases ..
    java would be loading all static members first and would be assigning default values .. and then will be running all the initializers from to bottom ..
    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Plz help.
    Thanks
    Abhishek Roshan

    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Because the implementors of Java intentionally chose to do it that way.
    There are TWO stages to the process: preparation (which occurs first) and initialization.
    See the Java Language Spec section 12.4.1 'When Initialization Occurs
    The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
    Note the clause beginning 'may not refer to class variables'. And the authors give the reason for that restriction in the last sentence: detect circular initializations.
    Then if you check that referenced section 8.3.2.3 you will find this
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3
    8.3.2.3. Restrictions on the use of Fields during Initialization
    The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
      The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
      The usage is not on the left hand side of an assignment.
      The usage is via a simple name.
      C is the innermost class or interface enclosing the usage.
    When a method is used (your example 2) no circular initialization can occur because methods are not 'initialized'.

  • Static method and exception

    I have file which is reading from file and deleting it.
    delete is done by static method.
    now i need to do like this if file is empty it should throw exception and delte the file.
    so i added else like this
    else{
    throw new empty("Empty");
    but it is only thorowing exception not deleting file.as that static code is unreachable after throwing exception.
    any idea

    Hi zodok now this is original file just go through else statement in bold
    containing boolean a=deleteFile(fileName);
    package com.dhl.auditdatamgr.utils;
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.StringTokenizer;
    import java.util.regex.Pattern;
    import com.dhl.auditdatamgr.business.DetailedFacilityAuditData;
    import com.dhl.auditdatamgr.exceptions.FileFormatException;
    import com.dhl.auditdatamgr.exceptions.SystemException;
    import com.dhl.auditdatamgr.exceptions.EmptyFileException;
    import com.dhl.auditdatamgr.utils.db.DataUtil;
    * @author mahiseth
    public class AuditFileParser
          * Constructor
         protected AuditFileParser()
              super();
         public static List parseFile(String fileName, String regex)
              throws IllegalArgumentException, FileNotFoundException, FileFormatException,SystemException, EmptyFileException
              DataUtil.enforceNotNullOrEmpty(fileName);
              DataUtil.enforceNotNullOrEmpty(regex);
              List rowList = new ArrayList();
              BufferedReader br = null;
              try
                   br = new BufferedReader(
                                                 new FileReader(new File(fileName)));
                   String line = null;
                   DetailedFacilityAuditData detailedAuditData = null;
                   Integer huExpected = null;
                   Integer huMissing = null;
                   Integer huExtra = null;
                   Integer shipmentExpected = null;
                   Integer shipmentMissing = null;
                   Integer shipmentExtra = null;
                   Integer pieceIdsExpected = null;
                   Integer pieceIdsMissing = null;
                   Integer pieceIdsExtra = null;
                   Pattern p = Pattern.compile(regex);
                   //while((line = br.readLine()) != null)
                   if ((line = br.readLine()) != null){
                        //System.out.println("Line: " + line);
                        //Pattern p = Pattern.compile("[\\p{Punct}&&[|]]");
                        String [] lineItems = p.split(line.trim());
                        if (lineItems.length != 18){
                                                 System.out.println("line = >>" + line + "<<");
                                                    System.out.println("lineItems.length = " + lineItems.length);
                                                    System.out.println("lineItems = " + java.util.Arrays.asList(lineItems));
                        detailedAuditData = new DetailedFacilityAuditData();
                        DataUtil.enforceNotNullOrEmpty(lineItems[0]);     
                        DataUtil.enforceNotNullOrEmpty(lineItems[5]);
                        DataUtil.enforceNotNullOrEmpty(lineItems[6]);     
                        DataUtil.enforceNotNullOrEmpty(lineItems[3]);          
                        detailedAuditData.setHuid(lineItems[0]);
                        detailedAuditData.setAuditAtServiceArea(lineItems[5]);
                        detailedAuditData.setAuditAtFacility(lineItems[6]);
                        detailedAuditData.setAuditTime(DataUtil.convertToTimestamp(lineItems[3]));
                        detailedAuditData.setHuType(lineItems[4]);
                        detailedAuditData.setBuiltAtServiceArea(lineItems[1]);
                        detailedAuditData.setBuiltAtFacility(lineItems[2]);
                        if(lineItems[9] != null && !lineItems[9].equals(""))
                             huExpected = new Integer(Integer.parseInt(lineItems[9]));
                             detailedAuditData.setHuExpected(huExpected);
                        if(lineItems[12] != null && !lineItems[12].equals(""))
                             huMissing = new Integer(Integer.parseInt(lineItems[12]));
                             detailedAuditData.setHuMissing(huMissing);
                        if(lineItems[13] != null && !lineItems[13].equals(""))
                             huExtra = new Integer(Integer.parseInt(lineItems[13]));
                             detailedAuditData.setHuExtra(huExtra);
                        if(lineItems[7] != null && !lineItems[7].equals(""))
                             System.out.println("Shipment expected is: " + lineItems[7]);
                             shipmentExpected = new Integer(Integer.parseInt(lineItems[7]));
                             detailedAuditData.setShipmentExpected(shipmentExpected);
                        if(lineItems[10] != null && !lineItems[10].equals(""))
                             shipmentMissing = new Integer(Integer.parseInt(lineItems[10]));
                             detailedAuditData.setShipmentMissing(shipmentMissing);
                        if(lineItems[11] != null && !lineItems[11].equals(""))
                             shipmentExtra = new Integer(Integer.parseInt(lineItems[11]));
                             detailedAuditData.setShipmentExtra(shipmentExtra);
                        if(lineItems[8] != null && !lineItems[8].equals(""))
                             pieceIdsExpected = new Integer(Integer.parseInt(lineItems[8]));
                             detailedAuditData.setPieceIdsExpected(pieceIdsExpected);
                        if(lineItems[14] != null && !lineItems[14].equals(""))
                             pieceIdsMissing = new Integer(Integer.parseInt(lineItems[14]));
                             detailedAuditData.setPieceIdsMissing(pieceIdsMissing);
                        if(lineItems[15] != null && !lineItems[15].equals(""))
                             pieceIdsExtra = new Integer(Integer.parseInt(lineItems[15]));
                             detailedAuditData.setPieceIdsExtra(pieceIdsExtra);
                        detailedAuditData.setAuditor(lineItems[16]);
                        detailedAuditData.setAuditDate(DataUtil.convertToDate(lineItems[17]));
                        rowList.add(detailedAuditData);
              } else{
                   System.out.println("file");
                   boolean a=deleteFile(fileName);
                   System.out.println(a);
                   throw new EmptyFileException("File is Empty");
              catch (IOException e)
                   throw new SystemException("An error occurred while trying to read the audit data file. " ,e);
                   //e.printStackTrace();
              } catch (ParseException e)
                   throw new FileFormatException("An error occurred while parsing the audit data file. " ,e);
                   //e.printStackTrace();
              catch (ArrayIndexOutOfBoundsException ae)
                   throw new FileFormatException("A required field is missing. " ,ae);
              finally
                    try
                        br.close();
                   } catch (IOException e1)
                        e1.printStackTrace();
              return rowList;
          * @param fileName - File name or directory to be deleted
          * @return true if and only if the file is successfully deleted, false otherwise
          * @throws IllegalArgumentException
         public static boolean deleteFile(String fileName)
              throws IllegalArgumentException
              DataUtil.enforceNotNullOrEmpty(fileName);
              File f = new File(fileName);
              boolean deleteStatus = false;
              deleteStatus = f.delete();
              return deleteStatus;
    }

  • Static classes and variables

    Hello,
    I put all of my constants in an *{color:#3366ff}interface{color}* called Constants.java (I only put constants in this file) and when obfuscated the Constants.class file is removed from .jar and constants are inlined into classes this is Great! However, do I gain anything by placing all of my static methods into one class? Currently, there are all over the place and also I have classes that are already static like HttpMgr.java/ErrorMgr.java/InfoMgr.java I am thinking about merging these classes together with all static methods defined within the project. Do I gain or loss anything by doing this?
    Thanks!

    you will gain some bytes by merging all the static classes in one.
    you can create a ManagerTool.java class and write inside all the static methods ...

  • Static methods and how to access

    Hi,
    This seems like a silly quesion but i am trying to access a static method but it tells me that i cant.
    The method i am calling from is not static
    Thanks

    syntax: class name dot static method name (assuming the method is accessible): StaticMethodClassName.aStaticMethod();
    can't reference a class member (variable, object, method, ...) from a static method because a static method is not a class member (it is simply a method whose scope is confined to that of the class in which it is defined).
    example:
    class Foo
    int i;
    public static void hasSyntaxErr() // this method is not a member of Foo
    i = 0; // not allowed because i is a member of Foo
    class Fooo
    void testStatic() { Foo.hasSyntaxErr(); }
    }

  • Difference between calling static method and not static method?

    Hi,
    Suppose i want to write a util method, and many class might call this method. what is better? writing the method as static method or not static method. what is the difference. what is the advantace in what case?

    writing the method as static method or not static
    method. what is the difference.The difference is the one between static and non-static. Any tutorial or the JLs will clarify the difference, no need to repeat it here.
    what is the advantace in what case?It's usually not like you have much of a choice. If you need access to an instance's attributes, you can't make it static. Otherwise, make it static.

  • Question about functions methods and variables

    Sorry but i couldn't figure out a better title.
    When does a method alter the variables it gets directly and when does a method just alter a clone of the variables it gets?
    How about a funcion?
    for example:
    public void (int i)
    i = 4;
    sometimes this method alters the integer which was given to it directly and sometimes it automatically creates a clone of the integer and alters that one. I just can't figure out why a method would do the first or the second.
    Im trying to achieve the direct changeing of the given variable without creating an unessecary clone.
    Thank You

    Comp-Freak wrote:
    Sorry but i couldn't figure out a better title.
    When does a method alter the variables it gets directly and when does a method just alter a clone of the variables it gets?
    How about a funcion?
    for example:
    public void (int i)
    i = 4;
    sometimes this method alters the integer which was given to it directly and sometimes it automatically creates a clone of the integer and alters that one. I just can't figure out why a method would do the first or the second.
    Im trying to achieve the direct changeing of the given variable without creating an unessecary clone.
    Thank YouThats quite all right about the title, trust me we get much worse titles on this forum. Most of the time to the effect of "Plz urgentlly!!!!111one"
    In Java, all variables passed into methods are passed by value, which means that if I pass an int variable to a method, that methods argument will always be a seperate variable. There is no way to pass variables by reference so that you are altering the original variable you passed in.
    It actually works the same way for reference variables that point to a particular object.
    public Object o = new Object();
    methodOne(o);
    public void methodOne(Object oArg) {
      o == oArg;  //true
    }It is essentially the same in this case, there are two seperate reference variables here, o and oArg is created once the method is called. There is only one Object created however and both reference variables point to it, so an == check will verify this that it is true.

  • Java method and variable visiblity and filesize...

    I have now almost ready application, and I found out that losing some wight of it wouldn't hurt...
    I noticed that I have some unused constructors and even some methods that are depricated after some finetuning..
    I removed those and noticed that method obviously take quite a lot space in compiled and Jar-packed app, so I managed to lose nearly 100 KB... Now I wonder if also changing methods' visibility (private, public...) or even variables vivibility have any affect on this...
    Any other hints how to make this app even smaller ?
    TIA,
    P_tr

    there's lots of ways to optimize your code. Here's 2 articles on it:
    http://www.deutronium.de.vu/tutorials/javasize.html
    http://www.deutronium.de.vu/tutorials/javaspeed.html

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • How do I identify which is static and which is non static method?

    I have a question which is how can i justify which is static and which is non static method in a program? I need to explain why ? I think it the version 2 which is static. I can only said that it using using a reference. But am I correct or ?? Please advise....
    if I have the following :
    class Square
    private double side;
    public Square(double side)
    { this.side = side;
    public double findAreaVersion1()
    { return side * side;
    public double findAreaVersion2(Square sq)
    { return sq.side * sq.side;
    public void setSide(double s)
    { side = s;
    public double getSide()
    { return side;
    } //class Square
    Message was edited by:
    SummerCool

    I have a question which is how can i justify which is
    static and which is non static method in a program? I
    need to explain why ? I think it the version 2 which
    is static. I can only said that it using using a
    reference. But am I correct or ?? Please advise....If I am reading this correctly, that you think that your version 2 is a static method, then you are wrong and need to review your java textbook on static vs non-static functions and variables.

  • Static method or not static method

    I have a simple class, ClassA, with no shared class variables, and has only one static method only:
    class ClassA {
    public static void doIO (args) {
    try {
    //very time consuming I/O task
    catach (Exceptions e) { 
    //try to resolve the problem
    This doIO method will be called simultaneously from different objects.
    My questions are:
    1) Would this static method approach cause any robustness, efficiency problem? Or, should I change the method into a non-static method, and create a new instance of ClassA every time?
    2) If there are 20 threads call ClassA.doIO(args) at the same time, would the method be executed in parallel or queued?
    Many thanks.
    java9394

    Using a static method makes this implementation as efficient as possible. Since the class has no instance variables, there is no benefit, to either making it non-static, or creating multiple instances. If you have 20 threads calling it, they will run concurrently. So, if you do not like this behavior, the method can be declared both static, and synchronized.

  • Can I have a static method?

    I want to know whether we can have static method and static block in Ejb.
    also I want to know the use of these and when these will be invoked by the container

    Technically speaking you can have static methods or static blocks the java compiler or teh ejb deployer will not complain
    However its always a good practice to avoid having static blocks, static methods in EJB
    if you have the urge to initialise or have a startup code in your application when EJB is loaded , you can implement the code in ejbCreate()
    - I dont see any other reason where you might need static block
    if there is any other reason please explain what cirumstances drives you to have static {} static mthd()
    if it is statess session Bean avoid having even non-static member variables
    Reasons for not having non-static member variable in Stateless Session EJB is
    1. stateless EJBs are pooled so the instances are pooled after use.. so there is a chance you might get the same instance with previous assigned values
    Hope the info helps!

Maybe you are looking for