Can't we declare a static variable inside a memberfunction of a class?
Hi,
class A{
public void fun()
static int i=10;
can' we declare static variable in member function of class?
Thanks,
It is a common idiom in C and C++, but it is forbidden
in Java because it adds hidden dependencies.
The C way of writing a serial number generator:
int generate() {
static int n = 0;
return n++;
}Pure C has only global functions. So it needs inner
static variables to help to hide the data. I've had
lots of headaches trying to make C programs with inner
static variables work correctly because they usually
are hidden in cross-reference listings.
The Java way:
public static class SerialNumberGenerator() {
private static int n = 0;
public static int generate() {
return n++;
}The code above is as static as the C code given
before, but it tries to be more explicit (no hidden
variables).Hum... have you tried to compile your sample ?
(And anyway, what the hell would a static class be used for ???)
But perhaps you meant:
public final class SerialNumberGenerator {
private static int n = 0;
public static int generate() {
return n++;
Similar Messages
-
I want to access that BEA instance variable inside of a external java class
Hi,
This is N.pradeep. I am a java programmer, and I am new to BEA AquaLogic BPM studio5.7. I have a question regarding how to retrieve an instance variable of BEA Aqua Logic to an external Java Program. i.e. I want to access that BEA instance variable inside of a external java class, and vice versa.You can use PAPI or PAPI-WS for accessing BPM instance variable from a Java code, thougt I am not sure how the reverse will be done. Assuming that you are aware aof PAPI-WS and have created the necessary stubs out of the PAPI-WS WSDL using Axis, you can access instance variables using the API's or operations defined therein.
Thanks and Regards
Vivek Nandey
BEA Certified Developer for Integration Solutions
[email protected] -
[Bash] How to `declare` a global variable inside a function?
#!/bin/bash
# Not using declare -A, array will be treated as indexed array rather than an associative array
seta()
for ((n=0;n<$1;n++)); do
printf -v a_$n[k] %s k$n
printf -v a_$n[j] %s j$n
eval echo inside seta: a_$n[k] = \$\{a_$n\[k\]\}
done
seta 3
echo outside: a_0[k] = ${a_0[k]}
echo outside: a_0[j] = ${a_0[j]}
echo
# Use declare -A inside function, array will be undefined outside
setb()
for ((n=0;n<$1;n++)); do
declare -A b_$n # Note here
printf -v b_$n[k] %s k$n
printf -v b_$n[j] %s j$n
eval echo inside setb: b_$n[k] = \$\{b_$n\[k\]\}
done
setb 3
echo outside: b_0[k] = ${b_0[k]}
echo outside: b_0[j] = ${b_0[j]}
echo
# The bad solution, only works if we know beforehand how many c_? arrays will be assigned inside setc()
for ((n=0;n<3;n++)); do
declare -A c_$n
done
setc()
for ((n=0;n<$1;n++)); do
printf -v c_$n[k] %s k$n
printf -v c_$n[j] %s j$n
eval echo inside setc: c_$n[k] = \$\{c_$n\[k\]\}
done
setc 3
echo outside: c_0[k] = ${c_0[k]}
echo outside: c_0[j] = ${c_0[j]}
My original code does the declare -A as in setb(). I was surprised when I saw all blank output... Now the problem is illustrated clearly by the setb() example.
The setc() example works, but a bit ugly: look at the two 3's...
My ideal solution would be, something like `declare_global -A b_$n` in setb()
Any ideas?with current bash versions, i don't think it is possible to declare global associative arrays in functions.
what you are after is the "-g" option of typeset which is available in zsh.
i think i read somewhere that something similar may be planned for bash 4.2. -
How to give different value to a static variable???
Hi all:
Is there any solution to set different values to a static variable???I had try two ways but all have errors!
1.Way_1
protected String tmp=null;
protected void initSituation(int sayorpress)
if (sayorpress==0)
tmp = "string1";
else if (sayorpress==1)
tmp = "string2";
protected static String RESOURCE_STRING = tmp; <---error
Error:non-static variable tmp cannot be referenced from a static context
2.Way_2
protected void initSituation(int sayorpress)
if (sayorpress==0)
protected static String RESOURCE_STRING = "string1"; <---error
else if (sayorpress==1)
protected static String RESOURCE_STRING = "string2"; <---error
Error:illegal start of expression at
not an expression statement at
Thank you very mich!!!Try this:
protected static String RESOURCE_STRING = null;
protected void initSituation(int sayorpress)
if (sayorpress==0)
yourClass.RESOURCE_STRING = "string1";
else if (sayorpress==1)
yourClass.RESOURCE_STRING = "string2";
You cannot declare a static variable inside a method. But you can access a static variable thorugh your class. -
Clarification about static variables declaration
I'm getting "Illegal Start of Expression" error, When i try to declare a static variable within a static metho or nonstatic method.
Could you please clarify me,
Is it possible to declare a static varible within a static method or non static method ?
ThanksHi Vikas,
First, note that this forum is devoted to Sun Java Studio Creator IDE. General Java questions can be asked on forums here: http://forum.java.sun.com/
Second, note that static variable can be defined only as member of class. It cannot be defined inside of method.
Thanks, Misha
(Creator team) -
Can we define 'Static Variables' in BPEL process ?
Is the idea of 'STATIC VARIABLES' supported in Oracle BPEL?
What I mean by that is, I need all my in-flight BPEL process INSTANCES to read a common variable and then decide the next course of action.
Is this possible?
Thanks in advance,
MahendraHi Hans,
In Cocoa and Objective-C a static variable needs to be declared in the implementation file and not the header as you would normally do. Standard C variables can be set at the same time as the declaration but Cocoa objects need an extra step.
For example:
#import "TestObject.h"
// declare your static variable here
static NSArray *count;
@implementation TestObject
- (id) init {
self = [super init];
if (self != nil) {
// set the variable here
// the 'if' statement ensures it is only set once
if (!count) {
count = [[NSArray arrayWithObjects:@"One",@"Two",@"Three",Nil] retain];
return self;
@end
Hope this helps,
Martin.
PowerMac G5 1.6Ghz Mac OS X (10.4.9) 4 gig RAM & NVidia 6800 Ultra -
Is it a bad way to declare somany Static Variables in a program?
-Achyuth Bok..
So if in a swings program if i am using only one frame through out the program, by adding and deleting components on it.
Then i can declare that frame as Static, right.
So that i can call the same frame(and not instance of it) from different class.
And if i have to take the value entered in a JTextField from another class, Then that JTextField can also be declared as Static right.
-Achyuth B -
Can a static variable wil be serialized?
can a static variable wil be serialized? plz send reply soon
No. Serialization is about the state of the object, but static variables reflect the state of the class as a whole.
And don't say things like "reply soon." People will reply if and when they feel like it, without regard to you requests for "soon." -
Using Static Variable against Context Attribute for Holding IWDView
Dear Friends,
I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
Clarification on this is highly appreciated
The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?Hi Sujai ,
As you have specified the problem that we face when we use static attributes, when end users are using the application .
Static means i have n number of objects but the static variable value will remain same every where.
when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
so every user has a unique Iview parameter , when context is used and
when static is used , assume you have userA , his iview is set this intially and u have another user B , when he is using , since the variable is static and when you access this variable you will get the value of userA.
Regards
Govardan Raj -
Static variable in session bean
Can we declare static variable in session bean. If we declare what will happen. Will it create error in compile time or not deployed in server.
From a Java language perspective, nothing stops you from declaring a static variable in a session
bean class. It will compile as long as its syntactically correct.
From an EJB programming model perspective, the use of non-final static variables
is discouraged because it breaks the JVM-transparency that is an important aspect of the
EJB architecture. It should be possible to deploy a single EJB application to a cluster and
have it behave exactly as if it were deployed to only one server instance (albeit with higher
overall throughput/performance). Using non-final static variables breaks this property
because the bean instances in one JVM will see a different value for the static variable
than bean instances in a different JVM.
It also forces you to deal with synchronization
of the shared data, which is a complexity that was carefully avoided in the EJB programming
model by ensuring that each bean instance is single-threaded.
Bottom line is you can have "final static" data members in EJB classes but you should
avoid non-final (mutable) static data.
--ken -
Bind variable inside a package
Can we declare a bind variable inside a package specification?
CREATE OR REPLACE PACKAGE GET_EMPLOYEEDETAILS
IS
PROCEDURE GET_FIRSTNAME(E_ID IN EMPLOYEES.EMPLOYEE_ID%TYPE, F_NAME OUT EMPLOYEES.FIRST_NAME%TYPE);
VARIABLE O VARCHAR2(20);
END GET_EMPLOYEEDETAILS ;
CREATE OR REPLACE PACKAGE BODY GET_EMPLOYEEDETAILS
IS
PROCEDURE GET_FIRSTNAME(E_ID IN EMPLOYEES.EMPLOYEE_ID%TYPE, F_NAME OUT EMPLOYEES.FIRST_NAME%TYPE)
IS
BEGIN
SELECT FIRST_NAME INTO F_NAME FROM EMPLOYEES WHERE EMPLOYEE_ID = E_ID;
DBMS_OUTPUT.PUT_LINE(F_NAME);
END;
END GET_EMPLOYEEDETAILS;
Output:
ERROR at line 4: PLS-00103: Encountered the symbol "VARCHAR2" when expecting one of the following:
:= . ( @ % ; not null range default character
The symbol ":=" was substituted for "VARCHAR2" to continue.
2. IS
3. PROCEDURE GET_FIRSTNAME(E_ID IN EMPLOYEES.EMPLOYEE_ID%TYPE, F_NAME OUT EMPLOYEES.FIRST_NAME%TYPE);
4. VARIABLE O VARCHAR2(20);
5. END GET_EMPLOYEEDETAILS ;
6. /
or is there any alternative for bind variables inside an package
Thanks in advance
Message was edited by: 1009739The "VARIABLE O VARCHAR2(20);" syntax is the way SQLPlus declared bind variables - it is specific to the client. Because PL/SQL packages and procedures are server code that continue past sessions, its only access to the client environment is what the client gives it - it can't go and create a bind variable in the client.
PL/SQL procedures, functions and packages run from lots of environments, so they cannot access bind variables inside their body - you have to pass any external variables as parameters.
Anonymous PL/SQL blocks can access bind variables.
You can declare package public global variables - just leave out that "VARIABLE". E.g.
CREATE OR REPLACE PACKAGE GET_EMPLOYEEDETAILS
IS
PROCEDURE GET_FIRSTNAME(E_ID IN EMP.EMPNO%TYPE, F_NAME OUT EMP.ENAME%TYPE);
O VARCHAR2(20);
END GET_EMPLOYEEDETAILS ;
For local variables in your procedure, just put them between the IS and BEGIN. Using them in SQL inside the PL/SQL automatically uses them as a bind variable.
create or replace PROCEDURE GET_FIRSTNAME(E_ID IN EMP.EMPNO%TYPE, F_NAME OUT EMP.ENAME%TYPE)
IS
O VARCHAR2(20);
O2 VARCHAR2(21);
BEGIN
O := 'FR%';
SELECT ENAME INTO F_NAME FROM EMP WHERE EMPNO = E_ID and ENAME like O;
O2 := F_NAME || '2';
DBMS_OUTPUT.PUT_LINE(F_NAME);
END;
O is bound in the query.
To access bind variables from anonymous PL/SQL, first declare them in the calling environment. In SQL Plus that's
VARIABLE O VARCHAR2(20);
In Pro*C it's
EXEC SQL BEGIN DECLARE SECTION;
char[21] O
EXEC SQL END DECLARE SECTION;
Then reference it in anonymous PL/SQL with a colon as prefix:
BEGIN
SELECT FIRST_NAME INTO :O FROM EMPLOYEES WHERE EMPLOYEE_ID = E_ID;
END;
This only works for anonymous blocks (starting with BEGIN or DECLARE). As I said, PL/SQL procedures, functions and packages cannot see bind variables from the calling environment -
Hello all,
I'd like to receive some hints about how to parallelize the code below that Thread Analyser has detected races for static variables:
#pragma omp parallel for private(i)
for (i=0; i<n; i++){
x = calc(a);
int calc(int a){
static int x,y,z=0;
x = 2 * a / 2.2345; // Thread Analyser detected write race here
y = x * 3.4567; // Thread Analyser detected write race here
z += x * y; // Thrd Analyser detected write and read races here
return z;
Best Regards,
GlauberYou can either declare the static variables as "threadprivate", or put the accesses to these variables in critical sections. Like
int calc(int a){
static int x,y,z=0;
#pragma omp threadprivate(x,y,z)
x = 2 * a / 2.2345;
y = x * 3.4567;
z += x * y;
return z;
or
int calc(int a){
static int x,y,z=0;
int t;
#pragma omp critical
x = 2 * a / 2.2345;
y = x * 3.4567;
z += x * y;
t = z;
return t;
Notice the use of 't' in the above code, as you cannot put a 'return' in a critical section.
While the above techniques may get rid of the data races, they may not fix the problem you are facing. Making a code thread safe is more than merely getting rid of the data races. If you can show in more details how the static variables are used, we may be able to give more specific helps.
-- Yuan -
Hi all,
does anyone know how to define/use static variables inside a BPEL process? Or, is there any way so I can keep data from a (synchroneous) invocation to be used during the next (synchroneous) invocation?
thanks for your help, I have been working on this for many many days !
Abdel.How about a BPEL process that maintains your static variables and uses a custom correlation token. Queries to the process can retrieve the variable requested, and if they use the custom correlation token then the process will act as a singleton.
I suggest using event processing rather than simple receive to handle the messages. -
Modifying static variable in 1object dosent effect value in another object
Hi,
I have a simple class that declares a static variable x...
class DeclareStatic
static int x = 10;
}I have another class that modifies this static variable (x)...
class ModifyStatic
public static void main(String[] Args)
DeclareStatic.x = 20;
}The problem I have is when I run the next class to simply print out the static variable x, I get 10 (the originally assigned value), not 20 (the modified value)...
class StaticTest
public static void main(String[] Args)
System.out.println(DeclareStatic.x);
}It is my understanding that by definition of being static, there is only 1 copy of this static variable(x), shared amongst all objects. Therefore, when I attempt to modify this value with a direct reference (DeclareStatic.x =20;), why isn't the change refelected in other classes which access the variable?
This also leads to the question how DO I modify a (non final) static variable from an object and have the change reflected in all other objects?
I have spent some time researching this on-line and in my java books to no avail, any help is greatly appreciated as I am studying to sit the SCJP and attention to detail is everything!
Thanks,
Alan Kilbride ;o)Hi,
I have a simple class that declares a static variable
x...
class DeclareStatic
static int x = 10;
}I have another class that modifies this static
variable (x)...
class ModifyStatic
public static void main(String[] Args)
DeclareStatic.x = 20;
}The problem I have is when I run the next class to
simply print out the static variable x, I get 10 (the
originally assigned value), not 20 (the modified
value)...
class StaticTest
public static void main(String[] Args)
System.out.println(DeclareStatic.x);
}It is my understanding that by definition of being
static, there is only 1 copy of this static
variable(x), shared amongst all objects. Therefore,
when I attempt to modify this value with a direct
reference (DeclareStatic.x =20;), why isn't the
change refelected in other classes which access the
variable?Because your test code never makes a reference to the ModifyStatic class. You could delete ModifyStatic from your system and the code would run exactly the same.
Jim S. -
Static variables and JAR files problem
Hello All,
I am trying to get two applets to communicate.
Both are held in the same JAR file loaded from the same location. The JAR file also contains a class with some static variables which are used to comunicate between the two applets.
The applets are on separate frames in the browser and the system works fine when I don't use a JAR file but when I put the class files into a JAR file, each applet has it's own static variables (not very static).
Can anyone tell me why static variables stop working when the code is loaded from a JAR file.
Thanks in advance,
Alastair.Ok,
I've just tried the below setup and I get the following security exception:
java.security.AccessControlException: access denied (java.util.PropertyPermission java.home read)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
at java.lang.System.getProperty(Unknown Source)
at sun.plugin.security.PluginClassLoader.getPermissions(Unknown Source)
at java.security.SecureClassLoader.getProtectionDomain(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at sun.applet.AppletClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.applet.AppletClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at appSend.init(appSend.java:62)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I now have one JAR file which contains the two classes.
appSend.class & appReceive.class
and a separate details.class file
The two HTML files are in separate folders but the JAR file is still the same for both.
Classes\ -> contains the JAR file (myCode.JAR) and details.class
Sender\ -> contains the HTML file appSender.html (see below for
Applet tag)
Receiver\ -> contains the HTML file appReceiver.html (see below for
Applet tag)
appSender.html
<HTML>
<HEAD>
</HEAD>
<BODY BGCOLOR="000000">
<CENTER>
<APPLET
name = "appSender"
code = "appSend.class"
archive = "myCode.JAR"
codebase = "../Classes"
width = "500"
height = "300"
>
</APPLET>
</CENTER>
</BODY>
</HTML>
appReceiver.html
<HTML>
<HEAD>
</HEAD>
<BODY BGCOLOR="000000">
<CENTER>
<APPLET
name = "appReceiver"
code = "appReceive.class"
archive = "myCode.JAR"
codebase = "../Classes"
width = "500"
height = "300"
>
</APPLET>
</CENTER>
</BODY>
</HTML>
Is this how it should be? or have I made a mistake with the tags?
Can the ClassLoaders in either applet see the details.class file through the codebase tag?
I'm guessing from the security exception that the ClassLoader for each applet can only load classes from within the JAR file? and can't just use the codebase tag, which is not very helpful!
Thanks for your help so far.
Regards,
Alastair.
Maybe you are looking for
-
Sir i have lost my apple iphone and i do not remember IMEI number of the iphone and the sticker affiexed on the box is also not present (lost) but i have the bar code 602-7484-A printed on the box and police is asking for the IMEI number so please he
-
XI mail adapter - File name should be same in attachment
Hi all, Here is our scenario: First part of our scenario involves picking *.pgp (e.g. addressB.pgp) file from partner FTP server and after decrypting put it on local Unix path - This part works ok In second part, we send this file by mail to static m
-
Bad Image iTunes.exe c:windows/system32\d3d8thk.dll
I started to download 4.0 for iPhone and iTunes upgrade displayed, so I clicked OK. Download was successful installed no error. Clicked to open got this message: Bad image iTunes.exe c:windows/system32\d3d8thk.dll designed not to rum on windows or it
-
Hi, What I want to do is pretty simple (but I just can't figure it out ). I want to connect an analog input to an analog output, but control this like a relay. For example, when switch is true, my pins are connected so the input on pin A gets passed
-
I just purchased a Verizon WiFi device on 7/27/11 for $108.30 and signed up for a 5G plan that I was told would be $50/mo. So, I was surprised to get a bill yesterday for $101.82 which included $64.52 for monthly service (which I assume is the $50/m