Assert keyword?
I'm trying to implement some code that I found in a book, and they use "assert", but when I try to compile with NetBeans 3.6, I get a warning that says,
"warning, as of Java 1.4, assert is a keyword, and may not used as an identifiier"
here's an example of the way it is used in the program:
while ((u = extractMin()) != null)
assert !isSettled(u);
}can someone help me out with how I would write that statement a different way, without using "assert"?
Thanks!
Actually, it looks like you are using a true assertion, rather than trying to use assert as a identifier.
Take a look at the following web-page.
http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.htmlIt will tell you how to compile using assertions, which, I believe, is turned off by default.
� {�
Similar Messages
-
Assert keyword reference in javafx
I've been looking for a javafx webpage that will get me
the list of keywords in javafx 1.2. However, this link:
http://openjfx.java.sun.com/current-build/doc/reference/JavaFXReference.html
doesn't seem to work anymore. I did find this one:
http://jarfiller.com/reference/javafxscript/
Which has a full page of examples on how to use the keyword assert.
So I tried this in netbeans:
package javafxapplication19;
assert(true);
But this will not compile either with Netbeans 6.8 or javafxc 1.2.3.
Question is where can I get a list of javafx keywords on the net?
And what am I doing wrong with my simple javafx program?
TomAh, openjfx is back up. The [language reference|http://openjfx.java.sun.com/current-build/doc/reference/apas01.html] has this list of reserved words:
{noformat}abstract after and as assert at attribute before bind bound break{noformat}
{noformat}catch class continue def delete else exclusive extends false finally{noformat}
{noformat}first for from function if import indexof in init insert instanceof into{noformat}
{noformat}inverse last lazy mixin mod new not null on or override package{noformat}
{noformat}postinit private protected public-init public public-read replace return{noformat}
{noformat}reverse sizeof static step super then this throw trigger true try tween{noformat}
{noformat}typeof var where while with{noformat}
Hm, seems somewhat out of date.
Good point about the difference between "reserved words" and keywords that are
not reserved. I didn't know about this. However, the file {color:#ff00ff}v4Parser.g{color} right
next to the file {color:#ff00ff}v4Lexer.g{color} I referenced above has a nice explanation of
the difference between reserved words and non-reserved keywords. As usual, the
source code seems to be the definitive documentation.
Note, you can still use the double angle bracket syntax to use even reserved words as identifiers,
for example, {color:#ff00ff}var <<typeof>> = 1{color}. Why anyone would want to do this, I'm not sure.
I still don't know what {color:#ff00ff}typeof{color} does. Yes, {color:#ff00ff}invalidate{color} was added after 1.2. I'm
not sure what its status is though. Not that I'm trying to keep secrets. If it's merely
experimental, though, I wouldn't want to encourage people to use it. Sufficiently motivated
individuals are welcome to look through the source code. :-)
Edited by: smarks on Apr 6, 2010 11:15 AM -
J2SE 1.4 assertion facility
I'm trying to test drive the new assertion facility in J2SE 1.4 but can't get even a simple example to work:
public class Foo
public void m1( int value )
assert 0 <= value;
System.out.println( "OK" );
public static void main( String[] args )
Foo foo = new Foo();
System.out.print( "foo.m1( 1 ): " );
foo.m1( 1 );
System.out.print( "foo.m1( -1 ): " );
foo.m1( -1 );
Code fails with the following error:
Foo.java:5: Invalid expression statement.
assert 0 <= value;
The compiler fails to recognize the 'assert' keyword - when I change code to:
boolean b = true;
assert b;
the error is:
Foo.java:7: Class assert not found.
assert b;
So, it thinks I'm defining a variable b of type assert rather than recognizing the keyword 'assert'!
I've doing all this in the new J2SE 1.4 - I do have other versions of the JDK on my machine, but am pretty sure I'm compiling against the right one - when I type 'java -version' on command line I get:
java version "1.4.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
Anyone any ideas?
Thanks,
Alanwhat bs. post-condition type assertions typically
"validate the internal state of the receiver".
pre-condition type assertains are typically used to
validate the state of arguments passed in.
Pre-condition type asserts define the "contract" a
caller must agree to prior to calling. It's very
simple, and very effective.No, you shouldn't use assertions to test pre-conditions. The pre-conditions should always be checked, not just in debug mode. Otherwise, the program could behave differently in debug and release modes, and that would be very undesirable! -
I'm a fairly new Java programmer, coming from a C++ background. Over the past several months, I've written about 26000 lines of Java code, with heavy use of the assert statement to catch bugs and invalid data. Works great. I'm using Borland JBuilder 9, Weblogic edition.
Now that I'm trying to deploy, I've found that assert is broken. You see, in C++ land, assert is useful because it is ignored unless you are in debug mode. Ignored means the compiler ignores it, and the arguments in it aren't evaluated. Won't affect performance.
But now, when I adjust the project settings and uncheck the box that says "enable the assert keyword", I suddenly find my code full of errors: assert isn't ignored, it's just uncompilable!
Hopefully I'm missing something important here. Or is this just broken? Is there a way I can make it ignore (and not evaluate!) the contents of the assert statements? I guess in C++ it's easier, becase assert is a macro. Hmm, maybe this is the reason why it is the way it is: no macros in Java. Am I right?
--- Ericassert's not broken, it's a flaw either in JBuilder or your understanding.
Why is it that when people have problems they automatically assume that they're doing everything right and the JVM is bugged? I don't get it.
I think you're the problem. Dig deeper - there's a flag in the JVM that will tell the compiler/runtime to ignore the asserts. I just don't know what it is, because I don't use assert. I find that it's always turned off at runtime. During development, I'd rather have a full set of JUnit tests than all the asserts in the world. JMO -
i am trying to use "assert" more often.
a simple application would be with port ranges:
(1) in unix the max. priviledged port sets the lower
bound of user specifiable ports. but i don't think
this is platform independent?
(2) what is the maximum allowable port number?
i found this: 32767
thanks.some advice: don't use assert. and, when i say this, i don't mean "don't verify your code", i mean, don't use the assert keyword. the problem comes from the fact that many checks that are asserts should really just be if blocks which throw runtimeexceptions (code that should always be enabled). and, if you have that kind of code using asserts, then you're never going to want to turn them off in production, and then, what's the point in the first place? if you are going to use asserts, i'd recommend only using them in code which is performance intensive (which you know you want turned off in production), and just use normal checks for everything else.
as for your actual question, i think 1024 tends to be a "standard" for the max privileged port number. -
Difference in Null and Empty String
Hi,
I have been wondering about the difference between Null and Empty String in Java. So I wrote a small program like this:
public class CompareEmptyAndNullString {
public static void main(String args[]) {
String sNull = null;
String sEmpty = "";
try {
if (sNull.equalsIgnoreCase(sEmpty)) {
System.out.println("Null and Empty Strings are Equal");
} else {
System.out.println("Null and Empty Strings are Equal");
} catch (Exception e) {
e.printStackTrace();
This program throws Exception: java.lang.NullPointerException
at practice.programs.CompareEmptyAndNullString.main(CompareEmptyAndNullString.java:10)
Now if I change the IF Clause to if (sEmpty.equalsIgnoreCase(sNull)) then the Program outputs this: Null and Empty Strings are Equal
Can anyone explain why this would happen ?
Thanks in Advance !!JavaProwler wrote:
Saish,
Whether you do any of the following code, the JUnit Test always passes: I mean he NOT Sign doesnt make a difference ...
assert (! "".equals(null));
assert ("".equals(null));
You probably have assertions turned off. Note the the assert keyword has nothing to do with JUnit tests.
I think that older versions of JUnit, before assert was a language keyword (which started in 1.4 or 1.5), had a method called assert. Thus, if you have old-style JUnit tests, they might still compile, but the behavior is completely different from what it was in JUnit, and has nothing to do with JUnit at all.
If you turn assertions on (-ea flag in the JVM command line, I think), the second one will throw AssertionError. -
Oh no! C++ Templates in 1.5???
To quote Joshua Bloch, re: J2SE 1.5 ...
"If I had to pick one that might require some adjustment, it would be generics, because you'll have to get used to providing additional information in declarations. Instead of merely saying:
List words = new ArrayList();
You'll have to say:
List<String> words = new ArrayList<String>();
Surely this is just WRONG. I can see the advantages of compile time detection but, well, there has to be a better solution.
Eek - it's that revolting template thing from C++ all over again - or did I genuinely miss something (I doubt it)?
/sTo expand a little... how is forcing templating on every use of collections (I refuse to call this 'generics') any less work than casting?
It seems there's a core issue with handling collections that has yet to be solved, and as such, this issue is consistently thrown back at developers as a requirement for casting or templating.
Again, I restate (as people, I've noticed, tend to have a short memory) that I see the advantages of compile-time validation using templating but I'm sure that there HAS to be a better way.
I'd prefer that such language changes wait up until the issue is genuinely resolved - and before I (and YOU) have to maintain such ugly code, as well as the badly misused assert keyword in 1.4 (not to be used in production code? yeah right), and of course the existing class cast issues that are very familiar but easy to teach how others to solve.
I'm sure you understand my point that IMHO these changes have ramifications well beyond syntactic sugar.
When it comes to making real systems, the fewer issues the better.
I'm asking for a real solution to collections not some halfway-deal that just causes more issues than it solves.
Personally I see generics as syntactic suger but I
also see them as a good thing. Instead of having to
cast many times through out your code (which Lists and
Vectors cause), you define the Collection as being
able to hold only one type of object. This catches a
lot of casting errors which is definitely a good
thing. -
Apropreate Throwable on contract violation?
I'm just wondering, can anyone suggest how to deal with an implementation returning an incorrect value.
Here's a simple example to show what I mean. Imagine I wanted to make an abstract class which allows you to roll dice and return the sum of the rolls, but the action of rolling one die is implemented by subclass.
public abstract class DiceRoller {
* Returns a dice roll (a number randomly chosen from 1 to 6)
* @return a number from 1 to 6
protected abstract int rollOneDie();
* Returns a the sum of two dice rolls.
* @return a number from 2 to 12
public final int rollTwoDice() {
int die1 = rollOneDie();
int die2 = rollOneDie();
if (die1 < 1 || die1 > 6 || die2 < 1 || die2 > 6) {
throw new AssertionError("implementation of rollOneDie() did something bad!");
return die1 + die2;
}Is AssertionError apropreate here? I don't think IllegalArgumentException would be right because that would imply the programmer made a mistake in calling rollTwoDice(). Does anyone know what the convension should be in this case?
This isn't actually what I'm trying to code, but I thought I'd come up with a simpleexample rather than trying to explain my program.I may not have explained correctly what I'm asking. I'm asking about this from an API point of view, where you would compile the abstract class DiceRoller withuot a concrete implementation, and then release it for clients to implement their own rollOneDie(). I want rollTwoDice() to check incase they screw up the implementation it's better to throw an exception at that point than let the program continue. (fast-fail) Yeh I could just miss out the test and hope the client reads the javadoc for the abstract method they are implementing, and if not that they spot their mistake.
Imagine for instance the client implemented rollOnedie() as such:
@Override
protected int rollOneDie() {
return (new Random()).nextInt(6); // OOPS! That return 0 to 5!!! Should be 1 to 6.
}Then they unit test rollOneDie() a few times and it returns 3, 4, 2, 2, 4 and assume it to be okay, they they put it into their real application and it sometimes returns 0, meaning that rollTwoDice() (through no fault of it's own) can return 0 or 1 and can't return 11 or 12! But if I have the assertion in place, then when their implementation returns 0, they get an assertion error, find a stack trace and friendly message explaining that their rollOneDie() returned 0, outside of the expected range 1-6. e.g. a nicer version of what I suggested might look like this:
int die1 = rollOneDie();
int die2 = rollOneDie();
if (die1 < 1 || die1 > 6) {
throw new AssertionError("A call to rollOneDie() returned "
+ die1 + ", expected number in the range 1 to 6!");
} else if (die2 < 1 || die2 > 6) {
throw new AssertionError("A call to rollOneDie() returned "
+ die2 + ", expected number in the range 1 to 6!");
} else {
return die1 + die2;
}- My unit testing rollTwoDice() wont be applicable here as the real implementation of the abstract method is, yes you can unit test rollTwoDice() to see how it behaves with a dummy implementation of rollOneDie(), but no ammount of testing rollTwoDice() can prevent the API client from writing an incorrect implementation of rollOneDie();
- I wouldn't want to use the assert keyword here because that's strictly for checking returns of private implimentations and cases which can never happen. Plus it can be disabled, which I don't want.
- IllegalArgumentException is defined as +"Thrown to indicate that a method has been passed an illegal or inappropriate argument."+ and and illegal arguments have been passed to anything here.
- enums are a good idea for the dice problem but the real problem returns a number between 0L to Long.MAX_VALUE, not just numbers 1 to 6, besides even if this were the real problem what would you do if rollOneDie() returned null?
Anyway, my question is, is AssertionError apropreate to use here? -
JDeveloper 9i RC and JDK 1.4?
Sorry if this is an FAQ, but I haven't found it anywhere...
The RC download of Oracle9i JDeveloper does not appear to support JDK 1.4 properly. I can set up the JDK classpaths for compilation, and the JDK Java executable for running, however JDeveloper still uses its own compiler "ocj".
ocj does not appear to support the new 1.4 language features, particularly "assert". The ocj command-line help tells me there is a "-target 1.4" option, but this doesn't appear to do anything!
Even if it did, I'm not sure where I can put this option within the Project Properties to get compiles within the IDE (as opposed to command-line) to use it.
Can anyone help with this?
Thanks,
Ellis.Hi,
The Oracle9i JDeveloper production ojc compiler will support the 1.4 assert keyword.
Thanks,
Brian
JDeveloper Team -
How to run java older version java program with newer version 1.6.
Hello frds.....i have a one query regarding jkd newer version. I was using older version of jdk 1.4 for my java program and projects' work. Now i installed newer version of java 1.6 in my machine, so when i tried to compile and run my older version programs in the newer version, its showing many errors. So can anybody helps me on this query that how can i run my older version java programs in newer version 1.6 or what types of changes i will be do in my java programs.
Thanks in advance
KshitizEJP wrote:
so when i tried to compile and run my older version programs in the newer version, its showing many errorsI doubt it. There is only one incompatibility between 1.4 and 1.6, and that is the introduction of the 'assert' keyword. (or did that happen in 1.4?)I believe that was the one and only incompatible change made in 1.4.
(Although I'm saying that from memory, and 1.4 was a long time ago -- so the "one and only" part could be wrong.) -
I'm thinking about use jdk1.4, but...
but I'm seeing lot of posts about errors using jdk1.4.
I've heard that 1.4 manages the repaint of swing components better than 1.3, is this true?
Why is 1.4 few compatible with 1.3?
Should I change to 1.4?Best thing to do is try it. There are a lot of new problems with the new JRE, but these may not affect anything you are developing. On the plus side, you get fairly massive speed increases, plus access to all the new APIs.
There may be issues with 1.4 and any IDE you might be using, not least because of the new class file version, the assert keyword, the focus problems usw... -
Hi,
Since Assertions are new addition to ver 1.4, can "assert" be treated as a new keyword? I could not find this anywhere else even in the Java Docs. Can someone please clarify?
Thanks,
Venkat DhurjatiThanks for your answer. My question is can we include the word "assert" in Java list of keywords. ie., just like "abstract" is a keyword, is "assert" also a keyword?
- Venkat -
Assertion Failed - Dump when clicking on the links from Portal for WD Comp
Hi,
We have a WD Component which is integrated to the Portal . When we click on the link in the Portal for the first 2 times, the selection screen is shown correctly ( when debugged, the program stops in WDDOINIT method before the sel.screen is shown).
When we click on the link for the third or fourth time with no time gap, it shows a dump. This is the dump I am getting.
Runtime Errors ASSERTION_FAILED
Date and Time 01/06/2011 10:13:58
Short text
The ASSERT condition was violated.
What happened?
In the running application program, the ASSERT statement recognized a
situation that should not have occurred.
The runtime error was triggered for one of these reasons:
- For the checkpoint group specified with the ASSERT statement, the
activation mode is set to "abort".
- Via a system variant, the activation mode is globally set to "abort"
for checkpoint groups in this system.
- The activation mode is set to "abort" on program level.
- The ASSERT statement is not assigned to any checkpoint group.
How to correct the error
Probably the only way to eliminate the error is to correct the program.
If the error occures in a non-modified SAP program, you may be able to
find an interim solution in an SAP Note.
If you have access to SAP Notes, carry out a search with the following
keywords:
"ASSERTION_FAILED" " "
"CL_NW7_VIEW_ELEMENT_ADAPTER===CP" or "CL_NW7_VIEW_ELEMENT_ADAPTER===CM004"
"DISPATCH_NW7_EVENT"
If you cannot solve the problem yourself and want to send an error
notification to SAP, include the following information:
1. The description of the current problem (short dump)
To save the description, choose "System->List->Save->Local File
(Unconverted)".
2. Corresponding system log
Display the system log by calling transaction SM21.
Restrict the time interval to 10 minutes before and five minutes
after the short dump. Then choose "System->List->Save->Local File
(Unconverted)".
3. If the problem occurs in a problem of your own or a modified SAP
program: The source code of the program
In the editor, choose "Utilities->More
Utilities->Upload/Download->Download".
4. Details about the conditions under which the error occurred or which
actions and input led to the error.
User and Transaction
Client.............. 010
User................ "STECURRY"
Language Key........ "E"
Transaction......... " "
Transactions ID..... "4D250E9ADDFB00BDE10080000A041004"
Program............. "CL_NW7_VIEW_ELEMENT_ADAPTER===CP"
Screen.............. "SAPMHTTP 0010"
Screen Line......... 2
Information on Caller ofr "HTTPS" Connection:
Plug-in Type.......... "HTTPS"
Caller IP............. "10.6.4.220"
Caller Port........... 443
Universal Resource Id. "/sap/bc/webdynpro/sap/ZEM_INV_APP_ASSIGNMENTS/"
Information on where terminated
Termination occurred in the ABAP program "CL_NW7_VIEW_ELEMENT_ADAPTER===CP" -
in "DISPATCH_NW7_EVENT".
The main program was "SAPMHTTP ".
In the source code you have the termination point in line 5
of the (Include) program "CL_NW7_VIEW_ELEMENT_ADAPTER===CM004".
Source Code Extract
Line
SourceCde
1
METHOD dispatch_nw7_event.
2
DATA: l_event_handler TYPE REF TO if_wdr_nw7_event_handler.
3
4
l_event_handler = get_nw7_event_handler( i_event_handler_id ).
>>>>>
assert l_event_handler is not initial.
6
7
" View-based Delta Rendering: tracking of client events
8
raise event on_nw7_handle_event
9
exporting
10
event_handler = l_event_handler
11
event_name = i_event_name.
12
13
14
l_event_handler->handle_event(
15
i_event_name = i_event_name
16
i_event_parameters = i_event_parameters
17
i_update_data = i_update_data
18
i_event_queue = i_event_queue ).
19
ENDMETHOD.
- I have cut the dump to make it short and clear.
One of my colleague ran a HTTP watch trace and I am attaching it as well.
<body> <table cellpadding="0" cellspacing="0" border="0" width="100%"> <tr> <td> <h1> Error when processing your request </h1> <br> <h2> What has happened? </h2> <p> The URL https://uswasspq.deloitte.com:/sap/bc/webdynpro/sap/ZEM_INV_APPROVER_MAIN//ucfLOADING was not called due to an error. </p> </td> </tr> <tr> <td> </td> </tr> <tr> <td class="emphasize"> <strong> Note </strong> <br> <ul> <li> The following error text was processed in the system SPQ : <b> User session (HTTP/SMTP/..) closed after timeout </b> </li> </ul> <ul> <li> The error occurred on the application server usuxc204_SPQ_01 and in the work process 1 . </li> </ul> <ul> <li> The termination type was: ERROR_MESSAGE_STATE </li> </ul> <ul> <li> The ABAP call stack was: <br> Method: PREPROCESS_REQUEST of program CL_WDR_CLIENT_ABSTRACT_HTTP===CP<BR>Method: IF_HTTP_EXTENSIONHANDLE_REQUEST of program CL_WDR_MAIN_TASK==============CP<BR>Method: EXECUTE_REQUEST_FROM_MEMORY of program CL_HTTP_SERVER================CP<BR>Function: HTTP_DISPATCH_REQUEST of program SAPLHTTP_RUNTIME<BR>Module: %_HTTP_START of program SAPMHTTP<BR> </li> </ul> </td> </tr> <tr> <td> </td> </tr> <tr> <td> <p> </p> <h2> What can I do? </h2> <ul> <li> If the termination type was RABAX_STATE, then you can find more information on the cause of the termination in the system SPQ in transaction ST22. </li> </ul> <ul> <li> If the termination type was ABORT_MESSAGE_STATE, then you can find more information on the cause of the termination on the application server usuxc204_SPQ_01 in transaction SM21. </li> </ul> <ul> <li> If the termination type was ERROR_MESSAGE_STATE, then you can search for more information in the trace file for the work process 1 in transaction ST11 on the application server usuxc204_SPQ_01 . In some situations, you may also need to analyze the trace files of other work processes. </li> </ul> <ul> <li> If you do not yet have a user ID, contact your system administrator. </li> </ul> <br/> <p class="note"> Error code: ICF-IE-https -c: 010 -u: STHUGHES -l: E -s: SPQ -i: usuxc204_SPQ_01 -w: 1 -d: 20110208 -t: 131808 -v: ERROR_MESSAGE_STATE -e: User session (HTTP/SMTP/..) closed after timeout </p> <br/> <p> HTTP 500 - Internal Server Error <br/> <p> Your SAP Internet Communication Framework Team </p> </td> </tr> </table> </body> </html>
After this error a URL is called form the WebDynpro to the following html page.
https://uswasspq.deloitte.com/sap/bc/webdynpro/sap/zem_inv_approver_main/dps_Error_Page.html ( this is the friendly message we have put so that the user does not see the dump on his screen.
I tried invalidating the nodes in the WDDOEXIT at the view level but it did not help. This is a show stopper for the project to go live.
Thanks,
Guru.Hi Guru,
It is not readable the way you posted and that might be the reason that you do not get reactions.
Can you please confirm the following.
1. Is this problem occurs with out portal when you run the application standalone in SAP GUI.
2. What is going on wddoinit method or wddomodify method, any resource handling there ? -
There seems to be a bug in JDeveloper regarding assertions. I have configured it to use JDK 1.4, enabled assertions in the IDE and set the target to 1.4. I also uncommented the line in jdev.conf that makes the editor recognize assert as a keyword. But when I try to compile a java class containing assertions, I get one of two errors:
1) If the assertion will always succeed, I get an internal compiler error. For example
assert 1 < 2;
2) Otherwise I get this error message
Error(35,10): constructor AssertionError(<anything>) not found in class java.lang.AssertionError
What can I do?
Knut StøreI forgot to say that the last error message is the same whether I add a message or not.
assert x != null : "Something is wrong";
or
assert x != null; -
How to use assert with wireless toolkit?
Hi,
I am trying to find out how to use assert with wireless toolkit. I have found that I need to pass "-source 1.4" to the java compiler. But I can't find any documentation on how to do it.
I'm using J2ME Wireless Toolkit 2.2.
thanks
LuddeHere's a quote from an article on Java World at http://www.javaworld.com/javaworld/jw-11-2001/jw-1109-assert.html
"To support the new assertion facility in J2SE 1.4, the Java platform adds the keyword assert to the language, an AssertionError class, and a few additional methods to java.lang.ClassLoader."
So I really think it's part of 1.4.
Maybe you are looking for
-
I accidentally set up to iTunes accounts and want to know if I can merge them?
Help please, can i merge two itunes accounts as i set up two!
-
Can anyone explain how they made this Jar file
Hi all, I have searched the forum without luck. Lots of people asked questions about protecting their jar files but almost everyone said to either use exe file or use obfuscators. But how can I make my jar so it is not possible to open it or when you
-
Restriction in Search help of Product Categories
Hi, I am working on SRM_SERVER 5.5 and I want to restrict the Product categories depending on the Organizational attribute of the user. Its search help is COM_CATEGORY_ID in the system and i didn't find any User-Exit or Enhancement to control these v
-
Sold-to party determination from ship-to
Hi, I have sucha case: I am enering SO using va01. I select sales area on the first screen and then on the second screen (SO screen) I put ship-to party. System pops up selection screen with three possible SOLD-TOs to be selected. How the sold-to det
-
Can i use classes in jar files?
im planning to create a program that uses the saxon.jar so that i don't have to type in the command line to be able to use it. is this possible?