ImageVerifierCode 换一换
格式:DOC , 页数:16 ,大小:24.82KB ,
资源ID:2813579      下载积分:20 金币
快捷下载
登录下载
邮箱/手机:
温馨提示:
快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。 如填写123,账号就是123,密码也是123。
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝    微信支付   
验证码:   换一换

加入VIP,免费下载
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【https://www.docduoduo.com/d-2813579.html】到电脑端继续下载(重复下载不扣费)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录   QQ登录   微博登录 

下载须知

1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。
2: 试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。
3: 文件的所有权益归上传用户所有。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 本站仅提供交流平台,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

版权提示 | 免责声明

本文(java十大常见代码错误(Java ten common code errors).doc)为本站会员(dzzj200808)主动上传,道客多多仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知道客多多(发送邮件至docduoduo@163.com或直接QQ联系客服),我们立即给予删除!

java十大常见代码错误(Java ten common code errors).doc

1、java十大常见代码错误(Java ten common code errors)As a junior Java developer, perhaps your experience is not enough, maybe because of your carelessness to the company, the project caused a loss, then it is unforgivable. As a technical personnel, only by constantly learning and improving their own technical l

2、evel, can they create higher value for themselves and for the company. The following is the author finishing Java common ten code errors, I hope to help you!1. Accessing non static member variables in static methods (for example, in the main method)Many of the programs that have just touched Java ar

3、e far from having access to member variables in the main method. The Main method is generally labeled as “static“, which means that we do not need to instantiate this class to call the main method. For example, the Java virtual machine can call the MyApplication class in such a way:MyApplication.mai

4、n (command line parameter);There is no instantiation of the MyApplication class, or there is no access to any member variables. For example, the following program produces a compiler error.Public class StaticDemoPublic String my_member_vaiable = “somedata“;Public static void main (String args)Access

5、 a non-satic member from static / / methodSystem.out.println (“This generates a compiler error“ +)My_member_variable);If you want to access a member variable in a static method (such as the main method), you need to instantiate an object. The following code shows you how to access a non static membe

6、r variable correctly. The idea is to instantiate an object first.Public class NonStaticDemoPublic String my_member_variable = “somedata“;Public static void main (String args)NonStaticDemo demo = new NonStaticDemo ();Member variable of demo / / AccessSystem.out.println (“This WONT generate an error“

7、+)Demo.my_member_variable);2, when overloaded, the wrong typing method name overload allows programmers to overwrite the method with new codeOverloading is a convenient feature, and many object-oriented programmers use it in large amounts. If you use the AWT1.1 time processing model, you usually ove

8、rride the listener method to implement custom functions. One of the most common errors in overloaded methods is the wrong way to type the name of the method to be overloaded. If you enter the method name by mistake, youre not overloaded with this method. On the contrary, youre redefining a method, b

9、ut the methods parameters and the return type are the same as the way you want to override it.Public class MyWindowListener extends WindowAdapter Should be WindowClosed / / ThisPublic void WindowClose (WindowEvent E) When user closes window / / ExitSystem.exit (0);This method is not compiled, and it

10、s easy to catch it. In the past, I had noticed a method, and believed it was called, and spent a lot of time looking for this mistake. The error is that your method will not be called, and you think your method has been skipped. One possible solution is to add a printout. Record information in the l

11、og file. Or use a trace debugger (such as VJ+ or Borland JBuilder) to debug one line and one line. If your method cant be called, its probably your method name.3, comparison and distribution (“=“ strong “= =“)When we use the = = operator, we are actually in a reference comparison object, to see if t

12、hey are not pointing to the same object.For example, we cannot use the = = operator to compare two strings are equal. We should use it. Equals method to compare two objects, this method is shared by all classes, it inherits from the java.lang.Object.Here is the correct method to compare two strings

13、of equal numbers:Bad / / wayIf (ABC + DEF) = = “ABCDEF“)Good / / wayIf (ABC + def). Equals (“ABCDEF“)5, confusion value transfer and reference deliveryIts a mistake thats not easy to find. Because when you look at the code, youre pretty sure its a reference pass, and its actually a value passing. Ja

14、va both will be used, so you need to understand when you need value transfer and when you need to pass by reference. When you pass a simple data type to a function, such as char, int, float, or double, you are passing a value. This means that a copy of this data type is copied, and this copy is pass

15、ed into the function. If this function modifies this value, only the copy of this value is modified. When the function is finished, it will return to the control call function, when the “true“ value is not affected, and no change is stored.If you want to modify a simple data type, you can locate thi

16、s data type as a return value or encapsulate it into an object.When you want to pass a Java object to a function, such as an array, a vector, or a string, you pass the reference to an object. The string here is also an object, not a simple data type. This means that you pass an object to a function,

17、 and you pass the reference to that object, instead of copying it. Any change to the member variable of this object will persist, and the quality of the change depends on whether you intend it or not.One thing to note is that if the string does not contain any method to change its value, youd better

18、 pass it as a value.6. Write an empty exception handlingI know that an empty exception handling is just as tempting as ignoring errors. But if something goes wrong, you dont get an output of the wrong message, which makes it unlikely to find the cause of the error. Even the simplest treatment is ver

19、y useful. For example, add your trycatch to your code and try to catch any of the throws and print the wrong information. You dont have to write custom processing for every exception (though its a good programming habit). But dont empty this exception, or you wont know what went wrong.Give an exampl

20、e:Public static void main (String args)TryCode goes here / / YourCatch (Exception E)System.out.println (“Err -“ + e);7. Forget the index in Java from 0If you have a C/C+ programming background, you wont find the same problem when youre using other programming languages.In Java, the index of the arra

