What if the parameter passed in the method is an object and not a base data type?Everything passed in Java is a value, but this value is the value that the variable carries. The variables that reference the object carry the remote control instead of the object itself. If you pass in a parameter to a method, you actually pass in a remotely controlled copy.
Can a method be declared as multiple return values?Method can only declare a single return value. If you need to return a value of 3 int, declare the type of the return value as an int array and return the value in the array. You can use ArrayList if there is a mix of different types of values that need to be returned.
Setter and Getter MethodsThe setter and getter method is essentially a package that prevents the outside world from being manipulated directly with the Origin operator, resulting in improper consequences. To set the value of the property must be uniform through the setter method, you can increase the value of the validation of the incoming data in the setter method, so that the value in the attribute is not arbitrarily modified.
Class Student {private String name = "Tom";p rivate int age = 18;public String getName () {return name;} public void SetName (String name) {if (name! = null &&!name.equals ("")) {this.name = name; Name cannot be empty}}public int getage () {return age;} public void Setage (int ages) {if (> 0) {this.age = age;//non-negative}}}public class Studentdriver {public static void Mai N (string[] args) {Student stu = new Student (); Stu.setage ( -6); Stu.setname (""); System.out.println ("Name:" + stu.getname () + "Age:" + stu.getage ());}}
Run Result: Name: Tom Age: 18
The two set operations in the main () method did not successfully set the Stu completion property, or the Stu property is its default value. Using the methods in the setter () to filter the bad attributes in the code above avoids the artificial modification of attributes in the class.
The difference between an instance variable and a local variable:
- Instance variables are declared in a class and not in a method;
Class Student {private String name = "Tom";p rivate int age =; Other code}<span style= "White-space:pre" ></span>
- Local variables are declared in the method;
Class Addthing {int A, b = 12;//instance variable public int add () {int total = a + b;//local variable return total;}}
- Local variables must be initialized before they are used
Class foo{public void Go () {int X;int z = x + 3;//cannot be compiled because there is no value before use}}
Equality in JavaFor the base data type, the byte sequence is compared with "= =", for example:
<span style= "White-space:pre" ></span>int a = 3;byte B = 3; String str = a==b? " Equal ":" Unequal "; System.out.println (str);
The above program will print "equal".
Headfirstjava Learning Experience--method