Additional Java SyntaxOdd cornersReserved wordsUnused keywordsnativestrictfptransientvolatileThe for loopsynchronizedLabeled statementsArray initialization and literalsInitialization blocksStatic initialization blocksExpression statementsMethod call expressionsEscape sequencesInterfacesThings that aren’t always obviousThe EndJan 14, 2019Additional Java Syntax2Odd cornersWe have already covered all of the commonly used Java syntaxSome Java features are seldom used, because:They are needed in only a few specialized situations, orIt’s just as easy to do without them, orFew people know about themYou should be at least aware of these features, because:You may encounter them in someone else’s codeThey may do something you will need somedayThere are also a few useful features that we just didn’t get around to, or didn’t discuss in sufficient detail3Reserved wordsA reserved word, or keyword, is one that has a special meaning, and you may not use it as a nameExamples: if, while, class, packageThere are also important keywords that we have not talked about:native, strictfp, transient, volatileAnd there are keywords that are not used (but you still can’t use them as names):const, goto4Unused keywordsconst is used in some languages to declare constantsJava has this keyword, but used final insteadA final variable does not have to be given a value when it is assigned, but it can be given a value only once:final int lesser;if (x < y) lesser = x; else lesser = y; // legal!The keyword final is also used to indicate that:A class cannot be subclassedA method cannot be overriddenIt does not indicate that a variable cannot be shadowedSome languages allow you to put a label on a statement, and to goto (jump to) that statement from elsewhere in the programJava reserves the goto keyword but does not use it5nativeSometimes you may wish to use a method that is defined in some other language (such as C or C++)The method modifier native tells Java to link to this “native” methodTo do this, you need to look into the JNI (Java Native Interface) APIDrawbacks:You lose platform independenceFor security reasons, you cannot use native code in an applet6strictfpWhile Java is extremely platform independent, it isn’t perfectDue to differing machine implementations of floating-point arithmetic, floating-point results may be off by a couple of the least significant bitsThere is a standard, IEEE 754, that specifies exactly how floating-point arithmetic should be carried outIt is computationally much less efficient to meet this standard if the hardware does not already meet itIf this degree of platform independence is required, you can use strictfp in front of any class, interface, or method declarationA constructor cannot be declared FP-strict; to do this, you should designate the entire class as FP-strictA method in an interface cannot be declared FP-strict, because that’s implementation information, not an interface propertynative methods cannot be declared FP-strictEvery compile-time constant expression is automatically FP-strict7transientYou can serialize an object (turn it into a linear sequence of bytes) to write it to an output stream, then de-serialize it to read it in againEvery field in the object must itself be SerializableIf an object has fields that are not Serializable, and you don’t care that much about them anyway, you can declare them as transienttransient variables don’t get serialized or de-serialized8volatileWhen the compiler optimizes your program, it may keep a variable in a register for several steps in a computationIf another Thread might modify that variable, and you want to always get the current value (as set by some other Thread) of that variable, you can mark it as volatileLocal variables never need to be marked volatile9The for loopThe form of a for loop is: for (initialization; condition; step) bodyThe initialization may be a declaration or expression, or a comma-separated list of expressionsRecall that = is an operator, so var = expr is an expressionThe step may be an expression or a comma-separated list of expressionsThe initialization, condition, and step may be empty--but the semicolons may not be omittedAn empty condition is equivalent to trueHence, for(;;); is an infinite loopExample:for (i = 0, j = a.length - 1; j > i; i++, j--) swap(a, i, j);10synchronizedYou need synchronized whenever you may have multiple Threads accessing the same object at the same timeA Thread gets a lock on a synchronized object before it uses it, and releases the lock (so another Thread can use the data) when it is doneYou can synchronize various ways:synchronized(object) statement;synchronized instanceMethod(parameters) {body} is equivalent to instanceMethod(parameters) {synchronized(this) {body}}synchronized staticMethod(parameters) {body} is equivalent to staticMethod(parameters) {synchronized(class) {body}}Constructors and initializers cannot be synchronizedNon-synchronized methods can execute at the same time as synchronized methods, on the same object11Labeled statementsA labeled statement has the syntax label : statementThe label has the same syntax as a variable nameThe scope of the label is the statementA break statement is only legal within a loop or switch statement and has one of the formsbreak; // exit innermost enclosing loop or switchbreak label; // exit labeled enclosing loop or switchA continue statement is only legal within a loop, and has one of the forms:continue; // resume from test of innermost loopcontinue label; // resume from test of labeled loopAny statement may be labeled, but it only makes sense on a loop or switch statement12Array initialization and literalsArray initialization and array literals are very convenient, and are less well-known than they ought to beInitialization examples:int primes[ ] = {2, 3, 5, 7, 11, 13, 19};String languages[ ] = { "Java", "C", "C++" };int game[ ][ ] = { {3, 7}, {5, 4} };Examples of array literals:myPrintArray(new int[] {2, 3, 5, 7, 11});int foo[ ];foo = new int[ ]{42, 83};Person people[ ] = { new Person("Alice"), new Person("Bob"), new Person("Carla"), new Person("Don") };13Initialization blocksThe fields of an object may be initialized when they are
View Full Document