TIOBE - Java Coding Standard Version head

Size: px
Start display at page:

Download "TIOBE - Java Coding Standard Version head"

Transcription

1 TIOBE - Java Coding Standard Version head issued by the CCB Coding Standards

2 TIOBE - Java Coding Standard Table of Contents Change History...1 Introduction...2 Purpose...2 Basic...3 Rule Basic2...3 Rule Basic3...4 Rule Basic4...4 Rule Basic5...5 Rule Basic6...5 Rule Basic7...5 Rule Basic8...6 Rule Basic9...6 Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic Rule Basic CodeSize...18 Rule CodeSize Rule CodeSize Rule CodeSize Rule CodeSize Rule CodeSize Rule CodeSize Rule CodeSize Rule CodeSize Rule CodeSize Comments...23 Rule Comments Rule Comments Rule Comments Rule Comments i

3 TIOBE - Java Coding Standard Table of Contents Controversial...26 Rule Controversial Rule Controversial Rule Controversial Rule Controversial Rule Controversial Coupling...29 Rule Coupling Rule Coupling Design...31 Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design Rule Design ii

4 Design TIOBE - Java Coding Standard Table of Contents Rule Design Rule Design Finalizer...50 Rule Finalizer Rule Finalizer Rule Finalizer Rule Finalizer Rule Finalizer Rule Finalizer Rule Finalizer ImportStatement...53 Rule Import Rule ImportStatement Rule ImportStatement Rule ImportStatement Rule ImportStatement Rule ImportStatement Rule ImportStatement JavaLogging...57 Rule JavaLogging Rule JavaLogging Rule JavaLogging Rule JavaLogging Naming...59 Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Rule Naming Optimization...66 Rule Optimization Rule Optimization Rule Optimization Rule Optimization iii

5 TIOBE - Java Coding Standard Table of Contents Optimization Rule Optimization Rule Optimization StrictException...69 Rule StrictException Rule StrictException Rule StrictException Rule StrictException Rule StrictException Rule StrictException Rule StrictException Rule StrictException Rule StrictException StringandStringBuffer...75 Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer Rule StringandStringBuffer TypeResolution...81 Rule TypeResolution UnusedCode...82 Rule UnusedCode Rule UnusedCode Rule UnusedCode Style...84 Rule Comments Rule Style Rule Style Literature...85 iv

6 Change History Revision Date :56:46 Paul Jansen (TIOBE): - Ticket 20396: Improved the description of rules Basic10, Basic 11, Basic 12, Basic23, Basic24, Basic29 and Basic :34:29 Paul Jansen (TIOBE): - Ticket 20029: Adjusted scope of this document :39:34 Bram Stappers (TIOBE) - Ticket 10002: Improved description of rule Basic :56:13 Bram Stappers (TIOBE) - Ticket 15954: Added rule ImportStatement :26:38 Bram Stappers (TIOBE): - Ticket 16337: Updated TIOBE logo/images :59:09 Paul Jansen (TIOBE): - TICS ticket 16256: Removed rule Style :47:47 - Added rule "Basic102" :27:25 - Added rule "Optimization100". - Updated the document to support the Google Android standard :18:55 Improved synopsis of rule "Basic18" :28:16 Improved rule "Naming4" :06:11 Logo front page changed :10:54 Changed front page :45:44 Added new rule "Design 44" :44:57 Rule "Controversial4" set from 3 to :09:07 New rule added: Design :25: :02:19 Title page improved :26:08 Minor corrections :26:03 Rule "Design31" removed. Removed the following rules: CodeSize8, Controversial11, and Optimization2. Set the following rules temporarily to unchecked: Design4 and Design33. Extended rule Naming18 for variables starting with 'mx' :58:08 Rule "Controversial12" removed and the level of rule "Optimization1" set from 2 to :46:26 Introduction improved :06:23 Rule Optimization3 removed :34:50 Revision after feedback from Manuel Bilderbeek and Jacques Bergmans (Océ Technologies) :00:00 Initial Version. 1

7 Introduction Purpose This document defines the TIOBE Java Coding Standard. The coding standard consists of rules and recommendations for code written and/or maintained in the Java programming language. Scope This coding standard applies to all Java code that is written and/or maintained. The procedure to be followed when a rule must be broken is outside the scope of this document. This coding standard does specify rules and recommendations to prevent coding errors to prevent coding using obsolete or deprecated language features to prevent coding using undefined or implementation defined language features to achieve a certain consistency in coding style The TIOBE Java coding standard does not attempt to teach how to design effective Java code. It also does not categorically rule out any programming idioms that Java is designed to support. 2

8 Basic The Basic Ruleset contains a collection of good practices which everyone should follow. Rules Basic2 Avoid empty 'if' statements Basic3 Avoid empty 'while' statements Basic4 Avoid empty try blocks Basic5 Avoid empty finally blocks Basic6 Avoid empty switch statements Basic7 Avoid modifying an outer loop incrementer in an inner loop for update expression Basic8 This for loop could be simplified to a while loop Basic9 Avoid unnecessary temporaries when converting primitives to Strings Basic10 Ensure you override both equals() and hashcode() Basic11 Double checked locking is not thread safe in Java Basic12 Avoid returning from a finally block Basic13 Avoid empty synchronized blocks Basic14 Avoid unnecessary return statements Basic15 Empty static initializer was found Basic16 Do not use 'if' statements that are always true or always false Basic17 An empty statement (semicolon) not part of a loop Basic18 Avoid instantiating Boolean objects; reference Boolean.TRUE or Boolean.FALSE Basic19 Unnecessary final modifier in final class Basic21 Overriding method merely calls super Basic22 This usage of the Collection.toArray() method will throw a ClassCastException Basic23 Avoid creating BigDecimal with a decimal (float/double) literal. Use a String literal Basic24 An operation on an Immutable object (BigDecimal or BigInteger) won't change the object itself Basic25 The null check here is misplaced; if the variable is null there'll be a NullPointerException Basic28 Method call on object which may be null Basic29 Don't create instances of already existing BigInteger and BigDecimal (ZERO, ONE, TEN) Basic30 Do not start a literal by 0 unless it's an octal value Basic100 Each variable should have an initializer. Basic101 Use standard brace style. Basic102 Avoid implicit allocation of objects Rule Basic2 Synopsis: Avoid empty 'if' statements Level: 2 Category: Basic 3

