More about Methods

Passing by Value
The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application (which is how Java handles it), but other languages could choose parameter storage differently. Java is strictly pass-by-value, exactly as in C.
public class PassByValueExample {
public static void main(String args[]) {
int number = 3;
printNext(number);
System.out.println("number Inside main(): "+number);
}
public static void printNext(int number){
number++;
System.out.println("number Inside printNext(): "+number);
}
}
Output:
number Inside printNext(): 4
number Inside main(): 3
Pass-by-reference
The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.
Pass by Reference means the passing the address itself rather than passing the value and pass by value means passing a copy of the value as an argument.
public class PassByReferenceConfusion {
public static void main(String args[]) {
Car car = new Car("BMW");
System.out.println("Brand of Car Inside main() before: "+ car.brand);
printBrand(car);
System.out.println("Brand of Car Inside main()after: "+ car.brand);
}
public static void printBrand(Car car){
car.brand = "Maruti";
System.out.println("Brand of Car Inside printBrand(): "+car.brand);
}
private static class Car{
private String brand;
public Car(String brand){
this.brand = brand;
}
}
}
Output:
Brand of Car Inside main() before: BMW
Brand of Car Inside printBrand(): Maruti
Brand of Car Inside main()after: Maruti
Pass by value v/s Pass by reference
Pass by Reference means the passing the address itself rather than passing the value and pass by value means passing a copy of the value as an argument.
This is simple enough, however there is an important but simple principle at work here. If a variable is passed, the method receives a copy of the variable's value. The value of the original variable cannot be changed within the method. This seems reasonable because the method only has a copy of the value; it does not have access to the original variable. This process is called pass by value.
However, if the variable passed is an object, then the effect is different. We often say things like, "this method returns an object ...", or "this method is passed an object as an argument ..." But this is not quite true, more precisely, we should say, something like "this method returns a reference to an object ..." or "this method is passed a reference to an object as an argument ..."
Generally, objects are never passed to methods or returned by methods. It is always "a reference to an object" that is passed or returned. In general, pass by value refers to passing a constant or a variable holding a primitive data type to a method, and pass by reference refers to passing an object variable to a method. In both cases a copy of the variable is passed to the method. It is a copy of the "value" for a primitive data type variable; it is a copy of the "reference" for an object variable. So, a method receiving an object variable as an argument receives a copy of the reference to the original object.
Here's the clincher: If the method uses that reference to make changes to the object, then the original object is changed. This is reasonable because both the original reference and the copy of the reference "refer to" to same thing — the original object. There is one exception: strings. Since String objects are immutable in Java, a method that is passed a reference to a String object cannot change the original object.
Access Control
In Java the unit of programming is the class from which objects are eventually instantiated. An Object encapsulates data (attributes) and methods (behaviors), the implementation details are hidden within the objects themselves.
Class rules
* There can only be one public class per source code file
* The name of the public class must match the name of the file
* If the class is part of a package this must be the first line of code
* Import declarations must be between package details and the class declaration
* Import and package statements apply to all classes within the source code file
Declarations and Modifiers
Class Access
There are two types of modifiers that can be used for class declaration
Access Modifiers - public and default (package)
Nonaccess Modifiers - strictfp, final and abstract
Every class you declare has an access control, whether you explicity type one or not. When a class has access to another class it means he can do one of 3 things
Create an instance of that class
Extend the class (become a subclass)
Access certain methods and variables within that class
Access means visibility, if you do not have access to a class you cannot use any methods or variables of that class.
Class Access Modifiers
Default Access When no modifier is present then default access is applied, think of default access as package access, a class with default access can be seen only by classes within the same package
Public Access When declared with public access it gives all classes from all packages access to the public class, although you still need to import the class
Class non-Access Modifers
Final Classes When used with classes this means that the class cannot be subclassed (cannot extend). Many of classes in the Java library are final classes.
Abstract Classes

An abstract class can never be instantiated, its sole purpose is to be extended (subclassed). If a single method in a class is abstract the whole class must be declared abstract. You can put non-abstract methods in a abstract class (also known as a concrete method), you will be unable to override the non-abstract method. An abstract class can extend another abstract class.

You cannot mark a class as both abstract and final as they mean the opposite, you will get a compiler error (illegal combination of modifiers).

