Java programming 10 errors

zhaozj2021-02-16  55

(How to spot them. How to fix / prevent them.) By David ReillyWhether you program regularly in Java, and know it like the back of your hand, or whether you're new to the language or a casual programmer, you'll make mistakes. It's natural, it's human, and guess what? You'll more than likely make the same mistakes that others do, over and over again. Here's my top ten list of errors that we all seem to make at one time or another , How to spot them, and how to fix.

10. Accessing non-static member variables from static methods (such as main) Many programmers, particularly when first introduced to Java, have problems with accessing member variables from their main method The method signature for main is marked static -. Meaning that we don 'T NEED TO CREATE AN Instance of The Class to Invoke The Main Method. for Example, A Java Virtual Machine (JVM) Could Call The Class MyApplication Like this:

MyApplication.main (Command_line_args);

This Means, However, That there isn't an instance of myapplication - it doesn't Have Any Member Variables To Access! Take for Example The Following Application, Which Will Generate A Compiler Error Message.

public class StaticDemo {public String my_member_variable = "somedata"; public static void main (String args []) {// Access a non-static member from static method System.out.println ( "This generates a compiler error" my_member_variable) ;.}} If you want to access its member variables from a non-static method (like main), you must create an instance of the object Here's a simple example of how to correctly write code to access non-static member variables, by First Creat.Public Class of the Object.public Class NonStaticDemo {public string my_member_variable = "somedata";

Public static void main (string args []) {nonstaticDemo demo = new nonStaticDemo ();

// Access member variable of demo System.out.println ( "This WILL NOT generate an error" demo.my_member_variable);.}} 9 Mistyping the name of a method when overridingOverriding allows programmers to replace a method's implementation with new code . overriding is a handy feature, and most OO programmers make heavy use of it. If you use the AWT 1.1 event handling model, you'll often override listener implementations to provide custom functionality. One easy trap to fall into with overriding, is to MISTYPE The Method Name. if you missype the name, You're no longer overriding a method - You're Creating an entirely new method, but with reburn Type Parameter And Return Type.

Public class myWindowlistener Extends Windowadapter {// this stay be windowclosedpublic void windowclose (WindowEvent E) {// exit when user closes windowsystem.exit (0);}});

Compilers Won't pick up on this one, and the problem. In The Past, I'VE LOOKED ATHETHOD, BELIEVED THAT IT WAS Being Called, and Taken Ages To Spot The Problem. The Symptom of this error will be that your code is not being called, or you think the method has skipped over its code. The only way to ever be certain is to add a println statement, to record a message in a log file, or to use good trace debugger (like Visual J or Borland JBuilder) and step through line by line. If your method still is not being called, then it's likely you've mistyped the name.8. Comparison assignment (= rather than ==) This is an easy error to make If you're used other languages ​​before, such as Pascal, you'll realize just how poor a choice this was by the language's designers In Pascal, for example, we use the:.. = operator for assignment And Leave = for Comparison. this Looks Like A Throwback To C / C , from Which Java Draws Its Roots.

Fortunately, Even if you don't spot this one by looking at code on the screen, your compiler will. Most Commonly, It Will Report An Error Message Like this: "Can't Convert XXX Boolean", WHERE XXX IS A JAVA Type That You're Assigning INSTEAD OF Comparing.

7. Comparing two objects (== instead of .equals) When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We can not compare, for example, two strings for equality Using the == Operator. We Must Instead Use The .Equals Method, Which Is A Method Inherited by All classes from java.lang.object.

Here's The Correct Way To Compare Two strings.String ABC = "ABC"; string def = "def";

// Bad Wayif == "abcdef") {...} // good wayif ((abc def) .Equals ("abcdef")) {.....} 6 . Confusion over passing by value, and passing by referenceThis can be a frustrating problem to diagnose, because when you look at the code, you might be sure that its passing by reference, but find that its actually being passed by value. Java uses both SO you need to understand when you're passing by value, and when're passing by reference.

WHEN You Pass, To a Function. That Means That A Copy of The Data Type Is Duplicated, and Passed To The Function. IF THE function chooses to modify that value, it will be modifying the copy only. Once the function finishes, and control is returned to the returning function, the "real" variable will be untouched, and no changes will have been saved. If you need to Modify A Primitive Data Type, Make It A Return Value for A Function, or Wrap It INSIDE AN Object.

You Pass A Java Object, Such As An Array, A Vector, OR A String, To A Function Then You are passing by reference. Yes - a string is actually an Object, not a primitive data type. So what means what if you pass an object to a function, you are passing a reference to it, not a duplicate Any changes you make to the object's member variables will be permanent -. which can be either good or bad, depending on whether this was what you intended.

ON A Side Note, Since String Contains No Methods To Modify ITS Contents, You Might As Well Be Passing By Value.

5. Writing blank exception handlersI know it's very tempting to write blank exception handlers, and to just ignore errors. But if you run into problems, and have not written any error messages, it becomes almost impossible to find out the cause of the error . Even the simplest exception handler can be of benefit. For example, put a try {..} catch Exception around your code, to catch ANY type of exception, and print out the message. You do not need to write a custom handler For EVERY EXCEPTION (THOUGH THIS STILL Good Programming Practice). Don't Ever Leave It Blank, or you Won't know what's have.com.com

Public static void main (string args []) {Try {// Your code goes here ..} catch (exception e) {system.out.println ("Err -" E);}} 4. Forgetting That Java IS zero-indexedIf you've come from a C / C background, you may not find this quite as much a problem as those who have used other languages. In Java, arrays are zero-indexed, meaning that the first element's index is actually 0 CONFUSED? Let's Look At A Quick Example.

// Create an array of three stringsstring [] stratay = new string [3];

// first Element's index is actially 0strarray [0] = "first string";

// Second Element's Index Is Actually 1strarray [1] = "Second String";

// Final element's index is actually 2strArray [2] = "Third and final string";. In this example, we have an array of three strings, but to access elements of the array we actually subtract one Now, if we were to try and access strArray [3], we'd be accessing the fourth element This will case an ArrayOutOfBoundsException to be thrown -. the most obvious sign of forgetting the zero-indexing rule.Other areas where zero-indexing can get you into trouble is with . strings Suppose you wanted to get a character at a particular offset within a string Using the String.charAt (int) function you can look this information up -. but under Java, the String class is also zero-indexed That means than the. first character is at offset 0, and second at offset 1. you can run into some very frustrating problems unless you are aware of this -. particularly if you write applications with heavy string processing you can be working on the wrong character, and also throw Exceptions at run-time. Just Like the arrayo Utofboundsexception, There IS A String Equivalent. Accessing Beyond The Bounds of A String Will CauseXception To Be Thrown, As Demonstrate by this Example.

Public class strdemo {public static void main (string args []) {string ABC = "abc";

System.out.println ("Char at Offset 0:" Abc.charat (0)); System.out.Println ("Char at Offset 1:" Abc.charat (1)); System.out.Println "CHAR AT OFFSET 2:" Abc.charat (2));

// This line should throw a StringIndexOutOfBoundsException System.out.println ( "Char at offset 3:" abc.charAt (3));}} Note too, that zero-indexing does not just apply to arrays, or to Strings . Other parts of Java are also indexed, but not always consistently. The java.util.Date, and java.util.Calendar classes start their months with 0, but days start normally with 1. This problem is demonstrated by the following application. Import java.util.date; import java.util.calendar;

Public class zeroIndexeddate {public static void main (string args []) {// get today's date date today = new date ();

// Print Return Value of getMonthsystem.out.println ("Date.getMonth () Returns:" Today.getMonth ());

// Get Today's Date Using a Calendarcalendar RightNow = Calendar.GetInstance ();

// Print Return Value of Get (Calendar.Mont) System.out.println ("Calendar.get (Month) Returns:" RightNow.Get (Calendar.Mont));}}}}} ZERO-INDEXING IS Only A Problem if you Don't realize what its ketorring. if you think You're Running Into a Problem, ALWAYS Consult Your API Documentation.

3. Preventing concurrent access to shared variables by threadsWhen writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts. When two or more threads access the same data concurrently, there exists the possibility (and Murphy's law holding, the probability) that two threads will access or modify the same data at the same time. Do not be fooled into thinking that such problems will not occur on single-threaded processors. While accessing some data (performing a read), your thread may be suspended, and another thread scheduled. It writes its data, which is then overwritten when the first thread makes its changes.Such problems are not just limited to multi-threaded applications or applets. If you Write Java Apis, or JavaBeans, Then Your Code May Not Be Thread-Safe. Even if you never write a single cople thing buy you your code will willile. for the sanity of others, if Not YourSelf, you Should Always Take Precault to Prevent Concurrent Access To Shared Data.

How can this problem be solved? The simplest method is to make your variables private (but you do that already, right?) And to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the Following Accessor Methods, Which Provide a Safe Way to Change The Value of a Counter.

Public class mycounter {private int count = 0; // count starts at zero

Public synchronized void setcount (int Amount) {count = amount;

public synchronized int getCount () {return count;}.} 2 Capitalization errorsThis is one of the most frequent errors that we all make It's so simple to do, and sometimes one can look at an uncapitalized variable or method and still not spot the. problem. I myself have often been puzzled by these errors, because I recognize that the method or variable does exist, but do not spot the lack of capitalization.While there's no silver bullet for detecting this error, you can easily train yourself to make Less of them. There's a very Simple Trick you can Learn: -

all methods and member variables in the Java API begin with lowercase letters all methods and member variables use capitalization where a new word begins eg - getDoublevalue () If you use this pattern for all of your member variables and classes, and then make a conscious effort To Get It Right, You Can Gradually Reduce The Number of Mistakes You'll Make. It. It.....................

(drum roll) and the number one error That Java Programmers make !!!!!

! 1. Null pointers Null pointers are one of the most common errors that Java programmers make Compilers can not check this one for you -. It will only surface at runtime, and if you do not discover it, your users certainly will.

When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you have not initialized an object, or you Haven't Checked The Return Value of A Function.

Many functions return null to indicate an error condition - but unless you check your return values, you'll never know what's happening Since the cause is an error condition, normal testing may not pick it up -. Which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference! Another cause is where your initialization has been sloppy, or where it is conditional. for example, examine the following Code, and see if you can spot the problem.

Public static void main (string args []) {// accept up to 3 parameterstring [] list = new string [3];

INT INDEX = 0;

While (Index

// Check all the parameters for (int i = 0; i

转载请注明原文地址:https://www.9cbs.com/read-16344.html

New Post(0)