Constant declaration
I am trying to declare a constant. I keep getting an "illegal start of expression error" on the lines that declare my constants. I have tried changing "public" to "private" and I have also tried leaving the first modifier off entirely, but it still gives me the error. Can anyone tell what I am doing wrong here?
class Example2 {
public static void main(String [] args) {
public static final int DODGE = 1;
public static final int FORD = 2;
int vehicle;
vechicle = FORD;
switch(vehicle) {
case FORD: System.out.println("You chose Ford");
break;
case DODGE: System.out.println("You chose Dodge");
break;
}
I am trying to declare a constant. I keep getting an
"illegal start of expression error" on the lines that
declare my constants. I have tried changing "public"
to "private" and I have also tried leaving the first
modifier off entirely, but it still gives me the
error. Can anyone tell what I am doing wrong here?
class Example2 {
public static void main(String [] args) {
public static final int DODGE = 1;
public static final int FORD = 2;
int vehicle;
vechicle = FORD;
switch(vehicle) {
case FORD: System.out.println("You chose
Ford");
break;
.println("You chose Dodge");
break;you could try 'enum' , this keyword exists since 1.5
sorry for late response
Message was edited by:
p_epi
Similar Messages
-
File with constants declared?
How do I create a file with some constants declared? Do I have to make a class out of them? Then, how do I import the file into other classes?
Here's what I have:
interface ConvertTypes
public static final int IDC = 1,MDS = 2, IDC_AND_MDS = 3;
class ctest implements ConvertTypes
public static void main(String[] args)
System.out.println(IDC);
Here's the error I get after I compile ConvertTypes and ctest:
Z:\ctest.java:1: cannot resolve symbol
symbol : class ConvertTypes
location: class ctest
class ctest implements ConvertTypes
^
Z:\\ctest.java:5: cannot resolve symbol
symbol : variable IDC
location: class ctest
System.out.println(IDC); -
(Since there is no "possible/future features" forum, I'm posting here, since a lot of the postings here deal with such matters.)
Like some other Java users I'm a fan of the const declaration concept - const methods (not modifying the instance) and parameters (the object the parameter references will not be modified by the method). In part because it adds valuable error checking ability at compile time, and in part because it makes method declarations a lot clearer in many cases.
(I'm not advocating a run-time conversion between const/non-const like in C/C++. Like e.g. final, this characteristic should be fixed after compilation.)
I know there is an RFE on this - which was closed some years back, without much evaluation (not posted there, anyway). I've also been able to find some shallow discussions in the forums, and some have hinted that it can be a complex feature in some scenario, perhaps implying that it would not be without caveats.
Perhaps some readers here know more about this issue and why the const keyword (which is reserved in the Java spec) has been decided to be unused?I don't have a deep knowledge of this, but AFAIK it's not practical (or possible) for the compiler to enforce this.
Consider this method:
static void printAndPeel(const Apple a, Fruit f) {
System.out.println(a + "is an apple");
System.out.println(f + "is an unpeeled fruit");
f.peel();
System.out.println(f + "is a peeled fruit");
The 'const' Apple referred to by a is unchanged by the method 99% of the time. But when a==f , a strange bug occurs (from the point of view of anyone expecting a to remain unpeeled). The same would happen if this were a non-static const method of Apple, where 'this' takes the place of the parameter 'const Apple a'.
Presumably the source of the problem is that you want objects to be const (within the scope of a method, say), but using syntax which declares references to objects as const. But there can be all kinds of references to an object, including ones in different threads.
You could ensure an object was const by:
(a) making it immutable always,
(b) making it mutable but (say within the scope a method), ensuring that absolutely all references to the object are const (the Collections.unmodifiableCollection() wrapper attempts to do this),
(c) having some kind of lock in the object itself which is enabled during the scope of a method, and throws an exception if someone tries to modify the object.
Re these:
(a) is the way to go, I think. I'd like to see an 'immutable' keyword you could apply to a class, which ensured all its fields were final and immutable (primitives would count as immutable). This would both be useful as a compile-time check for developers, and as a hint for the JVM to do various optimisations.
(b) I don't see how this could work at compile time. If an object is mutable, you want it to be temporarily immutable sometimes (within the scope of a method, say). The compiler would have to prove that all non-const references accessible in that method could not point to the const object - even references of type Object! This places very stringent restrictions on what you can do in a method. Additionally, you have to ensure other threads can't change the object - very hard to enforce.
(c) sounds possible but not ideal, because it's a runtime check. The above printAndPeel() method would compile OK and fail occasionally when run. But maybe this solution could be implemented in the VM in a fairly efficient manner by reusing the synchronisation locks somehow? -
Constant declaration of VARRAY index by varchar2 within package header
Hi there
I'm looking for the correct syntax to declare a constant
of a varray type which is indexed by varchar2. I've tried
the following:
create or replace package nl_types
is
TYPE nt_assoc_small IS TABLE OF INTEGER INDEX BY VARCHAR2(32);
nl_bindcnt constant nt_assoc_small ('xml_gkregnl') := 3;
end;
I know this array hat just one element, but there will
be even more when I got this example case to work. As
I tried to compile this package, the compiler said:
13/16 PL/SQL: Declaration ignored
13/25 PLS-00566: type name "NT_ASSOC_SMALL" cannot be constrained
13/70 PLS-00320: the declaration of the type of this expression is
incomplete or malformed
O.K. then: Does anybody know the "wellformed" declaration
for this kind of varray?
Thanx in advance,
Martin.That's not a VARRAY declaration, it's a PL/SQL table / associative array.
There is no syntax to declare the contents of an associative array in-line.
They can either be assigned to directly or populated by BULK COLLECT (except for associative arrays indexed by VARCHAR2). Perhaps you could assign the return value of a function?
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
SQL> CREATE OR REPLACE PACKAGE types AS
2
3 TYPE associative_array_type IS TABLE OF INTEGER
4 INDEX BY VARCHAR2 (32);
5
6 FUNCTION default_associative_array_type
7 RETURN associative_array_type;
8
9 END;
10 /
Package created.
SQL> CREATE OR REPLACE PACKAGE BODY types AS
2
3 FUNCTION default_associative_array_type
4 RETURN associative_array_type
5 IS
6 associative_array associative_array_type;
7 BEGIN
8 associative_array ('xml_gkregnl') := 3;
9 RETURN associative_array;
10 END;
11
12 END;
13 /
Package body created.
SQL> CREATE OR REPLACE PACKAGE constants AS
2
3 associative_array CONSTANT types.associative_array_type :=
4 types.default_associative_array_type;
5
6 END;
7 /
Package created.
SQL> SET SERVEROUTPUT ON;
SQL> BEGIN
2 DBMS_OUTPUT.PUT_LINE (
3 'constants.associative_array (''xml_gkregnl'') => ' ||
4 constants.associative_array ('xml_gkregnl'));
5 END;
6 /
constants.associative_array ('xml_gkregnl') => 3
PL/SQL procedure successfully completed.
SQL> -
Constant declaration and the optimizer
Assume there is a Plsql package A with a defined constant 'constA'
Assume we have an sql query in PLSQL package B that references A.constA.
Will the optimizer always give the same plan for the query whether I used the literal constant or the reference A.constA?
I assume that replacement of references to A.constA would have to be don't before the optimizer begins it's evaluation. I assume that does not happen; therefore, using A.constA has prevented the optimizer from using the statistics on the table.
Ie. It is true that use of literals may provide better performance than references to declared constants.Hi,
Will the optimizer always give the same plan for the query whether I used the literal constant or the reference A.constA?Assuming bind peeking is not turned off and all other parameters influencing CBO are the same - yes.
"The same plan" in this context means not "the same piece of memory in library cache", but "the same execution path", because query with literal and a constant will result in different SQL queries, hence different shareable parent cursors.
It is true that use of literals may provide better performance than references to declared constants.Yes. If you have a constant to use in SQL, then it's better to use it as a literal rather than bind (using a PL/SQL constant in a query results in using bind variable - but maybe that behavior will be changed sometime).
The main issue with using binds for constant is a case you use several constants for exactly the same query and there's data skew. CBO is not doing well with that until 11g (which introduced adaptive cursor sharing). -
Constant declaration problem in View?
Hi All,
In Webdynproapplication I am trying to declare the Constant value after the public static void wdDoModifyView() method in View. When I am saving this it's automatically disappear.
Please to give me ides why this is not viewing when iam saving the value after declaring constant in View.
Please help me out.
Thanks
Nageswara.Hi, I would like to expand on Raman's reply:
For the source code of every controller, you will see a placeholder in the file demarcated as follows:
//@@begin others
//@@end
Here you can enter any Java code that you like, (constants, variables and functions). This section of the file is saved "as is" by the IDE and not regenerated all the time.
Often in a Web Dynpro project you have parameters variables in the default controller which you would like to use in other controllers, but which are never used directly in displays. In general, the Context should only contain variables and parameters which are directly needed by UI elements in Views. Instead of putting these variables in the Context, a cleaner way is to create these variables in the "others" section, together with getter and setter functions (also in this section), and calling the functions from other controllers as needed.
Walter -
How to retrieve constants value from compiled code in jar file?
Hi everyone,
I've been looking for a way to solve this for a week now, without any much success... and I've finally decided to ask the Java gurus for a solution! :-)
Here's what I am basically trying to do:
I have several jar files in which there are only compiled code (.class).
In every class, there are 2 constants (declared as static final String) that I would like to retrieve (one is the version and the other the date of the last modification).
My goal is to print a list of all the classes in the jar files with the values of these 2 constants for each class.
The solution that I have right now to do this does not work properly: for now, I read all the elements of the classpath, check if these are jar files, and if so, I look into each one and load all the classes one by one and print the results.
The problem with this is that it uses the method Class.forName(className) and as some classes are unfortunately present in many jar files (2 or 3 copies), once the classes have been loaded, then it won't be "reloaded".
Without the possibility to "reload" these classes, I cannot see inconsistencies in the versions of the classes present in the jar files.
I have read many articles, and I thought that I could then use a custom classloader and create a new instance of this classloader for each jar file.
2 problems with this:
- according to many posts in the different forums I have read, the jar files should not appear in the CLASSPATH (but this would be easier for me if I could use it...)
- some classes will not be loaded if some classes (present in other jar files) are not loaded... and this makes things really really complicated to implement...
So, I thought that I was maybe doing this the wrong way, and that there might be an easy way out of this...
In fact, I do not need to load the classes... all I need to do, is take a sneak peek at the constants and print their values... and that's it!
Somehow, I think that this is possible to retrieve the values of compile time constants (declared as static final String) as I can see that with Eclipse (when opening a jar file).
So, my question is: how can I do that within my java application?
Or maybe there is another easier solution to do what I need?
Thanks in advance for your help!Hi everyone,
I've been looking for a way to solve this for a week now, without any much success... and I've finally decided to ask the Java gurus for a solution! :-)
Here's what I am basically trying to do:
I have several jar files in which there are only compiled code (.class).
In every class, there are 2 constants (declared as static final String) that I would like to retrieve (one is the version and the other the date of the last modification).
My goal is to print a list of all the classes in the jar files with the values of these 2 constants for each class.
The solution that I have right now to do this does not work properly: for now, I read all the elements of the classpath, check if these are jar files, and if so, I look into each one and load all the classes one by one and print the results.
The problem with this is that it uses the method Class.forName(className) and as some classes are unfortunately present in many jar files (2 or 3 copies), once the classes have been loaded, then it won't be "reloaded".
Without the possibility to "reload" these classes, I cannot see inconsistencies in the versions of the classes present in the jar files.
I have read many articles, and I thought that I could then use a custom classloader and create a new instance of this classloader for each jar file.
2 problems with this:
- according to many posts in the different forums I have read, the jar files should not appear in the CLASSPATH (but this would be easier for me if I could use it...)
- some classes will not be loaded if some classes (present in other jar files) are not loaded... and this makes things really really complicated to implement...
So, I thought that I was maybe doing this the wrong way, and that there might be an easy way out of this...
In fact, I do not need to load the classes... all I need to do, is take a sneak peek at the constants and print their values... and that's it!
Somehow, I think that this is possible to retrieve the values of compile time constants (declared as static final String) as I can see that with Eclipse (when opening a jar file).
So, my question is: how can I do that within my java application?
Or maybe there is another easier solution to do what I need?
Thanks in advance for your help! -
Problem with Expilicit Instantiation using const
Hello All,
I have a global template function
template <typename T> int getValue(T t);
defined in file "a.h"
I am trying to do explicit instantiation of this function in "b.h" like this:
#include "a.h"
struct B;
template <> int getValue<const B&>(const B& t);
where "B" is any Structure.
Definition of above function is present in "b.C" as:
template<> int getValue<const B&>(const B& t)
return t.getIntValue();
getIntValue() defined in Struct B returns int identifier of that object.
On Compiling this code using Forte Compiler 5.3 update 2 i am getting following Errors.
>>
/opt/SUNWspro/bin/../WS6U2/bin/CC -g -c -o output/main.o
main.C
main.C:
*** Error code 1
"b.h", line 3: Error: No match found to do explicit
instantation of type int(const B&).
1 Error(s) detected.
dmake: Fatal error: Command failed for target `output/main.o'
<<
Can anybody tell me what can be the problem. One thing to note is that same code use to compile using Forte 5.3 update 1.
Also if I remove const declaration in explicit instantiation the code compiles.
Please respond ASAP.
Best Regards,
SanyamThe compiler does not generate template instances that are already in libCstd, which is linked by default to programs. Instead of trying to force those instances into your shared library, you should build your library with a dependency on libCstd.
Remember that no system libraries are referenced automatically when you create a shared library -- you have to mention them explicitly. Normally you want to link against libCstd, libCrun, libm and libc. Refer to the C++ User's Guide that comes with the compiler, the "Building Libraries" chapter. -
Are PL/SQL Package Body Constants in Shared Area or Private Area
Based on this it not clear to me if PL/SQL Package Body Constants are stored in shared area or private area.
http://docs.oracle.com/cd/B28359_01/server.111/b28318/memory.htm
"PL/SQL Program Units and the Shared Pool
Oracle Database processes PL/SQL program units (procedures, functions, packages, anonymous blocks, and database triggers) much the same way it processes individual SQL statements. Oracle Database allocates a shared area to hold the parsed, compiled form of a program unit. Oracle Database allocates a private area to hold values specific to the session that runs the program unit, including local, global, and package variables (also known as package instantiation) and buffers for executing SQL. If more than one user runs the same program unit, then a single, shared area is used by all users, while each user maintains a separate copy of his or her private SQL area, holding values specific to his or her session.
Individual SQL statements contained within a PL/SQL program unit are processed as described in the previous sections. Despite their origins within a PL/SQL program unit, these SQL statements use a shared area to hold their parsed representations and a private area for each session that runs the statement."
I am also curious what are the fine grained differences from a memory and performance perspective (multi-session) for the two examples below. Is one more efficient?
Example 1.
create or replace
package body
application_util
as
c_create_metadata constant varchar2(6000) := ...
procedure process_xxx
as
begin
end process_xxx;
end application_util;
vs.
Example 2.
create or replace
package body
application_util
as
procedure process_xxx
as
c_create_metadata constant varchar2(6000) := ...
begin
end process_xxx;
end application_util;>
What i am asking is fairly granular, so here it is again, let's assume latest version of oracle..
In a general sense, is the runtime process able to manage memory more effectively in either case, one even slightly more performant, etc
ie does example 1 have different memory management characteristics than example 2.
Specifically i am talking about the memory allocation and unallocation for the constant varchar2(6000)
Ok, a compiler's purpose is basically to create an optimized execution path from source code.
The constant varchar2(6000) := would exist somewhere in the parse tree/execution path (this is stored in the shared area?).
I guess among the things i'm after is
1) does each session use space needed for an additional varchar2(6000) or does runtime processor simply point to the constant string in the parse tree (compiled form which is shared).
2) if each session requires allocation of space needed for an additional varchar2(6000), then for example 1 and example 2
at what point does the constant varchar allocation take place and when is the memory unallocated.
Basically does defining the constant within the procedure have different memory characteristics than defining the constant at the package body level?
>
Each 'block' or 'subprogram' has a different scope. So the 'constant' defined in your example1 is 'different' (and has a different scope) than the 'constant' defined in example2.
Those are two DIFFERENT objects. The value of the 'constant' is NOT assigned until control passes to that block.
See the PL/SQL Language doc
http://docs.oracle.com/cd/E14072_01/appdev.112/e10472/fundamentals.htm#BEIJHGDF
>
Initial Values of Variables and Constants
In a variable declaration, the initial value is optional (the default is NULL). In a constant declaration, the initial value is required (and the constant can never have a different value).
The initial value is assigned to the variable or constant every time control passes to the block or subprogram that contains the declaration. If the declaration is in a package specification, the initial value is assigned to the variable or constant once for each session (whether the variable or constant is public or private).
>
Perhaps this example code will show you why, especially for the second example, a 'constant' is not necessarily CONSTANT. ;)
Here is the package spec and body
create or replace package pk_test as
spec_user varchar2(6000);
spec_constant varchar2(6000) := 'dummy constant';
spec_constant1 constant varchar2(6000) := 'first constant';
spec_constant2 constant varchar2(6000) := 'this is the second constant';
spec_constant3 constant varchar2(6000) := spec_constant;
procedure process_xxx;
procedure change_constant;
end pk_test;
create or replace package body pk_test as
procedure process_xxx
as
c_create_metadata constant varchar2(6000) := spec_constant;
begin
dbms_output.put_line('constant value is [' || c_create_metadata || '].');
end process_xxx;
procedure change_constant
as
begin
spec_constant := spec_constant2;
end change_constant;
begin
dbms_output.enable;
select user into spec_user from dual;
spec_constant := 'User is ' || spec_user || '.';
end pk_test;The package init code sets the value of a packge variable (that is NOT a constant) based on the session USER (last code line in package body).
The 'process_xxx' procedure gets the value of it's 'constant from that 'non constant' package variable.
c_create_metadata constant varchar2(6000) := spec_constant;The 'change_constant' procedure changes the value of the package variable used as the source of the 'process_xxx' constant.
Now the fun part.
execute the 'process_xxx' procedure as user SCOTT.
SQL> exec pk_test.process_xxx;
constant value is [User is SCOTT.].Now execute 'process_xxx' as another user
SQL> exec pk_test.process_xxx;
constant value is [User is HR.].Now exec the 'change_constant' procedure.
Now exec the 'process_xxx' procedure as user SCOTT again.
SQL> exec pk_test.process_xxx;
constant value is [this is the second constant].That 'constant' defined in the 'process_xxx' procedure IS NOT CONSTANT; it now has a DIFFERENT VALUE.
If you exec the procedure as user HR it will still show the HR constant value.
That should convince you that each session has its own set of 'constant' values and so does each block.
Actually the bigger memory issue is the one you didn't ask about: varchar2(6000)
Because you declared that using a value of 6,000 (which is 2 ,000 or more) the actual memory allocation not done until RUN TIME and will only use the actual amount of memory needed.
That is, it WILL NOT pre-allocate 6000 bytes. See the same doc
http://docs.oracle.com/cd/E14072_01/appdev.112/e10472/datatypes.htm#CJAEDAEA
>
Memory Allocation for Character Variables
For a CHAR variable, or for a VARCHAR2 variable whose maximum size is less than 2,000 bytes, PL/SQL allocates enough memory for the maximum size at compile time. For a VARCHAR2 whose maximum size is 2,000 bytes or more, PL/SQL allocates enough memory to store the actual value at run time. In this way, PL/SQL optimizes smaller VARCHAR2 variables for performance and larger ones for efficient memory use.
For example, if you assign the same 500-byte value to VARCHAR2(1999 BYTE) and VARCHAR2(2000 BYTE) variables, PL/SQL allocates 1999 bytes for the former variable at compile time and 500 bytes for the latter variable at run time.
>
So when you have variables and don't know how much space is really needed do NOT do this:
myVar1 VARCHAR2(1000);
myVar2 VARCHAR2(1000);
myVar3 VARCHAR2(1000);The above WILL allocate 3000 bytes of expensive memory even if it those variables are NEVER used.
This may look worse but, as the doc states, it won't really allocate anything if those variables are not used. And when they are used it will only use what is needed.
myVar1 VARCHAR2(2000);
myVar2 VARCHAR2(2000);
myVar3 VARCHAR2(2000); -
PL/SQL Package with only Constants
We have created a PL/SQL package with a Spec and NO BODY with only constant values.
When a user logs onto the Database for the first time, and runs a program the first time the "Constants" package is called you get a ORA-06502, but every time after the first there is no issues. This only happens the first the user logs onto the database ( Session based ).
CoryYou have a wrong declaration in your package, some like c2 in the following example.
EDV@mtso> create or replace package xxx
2 is
3 c1 number := 1;
4 c2 number := 'aa';
5 c3 number := 3;
6 end;
7 /
Package created.
EDV@mtso> var t number
EDV@mtso> exec :t := xxx.c1;
BEGIN :t := xxx.c1; END;
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at "EDV.XXX", line 4
ORA-06512: at line 1
EDV@mtso> print t
T
EDV@mtso> exec :t := xxx.c1;
PL/SQL procedure successfully completed.
EDV@mtso> print t
T
1
EDV@mtso> exec :t := xxx.c3;
PL/SQL procedure successfully completed.
EDV@mtso> print t
T
EDV@mtso> Note that constants declared before the errorous one have a value, constants declare after that one have no value.
Anton
Message was edited by:
ascheffer -
Suns standard classes use of constants - bad coding convention
Wasn't sure where to post this, it didn't quite fit into Java Runtime Environment or Java Virtual Machine forums.
I was browsing through The Java Standard classes and was amazed by their use of constants. Throughout the codes there is inserted direct constants in the code without any use of global constant declarations.
Eg: java.lang.StringCoding:
All over the code is inserted "ISO-8859-1" (used as default encoding) directly instead of using a declared constant DEFAULTENCODING. What if Sun want to change default encoding?
Seems strange to me that such coding conventions are used by Sun. Any reason for this or just sloppy programing?
GilLooks like sloppy programming to me. I see no possible
reason for it. You're not the first person to
criticise Sun's source code. Maybe they outsourced it
to http://www.newtechusa.com/PPI/main.asp (I can never
remember how to format links, no matter how often
people tell me!)
RObinThere's logic in getting primates to program.
Based on the popular theory that an infinite number of monkeys could
randomly produce the works of Shakespeare, they could also produce the perfect software implementation of any given problem. The downside being that the printed documentation will be smeared liberally with faeces.
regards,
Owen -
How to avaoid java.lang.IllegalArgumentException: No enum const class
HI ,
Iam getting java.lang.IllegalArgumentException when iam using switch case through Enum contants.
//Enum Constants declaration
public enum USEOFPROCEEDSVALUES { U1,U2,U3, U4}
//Using Enum in Java class
Test.java
USEOFPROCEEDSVALUES useOfProceedsVar =USEOFPROCEEDSVALUES.valueOf(useOfproceeds);
switch (useOfProceedsVar) {
case U1:
revenueSourceCode="REVENUE_SOURCE_CODE.POWER";
break;
case U2:
revenueSourceCode="REVENUE _SOURCE_CODE.WATER";
break;
case U3:
revenueSourceCode="REVENUE_SOURCE_CODE.POWER";
break;
case U4:
revenueSourceCode=REVENUE_SOURCE_CODE.POWER";
break;
default:
revenueSourceCode=null;
Exception raising if there is either of these not U1,U2,U3,U4 ara not avalabele. i.e is if useOfProceedsVar is A6 then exception raising
How to avoid this exception
Thanks for early replyuser818909 wrote:
HI ,
Iam getting java.lang.IllegalArgumentException when iam using switch case through Enum contants.
//Enum Constants declaration
public enum USEOFPROCEEDSVALUES { U1,U2,U3, U4}
//Using Enum in Java class
Exception raising if there is either of these not U1,U2,U3,U4 ara not avalabele. i.e is if useOfProceedsVar is A6 then exception raisingActually useOfProceedsVar can never be A6, it can only take a value from the enum.
The exception will be raised by valueOf, which (quite correctly) throws it if the String you pass to it doesn't match any of the enum constants.
>
How to avoid this exception
Don't avoid it, process it. What do you want your code to do if the string doesn't match any of your enum constants? Whatever it is, stick it in a catch clause. -
Hi
I'm trying to construct a class called Continent
public Continent{
String continentName;
// some other variables etc etc
public Continent (String conName){
this.continentName = conName;
// Class CONSTANT declaration
public static final Continent
ASIA = new Continent ("Asia"),
EUROPE = new Continent ("Europe"),
AMERICA = new Continent ("America")
// etc etc
}then I construct a class called Country
public Country {
String countryName;
Continent continent;
// some other variable
public Country (String name, Continent c){
this.countryName = name;
this.continent = c;
public static void main(String[] Args){
Country c = new Country ("Wales", Continent.EUROPE);
System.out.println (c.countryName + " exists in "
+ c.continent);
}What I expected to be output was something like:
Wales exists in Europe
but what actually was output was
Wales exists in Asia
?!!?? What's this all about please. Why doesn't my code work properly
TIAWell, it looks as though you might have overlooked something between your compiling, editing and running because I copied your code and it worked fine after I made several changes to it.
First, in the code as it is posted, you're missing the class declarations for both Continent and Country. That will result in compilation errors.
Second, by printing out c.continent in the Country source, you will see the object identification of the continent instance and not the String name for it. I added a getName( ) method in Continent to take care of that. Your code with the modifications is pasted below.
public class Continent {
// Class CONSTANT declaration
public static final Continent ASIA = new Continent ("Asia"),EUROPE = new Continent ("Europe"), AMERICA = new Continent ("America");
String continentName;
public Continent (String conName) {
this.continentName = conName;
/** Returns the String name associated
* with a Continent instance.
public String getName() {
return continentName;
public class Country {
String countryName;
Continent continent;
public Country (String name, Continent c) {
this.countryName = name;
this.continent = c;
public static void main(String[] Args) {
//Country c = new Country ("Wales", Continent.EUROPE);
//Country c = new Country ("Wales", Continent.ASIA);
Country c = new Country ("Wales", Continent.AMERICA);
System.out.println (c.countryName + " exists in " + c.continent.getName());
}As shown here, you will see "Wales exists in America" for your output.
Jeff -
hello,
i have to display the constants on entering the program name ,for that i have read the report into a table.i checked the line in the table using
loop at it_na INTO wa_na WHERE TABLE_LINE CS 'CONSTANTS' .
write : wa_na-text.
ENDLOOP.
but the problem is that it displays only the first constant.
how to display all the constants declared within the declaration
eg:constants : a(10) type c value 'asdf',
b(25) type c value 'cvbn'.Hi,
Try with SCAN statement.. But this is also internal use.. But this works very fine..
DATA: abap_source TYPE TABLE OF rssource.
DATA: l_token_analysis LIKE stokex OCCURS 0 WITH HEADER LINE ,
l_statements LIKE sstmnt OCCURS 0,
l_keyword LIKE rssource OCCURS 0 WITH HEADER LINE .
READ REPORT 'PROGNAME' INTO abap_source.
IF sy-subrc = 0.
l_keyword = 'CONSTANTS'.
APPEND l_keyword.
SCAN ABAP-SOURCE abap_source
TOKENS INTO l_token_analysis
STATEMENTS INTO l_statements
KEYWORDS FROM l_keyword
WITH ANALYSIS
WITHOUT TRMAC.
ENDIF.
Table l_token_analysis will have contents matching l_keyword. line by line
Table l_statements will have the start and end point and no of fields matced..
have a closer look on l_statements and l_token_analysis.
Regards,
Ravi. -
How to see the file at the application server
HI TO ALL SDNERS ,
THIS IS MY CODE WHERE TO CHECK THE DOWNLOADED FILE AT THE APPLICATION SERVER.IN TCODE AL11 I HAVE SEEN THERE IS NO FILE GETTING CREATED.WHEN TRANSFERRING THE SY-SUBRC VALUE IS ZERO.
Program Name : ZME11_BDC.
Title : PURCHASE INFORMATION RECORD LOAD PROGRAM
Program Objective : THIS PROGRAM READS IN THE PURCHASE
INFORMATION FILE. IT CREATES A BDC SESSION TO
USE TO LOAD THE PURCHASE INFORMATION RECORDS
INTO SAP using the ME11 Transaction.
REPORT ZME11_BDC no standard page heading MESSAGE-ID ZHNC line-size 55.
constants declaration
constants: c_x value 'X',
c_sess type apqi-groupid value 'zcustomer',
c_xd01 type tstc-tcode value 'ME11'.
DECLARING VARIABLES
DATA: V_MSG(255),
V_ERREC TYPE I,"NO OF FAILED RECORDS
V_LINES."NO OF RECORDS
FLAG DECLARATIONS
DATA: FG_DATA_EXIST VALUE 'X',"CHECK FOR DATA
FG_SESSION_OPEN VALUE ''.
STRUCTURES AND INTERNAL TABLE DECLARATIONS
TYPES :BEGIN OF TY_PIR,
LIFNR TYPE EINA-LIFNR,
MATNR TYPE EINA-MATNR,
EKORG TYPE EINE-EKORG,
WERKS TYPE EINE-WERKS,
VERKF TYPE EINA-VERKF,"sales person
TELF1 TYPE EINA-TELF1,"telephone
URZLA TYPE EINA-URZLA,"country
REGIO TYPE EINA-REGIO,"region
APLFZ(5),"plan deleivery time
EKGRP TYPE EINE-EKGRP,"purchase group
NORBM(13),
NETPR(13),
END OF TY_PIR.
DATA : IT_PIR TYPE TABLE OF TY_PIR,
WA_PIR LIKE LINE OF IT_PIR.
DATA: BEGIN OF IT_BDCDATA.
INCLUDE STRUCTURE BDCDATA.
DATA END OF IT_BDCDATA.
DATA : BEGIN OF IT_BDCMSG.
INCLUDE STRUCTURE BDCMSGCOLL.
DATA END OF IT_BDCMSG.
SELECTION SCREEN
SELECTION-SCREEN BEGIN OF BLOCK B1 WITH FRAME TITLE TEXT-001.
PARAMETER : FNAME TYPE RLGRAP-FILENAME.
SELECTION-SCREEN END OF BLOCK B1.
AT SELECTION ON VALUE REQUEST
AT SELECTION-SCREEN ON VALUE-REQUEST FOR FNAME.
CALL FUNCTION 'F4_FILENAME'
EXPORTING
PROGRAM_NAME = SYST-CPROG
DYNPRO_NUMBER = SYST-DYNNR
FIELD_NAME = ' '
IMPORTING
FILE_NAME = FNAME.
START OF SELECTION
START-OF-SELECTION.
PERFORM F_GET_DATA USING FNAME
CHANGING IT_PIR.
PERFORM F_GENERATE_DATASET USING FNAME
CHANGING IT_PIR WA_PIR.
*& Form F_GET_DATA
text
-->P_V_FNAME text
<--P_IT_PIR text
FORM F_GET_DATA USING P_FNAME LIKE FNAME
CHANGING P_IT_PIR LIKE IT_PIR.
DATA: LV_FILE TYPE STRING.
LV_FILE = FNAME.
CALL FUNCTION 'GUI_UPLOAD'
EXPORTING
FILENAME = LV_FILE
FILETYPE = 'DAT'
HAS_FIELD_SEPARATOR = 'X'
HEADER_LENGTH = 0
READ_BY_LINE = 'X'
DAT_MODE = ' '
CODEPAGE = ' '
IGNORE_CERR = ABAP_TRUE
REPLACEMENT = '#'
CHECK_BOM = ' '
IMPORTING
FILELENGTH =
HEADER =
TABLES
DATA_TAB = P_IT_PIR
EXCEPTIONS
FILE_OPEN_ERROR = 1
FILE_READ_ERROR = 2
NO_BATCH = 3
GUI_REFUSE_FILETRANSFER = 4
INVALID_TYPE = 5
NO_AUTHORITY = 6
UNKNOWN_ERROR = 7
BAD_DATA_FORMAT = 8
HEADER_NOT_ALLOWED = 9
SEPARATOR_NOT_ALLOWED = 10
HEADER_TOO_LONG = 11
UNKNOWN_DP_ERROR = 12
ACCESS_DENIED = 13
DP_OUT_OF_MEMORY = 14
DISK_FULL = 15
DP_TIMEOUT = 16
OTHERS = 17
IF SY-SUBRC <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
IF P_IT_PIR IS INITIAL.
FG_DATA_EXIST = ''.
ENDIF.
ENDFORM. " F_GET_DATA
*& Form F_GENERATE_DATASET
text
-->P_V_FNAME text
<--P_IT_PIR text
FORM F_GENERATE_DATASET USING P_V_FNAME LIKE FNAME
CHANGING P_IT_PIR LIKE IT_PIR
P_WA_PIR LIKE WA_PIR.
MESSAGE I001(ZHNC).
*OPENING FILE AT THE APPLICATION SERVER FOR WRITING
OPEN DATASET FNAME FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
IF SY-SUBRC EQ 0.
MESSAGE I002(ZHNC).
LOOP AT P_IT_PIR INTO P_WA_PIR.
SPLIT P_WA_PIR AT '*' INTO P_WA_PIR-LIFNR
P_WA_PIR-MATNR
P_WA_PIR-EKORG
P_WA_PIR-WERKS
P_WA_PIR-VERKF
P_WA_PIR-TELF1
P_WA_PIR-URZLA
P_WA_PIR-REGIO
P_WA_PIR-APLFZ
P_WA_PIR-EKGRP
P_WA_PIR-NORBM.
*TRANSFER THE FILE FROM INTERNAL TABLE TO APPLICATION SERVER
MESSAGE I003(ZHNC).
TRANSFER P_WA_PIR TO FNAME.
ENDLOOP.
*CLOSING THE FILE AT THE APPLICATION SERVER
CLOSE DATASET FNAME.
ENDIF.Hello,
I made a similar program. You can have a look at it.
*& Form write_to_app_server
text
--> p1 text
<-- p2 text
FORM write_to_app_server.
To get filename
PERFORM get_filename.
To write into the application server
OPEN DATASET g_filename_with_path FOR OUTPUT IN TEXT MODE.
IF sy-subrc = 0.
LOOP AT <l_table> INTO <l_line>.
TRANSFER <l_line> TO g_filename_with_path.
ENDLOOP.
CLOSE DATASET g_filename_with_path.
ELSE.
CLOSE DATASET g_filename_with_path.
ENDIF.
To send mail
PERFORM send_mail.
ENDFORM. " write_to_app_server
*& Form get_filename
text
--> p1 text
<-- p2 text
FORM get_filename.
DATA : l_log_path TYPE filepath-pathintern
VALUE 'Y28M_DOWNLOADS_BACKGROUND' .
CALL FUNCTION 'FILE_GET_NAME_USING_PATH'
EXPORTING
client = sy-mandt
logical_path = l_log_path
operating_system = sy-opsys
file_name = p_fname
IMPORTING
file_name_with_path = g_filename_with_path
EXCEPTIONS
path_not_found = 1
missing_parameter = 2
operating_system_not_found = 3
file_system_not_found = 4
OTHERS = 5.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
ENDFORM. " get_filename
You may find it useful.
Regards,
Karuna.
Maybe you are looking for
-
Getting error when refreshing the WebI report
Hi, I am building WebI reports using a universe which is constructed over a BI cube. Initially I am building the report and uploading it into CMS. When I am importing the report from CMS and refreshing it, I am getting an error "A database error has
-
Purchased a song on the Itouch had to restore it now It's not on there...HE
I've actually got a rather old computer but it runs on XP...alot of the time when I hook the touch up to the computer to sync it doesn't recognize it and makes me restore it...could be either A.) it's an old computer or B.) I bout it off of Ebay. any
-
I uninstalled MUSE CC while doing a clean up of my PC. Now it wont re install. It keeps coming up with an error, 202 I think. How can I re install it. I need it urgently. I hit download and then when it goes to Application Installer it says that ther
-
Adobe Forms Object Creation in PDF document dynamically
I have the following scenario: I have database of questions and answers, i need to build a webdynpro application that generates a PDF document with the content of this database, but in a dynamically way, for example i have one question like "What is
-
What is adaptive RFC and How to Use it
hi friends what is the adaptive RFC what is the use of it how we can use it explain me anyone and send pdf also thanks ramu.