Tuesday, September 1, 2015

Controlling Access to Members of a Class



Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:
  • At the top level—public, or package-private (no explicit modifier).
  • At the member level—public, private, protected, or package-private (no explicit modifier).
A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

The following table shows the access to members permitted by each modifier.

Access Levels
Modifier
Class
Package
Subclass
World
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier
Y
Y
N
N
private
Y
N
N
N

The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class declared outside this package have access to the member. The fourth column indicates whether all classes have access to the member.
Access levels affect you in two ways. First, when you use classes that come from another source, such as the classes in the Java platform, access levels determine which members of those classes your own classes can use. Second, when you write a class, you need to decide what access level every member variable and every method in your class should have.
Let's look at a collection of classes and see how access levels affect visibility. The following figure shows the four classes in this example and how they are related.


Fig: Classes and Packages of the Example Used to Illustrate Access Levels

The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them.

Visibility
Modifier
Alpha
Beta
Alphasub
Gamma
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier
Y
Y
N
N
private
Y
N
N
N

 Tips on Choosing an Access Level: 
If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.
  • Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.
  • Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

Source: https://docs.oracle.com

Monday, August 24, 2015

Java Garbage Collection

Garbage collection (GC) is the process that aims to free up occupied memory that is no longer referenced by any reachable Java object, and is an essential part of the Java virtual machine's (JVM's) dynamic memory management system. In a typical garbage collection cycle all objects that are still referenced, and thus reachable, are kept. The space occupied by previously referenced objects is freed and reclaimed to enable new object allocation. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector (a part of JVM) so we don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
  • By nulling the reference
  • By assigning a reference to another
  • By annonymous object etc.
1) By nulling a reference:
Employee e=new Employee();  
e=null;  
2) By assigning a reference to another:
Employee e1=new Employee();  
Employee e2=new Employee();  
e1=e2;//now the first object referred by e1 is available for garbage collection  
3) By annonymous object:
new Employee();  

finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
  1. protected void finalize(){}  
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).


gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
public static void gc(){}  
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java

public class TestGarbage1{  
 public void finalize(){System.out.println("object is garbage collected");}  
 public static void main(String args[]){  
  TestGarbage1 s1=new TestGarbage1();  
  TestGarbage1 s2=new TestGarbage1();  
  s1=null;  
  s2=null;  
  System.gc();  
 }  
}  

Output:
       object is garbage collected
       object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

To learn more about java garbage collection refer to the following link:

Sunday, August 23, 2015

Reading Data from Keyboard in Java

There are many ways to read data from the keyboard. For example:
  1. InputStreamReader
  2. Console
  3. Scanner
  4. DataInputStream etc.
InputStreamReader class: InputStreamReader class can be used to read data from keyboard.It performs two tasks:
  • connects to input stream of keyboard
  • converts the byte-oriented stream into character-oriented stream
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.

Example of reading data from keyboard by InputStreamReader and BufferdReader class:
In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard.
import java.io.*;  
class G5{  
public static void main(String args[])throws Exception{  
  
InputStreamReader r=new InputStreamReader(System.in);  
BufferedReader br=new BufferedReader(r);  
  
System.out.println("Enter your name");  
String name=br.readLine();  
System.out.println("Welcome "+name);  
 }  
}  
Output:Enter your name
       Amit
       Welcome Amit

Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until the user writes stop:
In this example, we are reading and printing the data until the user prints stop.
import java.io.*;  
class G5{  
public static void main(String args[])throws Exception{  
  
 InputStreamReader r=new InputStreamReader(System.in);  
 BufferedReader br=new BufferedReader(r);  
  
 String name="";  
  
  while(name.equals("stop")){  
   System.out.println("Enter data: ");  
   name=br.readLine();  
   System.out.println("data is: "+name);  
  }  
 br.close();  
 r.close();  
 }  
}  

Output:Enter data: Amit
       data is: Amit
       Enter data: 10
       data is: 10
       Enter data: stop
       data is: stop

Java Console class: The Java Console class is be used to get input from console. It provides methods to read text and password. If you read password using Console class, it will not be displayed to the user. The java.io.Console class is attached with system console internally. The Console class is introduced since 1.5.
Let's see a simple example to read text from console.

String text=System.console().readLine();  
System.out.println("Text is: "+text);  

Methods of Console class
Let's see the commonly used methods of Console class.

Method

Description
1) public String readLine()
is used to read a single line of text from the console.
2) public String readLine(String fmt,Object... args)
it provides a formatted prompt then reads the single line of text from the console.
3) public char[] readPassword()
is used to read password that is not being displayed on the console.
4) public char[] readPassword(String fmt,Object... args)
it provides a formatted prompt then reads the password that is not being displayed on the console.

How to get the object of Console
System class provides a static method console() that returns the unique instance of Console class.
  1. public static Console console(){}  
Let's see the code to get the instance of Console class.
  1. Console c=System.console();  
Java Console Example
import java.io.*;  
class ReadStringTest{  
public static void main(String args[]){  
Console c=System.console();  
System.out.println("Enter your name: ");  
String n=c.readLine();  
System.out.println("Welcome "+n);  
}  
}  

Output:
Enter your name: james gosling
Welcome james gosling

Java Console Example to read password
import java.io.*;  
class ReadPasswordTest{  
public static void main(String args[]){  
Console c=System.console();  
System.out.println("Enter password: ");  
char[] ch=c.readPassword();  
String pass=String.valueOf(ch);//converting char array into string  
System.out.println("Password is: "+pass);  
}  
}   

Output:
Enter password:
Password is: sonoo

Java Scanner class: There are various ways to read input from the keyboard; the java.util.Scanner class is one of them. The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault. It provides many methods to read and parse various primitive values. Java Scanner class is widely used to parse text for string and primitive types using regular expression. Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

Commonly used methods of Scanner class:  There is a list of commonly used Scanner class methods.

Method
Description
public String next()
it returns the next token from the scanner.
public String nextLine()
it moves the scanner position to the next line and returns the value as a string.
public byte nextByte()
it scans the next token as a byte.
public short nextShort()
it scans the next token as a short value.
public int nextInt()
it scans the next token as an int value.
public long nextLong()
it scans the next token as a long value.
public float nextFloat()
it scans the next token as a float value.
public double nextDouble()
it scans the next token as a double value.

Java Scanner Example to get input from console
Let's see the simple example of the Java Scanner class which reads the int, string and double value as an input:

import java.util.Scanner;  
class ScannerTest{  
 public static void main(String args[]){  
   Scanner sc=new Scanner(System.in);  
     
   System.out.println("Enter your rollno");  
   int rollno=sc.nextInt();  
   System.out.println("Enter your name");  
   String name=sc.next();  
   System.out.println("Enter your fee");  
   double fee=sc.nextDouble();  
   System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);  
   sc.close();  
 }  
}   

Output:
       Enter your rollno
       111
       Enter your name
       Ratan
       Enter
       450000
       Rollno:111 name:Ratan fee:450000

Java Scanner Example with delimiter
Let's see the example of Scanner class with delimiter. The \s represents whitespace.
import java.util.*;  
public class ScannerTest2{  
public static void main(String args[]){  
     String input = "10 tea 20 coffee 30 tea buiscuits";  
     Scanner s = new Scanner(input).useDelimiter("\\s");  
     System.out.println(s.nextInt());  
     System.out.println(s.next());  
     System.out.println(s.nextInt());  
     System.out.println(s.next());  
     s.close();   
 }
}  

Output:
10
tea
20
coffee