Access Specifiers/modifiers in java


Access Specifier:

  • To Explicitly mention the way how the data (variables and methods of a class) available to outside.
  • Access specifier is something which mentions the way how the member of a class has to be available to anything outside the class.
  • Access specifiers not not applicable to the local variables.(present inside method).
  • Access specifiers are the keywords using which we can control the accessibility of the members of a class.
  • There are 4 different ways in which we can control the accessibility of the members of a class
  • Thus there are "4" access specifiers and they are,
  1. public
  2. private
  3. protected
  4. default (not a keyword) 
  • if we not specify any keyword that will be considered as default 

Public:

  • The access specifier "public" makes the member of a class available to any location outside of the class.
  • Thus anything mentioned as public would be available to any location outside the class.
  • Means if we have a class with public access specifier then we can use it in other packages also by importing the corresponding package.

  1. package package1;
  2. public Class A{ 
  3. public void show(){
  4. }
  5. public static void main (String args[]) {
  6. }
  7. }

  1. package package2;
  2. import package1.*;
  3. public Class B {
  4. public static void main (String args[]) {
  5. A a = new A();
  6.  a.show();
  7. }
  8. }

Private:

  • Private would not allow the member of class available to any location outside the class.
  • private members would be available only within the same class.
  • Private members of a class would not be available to anything outside the class under any condition.
  • Private members of a class would also be not available to the sub class objects

  1. package package1;
  2. Class A{ 
  3. private void show(){
  4. }
  5. public static void main (String args[]) {
  6. A a= new A();
  7. a.show();
  8. }
  9. }

Default:

  • Any member of class mentioned without any access specifier then its considers that as default .
  • Default will act as "public " within the same package and same path.
  • The same default would act as private outside the package.
  • Default members of any class would be available to anything within the same package and would not be available outside the package under any condition.

  1. package package1;
  2. Class A{ 
  3. void show(){
  4. }
  5. public static void main (String args[]) {
  6. A a= new A(); // works fine in same class
  7. a.show();
  8. }
  9. }



  1. package package1;
  2. Class B{ 
  3. public static void main (String args[]) {
  4. A a= new A(); // works fine in same package
  5. a.show();
  6. }
  7. }

  1. package package2;
  2. import package1.*;
  3. Class B{ 
  4. public static void main (String args[]) {
  5. A a= new A(); // gives an error
  6. a.show(); // gives an error
  7. }
  8. }

 

Protected:

  • protected will act as public within the same package and acts as private outside the package.
  • But protected will also act as public outside the package only with respect to sub class objects.
  1. package package1;
  2. public Class A{ 
  3. protected void show() {
  4. }
  5. }

  1. package package2;
  2. import package1.*;
  3. public Class B extends A { 
  4. public static void main (String args[]) {
  5. B b= new B();
  6. b.show();
  7. }
  8. }
  • Access specifiers are applicable to static inner class and member inner class.
  • Access specifiers are not applicable to anonymous inner class and local inner class

Packages in java

Package:

  • Packages are nothing but all the related classes and interfaces and .class files.
  • Packages are the folders which are binding all the related ".class " files together
  • Binding: making something available to related functionalities.
  • A simple folder would only groups all the related files . But where as packages are also folders which binds all the related files.
  • Every package would be a folder. But every folder can not be a package

How to create user defined package:

  • By using a keyword "package".
  •  package package_name.
  1. package instanceofjavaforus;
  2. Class Demo{
  3. public static void main (String args[]) {
  4. }
  5. }

 

The Directory Structure of Packages:

  • To make java compiler to crate a package for us and automatically load all corresponding files into package
  1. package instanceofjavaforus;
  2. public Class Demo{
  3. public static void main (String args[]) {
  4. }
  5. }
  • Save this as Demo.java 
  • At this time there is no folder with name instanceofjavaforus 
  •  Javac -d . Demo.java.
  • -d : creates directory
  • instanceofjavaforus -> Demo.java: a folder with name instanceofjavaforus will be created and inside Demo.class will be there.

Creating Sub packages:

  • Create a package with a class;
  1. package pack;
  2. public  Class Demo{
  3. public static void main (String args[]) {
  4. }
  5. }
  •  C:/> javac -d . Demo.java
  • Now pack-> Demo.class folder structure will be created.
  • Now create sub package like this.

  1. package pack.subpack;
  2. public  Class Abc{
  3. public static void main (String args[]) {
  4. }
  5. }
  •  c:/> javac -d . Abc.java
  • pack->subpack -> Demo.class,Abc.class 

 How to create jar file representing our package: 

  •  By using dos command
  • c:/> jar -cvf file_name package_name.
  • Ex: jar -cvf instanceofjava.jar pack

