Thursday 29 March 2012

Java Basics-Part 1


A java source file can contain any number of classes but at most one class can be declared as public. If there is a public class, compulsory the name of the public class and the name of the source file must be matched otherwise Compile Time Error.If there is no public class, any name we can provide for java source file and there is no restriction.



Example:-
class A
{

}
class B
{

}
class C
{

}

Case -1:- If there is no public class then we can use any name as filename, there is no restriction in this case. File Name: “A.java” (or)” B.java” (or) “C.java “.

Case-2:- If class B declared as the public, then compulsory the name of the source file must be “B.java”, otherwise we will get compile time error.
Compile Time Error: - class B is public, should be declared filename as B.java.

Case-3:-If both A&B declared as public and the name of the source file is B.java, then we will get  Compile Time Error: - class A is public, should be declared filename as A.java.

Note:-It is always a good programming practice to maintain only one class for source and we can maintain that class name as source file name.

Import Statement:-

class Test
{
   public static void main(String[] args)
  {
     ArrayList al = new ArrayList();
   }
}

Compile Time Error:-can’t find symbol ArrayList.

We can resolve this problem by using fully qualified name.
       java.util.ArrayList al = new java.util.ArrayList();

the problem in this approach , using fully qualified name reduces the readability of the code.We can resolve this by using import statements.

import java.util.ArrayList;
class Test
{
    public static void main(String[] args)
   {
       ArrayList al = new ArrayList();
   }
}
 i.e., import statements simply acts as typing shortcut &improves readability of the code.

#include vs. import:-


In the case of #include all the required header files will be loaded at the beginning only.

But in the case of import the specified classed won’t be loaded at the beginning.Whenever we are using a particular class, then only corresponding class will be loaded. i.e., import statement follows load-on-fly.

Types of import statements:-

1. Explicit class import [import java.util.ArrayList] : It improves readability of the code, recommended to use.

2. Implicit class import [import java.util.*;] :  Not recommended to use because it reduces readability of the code.

Q) Which of the following import statements are valid?
i. import java.util.*;------------------------------Valid
ii. import java.util.ArrayList;------------------ Valid
iii. import java.util;------------------------------Not Valid
iv. import java.util.ArrayList.*;--------------Not Valid

Example1:

class MyObject extends java.rmi.UniCastRemoteObject
{

}
The above code compiles fine, even though we are not using import statement because we are using fully qualified name.

Example2:

import java.util.*;
import java.sql.*;
class Test
{
   Public static void main(String[] args)
  {
     Date d= new Date();
   }
}
Compile Time Error: - reference to Date is ambiguous, both classes java.util.Date and java.sql.Date

Note:-Even in the case of List (interface) also we can face the same ambiguity problem.Because it is available in both util and awt packages.

While resolving class names compiler will always gives the precedence in the following order.

1. Explicit class import.
2. Class name present in current working directory.
3. Implicit class import.

Whenever we are importing a package, sub package classes won’t be imported.

Ex: - 
import java.util.*;- in this case java.util.regex package classes won’t be
imported. If you want to import any of the regex package classes then its required to write one import statement (import java.util.regex.* ;)

import statement is totally compile time issue, there is no impact on runtime, more no of imports more will be the compile time. It is not required to import the members of the following packages because these are available by default for every java programmer.

i.java.lang package classes
ii.Current working directory classes[default package]

 

Static import:

 This concept is introduced in 1.5, According to static import, it improves readability. But according to worldwide experts it reduces the readability and increases the confusion of the code. Hence if there is no specific requirement, it is not recommended to use it. Whenever we are using static import it is not required to use class name while accessing static members.

Without static import:-

package com.basics;
import java.lang.*;


public class StaticImport
{
    // without static import
     public static void main(String[] args)
     {
          System.out.println(Math.sqrt(4)); // 2.0
          System.out.println(Math.random()); // 0.7138941126607322
          System.out.println(Math.max(10,20)); // 20
     }
}

With static import:-

package com.basics;
import static java.lang.Math.sqrt;
import static java.lang.Math.*;

//this class will explain the purpose of static imports.
public class StaticImport
{
      // with static import
      public static void main(String[] args)
      {
            System.out.println(sqrt(4));-----------// 2.0
            System.out.println(random());----------//0.2807616256825275
            System.out.println(max(10,20));--------// 20
       }
}

While resolving static members, compiler will always gives precedence in the following order.


1. Current class static members.
2. Explicit static import.
3. Implicit static import.

Example:-