21、y starts from 0, that is to say, the index of the first element must be 0. confused Lets take a look at the exampleAn array of Three Strings / / CreateString strArray = new String3;Elements index is / / First actually 0StrArray0 = “First string“;Elements index is / / Second actually 1StrArray1 = “Se

22、cond string“;Elements index is / / Final actually 2StrArray2 = “Third and final string“;In this example, we define an array with three strings, minus one when we access his element. Now,When we try to access strArray3, that is, the fourth element, there is a ArrayOutOfBoundsException exception throw

23、n. This is the most obvious example - forget the 0 index rules.Elsewhere, 0 index rules can also get you into trouble. For example, in a string. Suppose you want to get a character from the offset position determined by a string, and use String. CharAt (int) function, you can see this information. B

24、ut in Java, the string class index is from the beginning of 0, which means that the first character offset to 0, second to 1. you can get into some trouble, if you dont pay attention to this problem, especially the string processing is widely used in your application, then you are likely to use the

25、wrong character, while the runtime throws an StringIndexOutOfBoundsException exception exception, like ArrayOutOfBoundsException. The following example shows these:Public class StrDemoPublic static void main (String args)String ABC = “ABC“;System.out.println (“Char at offset 0; =“ abc.charAt (0);Sys

26、tem.out.println (“Char at offset 1; =“ abc.charAt (1);System.out.println (“Char at offset 2; =“ abc.charAt (2);Line should throw a StringIndexOutOfBoundsException / / ThisSystem.out.println (“Char at offset 3; =“ abc.charAt (3);It should also be noted that the 0 indexing rules should not be applied

27、only to arrays or strings, and other parts of Java will also be used. But not all of them are going to be used. Java.util.Date and java.util.Calendar, the month of the two categories started from 0, but the date usually starts at 1, and the following program proves this.Import java.util.Date;Import

28、java.java.util.Calendar;Public class ZeroIndexedDatePublic static void main (String args)Todays date / / GetDate today = new Date ();Return value of getMonth / / PrintSystem.out.println (“Date.getMonth () returns;“ +)Today.getMonth ();Todays date using a Calendar / / GetCalendar rightNow = Calendar.

29、getInstance ();Return value of / / print get (Calendar.MONTH)System.out.println (“Calendar.get (month) returns; +“ +RightNow.get (Calendar.MONTH);8. Prevent threads from accessing in shared variablesWhen writing a multithreaded application, many programmers like to cut corners. And this can cause th

30、read conflicts between their applications or small applications. When two or more threads access the same data, there is a certain probability (the size of the probability depends on the Murphy rule), which allows the two threads to access or modify the same data at the same time. (two). Dont be sil

31、ly enough to think that this isnt going to happen in single threaded applications. When you access the same data, your thread is likely to hang up, and when the second thread enters, it will overwrite the first thread modification.The problem is not just in multithreaded applications or small applic

32、ations. If you write Java API or Java Bean, your code is probably not thread safe. Even if youve never written a single application that uses threads, people can use your program. For others, not just you, you should take steps to prevent threads from accessing in shared variables.The easiest way to

33、 solve this problem is to make your variables private. Simultaneous access method. Access methods allow access to quasi member variables, but only in a control manner. The following access method can modify the value of the counter in a safe manner.Public class MyCounterPrivate int count = 0; /count

34、 starts at zeroPublic synchronized void setCount (int amount)Count = amount;Public synchronized int getCount ()Return count;9, uppercase errorThis is one of the most common mistakes we make. Hes very simple, but sometimes we look at a variable or method that doesnt have a capital, but we dont see it

35、. I myself often feel confused, because I think these methods and variables are present, but I cant find them without capital.Here you cant check it with silver bullets, you can only train yourself to reduce this error. Heres a trick:The methods and variable names used in Java API should begin with

36、lowercase letters.All new names with variable names and method names start with uppercase letters.If you define your variable name and class name in such a form, you are consciously making them correct, and you can gradually reduce the number of errors. This may take some time, but it may avoid more

37、 serious mistakes in the future.Down is the most common mistake Java programmers make!10, null pointerNull pointers are the most common mistakes Java programmers make. The compiler doesnt check this error for you, its only shown at runtime, and if you cant find it, your users will probably find it.W

38、hen trying to access an object, the objects reference is empty, and a NullPointerException exception is thrown. There are many reasons for null pointer errors, but in general, this error means that you have not initialized to an object, or you havent checked the return value of a function.Many funct

39、ions return an empty space that is used to indicate an error to be executed. If you dont scratch the return value, you cant know what happened. Since the cause is a wrong condition, the general test wont find it, which means that your user might find it for you at the end. If the API function indica

40、tes that an empty object is likely to be returned, it must be checked before using the objects reference.The other reason may be that you are not standard when initializing the object, or that its initialization is conditional. For example, check the code below to see if you can find the error.Publi

41、c static void main (String args)Up to / / Accept 3 parametersString list = new String3;Int index = 0;While (index args.length) All the parameters / / ChexkFor (int i = 0; I list.length; i+)If (listi.equals “-help“)/ /elseThe above code (as an example) shows the usual error. In some cases, the user i

42、nput three or more parameters, the code will run normally. However, if no parameters are entered, then an empty pointer exception is reached at run time. At some point, your variables will be initialized, but at other times they wont. A simple solution is to check that its very empty when you access the array elements.summaryThese errors are Java developers often make mistakes, although it is impossible to completely avoid errors in encoding,But you should avoid repeating mistakes.

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报