Importing a package:

  • We can import packages by using "import".
  • To import the package
  • import<space><package-name><.><* or name of class you want to use from that package
  • To import particular class inside a package>.
  • import<space><package-name><.><name of class you want to use from that package>
  • As per the naming convention: For  package names use  small case letters.
  1. import pack.Demo;
  2. public  Class Xyz extends Demo {
  3. public static void main (String args[]) {
  4. }
  5. }



  1. import pack.*;
  2. public  Class Xyz extends Demo {
  3. public static void main (String args[]) {
  4. }
  5. }

 

Commonly using Predefined packages in java:  

Java.lang:

Provides classes that are fundamental to the design of the Java programming language. like
  1. Integer
  2. boolean
  3. Class
  4. Object
  5. Runtime
  6. Thread
  7. System
  8. Process
  9. Package
  10. String

Java.util.*:

This package contains the collections framework classes, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous. some of the interfaces and classes present in java.util package are as follows.
  1. Collection
  2. Comparator
  3. Enumeration
  4. RandomAccess
  5. List
  6. Set
  7. Map
  8. Iteraot
  9. EventListener
  10. Scanner (class)

Java.io.* :

This package provides classes and interfaces for system input and output through data streams, serialization and the file system.Some of the classes present in java.io package are as follows.
  1. BufferedInputStream
  2. BufferedOutputStream
  3. BufferedReader
  4. SerializablePermission
  5. Console
  6. File
  7. FileReader
  8. FilerWriter
  9. InputStream
  10. PrintStream

Java.text.* :

This package is used for formatting date and time on day to day business
operations.Some of the classes present in java.text package are as follows
  1. Annotation
  2. Collater
  3. Format
  4. DateFormat
  5. DecimalFormat
  6. MessageFormat
  7. NumberFormat
  8. Normalizer
  9. RuleBasedCollator
  10. ParsePosition

Java.sql.* 

This package is used for retrieving the data from data base and performing
various operations on data base. here some of the classes present in java.sql.
  1. Drivermanger
  2. Date 
  3. Time
  4. SqlPermission
  5. Timestamp
some of the interfaces present in java.sql package
  1. CallableStatement
  2. Connection
  3. PreparedStatement
  4. ResultSet
  5. Statement
  6. SQLData
  7. SQLInput
  8. SQLOutput

What is the difference between equals() method and == operator


== operator:

  •  == operator used to compare objects references.
  • used to compare data of primitive data types
  • if  we are comparing two objects using "==" operator if reference of both are same then it will returns true otherwise returns false.
  • obj1==obj2;
  • If we are comparing primitive data type variables then it compares data of those two variables
  • Ex: int a=12; int b=12; if(a==b) returns true

Comparing primitive values: 


  1. package com.instanceofjava;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {

  6. int a=12;
  7. int b=13;
  8. int c=12;
  9.  
  10. if(a==b){
  11. System.out.println("a and b are equal");
  12.  
  13. if(b==c){
  14. System.out.println("a and b are equal");
  15.  
  16. }
  17. }
     

Comparing Objects:

  1. package com.instanceofjavaforus;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  Demo obj1= new Demo();
  8. Demo obj2=new Demo();
  9.  
  10. if(obj1==obj2){ // here both are two different objects(memory allocation wise);
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1=new String("abc");
  8. String s2=new String("abc");
  9.  
  10. if(s1==s2){ // here it returns false
  11. System.out.println("obj1 and obj2 are referring to same address");
  12. }else{
  13.  System.out.println("obj1 and obj2 are referring to different address");
  14.  
  15. }
  16. }

Comparing String Literals:

  •  If we declared two string literals with same data then those will refer same reference.
  • means if we create any object using string literal then it will be created in string pool 
  • then if we are created another literal with same data then it wont create another object rather refers same object in pool.
  • so if compare two string literals with same data using "==" operator then it returns true.
  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringLiteralDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1="abc";
  8. String s2="abc";
  9.  
  10. if(s1==s2){ // here it returns true
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

equals() method:

  • equals() method defined in "object" class.
  • By default equals methods behaves like "==" operator when comparing objects.
  • By default equals() method compares references of objects.
  • But All wrapper classes and String class overriding this equals method and comparing data .
  • Means in String class and in All wrapper classes this equals() methods is overridden so that to compare data of those class objects. 

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1=new String("abc");
  8. String s2=new String("abc");
  9.  
  10. if(s1.equals(s2)){ // here it returns true
  11.  
  12. System.out.println(" data present in obj1 and obj2 is same");
  13.  
  14. }else{
  15.  
  16.  System.out.println(" data present in obj1 and obj2 is different");
  17.  
  18. }
  19. }
  20. }


 Comparing custom objects:

  • If we want to compare custom objects means our own objects data.
  • Then we need to override equals method and in that we need to compare data.

  1. package com.instanceofjavaforus;

    public class Patient {
       String name;
       Patient(String name){
           this.name=name;
       }
          public boolean equals(Patient obj){
          
           if(this.name.equals(obj)){
               return true;
           }else{
               return false;
           }
       }
           public static void main(){
            Patient obj1= new Patient("sam");
           
            Patient obj2= new Patient("sam");
           
            System.out.println(obj1.equals(obj2)); //returns true
        }
           
    }