9 TIOBE - Java Coding Standard 07/12/18 Empty If Statement finds instances where a condition is checked but nothing is done about it. void bar(int x) { if (x == 0) { // empty! Rule Basic3 Synopsis: Avoid empty 'while' statements Level: 2 Category: Basic Empty While Statement finds all instances where a while statement does nothing. If it is a timing loop, then you should use Thread.sleep() for it; if it's a while loop that does a lot in the exit expression, rewrite it to make it clearer. void bar(int a, int b) { while (a == b) { // empty! Rule Basic4 Synopsis: Avoid empty try blocks Level: 1 Category: Basic Avoid empty try blocks - what's the point? public void bar() { try { catch (Exception e) { e.printstacktrace(); 4

10 TIOBE - Java Coding Standard 07/12/18 Rule Basic5 Synopsis: Avoid empty finally blocks Level: 5 Category: Basic Avoid empty finally blocks - these can be deleted. public void bar() { try { int x=2; finally { // empty! Rule Basic6 Synopsis: Avoid empty switch statements Level: 1 Category: Basic Avoid empty switch statements. public void bar() { int x = 2; switch (x) { // once there was code here // but it's been commented out or something Rule Basic7 Synopsis: Avoid modifying an outer loop incrementer in an inner loop for update expression Level: 1 Category: Basic 5

11 TIOBE - Java Coding Standard 07/12/18 Avoid jumbled loop incrementers - it's usually a mistake, and it's confusing even if it's what's intended. public class JumbledIncrementerRule1 { public void foo() { for (int i = 0; i < 10; i++) { for (int k = 0; k < 20; i++) { System.out.println("Hello"); Rule Basic8 Synopsis: This for loop could be simplified to a while loop Level: 4 Category: Basic Some for loops can be simplified to while loops - this makes them more concise. void bar() { for (;true;) { // No Init or Update part, may as well be: while (true) Rule Basic9 Synopsis: Avoid unnecessary temporaries when converting primitives to Strings Level: 3 Category: Basic Avoid unnecessary temporaries when converting primitives to Strings public String convert(int x) { // this wastes an object String foo = new Integer(x).toString(); // this is better return Integer.toString(x); 6

12 Rule Basic10 TIOBE - Java Coding Standard 07/12/18 Synopsis: Ensure you override both equals() and hashcode() Level: 2 Category: Basic Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashcode() from a parent class, consider implementing hashcode and explicitly delegating to your superclass. Justification: // this is bad public class Bar { public boolean equals(object o) { // do some comparison // and so is this public class Baz { public int hashcode() { // return some hash value // this is OK public boolean equals(object other) { // do some comparison public int hashcode() { // return some hash value You must override hashcode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable. from Effective Java, by Joshua Bloch. If two objects are equal according to the {@code equals(object) method, then calling the {@code hashcode method on each of the two objects must produce the same integer result.â So, implementing an equals() method comparing 2 members, and then implementing a hashcode() which only calls super.hashcode() is just as bad. Rule Basic11 Synopsis: Double checked locking is not thread safe in Java Level: 1 Category: Basic 7

13 TIOBE - Java Coding Standard 07/12/18 Partially created objects can be returned by the Double Checked Locking pattern when used in Java. An optimizing JRE may assign a reference to the baz variable before it creates the object the reference is intended to point to. Object baz; Justification: Object bar() { if(baz == null) { //baz may be non-null yet not fully created synchronized(this){ if(baz == null){ baz = new Object(); return baz; First of all, because the null-check is outside of the synchronized block when 2 threads are "simultaneously" doing the null-check then both will enter the if-statement. One of them will enter the synchronized block, and the other one is stopped. The first one will create a new Object and leave the synchronized block. That allows the 2nd thread to enter the synchronized block and create another Object. The 2nd thread will still create another Object because compiler generation of the instructions for writes that initialize the "baz" Object may be executed after. One of the suggested fixes is to declare the baz object as volatile: volatile Object baz; Object bar() { if(baz == null) { //baz may be non-null yet not fully created synchronized(this) { if(baz == null){ baz = new Object(); return baz; However, even if JVM prevents writes to volatile variables to be reordered and ensures that they are flushed to main memory immediately, it still permits reordering of reads and writes instructions for volatile variable with respect to reads and writes for nonvolatile variables. Which means, considering two threads A and B, unless all fields of "baz" type class are volatile as well, thread B can still perceive the constructor's effect as happening after "baz" object is set to reference by the thread A. For more details see 8

14 Rule Basic12 TIOBE - Java Coding Standard 07/12/18 Synopsis: Avoid returning from a finally block Level: 1 Category: Basic Avoid returning from a finally block - this can discard exceptions. Justification: public class Bar { public String foo() { try { throw new Exception( "My Exception" ); catch (Exception e) { throw e; finally { return "A. O. K."; // Very bad. According to Java Language Specification: "If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice: If the finally block completes normally, then the try statement completes abruptly for reason R. If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).â " Rule Basic13 Synopsis: Avoid empty synchronized blocks Level: 4 Category: Basic Avoid empty synchronized blocks - they're useless. public void bar() { synchronized (this) { // empty! 9

15 Rule Basic14 TIOBE - Java Coding Standard 07/12/18 Synopsis: Avoid unnecessary return statements Level: 3 Category: Basic Avoid unnecessary return statements in methods with return type void. public void bar() { int x = 42; return; Rule Basic15 Synopsis: Empty static initializer was found Level: 3 Category: Basic An empty static initializer was found. static { // empty Rule Basic16 Synopsis: Do not use 'if' statements that are always true or always false Level: 3 Category: Basic Do not use "if" statements that are always true or always false. public void close() { if (true) { //... 10

16 TIOBE - Java Coding Standard 07/12/18 Rule Basic17 Synopsis: An empty statement (semicolon) not part of a loop Level: 3 Category: Basic An empty statement (aka a semicolon by itself) that is not used as the sole body of a for loop or while loop is probably a bug. It could also be a double semicolon, which is useless and should be removed. public class MyClass { public void doit() { // this is probably not what you meant to do ; // the extra semicolon here this is not necessary System.out.println("look at the extra semicolon");; Rule Basic18 Synopsis: Avoid instantiating Boolean objects; reference Boolean.TRUE or Boolean.FALSE Level: 2 Category: Basic Avoid instantiating Boolean objects; you can reference Boolean.TRUE or Boolean.FALSE. Boolean bar = new Boolean("true"); // just do a Boolean bar = Boolean.TRUE; Boolean buz = Boolean.valueOf(false); // just do a Boolean buz = Boolean.FALSE; Rule Basic19 Synopsis: Unnecessary final modifier in final class Level: 5 Category: Basic 11

17 TIOBE - Java Coding Standard 07/12/18 When a class has the final modifier, all the methods are automatically final. public final class Foo { // This final modifier is not necessary, since the class is final // and thus, all methods are final private final void foo() { Rule Basic21 Synopsis: Overriding method merely calls super Level: 2 Category: Basic The overriding method merely calls the same method defined in a superclass public String foo() { return super.foo(); //Why bother overriding? Rule Basic22 Synopsis: This usage of the Collection.toArray() method will throw a ClassCastException Level: 1 Category: Basic if you need to get an array of a class from your Collection, you should pass an array of the desidered class as the parameter of the toarray method. Otherwise you will get a ClassCastException. import java.util.arraylist; import java.util.collection; public class Test { public static void main(string[] args) { Collection c=new ArrayList(); Integer obj=new Integer(1); c.add(obj); // this would trigger the rule (and throw a ClassCastException if executed) Integer[] a=(integer [])c.toarray(); // this wouldn't trigger the rule Integer[] b=(integer [])c.toarray(new Integer[c.size()]); 12

18 TIOBE - Java Coding Standard 07/12/18 Rule Basic23 Synopsis: Avoid creating BigDecimal with a decimal (float/double) literal. Use a String literal Level: 1 Category: Basic It is generally recommended that the valueof() should be used in preference to BigDecimal constructor with float/double parameter. The value returned is equal to that resulting from using the BigDecimal constructor with String parameter. Note: valueof() will use the canonical String representation of thedoublevalue passed in to instantiate thebigdecimal object. In other words: The value of thebigdecimalobject will be what you see when you dosystem.out.println(d).â import java.math.bigdecimal; public class Test { public static void main(string[] args) { // this would trigger the rule BigDecimal bd=new BigDecimal(1.123); // this wouldn't trigger the rule BigDecimal bd=new BigDecimal("1.123"); // this wouldn't trigger the rule BigDecimal bd=new BigDecimal(12); Justification: One might assume that "new BigDecimal(.1)" is exactly equal to.1, but it is actually equal to This is so because.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to.1, appearances notwithstanding. The (String) constructor, on the other hand, is perfectly predictable: 'new BigDecimal(".1")' is exactly equal to.1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one. Rule Basic24 Synopsis: An operation on an Immutable object (BigDecimal or BigInteger) won't change the object itself Level: 1 Category: Basic 13

19 TIOBE - Java Coding Standard 07/12/18 An operation on an Immutable object (BigDecimal or BigInteger) won't change the object itself. The result of the operation is a new object. Therefore, ignoring the operation result is an error. Justification: import java.math.*; class Test { void method1() { BigDecimal bd=new BigDecimal(10); bd.add(new BigDecimal(5)); // this will trigger the rule void method2() { BigDecimal bd=new BigDecimal(10); bd = bd.add(new BigDecimal(5)); // this won't trigger the rule The value of the immutable object instance cannot be change after it's created. When we attempt to alter the internal fields of an immutable object, the reference of the respective object it is changed to refer to a new instance of that type. Rule Basic25 Synopsis: The null check here is misplaced; if the variable is null there'll be a NullPointerException Level: 1 Category: Basic The null check here is misplaced. if the variable is null you'll get a NullPointerException. Either the check is useless (the variable will never be "null") or it's incorrect. Justification: void bar() { if (a.equals(baz) a == null) { If the variable is null, a NullPointerException is triggered when equals method is called. Rule Basic28 Synopsis: Method call on object which may be null Level: 1 Category: Basic 14

20 TIOBE - Java Coding Standard 07/12/18 The null check is broken since it will throw a Nullpointer itself. The reason is that a method is called on the object when it is null. It is likely that you used instead of && or vice versa. class Foo { String munge(string string) { // should be && if (string!=null!string.equals("")) return string; // should be if (string==null && string.equals("")) return string; Rule Basic29 Synopsis: Don't create instances of already existing BigInteger and BigDecimal (ZERO, ONE, TEN) Level: 5 Category: Basic Don't create instances of already existing BigInteger (BigInteger.ZERO, BigInteger.ONE) and for 1.5 on, BigInteger.TEN and BigDecimal (BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN) Justification: public class Test { public static void main(string[] args) { BigInteger bi=new BigInteger(1); BigInteger bi2=new BigInteger("0"); BigInteger bi3=new BigInteger(0.0); BigInteger bi4; bi4=new BigInteger(0); Avoid creating unnecessary new instance when there is already one(e.g. BigDecimal.ZERO). BigDecimal.ZERO will never change because BigDecimal is an immutable class. Rule Basic30 Synopsis: Do not start a literal by 0 unless it's an octal value Level: 2 Category: Basic 15

21 TIOBE - Java Coding Standard 07/12/18 Integer literals should not start with zero. Zero means that the rest of literal will be interpreted as an octal value. int i = 012; // set i with 10 not 12 int j = 010; // set j with 8 not 10 k = i * j; // set k with 80 not 120 Rule Basic100 Synopsis: Each variable should have an initializer. Level: 3 Category: Basic Local variables should be declared at the point they are first used. Nearly every local variable declaration should contain an initializer. If you don't yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do. Justification: Failure to initialize a local variable has been identified as a very common source of error. Also, declaring local variables without using them immediately may increase their scope. Rule Basic101 Synopsis: Use standard brace style. Level: 4 Category: Basic Braces do not go on their own line; they go on the same line as the code before them. So: class MyClass { int func() { if (something) { //... else if (somethingelse) { //... else { //... 16

22 We require braces around the statements for a conditional. Except, if the entire conditional (the condition and the body) fit on one line, you may (but are not obligated to) put it all on one line. That is, this is legal: if (condition) { body(); and this is legal: if (condition) body(); but this is still illegal: References if (condition) body(); // bad! Google Android Guidelines TIOBE - Java Coding Standard 07/12/18 Rule Basic102 Synopsis: Avoid implicit allocation of objects Level: 4 Category: Basic When writing code such as byte[] mylocalstackvariable = { 0x00, 0x00 ; Java implicitly allocates an object. For some applications this is a bad thing. It is better to make the allocation explicit: byte[] mylocalstackvariable = new byte[] {0x00, 0x00; This way everybody will realize that a new object is allocated. 17

23 CodeSize The Code Size Ruleset contains a collection of rules that find code size related problems. Rules CodeSize1 Avoid complex methods CodeSize2 Avoid really long methods CodeSize3 Avoid really long parameter lists CodeSize4 Avoid really long classes CodeSize5 Avoid complex code CodeSize6 This class has too many public methods and attributes CodeSize7 Too many fields CodeSize9 Avoid long type definitions CodeSize10 Avoid complex constructors Rule CodeSize1 Synopsis: Avoid complex methods Level: 2 Category: CodeSize The NPath complexity of a method is the number of acyclic execution paths through that method. A threshold of 200 is generally considered the point where measures should be taken to reduce complexity. Rule CodeSize2 Synopsis: Avoid really long methods Level: 2 Category: CodeSize Violations of this rule usually indicate that the method is doing too much (containing more than 100 statements). Try to reduce the method size by creating helper methods and removing any copy/pasted code. public void dosomething() { System.out.println("Hello world!"); System.out.println("Hello world!"); // 98 copies omitted for brevity. 18

24 Rule CodeSize3 TIOBE - Java Coding Standard 07/12/18 Synopsis: Avoid really long parameter lists Level: 2 Category: CodeSize Long parameter lists can indicate that a new object should be created to wrap the numerous parameters. Basically, try to group the parameters together. This rule triggers if a method has 10 or more parameters. public void adddata( int p0, int p1, int p2, int p3, int p4, int p5, int p5, int p6, int p7, int p8, int p9, int p10) { Rule CodeSize4 Synopsis: Avoid really long classes Level: 2 Category: CodeSize Long class files are indications that the class may be trying to do too much. Try to break it down, and reduce the size to something manageable. This rule triggers in case a class has 1000 or more lines of code. Rule CodeSize5 Synopsis: Avoid complex code Level: 2 Category: CodeSize Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity. This rule triggers if a method has a complexity of 10 or more. The higher the cyclomatic complexity, the harder it is to write a set of unit tests that cover all branches. Cyclomatic complexity is an indication how hard it is to test your code. // Cyclomatic Complexity = 12 1 public void example() { 2 if (a == b) { 19

25 3 if (a1 == b1) { fiddle(); 4 else if a2 == b2) { fiddle(); else { fiddle(); 5 else if (c == d) { 6 while (c == d) { fiddle(); 7 else if (e == f) { 8 for (int n = 0; n < h; n++) { fiddle(); else{ switch (z) { 9 case 1: fiddle(); break; 10 case 2: fiddle(); break; 11 case 3: fiddle(); break; 12 default: fiddle(); break; TIOBE - Java Coding Standard 07/12/18 Rule CodeSize6 Synopsis: This class has too many public methods and attributes Level: 2 Category: CodeSize A large number of public methods and attributes declared in a class can indicate the class may need to be broken up as increased effort will be required to thoroughly test it. This rule is triggered in case a class has 45 or more public methods and/or attributes. public String value; public Bar something; public Variable var; // [... more more public attributes...] public void dowork() { public void domorework() { public void doworkagain() { // [... more more public methods...] 20

26 Rule CodeSize7 TIOBE - Java Coding Standard 07/12/18 Synopsis: Too many fields Level: 3 Category: CodeSize Classes that have too many fields could be redesigned to have fewer fields, possibly through some nested object grouping of some of the information. For example, a class with city/state/zip fields could instead have one Address field. This rule is triggered in case a class has 15 or more fields. public class Person { String one; int two; int three; [... many more public fields...] Rule CodeSize9 Synopsis: Avoid long type definitions Level: 2 Category: CodeSize This rule uses the NCSS (Non Commenting Source Statements) algorithm to determine the number of lines of code for a given type. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one. If there are more than 1500 NCSSs in a class the rule will fire. public class Foo extends Bar { public Foo() { //this class has 6 NCSS lines super(); super.foo(); Rule CodeSize10 Synopsis: Avoid complex constructors Level: 2 Category: CodeSize 21

27 TIOBE - Java Coding Standard 07/12/18 NCSS stands for Non-Commenting Source Statements. As its name implies, NCSS represents anything that's not commentary. You could view it as the weight of the compiled code, or the amount of source code that actually does stuff, etc.. If there are more than 100 NCSSs in a method the rule will fire. This rule is similar to [CodeSize1]. public class Foo extends Bar { public Foo() { //this constructor has 2 NCSS lines super(); super.foo(); 22

28 Comments Rules Comments100 Every file should have a copyright statement at the top. Comments101 Use standard Java annotations. Comments103 Use TODO comments. Comments104 Each class should be preceded by JavaDoc comments. Rule Comments100 Synopsis: Every file should have a copyright statement at the top. Level: 7 Category: Comments For example /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Rule Comments101 Synopsis: Use standard Java annotations. Level: 5 Category: Comments Annotations should precede other modifiers for the same language element. Simple marker annotations can be listed on the same line with the language element. If there are multiple annotations, or parameterized annotations, they should each be listed one-per-line in alphabetical order. Android standard practices for the three predefined annotations in Java are: 23

29 TIOBE - Java Coding Standard annotation must be used whenever the use of the annotated element is discouraged. If you use annotation, you must also have Javadoc tag and it should name an alternate implementation. In addition, remember that method is still supposed to work. If you see old code that has Javadoc tag, please add annotation must be used whenever a method overrides the declaration or implementation from a super-class. For example, if you use Javadoc tag, and derive from a class (not an interface), you must also annotate that the the parent class's annotation should only be used under circumstances where it is impossible to eliminate a warning. If a warning passes this "impossible to eliminate" test, annotation must be used, so as to ensure that all warnings reflect actual problems in the code. When annotation is necessary, it must be prefixed with a TODO comment that explains the "impossible to eliminate" condition. This will normally identify an offending class that has an awkward interface. For example: // TODO: The third-party class com.third.useful.utility.rotate() needs List blix = Utility.rotate(blax); When annotation is required, the code should be refactored to isolate the software elements where the annotation applies. Rule Comments103 Synopsis: Use TODO comments. Level: 7 Category: Comments Use TODO comments for code that is temporary, a short-term solution, or good-enough but not perfect. TODOs should include the string TODO in all caps, followed by a colon: and // TODO: Remove this code after the UrlTable2 has been checked in. // TODO: Change this to use a flag instead of a constant. If your TODO is of the form "At a future date do something" make sure that you either include a very specific date ("Fix by November 2005") or a very specific event ("Remove this code after all production mixers understand protocol V7."). 24

30 Rule Comments104 TIOBE - Java Coding Standard 07/12/18 Synopsis: Each class should be preceded by JavaDoc comments. Level: 6 Category: Comments For example: import java.sql.resultset; import java.sql.sqlexception; /** * Does X and Y and provides an abstraction for Z. */... 25

31 Controversial The Controversial Ruleset contains rules that, for whatever reason, are considered controversial. Rules Controversial4 Avoid modifiers which are implied by the context Controversial5 Avoid assignments in operands Controversial7 Avoid importing anything from the 'sun.*' packages Controversial8 Suspicious decimal characters following octal escape in string literal Controversial10 This statement may have some unnecessary parentheses Rule Controversial4 Synopsis: Avoid modifiers which are implied by the context Level: 7 Category: Controversial Fields in interfaces are automatically public static final, and methods are public abstract. Classes or interfaces nested in an interface are automatically public and static (all nested interfaces are automatically static). For historical reasons, modifiers which are implied by the context are accepted by the compiler, but are superfluous. public interface Foo { public abstract void bar(); // both abstract and public are ignored by the compiler public static final int X = 0; // public, static, and final all ignored public static class Bar { // public, static ignored public static interface Baz { // ditto public class Bar { public static interface Baz { // static ignored Rule Controversial5 Synopsis: Avoid assignments in operands Level: 1 Category: Controversial Avoid assignments in operands; this can make code more complicated and harder to read. public void bar() { int x = 2; if ((x = getx()) == 3) { 26

32 System.out.println("3!"); private int getx() { return 3; TIOBE - Java Coding Standard 07/12/18 Rule Controversial7 Synopsis: Avoid importing anything from the 'sun.*' packages Level: 1 Category: Controversial Avoid importing anything from the 'sun.*' packages. These packages are not portable and are likely to change. import sun.misc.foo; Rule Controversial8 Synopsis: Suspicious decimal characters following octal escape in string literal Level: 1 Category: Controversial A suspicious octal escape sequence was found inside a String literal. The Java language specification (section ) says an octal escape sequence inside a literal String shall consist of a backslash followed by: OctalDigit OctalDigit OctalDigit ZeroToThree OctalDigit OctalDigit Any octal escape sequence followed by non-octal digits can be confusing, e.g. "\038" is interpreted as the octal escape sequence "\03" followed by the literal character "8". public void foo() { // interpreted as octal 12, followed by character '8' System.out.println("suspicious: \128"); Rule Controversial10 Synopsis: This statement may have some unnecessary parentheses Level: 6 27

33 TIOBE - Java Coding Standard 07/12/18 Category: Controversial Sometimes expressions are wrapped in unnecessary parentheses, making them look like a function call. boolean bar() { return (true); 28

34 Coupling These are rules which find instances of high or inappropriate coupling between objects and packages. Rules Coupling1 High amount of different objects as members denotes a high coupling Coupling2 A high number of imports can indicate a high degree of coupling within an object Rule Coupling1 Synopsis: High amount of different objects as members denotes a high coupling Level: 4 Category: Coupling This rule counts unique attributes, local variables and return types within an object. A number higher than specified threshold can indicate a high degree of coupling. This treshold has been set to 20. import com.blah; import org.bar; import org.bardo; private Blah var1; private Bar var2; //followed by many imports of unique objects void ObjectC dowork() { Bardo var55; ObjectA var44; ObjectZ var93; return something; Rule Coupling2 Synopsis: A high number of imports can indicate a high degree of coupling within an object Level: 3 Category: Coupling A high number of imports can indicate a high degree of coupling within an object. Rule counts the number of unique imports and reports a violation if the count is above the user defined threshold. This treshold has been set to 30. import blah.blah.baz; import blah.blah.bif; // 18 others from the same package elided 29

35 public void dowork() { TIOBE - Java Coding Standard 07/12/18 30

36 Design The Design Ruleset contains a collection of rules that find questionable designs. Rules Design1 Design2 Design3 Design4 Design5 Design6 Design7 Design8 Design9 Design10 Design11 Design12 Design13 Design14 Design15 Design16 Design17 Classes with only static methods should have a private constructor Avoid unnecessary if..then..else statements when returning a boolean Avoid unnecessary comparisons in boolean expressions Switch statements should have a default label Deeply nested if..then statements are hard to read Avoid reassigning parameters A high ratio of statements to labels in a switch statement. Consider refactoring Don't call overridable methods during object construction Avoid instantiation through private constructors from outside of the constructor's class This final field could be made static Ensure that resources are closed after use Non-static initializers are confusing The default label should be the last label in a switch statement A non-case label was present in a switch statement This call to Collection.toArray() may be optimizable Avoid equality comparisons with Double.NaN Avoid using equals() to compare against null Design18 Avoid if (x!= y)..; else..; Design19 Design20 Design21 Design22 Design23 Design24 Design25 Design26 Design27 Design28 Design29 Design30 Design32 Design33 Design34 Design35 Design36 Design39 Design40 Design41 Avoid instantiating an object just to call getclass() on it; use the.class public member instead Avoid idempotent operations (like assigning a variable to itself) When instantiating a SimpleDateFormat object, specify a Locale Declare private fields final, if possible When doing a String.toLowerCase()/toUpperCase() call, use a Locale Avoid protected fields in a final class. Change to private or package access Possible unsafe assignment to a non-final static field in a constructor Class cannot be instantiated and does not provide any static methods or fields Use block level rather than method level synchronization A switch statement does not contain a break Call Thread.notifyAll() rather than Thread.notify() An instanceof check is being performed on the caught exception. Create a separate catch clause for this exception type No need to check for null before an instanceof Use equals() to compare object references Position literals first in String comparisons Consider simply returning values instead of storing it in a local variable Singleton is not thread safe An Interface should be used only to model a behaviour; consider converting this to a class Static DateFormatter objects should be accessed in a synchronized manner Caught exception is rethrown, original stack trace may be lost 31

37 TIOBE - Java Coding Standard 07/12/18 Design42 Substitute calls to size() == 0 (or size()!= 0) with calls to isempty() Design43 Declare members privately Design44 Never initialize a final field to null Design100 The scope of local variables should be kept to a minimum. Rule Design1 Synopsis: Classes with only static methods should have a private constructor Level: 3 Category: Design If you have a class that has nothing but static methods, it allows either one instance or none at all. In either case a private constructor should be used. This also holds in case exactly one instance is allowed, because the Singleton pattern uses a private constructor. Note that this doesn't apply to abstract classes, since their subclasses may well include non-static methods. public class MaybeASingleton { public static void foo() { public static void bar() { Rule Design2 Synopsis: Avoid unnecessary if..then..else statements when returning a boolean Level: 4 Category: Design Avoid unnecessary if..then..else statements when returning a boolean. private int bar =2; public boolean isbarequalsto(int x) { // this bit of code if (bar == x) { return true; else { return false; // can be replaced with a simple // return bar == x; 32

38 Rule Design3 TIOBE - Java Coding Standard 07/12/18 Synopsis: Avoid unnecessary comparisons in boolean expressions Level: 4 Category: Design Avoid unnecessary comparisons in boolean expressions - this complicates simple code. public class Bar { // can be simplified to // bar = isfoo(); private boolean bar = (isfoo() == true); public isfoo() { return false; Rule Design4 Synopsis: Switch statements should have a default label Level: 2 Category: Design Switch statements should have a default label. public void bar() { int x = 2; switch (x) { case 2: int j = 8; Rule Design5 Synopsis: Deeply nested if..then statements are hard to read Level: 2 Category: Design Deeply nested if..then statements are hard to read. public void bar(int x, int y, int z) { 33

39 TIOBE - Java Coding Standard 07/12/18 if (x>y) { if (y>z) { if (z==x) { // whew, too deep Rule Design6 Synopsis: Avoid reassigning parameters Level: 2 Category: Design Reassigning values to parameters is a questionable practice. Use a temporary local variable instead. private void foo(string bar) { bar = "something else"; Rule Design7 Synopsis: A high ratio of statements to labels in a switch statement. Consider refactoring Level: 3 Category: Design A high ratio of statements to labels in a switch statement implies that the switch statement is doing too much work. Consider moving the statements into new methods, or creating subclasses based on the switch variable. public void bar(int x) { switch (x) { case 1: { // lots of statements break; case 2: { // lots of statements break; 34

40 Rule Design8 TIOBE - Java Coding Standard 07/12/18 Synopsis: Don't call overridable methods during object construction Level: 1 Category: Design Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to discern. It may leave the sub-class unable to construct its superclass or forced to replicate the construction process completely within itself, losing the ability to call super(). If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable. Note that this includes method calls throughout the control flow graph - i.e., if a constructor Foo() calls a private method bar() that calls a public method buz(), this denotes a problem. public class SeniorClass { public SeniorClass(){ tostring(); //may throw NullPointerException if overridden public String tostring(){ return "IAmSeniorClass"; public class JuniorClass extends SeniorClass { private String name; public JuniorClass(){ super(); //Automatic call leads to NullPointerException name = "JuniorClass"; public String tostring(){ return name.touppercase(); Rule Design9 Synopsis: Avoid instantiation through private constructors from outside of the constructor's class Level: 3 Category: Design Instantiation by way of private constructors from outside of the constructor's class often causes the generation of an accessor. A factory method, or non-privitization of the constructor can eliminate this situation. The generated class file is actually an interface. It gives the accessing class the ability to invoke a new hidden package scope constructor that takes the interface as a supplementary parameter. This turns a private constructor effectively into one with package scope, and is challenging to discern. public class Outer { void method(){ Inner ic = new Inner();//Causes generation of accessor class public class Inner { private Inner(){ 35

41 TIOBE - Java Coding Standard 07/12/18 Rule Design10 Synopsis: This final field could be made static Level: 4 Category: Design If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime. public final int BAR = 42; // this could be static and save some space Rule Design11 Synopsis: Ensure that resources are closed after use Level: 1 Category: Design Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use. public class Bar { public void foo() { Connection c = pool.getconnection(); try { // do stuff catch (SQLException ex) { // handle exception finally { // oops, should close the connection using 'close'! // c.close(); Rule Design12 Synopsis: Non-static initializers are confusing Level: 2 Category: Design 36

42 TIOBE - Java Coding Standard 07/12/18 A nonstatic initializer block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing. public class MyClass { // this block gets run before any call to a constructor { System.out.println("I am about to construct myself"); Rule Design13 Synopsis: The default label should be the last label in a switch statement Level: 3 Category: Design By convention, the default label should be the last label in a switch statement. void bar(int a) { switch (a) { case 1: // do something break; default: // the default case should be last, by convention break; case 2: break; Rule Design14 Synopsis: A non-case label was present in a switch statement Level: 2 Category: Design A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels. void bar(int a) { switch (a) { case 1: // do something break; 37

43 mylabel: // this is legal, but confusing! break; default: break; TIOBE - Java Coding Standard 07/12/18 Rule Design15 Synopsis: This call to Collection.toArray() may be optimizable Level: 5 Category: Design A call to Collection.toArray can use the Collection's size vs an empty Array of the desired type. class Foo { void bar(collection x) { // A bit inefficient x.toarray(new Foo[0]); // Much better; this one sizes the destination array, avoiding // a reflection call in some Collection implementations x.toarray(new Foo[x.size()]); Rule Design16 Synopsis: Avoid equality comparisons with Double.NaN Level: 1 Category: Design Avoid equality comparisons with Double.NaN - these are likely to be logic errors. public class Bar { boolean x = (y == Double.NaN); Rule Design17 Synopsis: Avoid using equals() to compare against null Level: 1 Category: Design 38

44 TIOBE - Java Coding Standard 07/12/18 Inexperienced programmers sometimes confuse comparison concepts and use equals() to compare to null. class Bar { void foo() { String x = "foo"; if (x.equals(null)) { // bad! dosomething(); Rule Design18 Synopsis: Avoid if (x!= y)..; else..; Level: 4 Category: Design In an "if" expression with an "else" clause, avoid negation in the test. For example, rephrase: if (x!= y) diff(); else same(); as: if (x == y) same(); else diff(); Most "if (x!= y)" cases without an "else" are often return cases, so consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?". boolean bar(int x, int y) { return (x!= y)? diff : same; Rule Design19 Synopsis: Avoid instantiating an object just to call getclass() on it; use the.class public member instead Level: 4 Category: Design Avoid instantiating an object just to call getclass() on it; use the.class public member instead. // Replace this Class c = new String().getClass(); // with this: Class c = String.class; 39

45 Rule Design20 TIOBE - Java Coding Standard 07/12/18 Synopsis: Avoid idempotent operations (like assigning a variable to itself) Level: 2 Category: Design Avoid idempotent operations - they are have no effect. public void bar() { int x = 2; x = x; Rule Design21 Synopsis: When instantiating a SimpleDateFormat object, specify a Locale Level: 1 Category: Design Be sure to specify a Locale when creating a new instance of SimpleDateFormat. // Should specify Locale.US (or whatever) private SimpleDateFormat sdf = new SimpleDateFormat("pattern"); Rule Design22 Synopsis: Declare private fields final, if possible Level: 3 Category: Design Identifies private fields whose values never change once they are initialized either in the declaration of the field or by a constructor. This aids in converting existing classes to immutable classes. private int x; // could be final public Foo() { x = 7; public void foo() { 40

46 TIOBE - Java Coding Standard 07/12/18 int a = x + 2; Rule Design23 Synopsis: When doing a String.toLowerCase()/toUpperCase() call, use a Locale Level: 4 Category: Design When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Turkish. class Foo { // BAD if (x.tolowercase().equals("list"))... /* This will not match "LIST" when in Turkish locale The above could be if (x.tolowercase(locale.us).equals("list"))... or simply if (x.equalsignorecase("list"))... */ // GOOD String z = a.tolowercase(locale.en); Rule Design24 Synopsis: Avoid protected fields in a final class. Change to private or package access Level: 2 Category: Design Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead. public final class Bar { private int x; protected int y; // Rule Design25 Synopsis: Possible unsafe assignment to a non-final static field in a constructor 41

TIOBE - Java Coding Standard Version head

TIOBE - Java Coding Standard Version head TIOBE - Java Coding Standard Version head issued by the CCB Coding Standards TIOBE - Java Coding Standard Table of Contents Change History...1 Introduction...3 Purpose...3 Basic...4 Rule Basic2...4 Rule

More information

TIOBE - Java Coding Standard Version head

TIOBE - Java Coding Standard Version head TIOBE - Java Coding Standard Version head issued by the CCB Coding Standards TIOBE - Java Coding Standard Table of Contents Change History...1 Introduction...3 Purpose...3 Basic...4 Rule Basic2...4 Rule

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

Name Definition Example Differences

Name Definition Example Differences Big Integer Instantiation Don't create instances of already existing BigInteger (BigInteger.ZERO, BigInteger.ONE) andfor Java 1.5 onwards, BigInteger.TEN and BigDecimal (BigDecimal.ZERO, BigDecimal.ONE,

More information

Points To Remember for SCJP

Points To Remember for SCJP Points To Remember for SCJP www.techfaq360.com The datatype in a switch statement must be convertible to int, i.e., only byte, short, char and int can be used in a switch statement, and the range of the

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Utilizing the Inspection Tool. Switching to PMD Perpective. Summary. Basic manual

Utilizing the Inspection Tool. Switching to PMD Perpective. Summary. Basic manual Utilizing the Inspection Tool Summary This guide will describe the egovframe s Code Inspection tool called PMD and its basic usage. Basic manual You can run Code Inspection from the IDE s PMD Perspective

More information

All code must follow best practices. Part (but not all) of this is adhering to the following guidelines:

All code must follow best practices. Part (but not all) of this is adhering to the following guidelines: Java Coding Guidelines Version 1.3.2 All code must follow best practices. Part (but not all) of this is adhering to the following guidelines: Development For code development, I recommend the following

More information

Introduction to Inheritance

Introduction to Inheritance Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits

More information

interface MyAnno interface str( ) val( )

interface MyAnno interface str( ) val( ) Unit 4 Annotations: basics of annotation-the Annotated element Interface. Using Default Values, Marker Annotations. Single-Member Annotations. The Built-In Annotations-Some Restrictions. 1 annotation Since

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Synchronization SPL/2010 SPL/20 1

Synchronization SPL/2010 SPL/20 1 Synchronization 1 Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2 Overview synchronization

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

COE318 Lecture Notes Week 8 (Oct 24, 2011)

COE318 Lecture Notes Week 8 (Oct 24, 2011) COE318 Software Systems Lecture Notes: Week 8 1 of 17 COE318 Lecture Notes Week 8 (Oct 24, 2011) Topics == vs..equals(...): A first look Casting Inheritance, interfaces, etc Introduction to Juni (unit

More information

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Casting -Allows a narrowing assignment by asking the Java compiler to trust us Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. Preface p. xix Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. 5 Java Applets and Applications p. 5

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 2 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

More information

Core Java Interview Questions and Answers.

Core Java Interview Questions and Answers. Core Java Interview Questions and Answers. Q: What is the difference between an Interface and an Abstract class? A: An abstract class can have instance methods that implement a default behavior. An Interface

More information

Symbol Tables Symbol Table: In computer science, a symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

17-654: Analysis of Software Artifacts. Tool Evaluation: EclipsePro Audit by Instantiations

17-654: Analysis of Software Artifacts. Tool Evaluation: EclipsePro Audit by Instantiations 17-654: Analysis of Software Artifacts Tool Evaluation: EclipsePro Audit by Instantiations Teams Diversity + Team13 Members: Adlan Israilov Brian Krausz Majid Alfifi Mohit Bhonde Raul Vejar 1 Index Index...

More information

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park CMSC 132: Object-Oriented Programming II Effective Java Department of Computer Science University of Maryland, College Park Effective Java Textbook Title Effective Java, Second Edition Author Joshua Bloch

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107 A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105

More information

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Software Design & Programming I

Software Design & Programming I Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 4 Making

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides 1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of

More information

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

INSTRUCTIONS TO CANDIDATES

INSTRUCTIONS TO CANDIDATES NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING MIDTERM ASSESSMENT FOR Semester 2 AY2017/2018 CS2030 Programming Methodology II March 2018 Time Allowed 90 Minutes INSTRUCTIONS TO CANDIDATES 1. This

More information

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Annotation Hammer Venkat Subramaniam (Also published at

Annotation Hammer Venkat Subramaniam (Also published at Annotation Hammer Venkat Subramaniam venkats@agiledeveloper.com (Also published at http://www.infoq.com) Abstract Annotations in Java 5 provide a very powerful metadata mechanism. Yet, like anything else,

More information

Language Fundamentals Summary

Language Fundamentals Summary Language Fundamentals Summary Claudia Niederée, Joachim W. Schmidt, Michael Skusa Software Systems Institute Object-oriented Analysis and Design 1999/2000 c.niederee@tu-harburg.de http://www.sts.tu-harburg.de

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

CMSC 331 Second Midterm Exam

CMSC 331 Second Midterm Exam 1 20/ 2 80/ 331 First Midterm Exam 11 November 2003 3 20/ 4 40/ 5 10/ CMSC 331 Second Midterm Exam 6 15/ 7 15/ Name: Student ID#: 200/ You will have seventy-five (75) minutes to complete this closed book

More information

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

9 Working with the Java Class Library

9 Working with the Java Class Library 9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and

More information

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines

More information

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM 1 of 18 9/6/2010 9:40 PM Flash CS4 Professional ActionScript 3.0 Language Reference Language Reference only Compiler Errors Home All Packages All Classes Language Elements Index Appendixes Conventions

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

/* Copyright 2012 Robert C. Ilardi

/* Copyright 2012 Robert C. Ilardi / Copyright 2012 Robert C. Ilardi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

More information

Classes, interfaces, & documentation. Review of basic building blocks

Classes, interfaces, & documentation. Review of basic building blocks Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform

More information

6.005 Elements of Software Construction Fall 2008

6.005 Elements of Software Construction Fall 2008 MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.005 elements

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 March 30, 2016 Collections and Equality Chapter 26 Announcements Dr. Steve Zdancewic is guest lecturing today He teaches CIS 120 in the Fall Midterm

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

Values and Variables 1 / 30

Values and Variables 1 / 30 Values and Variables 1 / 30 Values 2 / 30 Computing Computing is any purposeful activity that marries the representation of some dynamic domain with the representation of some dynamic machine that provides

More information

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

More information

Polymorphism. return a.doublevalue() + b.doublevalue();

Polymorphism. return a.doublevalue() + b.doublevalue(); Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Definition of DJ (Diminished Java)

Definition of DJ (Diminished Java) Definition of DJ (Diminished Java) version 0.5 Jay Ligatti 1 Introduction DJ is a small programming language similar to Java. DJ has been designed to try to satisfy two opposing goals: 1. DJ is a complete

More information