The first concrete class to extend an abstract class must implement all abstract methods.

Abstract classes can have constructors.


Method and Variable Access
Methods and Variables within a class are collectively known as members.There are two types of modifiers that can be used for a member declaration
* Access Modifiers - private, protected, public and default
* Nonaccess Modifiers - final, abstract, transient, synchronized, native, strictfp and static
Every member you declare has an access control, whether you explicity type one or not. Members accessed with using the dot operator (.) must belong to the same class, the this keyword is used to reference the currently executing object.
Member Access Modifiers
Public Access When the member is declared protected it means that only the following can access the member
  • class that declared the member
  • any subclasses
  • any class thats in the same package can access it
  • any class
Protected Access When the member is declared protected it means that only the following can access the member
  • class that declared the member
  • any subclasses
  • any class thats in the same package can access it
Default Access When the member has no modifier it has default access only the following can access the member
  • class that declared the member
  • any subclasses
Private Access When the member is declared protected it means that only the following can access the member. Methods that are declared private are implicity final.
  • class that declared the member
Member non-Access Modifers
Final When used this means that the member (method or variable) cannot be overridden. A variable in a interface is implicity marked as final.
Abstract An abstract method is a method that has been declared but not implemented, in other words the method contains no functional code. The abstract method must be implemented in either the sub-class or any other subclass that has extend it.
Transient This modifier can only be applied to variables, you are telling JVM to skip this variable when you attempt to serialize the object declaring it.
Synchronized When used this means that the method can be accessed by only one thread at a time. It can only be applied to methods.
Native Indicates that a method is implemented in a platform-dependent language such as C.
Strictfp Indicates that strict floating-point will be adhered too.
Static

The best way i can describe a static variable or method is that one copy of the static member is contained in memory that allows all instances to access this copy, an example of this is like having a single counter variable that all classes can update.

There is a rule that states that a static method of a class can't access a nonstatic member or variable of its own class. Static methods are also declared final implicity.

You can Make Static:        Methods, Variables and Top-Level nested Classes
You cannot make static:    Constructors, Classes, Interfaces, Inner Classes, Inner Class Methods/Variables, Local variables

There is also no this reference when using static, also all static variables and methods are loaded first in order of appearance, you may find a simple static block of code to initialize variables or execute code.


Access to members permitted by each modifier
Modifier
Class
Package
Subclass
World
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier (default)
Y
Y
N
N
private
Y
N
N
N

Example: -

class ST_Employee
{
    int eid;
    String name;
    static String company_name ="StudyTonight";
    public void show()
    {
        System.out.println(eid+" "+name+" "+company_name);
    }
    public static void main( String[] args )
    {
     ST_Employee se1 = new ST_Employee();
     se1.eid = 1976;
     se1.name = "Anuj";
     se1.show();
     ST_Employee se2 = new ST_Employee();
     se2.eid = 2014;
     se2.name = "Babloo";
     se2.show();
    }
}

Output

1976 Anuj StudyTonight
2014 Babloo StudyTonight
Recursion
Recursion is a basic programming technique you can use in Java, in which a method calls itself to solve some problem. A method that uses this technique is recursive. Many programming problems can be solved only by recursion, and some problems that can be solved by other techniques are better solved by recursion.
One of the classic problems for introducing recursion is calculating the factorial of an integer. The factorial of any given integer — call it n so that you sound mathematical — is the product of all the integers from 1 to n. Thus, the factorial of 5 is 120: 5 x 4 x 3 x 2 x 1.
The recursive way to look at the factorial problem is to realize that the factorial for any given number n is equal to n times the factorial of n–1, provided that n is greater than 1. If n is 1, the factorial of n is 1.
This definition of factorial is recursive because the definition includes the factorial method itself. It also includes the most important part of any recursive method: an end condition. The end condition indicates when the recursive method should stop calling itself. In this case, when n is 1, it just returns 1. Without an end condition, the recursive method keeps calling itself forever.
Example: -
class Calculation
{
int fact(int n)
{
int result;
if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
}
public class Factorial
{
public static void main(String args[])
{
Calculation obj_one = new Calculation();
int a = obj_one.fact(4);
System.out.println("The factorial of the number is : " + a);
}
}
C:\java>javac Factorial.java
C:\java>java Factorial
The factorial of the number is : 24


Free Web Hosting