Important points to note about equals() and "==":

  • "==" used to compare data for primitive data type variables .
  • "==" operator compares objects references
  • By default equals() method behaves like "==" operator for objects means compares objects references.
  • All wrapper classes and String class overriding this equals() method and compares data of two objects. if same returns true.(when ever we overrides equals() method we need to override hashcode() method too and if two objects on equal method same then both should have same hashcode).
  • And in equals() method in string class logic includes "==" operator too.

  1. package com.instanceofjava;
  2.  
  3. public boolean equals(Object anObject) {
  4.    if (this == anObject) {
  5.       return true;
  6.      }
  7.  if (anObject instanceof String) {
  8.      String anotherString = (String) anObject;
  9.      int n = value.length;
  10.     if (n == anotherString.value.length) {
  11.     char v1[] = value;
  12.      char v2[] = anotherString.value;
  13.   int i = 0;
  14. while (n-- != 0) {
  15.    if (v1[i] != v2[i])
  16.            return false;
  17.            i++;
  18.        }
  19.          return true;
  20.         }
  21.     }
  22.        return false;
  23.   }

Difference between throw and throws in java


Throw:

 

  • throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • If we are having our own validations in our code we can use this throw keyword.
  • For Ex: BookNotFoundException, InvalidAgeException (user defined) 




  1. //Custom exception
  2. package com.instanceofjavaforus;
  3. public class InvalidAgeException extends Exception {
  4.  InvaidAgeException(String msg){
  5.  super(msg);
  6.  }
  7. }
     

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public boolean isValidForVote(int age){
  4.  try{
  5.    if(age<18){
  6.   throw new InvalidAgeException ("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.   return false;
  12.  }
  13.   public static void main(String agrs[]){
  14.  ThrowDemo obj= new ThrowDemo();
  15.    obj.isValidForVote(17);
  16.   }
  17. }
We can throw predefined exceptions also

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public void method(){
  4.  try{
  5.   
  6.   throw new NullPointerException("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.  }
  12.   public static void main(String agrs[]){
  13.  ThrowDemo obj= new ThrowDemo();
  14.    obj.method();
  15.   }
  16. }
Like this we can throw checked exceptions and unchecked exceptions also. But throw keyword is mainly used to throw used defined exceptions / custom exceptions.

Throws:

  • The functionality of throws keyword is only to explicitly to mention that the method is proven transfer un  handled exceptions to the calling place.

  1. package com.instanceofjavaforus;
  2. public class ThrowSDemo {
  3. public void method(int a,int b) Throws ArithmeticException{
  4.  
  5. inc c= a/b;
  6.  }
  7.   public static void main(String agrs[]){
  8.  ThrowDemo obj= new ThrowDemo();
  9.    try{
  10. obj.method(1,0);
  11. }catch(Exception e){
  12.  System.out.println(e);
  13. }
  14.   }
  15. }

 Uses of throws keyword:

  • Using throws keyword we can explicitly provide the information about unhand-led exceptions of the method to the end user, Java compiler, JVM.
  • Using throws keyword we can avoid try-catch with respect to the statements which are proven to generate checked exceptions.
  • It us highly recommended not to avoid try-catch with respect to the statements which are proven to generate exceptions in main method using throws keyword to the main() method.



JDBC

JDBC:

  • The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. 
  • Using JDBC you can connect to the database and execute any type of statements related relational database. 
  • JDBC is a Java API for executing SQL statements and supports basic SQL functionality. 

JDBC Architecture:

http://instanceofjavaforus.blogspot.in/

  • Java application calls the JDBC API. JDBC loads a driver which connects to the database.

Connectivity Steps to JDBC:

5 Steps to connect java Application with the database using JDBC.They are:
  • Register the driver class
  • Creating Connection
  • Creating Statement
  • Execting Queries
  • Closing Connection

Register the driver class:

  • The forName() of class is used to register the driver class.Using this class is used load the class dynamically.
try {

Class.forName(com.mysql.jdbc.Driver”); //Or any other driver

}

catch(Exception x){

System.out.println( “Unable to load the driver class!” );

}

Creating the Connection:


  • DriverManager is the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. 
  • Its getConnection() method of Driver Manager class is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to 
  • the database and returns a connection object.

try{
 Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}
catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}

Creating Statement:


  • Once a connection is established we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. Statement 
  • A statement object is used to send and execute SQL statements to a database.
       statement = dbConnection.createStatement();

Three kinds of Statements:

  • Statement
  • Prepared Statement
  • Callable Statement

Statement:

  • Execute simple sql queries without parameters.
         Statement createStatement().

Prepared Statement: 

  • Execute precompiled sql queries with or without parameters.
        PreparedStatement prepareStatement(String sql).

Callable Statement: 

  • Execute a call to a database stored procedure.
       CallableStatement prepareCall(String sql)

Executing Queries:


  • Statement interface defines methods that are used to interact with database and execution of SQL statements.
  • The Statement class has three methods:
  • executeQuery()
  • executeUpdate()
  • execute(). 

executeQuery():


  • For a SELECT statement, the method to use is executeQuery . 

executeUpdate():

  • For statements that create or modify tables, the method to use is executeUpdate. 
  • statements and are executed with the method executeUpdate. 

execute():

  • execute() executes an SQL statement that is written as String object.

Connection Close():

  • This method is used to close the connection.
          con.close();

Syntax:

public void close() throws SQLException.


Difference between enumeration and iterator and listiterator?

Enumeration:

  • Enumeration interface implemented in java 1.2 version.So Enumeration is legacy interface.
  • Enumeration uses elements() method.
  • Enumeration can traverse in forward direction only.
  • Enumeration having methods like hasMoreElement(),nextElement().

Program:

package com.instanceofjavaforus;
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationDemo {
public static void main(String[] args) {
Vector vector=new Vector();
vector.add("indhu");
vector.add("sindhu");
vector.add("swathi");
vector.add("swathi");
vector.add(null);
vector.add(null);
Enumeration en = vector.elements();  
    while(en.hasMoreElements()){  
         System.out.println(en.nextElement());  
    }  
}
}

Output:

indhu
sindhu
swathi
swathi
null
null

Iterator:

  • Iterator is implemented on all Java collection classes.
  • Iterator uses iterator() method.
  • Iterator can traverse in forward direction only.
  • Iterator having methods like hasNext(), next(), remove().

Program:

package com.instanceofjavaforus;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class IteratorDemo{
public static void main(String[] args) {
TreeMap treeMap=new TreeMap();
treeMap.put("g", "indhu");
treeMap.put("d", "sindhu");
treeMap.put("3", "swathi");
treeMap.put("d", "sindhu");
if(!treeMap.isEmpty()){
Iterator it=treeMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}
}
}

}


Output:

swathi
sindhu
indhu

ListIterator:

  • ListIterator is implemented only for List type classes
  • ListIterator uses listIterator() method.
  • ListIterator can traverse in forward and backward directions.
  • ListIterator having methods like 
  • hasNext()
  • next()
  • previous()
  • hasPrevious()
  • remove()
  • nextIndex()
  • previousIndex().

Program:

package com.instanceofjavaforus;
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIteratorDemo{
public static void main(String[] args) {
ArrayList arrayList=new ArrayList();
arrayList.add("indhu");
arrayList.add("sindhu");
arrayList.add("saidesh");
arrayList.add(null);
arrayList.add(null);
ListIterator it=arrayList.listIterator();
while(it.hasNext()){
System.out.println(it.next());
}
}

}

Output:
indhu
sindhu
saidesh
null
null


Select Menu