package com.basics;
import static java.lang.Integer.MAX_VALUE;------(2)
import static java.lang.Byte.*;-----------------(3)
public class StaticPrecedence
{
   static int MAX_VALUE=888;------------------(1)
   public static void main(String[] args)
  {
     System.out.println(MAX_VALUE);
   }
}

  •  If we are commenting line-1,explicit static import will be considered and we will get output of Integer class MAX_VALUE (2147483647)
  • If we are commenting lin-1 and line-2 then Byte class MAX_VALUE will be consider and 127 as the output.
  • It is never recommended to use import concept until method level or variable level.But we have to use only at class level i.e., general import recommended to use, but not static import.

Q.Which of the following import statements are valid?
1. import static java.util.Date.*;----------valid
2. import static java.util.ArrayList;
3. import java.util.ArrayList;
4. import static java.lang.Math.sqrt;------valid
5. import java.util.ArrayList.*;
6. import java.lang.math.*;
7. import static java.lang.math.*;

Packages:-

  •  It is an encapsulation mechanism to group related classes & interfaces into a single module. The main purpose of the package statement is to resolve naming conflicts. There is universally accepted naming convention to name the packages. i.e. to use internet domain in reverse.
Ex: com.apple, com.veeram, com.icici etc...

package  com.veeram;
public class PackagesTest
{
    public static void main(String[] args)
   {
        System.out.println("Packages Demo");
    }
 }

compile 1 : javac  PackagesTest.java 
//The generated .class file will be placed in current working directory [default package].

comile 2 :  javac –d D: PackagesTest.java 
//the generated .class file will be placed in corresponding package structure.

If the specified package structure is not available then this command itself be create that structure.If the specified destination is not available then we will get compile time error.

Example:-
Compile:Javac -d Z: PackagesTest.java // the system can’t find the path specified.
Run:Java packages.PackagesTest // use fully qualified name to run the class.
Conclusion: - for any java source file there should be at most one package statement.
package pack1;
package pack2;--C.T.E
class Test
{

}

The Following is the valid structure of java source file.

1. Package statement--------------At most one.
2. Import statements--------------Any Number.
3. Class/interface declarations---Any Number.

Q. which of the following is valid sequence of statements in java source file?

1. import, package, class
2. package, import, class
3. import, class, interface
4. import, interface, class

Answer: 2,3,4 are valid sequence of statements

Q. which of the following are valid java source file?

1. empty file.
2. file contains only one statement which is import.
3.file contains only one statement which is package.

Answer: All options are valid.

Class level modifiers:-

Whenever we are using our own java classes compulsory we have to provide the information to the JVM.

1. Whether this class is accessible from anywhere or not.
2. Can we allowed to create an object of this class or not.
3. Shall we allowed to create child class or not.

We can specify this information by using corresponding modifiers.

   1.The only applicable modifiers for top level classes are :
        public, default, final, abstract and strictfp.
  If we are using any other modifier we will get compile time error.

  2 An inner class can be declared with the following modifier.
        public, default, final, abstract, strictfp, private, protected, static.

private Test
{

}..................compile time error: modifier private not allowed here.

Public classes:-

If a class is declared as public then we can access that class from anywhere.

package pack1;
public class A
{
   public void m1()
   {
      System.out.println("Hello");
    }
}

package pack2;
import pack1.A;
public class B
{
     public static void main(String[] args)
    {
        A a= new A();
        a.m1();
    }
}

If a class A is not declared as public then while compiling B class we will get “pack1.A is not public in pack1” can’t be accessed from outside package.

Default class:- 

 If a class declared as default then we can access that class only in current package but not from outside package.The default access is also known as package level access

Final classes:- 

Final is the modifier applicable for classes, methods and variables.Whatever the parent is by default available to the child through inheritance if the child is not satisfied with parent class implementation then child can override the  implementation in its own way. If the child is not allow to override [to meet security constraints ] then such type of methods we have to declare with final modifier i.e. final methods can’t be overridden .



package com.finalmodifier;
public class Parent
{
   public final void m1()
  {

   }
}
class Child extends Parent
{
   public void m1()
  {

  }
}
compile time error : m1() in Child can’t override , m1() in Parent overridden method is final.

If a class declared as final then we are not allow to create the child class
final class P
{
}
class C extends P
{

}
compile time error : can’t inherit from final P

Note:- The main advantage of final keyword is we can achieve security but the main limitation of final keyword is we are missing the key benefit of inheritance and polymorphism. Hence if there is no specific requirement it is not recommended to use final keyword.


No comments:

Post a Comment